Fredaaaaaa commited on
Commit
ea00170
Β·
verified Β·
1 Parent(s): 5eccead

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +159 -60
app.py CHANGED
@@ -2,9 +2,9 @@ import gradio as gr
2
  import pandas as pd
3
  import os
4
 
5
- # Load your labeled dataset with flexible column names
6
  def load_drug_interaction_dataset():
7
- """Load your labeled drug interaction dataset with flexible column names"""
8
  try:
9
  # Your exact dataset filename
10
  dataset_path = 'merged_cleaned_dataset.csv'
@@ -16,43 +16,28 @@ def load_drug_interaction_dataset():
16
  print(f"Dataset file {dataset_path} not found!")
17
  return create_fallback_database()
18
 
19
- # Load the dataset
20
  print(f"Loading dataset from: {dataset_path}")
21
  df = pd.read_csv(dataset_path)
22
  print(f"Dataset columns: {df.columns.tolist()}")
23
  print(f"Dataset shape: {df.shape}")
24
  print(f"First few rows:\n{df.head()}")
25
 
26
- # Attempt to detect column names (flexible mapping)
27
- possible_drug1_cols = ['Drug 1_normalized', 'Drug1', 'drug_1']
28
- possible_drug2_cols = ['Drug 2_normalized', 'Drug2', 'drug_2']
29
- possible_severity_cols = ['severity', 'Severity', 'SEVERITY']
30
-
31
- drug1_col = next((col for col in possible_drug1_cols if col in df.columns), None)
32
- drug2_col = next((col for col in possible_drug2_cols if col in df.columns), None)
33
- severity_col = next((col for col in possible_severity_cols if col in df.columns), None)
34
-
35
- if not all([drug1_col, drug2_col, severity_col]):
36
- print(f"Required columns not found. Detected: drug1={drug1_col}, drug2={drug2_col}, severity={severity_col}")
37
- return create_fallback_database()
38
-
39
- print(f"Using columns: drug1={drug1_col}, drug2={drug2_col}, severity={severity_col}")
40
-
41
- # Create interaction dictionary
42
  interaction_db = {}
43
  count = 0
44
 
45
- for index, row in df.iterrows():
46
  try:
47
- drug1 = str(row[drug1_col]).lower().strip()
48
- drug2 = str(row[drug2_col]).lower().strip()
49
- severity = str(row[severity_col]).strip()
 
50
 
51
- # Skip empty or invalid entries
52
  if (not all([drug1, drug2, severity]) or
53
  drug1 == 'nan' or drug2 == 'nan' or
54
  severity == 'nan' or severity.lower() == 'none'):
55
- print(f"Skipping invalid row {index}: {drug1}, {drug2}, {severity}")
56
  continue
57
 
58
  # Clean up severity labels
@@ -60,19 +45,13 @@ def load_drug_interaction_dataset():
60
  if severity == 'No interaction':
61
  severity = 'No Interaction'
62
 
63
- # Add both orders to the dictionary
64
  interaction_db[(drug1, drug2)] = severity
65
- interaction_db[(drug2, drug1)] = severity
66
  count += 1
67
- if count % 100 == 0: # Log progress
68
- print(f"Processed {count} interactions")
69
-
70
- # Verify known pair
71
- if drug1 == 'warfarin' and drug2 == 'aspirin':
72
- print(f"Found Warfarin, Aspirin at row {index} with severity: {severity}")
73
 
74
  except Exception as e:
75
- print(f"Error processing row {index}: {e}")
76
  continue
77
 
78
  print(f"βœ… Successfully loaded {count} drug interactions from dataset")
@@ -84,18 +63,96 @@ def load_drug_interaction_dataset():
84
  return create_fallback_database()
85
 
86
  def create_fallback_database():
87
- """Fallback database if dataset loading fails"""
88
  print("Using fallback database")
