-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain_docker.py
More file actions
2878 lines (2241 loc) · 145 KB
/
Copy pathmain_docker.py
File metadata and controls
2878 lines (2241 loc) · 145 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import numpy as np
# import langchain
import pandas as pd
import missingno as msno
import io
import sys
from ydata_profiling import ProfileReport
import streamlit as st
from streamlit_pandas_profiling import st_profile_report
import streamlit.components.v1 as components
import numpy as np
import plotly.figure_factory as ff
import matplotlib.pyplot as plt
import seaborn as sns
from statsmodels.imputation import mice
from sklearn.neural_network import MLPClassifier
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder, StandardScaler, MinMaxScaler, normalize
from sklearn.decomposition import PCA
from sklearn.metrics import accuracy_score, confusion_matrix, roc_curve, roc_auc_score, average_precision_score, precision_recall_curve, auc, f1_score
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.impute import SimpleImputer
from sklearn import svm
from langchain.agents import AgentType, initialize_agent
from langchain.chat_models import ChatOpenAI
from langchain_experimental.agents.agent_toolkits import create_pandas_dataframe_agent
from langchain.llms import OpenAI
import json
import base64
import plotly.io as pio
from bs4 import BeautifulSoup
from PIL import Image
from scipy import stats
import lifelines
from lifelines import KaplanMeierFitter, CoxPHFitter
from prompts import *
from sklearn.decomposition import PCA
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier, NeighborhoodComponentsAnalysis
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
import openai
from openai import OpenAI
from tableone import TableOne
from scipy import stats
from streamlit_chat import message
import random
from random import randint
import os
from sklearn import linear_model
import statsmodels.api as sm
import category_encoders as ce
from mpl_toolkits.mplot3d import Axes3D
import shap
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
import matplotlib.pyplot as plt
st.set_page_config(page_title='AutoAnalyzer', layout = 'centered', page_icon = ':chart_with_upwards_trend:', initial_sidebar_state = 'auto')
# if st.button('Click to toggle sidebar state'):
# st.session_state.sidebar_state = 'collapsed' if st.session_state.sidebar_state == 'expanded' else 'expanded'
# # Force an app rerun after switching the sidebar state.
# st.experimental_rerun()
# # Initialize a session state variable that tracks the sidebar state (either 'expanded' or 'collapsed').
if 'last_response' not in st.session_state:
st.session_state.last_response = ''
if 'df' not in st.session_state:
st.session_state.df = pd.DataFrame()
if 'modified_df' not in st.session_state:
st.session_state.modified_df = pd.DataFrame()
if "openai_api_key" not in st.session_state:
st.session_state.openai_api_key = ''
if "gen_csv" not in st.session_state:
st.session_state.gen_csv = None
if "df_to_download" not in st.session_state:
st.session_state.df_to_download = None
@st.cache_data
def is_valid_api_key(api_key):
openai.api_key = api_key
try:
# Send a test request to the OpenAI API
response = openai.Completion.create(model="text-davinci-003",
prompt="Hello world")['choices'][0]['text']
return True
except Exception:
pass
return False
def is_bytes_like(obj):
return isinstance(obj, (bytes, bytearray, memoryview))
def save_image(plot, filename):
if is_bytes_like(plot):
img = io.BytesIO(plot)
else:
img = io.BytesIO()
plot.savefig(img, format='png')
btn = st.download_button(
label="Download your plot.",
data = img,
file_name=filename,
mime='image/png',
)
@st.cache_data
def generate_regression_equation(intercept, coef, x_col):
equation = f"y = {round(intercept,4)}"
for c, feature in zip(coef, x_col):
equation += f" + {round(c,4)} * {feature}"
return equation
def df_download_options(df, report_type, format):
file_name = f'{report_type}.{format}'
if format == 'csv':
data = df.to_csv(index=True)
mime = 'text/csv'
if format == 'json':
data = df.to_json(orient='records')
mime = 'application/json'
if format == 'html':
data = df.to_html()
mime = 'text/html'
if True:
st.download_button(
label="Download your report.",
data=data,
# data=df.to_csv(index=True),
file_name=file_name,
mime=mime,
)
@st.cache_data
def plot_mult_linear_reg(df, x, y):
# with sklearn
regr = linear_model.LinearRegression()
regr.fit(x, y)
# st.write('Intercept: \n', regr.intercept_)
# st.write('Coefficients: \n', regr.coef_)
# with statsmodels
x = sm.add_constant(x) # adding a constant
model = sm.OLS(y, x).fit()
predictions = model.predict(x)
print_model = model.summary2()
st.write(print_model)
try:
df_mlr_output = print_model.tables[1]
except:
st.write("couldn't generate dataframe version")
return print_model, df_mlr_output, regr.intercept_, regr.coef_
@st.cache_data
def all_categorical(df):
categ_cols = df.select_dtypes(include=['object']).columns.tolist()
numeric_cols = [col for col in df.columns if df[col].nunique() == 2 and df[col].dtype != 'object']
filtered_categorical_cols = [col for col in categ_cols if df[col].nunique() <= 15]
all_categ = filtered_categorical_cols + numeric_cols
return all_categ
@st.cache_data
def all_numerical(df):
numerical_cols = df.select_dtypes(include='number').columns.tolist()
for col in df.select_dtypes(include='object').columns:
if df[col].nunique() == 2:
unique_values = df[col].unique()
if 0 in unique_values and 1 in unique_values:
continue
value_counts = df[col].value_counts()
most_frequent_value = value_counts.idxmax()
least_frequent_value = value_counts.idxmin()
if most_frequent_value != 0 and least_frequent_value != 1:
df[col] = np.where(df[col] == most_frequent_value, 0, 1)
st.write(f"Replaced most frequent value '{most_frequent_value}' with 0 and least frequent value '{least_frequent_value}' with 1 in column '{col}'.")
numerical_cols.append(col) # Update numerical_cols
return numerical_cols
def filter_dataframe(df):
# Get the column names and data types of the dataframe
columns = df.columns
dtypes = df.dtypes
# Create a sidebar for selecting columns to exclude
excluded_columns = st.multiselect("Exclude Columns", columns)
# Create a copy of the dataframe to apply the filters
filtered_df = df.copy()
# Exclude the selected columns from the dataframe
filtered_df = filtered_df.drop(excluded_columns, axis=1)
# Get the column names and data types of the filtered dataframe
filtered_columns = filtered_df.columns
filtered_dtypes = filtered_df.dtypes
# Create a sidebar for selecting numerical variables and their range
numerical_columns = [col for col, dtype in zip(filtered_columns, filtered_dtypes) if dtype in ['int64', 'float64']]
for col in numerical_columns:
min_val = filtered_df[col].min()
max_val = filtered_df[col].max()
st.write(f"**{col}**")
min_range, max_range = st.slider("", min_val, max_val, (min_val, max_val), key=col)
# Filter the dataframe based on the selected range
if min_range > min_val or max_range < max_val:
filtered_df = filtered_df[(filtered_df[col] >= min_range) & (filtered_df[col] <= max_range)]
# Create a sidebar for selecting categorical variables and their values
categorical_columns = [col for col, dtype in zip(filtered_columns, filtered_dtypes) if dtype == 'object']
for col in categorical_columns:
unique_values = filtered_df[col].unique()
selected_values = st.multiselect(col, unique_values, unique_values)
# Filter the dataframe based on the selected values
if len(selected_values) < len(unique_values):
filtered_df = filtered_df[filtered_df[col].isin(selected_values)]
return filtered_df
# Function to generate a download link
@st.cache_data
def get_download_link(file_path, file_type):
with open(file_path, "rb") as file:
contents = file.read()
base64_data = base64.b64encode(contents).decode("utf-8")
download_link = f'<a href="data:application/octet-stream;base64,{base64_data}" download="tableone_results.{file_type}">Click here to download the TableOne results in {file_type} format.</a>'
return download_link
@st.cache_data
def find_binary_categorical_variables(df):
binary_categorical_vars = []
for col in df.columns:
unique_values = df[col].unique()
if len(unique_values) == 2:
binary_categorical_vars.append(col)
return binary_categorical_vars
@st.cache_data
def calculate_odds_older(table):
odds_cases = table.iloc[1, 1] / table.iloc[1, 0]
odds_controls = table.iloc[0, 1] / table.iloc[0, 0]
odds_ratio = odds_cases / odds_controls
return odds_cases, odds_controls, odds_ratio
@st.cache_data
def calculate_odds(table):
odds_cases = table.iloc[1, 1] / table.iloc[1, 0]
odds_controls = table.iloc[0, 1] / table.iloc[0, 0]
odds_ratio = odds_cases / odds_controls
return odds_cases, odds_controls, odds_ratio
@st.cache_data
def generate_2x2_table(df, var1, var2):
table = pd.crosstab(df[var1], df[var2], margins=True)
table.columns = ['No ' + var2, 'Yes ' + var2, 'Total']
table.index = ['No ' + var1, 'Yes ' + var1, 'Total']
return table
@st.cache_data
def plot_survival_curve(df, time_col, event_col):
# Create a Kaplan-Meier fitter object
try:
kmf = KaplanMeierFitter()
# Fit the survival curve using the dataframe
kmf.fit(df[time_col], event_observed=df[event_col])
# Plot the survival curve
fig, ax = plt.subplots()
kmf.plot(ax=ax)
# Add labels and title to the plot
ax.set_xlabel('Time')
ax.set_ylabel('Survival Probability')
ax.set_title('Survival Curve')
# Display the plot
st.pyplot(fig)
return fig
except TypeError:
st.warning("Find the right columns for time and event.")
@st.cache_data
def calculate_rr_arr_nnt(tn, fp, fn, tp):
rr = (tp / (tp + fn)) / (fp / (fp + tn)) if fp + tn > 0 and tp + fn > 0 else np.inf
arr = (fn / (fn + tp)) - (fp / (fp + tn)) if fn + tp > 0 and fp + tn > 0 else np.inf
nnt = 1 / arr if arr > 0 else np.inf
return rr, arr, nnt
def fetch_api_key():
# Try to get the API key from an environment variable
api_key = os.getenv("OPENAI_API_KEY")
# If the API key is found in the environment variables, return it
if api_key:
return api_key
# If the API key is not found, check if it's already in the session state
if 'openai_api_key' in st.session_state and st.session_state.openai_api_key:
return st.session_state.openai_api_key
# If the API key is not in the environment variables or session state, prompt the user
st.sidebar.warning("Please enter your API key.")
api_key = st.sidebar.text_input("API Key:", key='api_key_input')
# If the user provides the API key, store it in the session state and return it
if api_key:
st.session_state.openai_api_key = api_key
return api_key
else:
# If no API key is provided, display an error
st.error("API key is required to proceed.")
return None
def check_password():
return True
# """Returns `True` if the user had the correct password."""
# def password_entered():
# """Checks whether a password entered by the user is correct."""
# if st.session_state["password"] == os.getenv("password"):
# st.session_state["password_correct"] = True
# del st.session_state["password"] # don't store password
# else:
# st.session_state["password_correct"] = False
# if "password_correct" not in st.session_state:
# # First run, show input for password.
# st.text_input(
# "GPT features require a password.", type="password", on_change=password_entered, key="password"
# )
# st.warning("*Please contact David Liebovitz, MD if you need an updated password for access.*")
# return False
# elif not st.session_state["password_correct"]:
# # Password not correct, show input + error.
# st.text_input(
# "GPT features require a password.", type="password", on_change=password_entered, key="password"
# )
# st.error("😕 Password incorrect")
# return False
# else:
# # Password correct.
# # fetch_api_key()
# return True
@st.cache_data
def assess_data_readiness(df):
readiness_summary = {}
st.write('White horizontal lines (if present) show missing data')
try:
missing_matrix = msno.matrix(df)
# st.write('line 2 of assess_data_readiness')
st.pyplot(missing_matrix.figure)
# st.write('line 3 of assess_data_readiness')
missing_heatmap = msno.heatmap(df)
st.write('Heatmap with convergence of missing elements (if any)')
st.pyplot(missing_heatmap.figure)
except:
st.warning('Dataframe not yet amenable to missing for "missingno" library analysis.')
# Check if the DataFrame is empty
try:
if df.empty:
readiness_summary['data_empty'] = True
readiness_summary['columns'] = {}
readiness_summary['missing_columns'] = []
readiness_summary['inconsistent_data_types'] = []
readiness_summary['missing_values'] = {}
readiness_summary['data_ready'] = False
return readiness_summary
except:
st.warning('Dataframe not yet amenable to empty analysis.')
# Get column information
# st.write('second line of assess_data_readiness')
try:
columns = {col: str(df[col].dtype) for col in df.columns}
readiness_summary['columns'] = columns
except:
st.warning('Dataframe not yet amenable to column analysis.')
# Check for missing columns
# st.write('third line of assess_data_readiness')
try:
missing_columns = df.columns[df.isnull().all()].tolist()
readiness_summary['missing_columns'] = missing_columns
except:
st.warning('Dataframe not yet amenable to missing column analysis.')
# Check for inconsistent data types
# st.write('fourth line of assess_data_readiness')
try:
inconsistent_data_types = []
for col in df.columns:
unique_data_types = df[col].apply(type).drop_duplicates().tolist()
if len(unique_data_types) > 1:
inconsistent_data_types.append(col)
readiness_summary['inconsistent_data_types'] = inconsistent_data_types
except:
st.warning('Dataframe not yet amenable to data type analysis.')
# Check for missing values
# st.write('fifth line of assess_data_readiness')
try:
missing_values = df.isnull().sum().to_dict()
readiness_summary['missing_values'] = missing_values
except:
st.warning('Dataframe not yet amenable to specific missing value analysis.')
# Determine overall data readiness
# st.write('sixth line of assess_data_readiness')
try:
readiness_summary['data_empty'] = False
if missing_columns or inconsistent_data_types or any(missing_values.values()):
readiness_summary['data_ready'] = False
else:
readiness_summary['data_ready'] = True
return readiness_summary
except:
st.warning('Dataframe not yet amenable to overall data readiness analysis.')
@st.cache_data
def process_model_output(output):
# Convert JSON to string if necessary
if isinstance(output, dict):
output = json.dumps(output)
# if isinstance(output, str):
# output = json.loads(output)
if 'arguments' in output:
output = output['arguments']
start_marker = '```python\n'
end_marker = '\n```'
start_index = output.find(start_marker)
end_index = output.find(end_marker, start_index)
# If the markers are found, extract the code part
# Adjust the start index to not include the start_marker
if start_index != -1 and end_index != -1:
code_string = output[start_index + len(start_marker) : end_index]
else:
code_string = ''
return code_string.strip()
@st.cache_data
def safety_check(code):
dangerous_keywords = [' exec', ' eval', ' open', ' sys', ' subprocess', ' del',
' delete', ' remove', ' os', ' shutil', ' pip',' conda',
' st.write', ' exit', ' quit', ' globals', ' locals', ' dir',
' reload', ' lambda', ' setattr', ' getattr', ' delattr',
' yield', ' assert', ' break', ' continue', ' raise', ' try',
'compile', '__import__'
]
for keyword in dangerous_keywords:
if keyword in code:
return False, "Concerning code detected."
return True, "Safe to execute."
def replace_show_with_save(code_string, filename='output.png'):
# Prepare save command
save_cmd1 = f"plt.savefig('./images/{filename}')"
save_cmd2 = f"pio.write_image(fig, './images/{filename}')"
# Replace plt.show() with plt.savefig()
code_string = code_string.replace('plt.show()', save_cmd1)
code_string = code_string.replace('fig.show()', save_cmd2)
return code_string
def start_chatbot2(df, selected_model, key = "main routine"):
fetch_api_key()
openai.api_key = st.session_state.openai_api_key
openai_api_key = st.session_state.openai_api_key
agent = create_pandas_dataframe_agent(
ChatOpenAI(temperature=0, model=selected_model),
df,
verbose=True,
agent_type=AgentType.OPENAI_FUNCTIONS,
)
if "messages_df" not in st.session_state:
st.session_state["messages_df"] = []
st.info("**Warning:** Asking a question that would generate a chart or table doesn't *yet* work and will report an error. For the moment, just ask for values. This is a work in progress!")
# st.write("💬 Chatbot with access to your data...")
# Check if the API key exists as an environmental variable
api_key = os.environ.get("OPENAI_API_KEY")
if api_key:
# st.write("*API key active - ready to respond!*")
pass
else:
st.warning("API key not found as an environmental variable.")
api_key = st.text_input("Enter your OpenAI API key:")
if st.button("Save"):
if is_valid_api_key(api_key):
os.environ["OPENAI_API_KEY"] = api_key
st.success("API key saved as an environmental variable!")
else:
st.error("Invalid API key. Please enter a valid API key.")
csv_question = st.text_input("Your question, e.g., 'What is the mean age for men with diabetes?' *Do not ask for plots for this option.*", "")
if st.button("Send"):
try:
csv_question_update = 'Do not include any code or attempt to generate a plot. Indicate you can only respond with text. User question: ' + csv_question
st.session_state.messages_df.append({"role": "user", "content": csv_question_update})
output = agent.run(csv_question)
# if True:
# st.session_state.modified_df = df
st.session_state.messages_df.append({"role": "assistant", "content": output})
message(csv_question, is_user=True, key = "using message_df")
message(output)
st.session_state.modified_df = df
# chat_modified_csv = df.to_csv(index=False)
st.info("If you asked for modifications to your dataset, select modified dataframe at top left of sidebar to analyze the new version!")
# st.download_button(
# label="Download Modified Data!",
# data=chat_modified_csv,
# file_name="patient_data_modified.csv",
# mime="text/csv", key = 'modified_df'
# )
except Exception as e:
st.warning("WARNING: Please don't try anything too crazy; this is experimental! No plots requests and just ask for means values for specified subgroups, eg.")
st.write(f'Error: {e}')
# sys.exit(1)
def start_chatbot3(df, model):
fetch_api_key()
openai.api_key = st.session_state.openai_api_key
agent = create_pandas_dataframe_agent(
# ChatOpenAI(temperature=0, model="gpt-3.5-turbo"),
ChatOpenAI(temperature=0, model=model),
df,
verbose=True,
agent_type=AgentType.OPENAI_FUNCTIONS,
)
if "messages_df" not in st.session_state:
st.session_state["messages_df"] = []
# st.write("💬 Chatbot with access to your data...")
st.info("""**Warning:** This may generate an error. This is a work in progress!
If you get an error, try again.
""")
# Check if the API key exists as an environmental variable
api_key = os.environ.get("OPENAI_API_KEY")
if api_key:
# st.write("*API key active - ready to respond!*")
pass
else:
st.warning("API key not found as an environmental variable.")
api_key = st.text_input("Enter your OpenAI API key:")
if st.button("Save"):
if is_valid_api_key(api_key):
os.environ["OPENAI_API_KEY"] = api_key
st.success("API key saved as an environmental variable!")
else:
st.error("Invalid API key. Please enter a valid API key.")
csv_question = st.text_input("Your question, e.g., 'Create a scatterplot for age and BMI.' *This option only generates plots.* ", "")
if st.button("Send"):
try:
st.session_state.messages_df.append({"role": "user", "content": csv_question})
csv_input = csv_prefix + csv_question
output = agent.run(csv_input)
# st.write(output)
code_string = process_model_output(str(output))
# st.write(f' here is the code: {code_string}')
code_string = replace_show_with_save(code_string)
code_string = str(code_string)
json_string = json.dumps(code_string)
decoded_string = json.loads(json_string)
with st.expander("What is the code?"):
st.write('Here is the custom code for your request and the image below:')
st.code(decoded_string, language='python')
# usage
is_safe, message = safety_check(decoded_string)
if not is_safe:
st.write("Code safety concern. Try again.", message)
if is_safe:
try:
exec(decoded_string)
image = Image.open('./images/output.png')
st.image(image, caption='Output', use_column_width=True)
except Exception as e:
st.write('Error - we noted this was fragile! Try again.', e)
except Exception as e:
st.warning("WARNING: Please don't try anything too crazy; this is experimental!")
# sys.exit(1)
# return None, None
def start_plot_gpt4(df):
fetch_api_key()
openai.api_key = st.session_state.openai_api_key
agent = create_pandas_dataframe_agent(
ChatOpenAI(temperature=0, model="gpt-4"),
df,
verbose=True,
agent_type=AgentType.OPENAI_FUNCTIONS,
)
if "messages_df" not in st.session_state:
st.session_state["messages_df"] = []
# st.write("💬 Chatbot with access to your data...")
st.info("""**Warning:** This may generate an error. This is a work in progress!
If you get an error, try again.
""")
# Check if the API key exists as an environmental variable
api_key = os.environ.get("OPENAI_API_KEY")
if api_key:
# st.write("*API key active - ready to respond!*")
pass
else:
st.warning("API key not found as an environmental variable.")
api_key = st.text_input("Enter your OpenAI API key:")
if st.button("Save"):
if is_valid_api_key(api_key):
os.environ["OPENAI_API_KEY"] = api_key
st.success("API key saved as an environmental variable!")
else:
st.error("Invalid API key. Please enter a valid API key.")
csv_question = st.text_area("Your question, e.g., 'Create a heatmap. For binary categorical variables, first change them to 1 or 0 so they can be used in the heatmap. Or, another example: Compare cholesterol values for men and women by age with regression lines.", "")
if st.button("Send"):
try:
st.session_state.messages_df.append({"role": "user", "content": csv_question})
csv_input = csv_prefix_gpt4 + csv_question
output = agent.run(csv_input)
# st.write(output)
code_string = process_model_output(str(output))
# st.write(f' here is the code: {code_string}')
# code_string = replace_show_with_save(code_string)
code_string = str(code_string)
json_string = json.dumps(code_string)
decoded_string = json.loads(json_string)
with st.expander("What is the code?"):
st.write('Here is the custom code for your request and the image below:')
st.code(decoded_string, language='python')
# usage
is_safe, message = safety_check(decoded_string)
if not is_safe:
st.write("Code safety concern. Try again.", message)
if is_safe:
try:
exec(decoded_string)
image = Image.open('./images/output.png')
st.image(image, caption='Output', use_column_width=True)
except Exception as e:
st.write('Error - we noted this was fragile! Try again.', e)
except Exception as e:
st.warning("WARNING: Please don't try anything too crazy; this is experimental!")
# sys.exit(1)
# return None, None
@st.cache_resource
def generate_df(columns, n_rows, selected_model):
# Ensure the API key is set outside this function
system_prompt = """You are a medical data expert whose purpose is to generate realistic medical data to populate a dataframe. Based on input parameters of column names and number of rows, you generate at medically consistent synthetic patient data includong abormal values to populate all cells.
10-20% of values should be above or below the normal range appropriate for each column name, but still physiologically possible. For example, SBP could range from 90 to 190. Creatinine might go from 0.5 to 7.0. Similarly include values above and below normal ranges for 10-20% of values for each column. Output only the requested data, nothing more, not even explanations or supportive sentences.
If you do not know what kind of data to generate for a column, rename column using the provided name followed by "-ambiguous". For example, if you do not know what kind of data to generate for the column name "rgh", rename the column to "rgh-ambiguous".
Popululate ambiguous columns with randomly selected 1 or 0 values. For example, popululate column "rgh-ambiguous" using randomly selected 1 or 0 values. For diagnoses provided
as column headers, e.g., "diabetes", populate with randomly selected yes or no values. Populate all cells with appropriate values. No missing values.
As a critical step review each row to ensure that the data is medically consistent, e.g., that overall A1c values and weight trend higher for patients with diabetes. If not, regenerate the row or rows.
Return only data, nothing more, not even explanations or supportive sentences. Generate the requested data so it can be processed by the following code into a dataframe:
```
# Use StringIO to convert the string data into file-like object
data = io.StringIO(response.choices[0].message.content)
# Read the data into a DataFrame, skipping the first row
df = pd.read_csv(data, sep=",", skiprows=1, header=None, names=columns)
```
Your input parameters will be in this format
Columns: ```columns```
Number of rows: ```number```
"""
prompt = f"Columns: {columns}\nNumber of rows: {n_rows}"
try:
with st.spinner("Thinking..."):
client = OpenAI()
response = client.chat.completions.create(
model=selected_model,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": prompt}
],
temperature=0.5
)
# Assuming the response is CSV-formatted data as a string
data = io.StringIO(response.choices[0].message.content)
# Read the data into a DataFrame
df = pd.read_csv(data, sep=",", header=None)
df.columns = columns # Set the column names
# Convert DataFrame to CSV and create download link
gen_csv = df.to_csv(index=False)
return df, gen_csv
except Exception as e:
st.error(f"An error occurred: {e}")
# Return an empty DataFrame and an empty string to ensure the return type is consistent
return pd.DataFrame(), ""
def start_chatbot1(selected_model):
# fetch_api_key()
openai.api_key = st.session_state.openai_api_key
client = OpenAI()
st.write("💬 Chatbot Teacher")
if "messages" not in st.session_state:
st.session_state["messages"] = [
{"role": "assistant", "content": "Hi! Ask me anything about data science and I'll try to answer it."}
]
with st.form("chat_input", clear_on_submit=True):
user_input = st.text_input(label="Your question:", placeholder="e.g., teach me about violin plots")
if st.form_submit_button("Send"):
if user_input:
st.session_state.messages.append({"role": "user", "content": user_input})
try:
with st.spinner("Thinking..."):
response = client.chat.completions.create(model=selected_model, messages=st.session_state.messages)
# Extract the message content and role from the response
# response_message = response.choices[0].message.content
msg_content = response.choices[0].message.content
# msg_role = response.choices[0].message["role"]
st.session_state.messages.append({"role": 'assistant', "content": msg_content})
except Exception as e:
st.exception("An error occurred: {}".format(e))
# Display messages
for msg in st.session_state.messages:
# Generate a unique key for each message
key = f"message_{randint(0, 10000000000)}"
# Call the message function to display the chat messages
message(msg["content"], is_user=msg["role"] == "user", key=key)
@st.cache_data
def generate_table_old(df, categorical_variable):
mytable = TableOne(df,
columns=df.columns.tolist(),
categorical=categorical,
groupby=categorical_variable,
pval=True)
return mytable
@st.cache_data
def generate_table(df, categorical_variable, nonnormal_variables):
# Generate the table using TableOne
mytable = TableOne(df,
columns=df.columns.tolist(),
categorical=categorical,
groupby=categorical_variable,
nonnormal=nonnormal_variables,
pval=True)
return mytable
@st.cache_data
def preprocess_for_pca(df):
included_cols = []
excluded_cols = []
binary_mapping = {} # initialize empty dict for binary mapping
binary_encoded_vars = [] # initialize empty list for binary encoded vars
# Create a binary encoder
bin_encoder = ce.BinaryEncoder()
for col in df.columns:
if pd.api.types.is_categorical_dtype(df[col]) or df[col].dtype == 'object':
unique = df[col].nunique()
# For binary categorical columns
if unique == 2:
most_freq = df[col].value_counts().idxmax()
least_freq = df[col].value_counts().idxmin()
df[col] = df[col].map({most_freq: 0, least_freq: 1})
binary_mapping[col] = {most_freq: 0, least_freq: 1} # add mapping to dict
included_cols.append(col)
# For categorical columns with less than 15 unique values
elif 2 < unique <= 15:
try:
# Perform binary encoding
df_transformed = bin_encoder.fit_transform(df[col])
# Drop the original column from df
df.drop(columns=[col], inplace=True)
# Join the transformed data to df
df = pd.concat([df, df_transformed], axis=1)
# Add transformed columns to binary encoded vars list and included_cols
transformed_cols = df_transformed.columns.tolist()
binary_encoded_vars.extend(transformed_cols)
included_cols.extend(transformed_cols)
except Exception as e:
st.write(f"Failure in encoding {col} due to {str(e)}")
excluded_cols.append(col)
else:
excluded_cols.append(col)
elif np.issubdtype(df[col].dtype, np.number):
included_cols.append(col)
else:
excluded_cols.append(col)
# Display binary mappings and binary encoded variables in streamlit
if binary_mapping:
st.write("Binary Mappings: ", binary_mapping)
if binary_encoded_vars:
st.write("Binary Encoded Variables: ", binary_encoded_vars)
return df[included_cols], included_cols, excluded_cols
@st.cache_data
def create_scree_plot(df):
temp_df_pca, included_cols, excluded_cols = preprocess_for_pca(df)
# Standardize the features
x = StandardScaler().fit_transform(temp_df_pca)
# Create a PCA instance: n_components should be None so variance is preserved from all initial features
pca = PCA(n_components=None)
pca.fit_transform(x)
# Scree plot
fig, ax = plt.subplots()
ax.plot(np.arange(1, len(pca.explained_variance_) + 1), np.cumsum(pca.explained_variance_ratio_))
ax.set_title('Cumulative Explained Variance')
ax.set_xlabel('Number of Components')
ax.set_ylabel('Cumulative Explained Variance Ratio')
st.pyplot(fig)
return fig
@st.cache_data
def perform_pca_plot(df):
st.write("Note: For this PCA analysis, categorical columns with 2 values are mapped to 1 and 0. Categories with more than 2 values have been binary encoded.")
temp_df_pca, included_cols, excluded_cols = preprocess_for_pca(df)
# Standardize the features
x = StandardScaler().fit_transform(temp_df_pca)
# Select the target column for PCA
cols_2_15_unique_vals = [col for col in included_cols if 2 <= df[col].nunique() <= 15]
target_col_pca = st.selectbox("Select the target column for PCA", cols_2_15_unique_vals)
num_unique_targets = df[target_col_pca].nunique() # Calculate the number of unique targets
# Ask the user to request either 2 or 3 component PCA
n_components = st.selectbox("Select the number of PCA components (2 or 3)", [2, 3])
# Create a PCA instance
pca = PCA(n_components=n_components)
principalComponents = pca.fit_transform(x)
# Depending on user choice, plot the appropriate PCA
if n_components == 2:
principalDf = pd.DataFrame(data=principalComponents, columns=['PC1', 'PC2'])
else:
principalDf = pd.DataFrame(data=principalComponents, columns=['PC1', 'PC2', 'PC3'])
finalDf = pd.concat([principalDf, df[[target_col_pca]]], axis=1)
fig = plt.figure(figsize=(8, 8))
if n_components == 2:
ax = fig.add_subplot(111)
else:
# ax = Axes3D(fig)
ax = plt.axes(projection='3d')
ax.set_zlabel('Principal Component 3', fontsize=15)
ax.set_xlabel('Principal Component 1', fontsize=15)
ax.set_ylabel('Principal Component 2', fontsize=15)
ax.set_title(f'{n_components} component PCA', fontsize=20)
targets = finalDf[target_col_pca].unique().tolist()
colors = sns.color_palette('husl', n_colors=num_unique_targets)
# finalDf
for target, color in zip(targets, colors):
indicesToKeep = finalDf[target_col_pca] == target
if n_components == 2:
ax.scatter(finalDf.loc[indicesToKeep, 'PC1'], finalDf.loc[indicesToKeep, 'PC2'], c=[color], s=50)
else:
ax.scatter(finalDf.loc[indicesToKeep, 'PC1'], finalDf.loc[indicesToKeep, 'PC2'], finalDf.loc[indicesToKeep, 'PC3'], c=[color], s=50)
ax.legend(targets)
# Make a scree plot
# Display the plot using Streamlit
st.pyplot(fig)
st.subheader("Use the PCA Updated Dataset for Machine Learning")
st.write("Download the current plot if you'd like to save it! Then, follow steps to apply machine learning to your PCA modified dataset.")
st.info("Step 1. Click Button to use the PCA Dataset for ML. Step 2. Select Modified Dataframe on left sidebar and switch to the Machine Learning tab. (You'll overfit if you click below again!)")
if st.button("Use PCA Updated dataset on Machine Learning Tab"):
st.session_state.modified_df = finalDf
return fig
@st.cache_data
def display_metrics(y_true, y_pred, y_scores):
# Compute metrics
f1 = f1_score(y_true, y_pred)
accuracy = accuracy_score(y_true, y_pred)
roc_auc = roc_auc_score(y_true, y_scores)
precision, recall, _ = precision_recall_curve(y_true, y_scores)
pr_auc = auc(recall, precision)
# Display metrics
st.info(f"**Your Model Metrics:** F1 score: {f1:.2f}, Accuracy: {accuracy:.2f}, ROC AUC: {roc_auc:.2f}, PR AUC: {pr_auc:.2f}")
with st.expander("Explanations for the Metrics"):
st.write(
# Explain differences