89
  return {
 
90
  ('warfarin', 'aspirin'): 'Severe',
 
91
  ('warfarin', 'ibuprofen'): 'Severe',
 
92
  ('simvastatin', 'clarithromycin'): 'Severe',
 
93
  ('clopidogrel', 'omeprazole'): 'Severe',
 
94
  ('methotrexate', 'naproxen'): 'Severe',
 
 
 
 
 
 
 
 
 
 
 
 
 
95
  ('digoxin', 'quinine'): 'Moderate',
 
96
  ('lisinopril', 'ibuprofen'): 'Moderate',
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
  ('metformin', 'ibuprofen'): 'Mild',
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
  ('vitamin c', 'vitamin d'): 'No Interaction',
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  }
100
 
101
  # Load your dataset
@@ -106,12 +163,12 @@ def predict_interaction(drug_names):
106
  """Predict interaction between two drugs using your labeled dataset"""
107
  try:
108
  if not drug_names or ',' not in drug_names:
109
- return "Please enter two drug names separated by a comma"
110
 
111
  # Split the input
112
  drugs = [drug.strip() for drug in drug_names.split(',')]
113
  if len(drugs) != 2:
114
- return "Please enter exactly two drug names"
115
 
116
  drug1, drug2 = drugs[0].lower(), drugs[1].lower()
117
  print(f"Looking up: '{drug1}' + '{drug2}'")
@@ -120,46 +177,88 @@ def predict_interaction(drug_names):
120
  prediction = interaction_db.get((drug1, drug2))
121
 
122
  if prediction:
123
- return f"Predicted Interaction: {prediction}"
 
 
 
 
 
 
 
 
 
 
124
  else:
125
- # Log all available keys for debugging
126
- print(f"Keys in interaction_db: {list(interaction_db.keys())[:10]}... (total {len(interaction_db)})")
127
- return f"Predicted Interaction: Moderate" # Default to Moderate if not found
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
 
129
  except Exception as e:
130
- return f"Error: {str(e)}"
131
 
132
  # Create interface
133
- with gr.Blocks() as demo:
134
- gr.Markdown("## Drug Interaction Predictor")
135
- gr.Markdown("**Using your merged_cleaned_dataset.csv**")
136
-
137
- drug_input = gr.Textbox(
138
- label="Enter drug names",
139
- placeholder="e.g., Warfarin, Aspirin",
140
- value="Warfarin, Aspirin"
141
- )
142
 
143
- predict_btn = gr.Button("Predict")
144
- output = gr.Textbox(label="Prediction")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
 
146
  # Show dataset info
147
- gr.Markdown(f"*Dataset: merged_cleaned_dataset.csv*")
148
- gr.Markdown(f"*Loaded {len(interaction_db)//2} interactions*")
149
 
150
  # Examples from your dataset
151
  gr.Examples(
152
  examples=[
153
- "warfarin, aspirin",
154
- "simvastatin, clarithromycin",
155
- "digoxin, quinine",
156
- "metformin, alcohol"
 
157
  ],
158
  inputs=drug_input,
159
- label="Try these examples:"
160
  )
161
 
162
  predict_btn.click(predict_interaction, drug_input, output)
 
 
 
 
 
 
163
 
164
  if __name__ == "__main__":
165
  demo.launch()
 
2
  import pandas as pd
3
  import os
4
 
5
+ # Load your labeled dataset with exact column names
6
  def load_drug_interaction_dataset():
7
+ """Load your labeled drug interaction dataset with exact column names"""
8
  try:
9
  # Your exact dataset filename
10
  dataset_path = 'merged_cleaned_dataset.csv'
 
16
  print(f"Dataset file {dataset_path} not found!")
17
  return create_fallback_database()
18
 
19
+ # Load the dataset with your exact column names
20
  print(f"Loading dataset from: {dataset_path}")
21
  df = pd.read_csv(dataset_path)
22
  print(f"Dataset columns: {df.columns.tolist()}")
23
  print(f"Dataset shape: {df.shape}")
24
  print(f"First few rows:\n{df.head()}")
25
 
26
+ # Create interaction dictionary using your exact column names
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  interaction_db = {}
28
  count = 0
29
 
30
+ for _, row in df.iterrows():
31
  try:
32
+ # Use your exact column names
33
+ drug1 = str(row['Drug 1_normalized']).lower().strip()
34
+ drug2 = str(row['Drug 2_normalized']).lower().strip()
35
+ severity = str(row['severity']).strip()
36
 
37
+ # Skip empty entries or invalid data
38
  if (not all([drug1, drug2, severity]) or
39
  drug1 == 'nan' or drug2 == 'nan' or
40
  severity == 'nan' or severity.lower() == 'none'):
 
41
  continue
42
 
43
  # Clean up severity labels
 
45
  if severity == 'No interaction':
46
  severity = 'No Interaction'
47
 
48
+ # Add both orders to the dictionary - STORE ONLY THE SEVERITY STRING
49
  interaction_db[(drug1, drug2)] = severity
50
+ interaction_db[(drug2, drug1)] = severity # Add reverse order
51
  count += 1
 
 
 
 
 
 
52
 
53
  except Exception as e:
54
+ print(f"Error processing row {_}: {e}")
55
  continue
56
 
57
  print(f"βœ… Successfully loaded {count} drug interactions from dataset")
 
63
  return create_fallback_database()
64
 
65
  def create_fallback_database():
66
+ """Fallback database if dataset loading fails - FIXED STRUCTURE"""
67
  print("Using fallback database")
68
  return {
69
+ # Severe interactions (Life-threatening) - STORE ONLY SEVERITY STRINGS
70
  ('warfarin', 'aspirin'): 'Severe',
71
+ ('aspirin', 'warfarin'): 'Severe',
72
  ('warfarin', 'ibuprofen'): 'Severe',
73
+ ('ibuprofen', 'warfarin'): 'Severe',
74
  ('simvastatin', 'clarithromycin'): 'Severe',
75
+ ('clarithromycin', 'simvastatin'): 'Severe',
76
  ('clopidogrel', 'omeprazole'): 'Severe',
77
+ ('omeprazole', 'clopidogrel'): 'Severe',
78
  ('methotrexate', 'naproxen'): 'Severe',
79
+ ('naproxen', 'methotrexate'): 'Severe',
80
+ ('lithium', 'ibuprofen'): 'Severe',
81
+ ('ibuprofen', 'lithium'): 'Severe',
82
+ ('ssri', 'maoi'): 'Severe',
83
+ ('maoi', 'ssri'): 'Severe',
84
+ ('simvastatin', 'verapamil'): 'Severe',
85
+ ('verapamil', 'simvastatin'): 'Severe',
86
+ ('warfarin', 'fluconazole'): 'Severe',
87
+ ('fluconazole', 'warfarin'): 'Severe',
88
+ ('digoxin', 'verapamil'): 'Severe',
89
+ ('verapamil', 'digoxin'): 'Severe',
90
+
91
+ # Moderate interactions (Requires monitoring)
92
  ('digoxin', 'quinine'): 'Moderate',
93
+ ('quinine', 'digoxin'): 'Moderate',
94
  ('lisinopril', 'ibuprofen'): 'Moderate',
95
+ ('ibuprofen', 'lisinopril'): 'Moderate',
96
+ ('metformin', 'alcohol'): 'Moderate',
97
+ ('alcohol', 'metformin'): 'Moderate',
98
+ ('levothyroxine', 'calcium'): 'Moderate',
99
+ ('calcium', 'levothyroxine'): 'Moderate',
100
+ ('atorvastatin', 'orange juice'): 'Moderate',
101
+ ('orange juice', 'atorvastatin'): 'Moderate',
102
+ ('phenytoin', 'warfarin'): 'Moderate',
103
+ ('warfarin', 'phenytoin'): 'Moderate',
104
+ ('theophylline', 'ciprofloxacin'): 'Moderate',
105
+ ('ciprofloxacin', 'theophylline'): 'Moderate',
106
+ ('warfarin', 'acetaminophen'): 'Moderate',
107
+ ('acetaminophen', 'warfarin'): 'Moderate',
108
+ ('metoprolol', 'verapamil'): 'Moderate',
109
+ ('verapamil', 'metoprolol'): 'Moderate',
110
+ ('spironolactone', 'digoxin'): 'Moderate',
111
+ ('digoxin', 'spironolactone'): 'Moderate',
112
+
113
+ # Mild interactions (Minimal clinical significance)
114
  ('metformin', 'ibuprofen'): 'Mild',
115
+ ('ibuprofen', 'metformin'): 'Mild',
116
+ ('omeprazole', 'calcium'): 'Mild',
117
+ ('calcium', 'omeprazole'): 'Mild',
118
+ ('vitamin d', 'calcium'): 'Mild',
119
+ ('calcium', 'vitamin d'): 'Mild',
120
+ ('aspirin', 'vitamin c'): 'Mild',
121
+ ('vitamin c', 'aspirin'): 'Mild',
122
+ ('atorvastatin', 'vitamin d'): 'Mild',
123
+ ('vitamin d', 'atorvastatin'): 'Mild',
124
+ ('metformin', 'vitamin b12'): 'Mild',
125
+ ('vitamin b12', 'metformin'): 'Mild',
126
+ ('omeprazole', 'vitamin b12'): 'Mild',
127
+ ('vitamin b12', 'omeprazole'): 'Mild',
128
+ ('aspirin', 'ginger'): 'Mild',
129
+ ('ginger', 'aspirin'): 'Mild',
130
+ ('warfarin', 'green tea'): 'Mild',
131
+ ('green tea', 'warfarin'): 'Mild',
132
+ ('levothyroxine', 'iron'): 'Mild',
133
+ ('iron', 'levothyroxine'): 'Mild',
134
+
135
+ # No interactions (Clinically safe)
136
  ('vitamin c', 'vitamin d'): 'No Interaction',
137
+ ('vitamin d', 'vitamin c'): 'No Interaction',
138
+ ('calcium', 'vitamin d'): 'No Interaction',
139
+ ('vitamin d', 'calcium'): 'No Interaction',
140
+ ('omeprazole', 'vitamin d'): 'No Interaction',
141
+ ('vitamin d', 'omeprazole'): 'No Interaction',
142
+ ('metformin', 'vitamin d'): 'No Interaction',
143
+ ('vitamin d', 'metformin'): 'No Interaction',
144
+ ('aspirin', 'vitamin e'): 'No Interaction',
145
+ ('vitamin e', 'aspirin'): 'No Interaction',
146
+ ('atorvastatin', 'coenzyme q10'): 'No Interaction',
147
+ ('coenzyme q10', 'atorvastatin'): 'No Interaction',
148
+ ('levothyroxine', 'vitamin d'): 'No Interaction',
149
+ ('vitamin d', 'levothyroxine'): 'No Interaction',
150
+ ('metoprolol', 'magnesium'): 'No Interaction',
151
+ ('magnesium', 'metoprolol'): 'No Interaction',
152
+ ('lisinopril', 'potassium'): 'No Interaction',
153
+ ('potassium', 'lisinopril'): 'No Interaction',
154
+ ('simvastatin', 'vitamin e'): 'No Interaction',
155
+ ('vitamin e', 'simvastatin'): 'No Interaction',
156
  }
157
 
158
  # Load your dataset
 
163
  """Predict interaction between two drugs using your labeled dataset"""
164
  try:
165
  if not drug_names or ',' not in drug_names:
166
+ return "❌ Please enter two drug names separated by a comma (e.g., 'Warfarin, Aspirin')"
167
 
168
  # Split the input
169
  drugs = [drug.strip() for drug in drug_names.split(',')]
170
  if len(drugs) != 2:
171
+ return "❌ Please enter exactly two drug names separated by a comma"
172
 
173
  drug1, drug2 = drugs[0].lower(), drugs[1].lower()
174
  print(f"Looking up: '{drug1}' + '{drug2}'")
 
177
  prediction = interaction_db.get((drug1, drug2))
178
 
179
  if prediction:
180
+ # Add appropriate emoji and formatting based on severity
181
+ if prediction.lower() == 'severe':
182
+ return f"🚨 **SEVERE INTERACTION**: {prediction}\n⚠️ This combination may be life-threatening. Consult healthcare provider immediately."
183
+ elif prediction.lower() == 'moderate':
184
+ return f"⚠️ **MODERATE INTERACTION**: {prediction}\nπŸ“‹ Requires monitoring. Consult healthcare provider."
185
+ elif prediction.lower() == 'mild':
186
+ return f"⚑ **MILD INTERACTION**: {prediction}\nπŸ’‘ Minimal clinical significance but monitor for effects."
187
+ elif 'no interaction' in prediction.lower():
188
+ return f"βœ… **NO INTERACTION**: {prediction}\n🟒 These drugs appear to be safe to use together."
189
+ else:
190
+ return f"πŸ“Š **INTERACTION LEVEL**: {prediction}"
191
  else:
192
+ # Try to find similar drugs for debugging
193
+ found_drugs = set()
194
+ for d1, d2 in interaction_db.keys():
195
+ found_drugs.add(d1)
196
+ found_drugs.add(d2)
197
+
198
+ print(f"Not found. Available drugs: {sorted(list(found_drugs))[:20]}...")
199
+
200
+ # Check if either drug exists in the database
201
+ drug1_exists = any(d1 == drug1 or d2 == drug1 for d1, d2 in interaction_db.keys())
202
+ drug2_exists = any(d1 == drug2 or d2 == drug2 for d1, d2 in interaction_db.keys())
203
+
204
+ if not drug1_exists and not drug2_exists:
205
+ return f"❓ **UNKNOWN DRUGS**: Neither '{drugs[0]}' nor '{drugs[1]}' found in database.\nπŸ’‘ Try checking spelling or use generic names."
206
+ elif not drug1_exists:
207
+ return f"❓ **UNKNOWN DRUG**: '{drugs[0]}' not found in database.\nπŸ’‘ Try checking spelling or use generic name."
208
+ elif not drug2_exists:
209
+ return f"❓ **UNKNOWN DRUG**: '{drugs[1]}' not found in database.\nπŸ’‘ Try checking spelling or use generic name."
210
+ else:
211
+ return f"❓ **NO DATA AVAILABLE**: No interaction data found for '{drugs[0]}' and '{drugs[1]}'.\nπŸ’‘ Consult healthcare provider for guidance."
212
 
213
  except Exception as e:
214
+ return f"❌ Error: {str(e)}"
215
 
216
  # Create interface
217
+ with gr.Blocks(title="Drug Interaction Predictor", theme=gr.themes.Soft()) as demo:
218
+ gr.Markdown("# πŸ’Š Drug Interaction Predictor")
219
+ gr.Markdown("**Predict potential drug interactions using clinical data**")
 
 
 
 
 
 
220
 
221
+ with gr.Row():
222
+ with gr.Column():
223
+ drug_input = gr.Textbox(
224
+ label="Enter two drug names (separated by comma)",
225
+ placeholder="e.g., Warfarin, Aspirin",
226
+ value="Warfarin, Aspirin",
227
+ lines=2
228
+ )
229
+
230
+ predict_btn = gr.Button("πŸ” Predict Interaction", variant="primary", size="lg")
231
+
232
+ with gr.Column():
233
+ output = gr.Textbox(
234
+ label="Interaction Prediction",
235
+ lines=4,
236
+ interactive=False
237
+ )
238
 
239
  # Show dataset info
240
+ gr.Markdown(f"*πŸ“Š Dataset loaded with {len(interaction_db)} drug pair interactions*")
 
241
 
242
  # Examples from your dataset
243
  gr.Examples(
244
  examples=[
245
+ "Warfarin, Aspirin",
246
+ "Simvastatin, Clarithromycin",
247
+ "Digoxin, Quinine",
248
+ "Metformin, Alcohol",
249
+ "Vitamin C, Vitamin D"
250
  ],
251
  inputs=drug_input,
252
+ label="πŸ§ͺ Try these examples:"
253
  )
254
 
255
  predict_btn.click(predict_interaction, drug_input, output)
256
+
257
+ # Add disclaimer
258
+ gr.Markdown("""
259
+ ---
260
+ **⚠️ Disclaimer**: This tool is for educational purposes only. Always consult with healthcare professionals before making any medical decisions.
261
+ """)
262
 
263
  if __name__ == "__main__":
264
  demo.launch()