Fredaaaaaa commited on
Commit
b31e718
·
verified ·
1 Parent(s): 56a839a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +176 -32
app.py CHANGED
@@ -12,6 +12,95 @@ try:
12
  except ImportError:
13
  print("Warning: pubchempy not found. PubChem feature extraction will be skipped.")
14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  # Load your labeled dataset with exact column names
16
  def load_drug_interaction_dataset():
17
  """Load your labeled drug interaction dataset with exact column names"""
@@ -71,7 +160,15 @@ def create_fallback_database():
71
  print("Initializing fallback database")
72
  return {
73
  ('warfarin', 'aspirin'): 'Severe',
74
- ('aspirin', 'warfarin'): 'Severe',
 
 
 
 
 
 
 
 
75
  ('warfarin', 'ibuprofen'): 'Severe',
76
  ('ibuprofen', 'warfarin'): 'Severe',
77
  ('simvastatin', 'clarithromycin'): 'Severe',
@@ -90,8 +187,32 @@ def create_fallback_database():
90
  ('fluconazole', 'warfarin'): 'Severe',
91
  ('digoxin', 'verapamil'): 'Severe',
92
  ('verapamil', 'digoxin'): 'Severe',
 
 
 
 
 
 
 
 
 
 
93
 
94
  # Moderate interactions
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
  ('digoxin', 'quinine'): 'Moderate',
96
  ('quinine', 'digoxin'): 'Moderate',
97
  ('lisinopril', 'ibuprofen'): 'Moderate',
@@ -114,8 +235,10 @@ def create_fallback_database():
114
  ('digoxin', 'spironolactone'): 'Moderate',
115
 
116
  # Mild interactions
 
 
117
  ('metformin', 'ibuprofen'): 'Mild',
118
- ('ibuprofen', 'metformin'): 'Mild',
119
  ('omeprazole', 'calcium'): 'Mild',
120
  ('calcium', 'omeprazole'): 'Mild',
121
  ('vitamin d', 'calcium'): 'Mild',
@@ -128,10 +251,10 @@ def create_fallback_database():
128
  ('vitamin b12', 'metformin'): 'Mild',
129
  ('omeprazole', 'vitamin b12'): 'Mild',
130
  ('vitamin b12', 'omeprazole'): 'Mild',
131
- ('aspirin', 'ginger'): 'Mild',
132
- ('ginger', 'aspirin'): 'Mild',
133
- ('warfarin', 'green tea'): 'Mild',
134
- ('green tea', 'warfarin'): 'Mild',
135
  ('levothyroxine', 'iron'): 'Mild',
136
  ('iron', 'levothyroxine'): 'Mild',
137
 
@@ -172,9 +295,7 @@ def get_pubchem_features(drug_name):
172
  'xlogp': compound.xlogp if compound.xlogp else 0,
173
  'tpsa': compound.tpsa if compound.tpsa else 0,
174
  'canonical_smiles': compound.canonical_smiles,
175
- 'canonical_smiles_2': compound.canonical_smiles_2,
176
- 'molecular_formula': compound.molecular_formula,
177
- 'molecular_formula_2': compound.molecular_formula_2
178
  }
179
  except Exception as e:
180
  print(f"Error fetching PubChem data for {drug_name}: {e}")
@@ -198,40 +319,55 @@ def predict_interaction(drug_names, dataset_db, fallback_db):
198
  """Predict interaction between two drugs using dataset, fallback, and PubChem"""
199
  try:
200
  if not drug_names or ',' not in drug_names:
201
- return "Error"
202
 
203
  drugs = [drug.strip() for drug in drug_names.split(',')]
204
  if len(drugs) != 2:
205
- return "Error"
 
 
 
 
 
 
206
 
207
- drug1, drug2 = drugs[0].lower(), drugs[1].lower()
208
- print(f"Looking up: '{drug1}' + '{drug2}'")
209
 
210
  # Validate drug names
211
- if len(drug1) < 2 or len(drug2) < 2: # Minimum length check for invalid inputs
212
- return "Error"
213
 
214
- # Check dataset first
215
- prediction = dataset_db.get((drug1, drug2))
216
  if prediction:
217
  return prediction
218
 
219
- # Check fallback database if not in dataset
220
- fallback_prediction = fallback_db.get((drug1, drug2))
221
  if fallback_prediction:
222
  return fallback_prediction
223
 
224
- # If not in fallback, fetch PubChem features and predict if available
225
- drug1_features = get_pubchem_features(drug1)
226
- drug2_features = get_pubchem_features(drug2)
 
 
 
 
 
 
 
 
 
227
  if drug1_features and drug2_features:
228
  return predict_from_features(drug1_features, drug2_features)
229
  else:
230
  # Balanced random choice for completely unknown drugs
231
  return random.choice(['Moderate', 'Mild'])
232
 
233
- except Exception:
234
- return "Error"
 
235
 
236
  # Load your dataset and fallback
237
  print("Loading drug interaction dataset...")
@@ -240,31 +376,39 @@ dataset_db, fallback_db = load_drug_interaction_dataset()
240
  # Create interface
241
  with gr.Blocks(title="Drug Interaction Predictor") as demo:
242
  gr.Markdown("# Drug Interaction Predictor")
 
243
 
244
  with gr.Row():
245
  with gr.Column():
246
  drug_input = gr.Textbox(
247
  label="Enter two drug names (separated by comma)",
248
- placeholder="e.g., Warfarin, Aspirin",
249
  lines=2
250
  )
251
 
252
- predict_btn = gr.Button("Predict Interaction")
253
 
254
  with gr.Column():
255
  output = gr.Textbox(
256
  label="Interaction Prediction",
257
- lines=1,
258
  interactive=False
259
  )
260
 
261
  predict_btn.click(fn=lambda x: predict_interaction(x, dataset_db, fallback_db), inputs=drug_input, outputs=output)
262
 
263
- # Add disclaimer
264
- #gr.Markdown("""
265
- #---
266
- #**Disclaimer**: This tool is for educational purposes only. Always consult with healthcare professionals before making any medical decisions.
267
- #""")
 
 
 
 
 
 
 
268
 
269
  if __name__ == "__main__":
270
  demo.launch()
 
12
  except ImportError:
13
  print("Warning: pubchempy not found. PubChem feature extraction will be skipped.")
14
 
15
+ # Active compound mapping for traditional drugs
16
+ DRUG_ACTIVE_COMPOUNDS = {
17
+ 'kanna': 'mesembrine',
18
+ 'sceletium tortuosum': 'mesembrine',
19
+ 'st johns wort': 'hyperforin',
20
+ 'st john\'s wort': 'hyperforin',
21
+ 'hypericum perforatum': 'hyperforin',
22
+ 'yohimbe': 'yohimbine',
23
+ 'pausinystalia johimbe': 'yohimbine',
24
+ 'kola nut': 'caffeine',
25
+ 'cola nitida': 'caffeine',
26
+ 'khat': 'cathinone',
27
+ 'catha edulis': 'cathinone',
28
+ 'kava': 'kavain',
29
+ 'piper methysticum': 'kavain',
30
+ 'valerian': 'valerenic acid',
31
+ 'valeriana officinalis': 'valerenic acid',
32
+ 'ashwagandha': 'withanoside iv',
33
+ 'withania somnifera': 'withanoside iv',
34
+ 'cannabis': 'thc',
35
+ 'cannabis sativa': 'thc',
36
+ 'licorice': 'glycyrrhizin',
37
+ 'glycyrrhiza glabra': 'glycyrrhizin',
38
+ 'rauvolfia': 'reserpine',
39
+ 'rauvolfia serpentina': 'reserpine',
40
+ 'turmeric': 'curcumin',
41
+ 'curcuma longa': 'curcumin',
42
+ 'ginger': 'gingerol',
43
+ 'zingiber officinale': 'gingerol',
44
+ 'garlic': 'allicin',
45
+ 'allium sativum': 'allicin',
46
+ 'feverfew': 'parthenolide',
47
+ 'tanacetum parthenium': 'parthenolide',
48
+ 'senna': 'sennoside a',
49
+ 'cassia angustifolia': 'sennoside a',
50
+ 'aloe ferox': 'aloin',
51
+ 'ephedra': 'ephedrine',
52
+ 'ephedra sinica': 'ephedrine',
53
+ 'willow bark': 'salicin',
54
+ 'salix alba': 'salicin',
55
+ 'echinacea': 'cichoric acid',
56
+ 'echinacea purpurea': 'cichoric acid',
57
+ 'ginkgo': 'ginkgolide',
58
+ 'ginkgo biloba': 'ginkgolide',
59
+ 'ginseng': 'ginsenoside',
60
+ 'panax ginseng': 'ginsenoside',
61
+ 'green tea': 'epigallocatechin gallate',
62
+ 'camellia sinensis': 'epigallocatechin gallate'
63
+ }
64
+
65
+ def extract_active_compound(drug_name):
66
+ """
67
+ Extract active compound from traditional drug name using mapping or PubChem
68
+ This function works in the background - user doesn't see this process
69
+ """
70
+ drug_lower = drug_name.lower().strip()
71
+
72
+ # First check our predefined mapping
73
+ if drug_lower in DRUG_ACTIVE_COMPOUNDS:
74
+ active_compound = DRUG_ACTIVE_COMPOUNDS[drug_lower]
75
+ print(f"Found active compound for {drug_name}: {active_compound}")
76
+ return active_compound
77
+
78
+ # If not in mapping and PubChem is available, try to get synonyms/related compounds
79
+ if PUBCHEM_AVAILABLE:
80
+ try:
81
+ compounds = pcp.get_compounds(drug_name, 'name')
82
+ if compounds:
83
+ compound = compounds[0]
84
+ # Try to get the main active ingredient name
85
+ synonyms = compound.synonyms if hasattr(compound, 'synonyms') else []
86
+ if synonyms:
87
+ # Look for common active compound patterns in synonyms
88
+ for synonym in synonyms[:10]: # Check first 10 synonyms
89
+ syn_lower = synonym.lower()
90
+ if any(pattern in syn_lower for pattern in ['acid', 'ine', 'ol', 'ide', 'ate']):
91
+ print(f"Found potential active compound for {drug_name}: {synonym}")
92
+ return synonym.lower()
93
+
94
+ # If no suitable synonym found, return the canonical name
95
+ if hasattr(compound, 'iupac_name') and compound.iupac_name:
96
+ return compound.iupac_name.lower()
97
+
98
+ except Exception as e:
99
+ print(f"Error extracting active compound for {drug_name}: {e}")
100
+
101
+ # If all else fails, return the original drug name (it might already be an active compound)
102
+ return drug_lower
103
+
104
  # Load your labeled dataset with exact column names
105
  def load_drug_interaction_dataset():
106
  """Load your labeled drug interaction dataset with exact column names"""
 
160
  print("Initializing fallback database")
161
  return {
162
  ('warfarin', 'aspirin'): 'Severe',
163
+ ('cathinone', 'yohimbine'): 'Severe',
164
+ ('codeine', 'hyperforin'): 'Severe',
165
+ ('glycyrrhizin', 'digitoxin'): 'Severe',
166
+ ('digoxin', 'glycyrrhizin'): 'Severe',
167
+ ('yohimbine', 'reserpine'): 'Severe',
168
+ ('ephedrine', 'yohimbine'): 'Severe',
169
+ ('ephedrine', 'cathinone'): 'Severe',
170
+ ('sennoside a', 'aloin'): 'Severe',
171
+ ('glycyrrhizin', 'sennoside a'): 'Severe',
172
  ('warfarin', 'ibuprofen'): 'Severe',
173
  ('ibuprofen', 'warfarin'): 'Severe',
174
  ('simvastatin', 'clarithromycin'): 'Severe',
 
187
  ('fluconazole', 'warfarin'): 'Severe',
188
  ('digoxin', 'verapamil'): 'Severe',
189
  ('verapamil', 'digoxin'): 'Severe',
190
+ ('amodiaquine', 'acebutolol'): 'Severe',
191
+ ('amodiaquine', 'artemether'): 'Severe',
192
+ ('amodiaquine', 'atenolol'): 'Severe',
193
+ ('amodiaquine', 'carvedilol'): 'Severe',
194
+ ('amodiaquine', 'efavirenz'): 'Severe',
195
+ ('amodiaquine', 'betaxolol'): 'Severe',
196
+ ('amodiaquine', 'bisoprolol'): 'Severe',
197
+ ('amodiaquine', 'metoprolol'): 'Severe',
198
+ ('amodiaquine', 'propranolol'): 'Severe',
199
+ ('amodiaquine', 'rifampicin'): 'Severe',
200
 
201
  # Moderate interactions
202
+ ('hyperforin', 'mesembrine'): 'Moderate',
203
+ ('kavain', 'valerenic acid'): 'Moderate',
204
+ ('kavain', 'withanoside iv'): 'Moderate',
205
+ ('thc', 'mesembrine'): 'Moderate',
206
+ ('thc', 'valerenic acid'): 'Moderate',
207
+ ('hyperforin', 'morphine'): 'Moderate',
208
+ ('allicin', 'gingerol'): 'Moderate',
209
+ ('parthenolide', 'curcumin'): 'Moderate',
210
+ ('yohimbine', 'caffeine'): 'Moderate',
211
+ ('amodiaquine', 'amitriptyline'): 'Moderate',
212
+ ('amodiaquine', 'candesartan'): 'Moderate',
213
+ ('amodiaquine', 'fluoxetine'): 'Moderate',
214
+ ('amodiaquine', 'haloperidol'): 'Moderate',
215
+ ('amodiaquine', 'chloroquine'): 'Moderate',
216
  ('digoxin', 'quinine'): 'Moderate',
217
  ('quinine', 'digoxin'): 'Moderate',
218
  ('lisinopril', 'ibuprofen'): 'Moderate',
 
235
  ('digoxin', 'spironolactone'): 'Moderate',
236
 
237
  # Mild interactions
238
+ ('amodiaquine', 'amlodipine'): 'Mild',
239
+ ('amodiaquine', 'carbamazepine'): 'Mild',
240
  ('metformin', 'ibuprofen'): 'Mild',
241
+ ('curcumin', 'gingerol'): 'Mild',
242
  ('omeprazole', 'calcium'): 'Mild',
243
  ('calcium', 'omeprazole'): 'Mild',
244
  ('vitamin d', 'calcium'): 'Mild',
 
251
  ('vitamin b12', 'metformin'): 'Mild',
252
  ('omeprazole', 'vitamin b12'): 'Mild',
253
  ('vitamin b12', 'omeprazole'): 'Mild',
254
+ ('aspirin', 'gingerol'): 'Mild',
255
+ ('gingerol', 'aspirin'): 'Mild',
256
+ ('warfarin', 'epigallocatechin gallate'): 'Mild',
257
+ ('epigallocatechin gallate', 'warfarin'): 'Mild',
258
  ('levothyroxine', 'iron'): 'Mild',
259
  ('iron', 'levothyroxine'): 'Mild',
260
 
 
295
  'xlogp': compound.xlogp if compound.xlogp else 0,
296
  'tpsa': compound.tpsa if compound.tpsa else 0,
297
  'canonical_smiles': compound.canonical_smiles,
298
+ 'molecular_formula': compound.molecular_formula
 
 
299
  }
300
  except Exception as e:
301
  print(f"Error fetching PubChem data for {drug_name}: {e}")
 
319
  """Predict interaction between two drugs using dataset, fallback, and PubChem"""
320
  try:
321
  if not drug_names or ',' not in drug_names:
322
+ return "Error: Please enter two drugs separated by comma"
323
 
324
  drugs = [drug.strip() for drug in drug_names.split(',')]
325
  if len(drugs) != 2:
326
+ return "Error: Please enter exactly two drugs"
327
+
328
+ drug1_original, drug2_original = drugs[0], drugs[1]
329
+
330
+ # Extract active compounds in the background (user doesn't see this)
331
+ drug1_active = extract_active_compound(drug1_original)
332
+ drug2_active = extract_active_compound(drug2_original)
333
 
334
+ print(f"Background extraction: '{drug1_original}' -> '{drug1_active}', '{drug2_original}' -> '{drug2_active}'")
 
335
 
336
  # Validate drug names
337
+ if len(drug1_active) < 2 or len(drug2_active) < 2:
338
+ return "Error: Invalid drug names"
339
 
340
+ # Check dataset first using active compounds
341
+ prediction = dataset_db.get((drug1_active, drug2_active))
342
  if prediction:
343
  return prediction
344
 
345
+ # Check fallback database using active compounds
346
+ fallback_prediction = fallback_db.get((drug1_active, drug2_active))
347
  if fallback_prediction:
348
  return fallback_prediction
349
 
350
+ # If not in databases, try original drug names as backup
351
+ prediction = dataset_db.get((drug1_original.lower(), drug2_original.lower()))
352
+ if prediction:
353
+ return prediction
354
+
355
+ fallback_prediction = fallback_db.get((drug1_original.lower(), drug2_original.lower()))
356
+ if fallback_prediction:
357
+ return fallback_prediction
358
+
359
+ # If still not found, fetch PubChem features and predict if available
360
+ drug1_features = get_pubchem_features(drug1_active)
361
+ drug2_features = get_pubchem_features(drug2_active)
362
  if drug1_features and drug2_features:
363
  return predict_from_features(drug1_features, drug2_features)
364
  else:
365
  # Balanced random choice for completely unknown drugs
366
  return random.choice(['Moderate', 'Mild'])
367
 
368
+ except Exception as e:
369
+ print(f"Error in prediction: {e}")
370
+ return "Error: Unable to process request"
371
 
372
  # Load your dataset and fallback
373
  print("Loading drug interaction dataset...")
 
376
  # Create interface
377
  with gr.Blocks(title="Drug Interaction Predictor") as demo:
378
  gr.Markdown("# Drug Interaction Predictor")
379
+ gr.Markdown("Enter two drug names (traditional or modern) to predict their interaction severity. Active compounds are automatically extracted in the background.")
380
 
381
  with gr.Row():
382
  with gr.Column():
383
  drug_input = gr.Textbox(
384
  label="Enter two drug names (separated by comma)",
385
+ placeholder="e.g., Warfarin, Aspirin or St John's Wort, Morphine",
386
  lines=2
387
  )
388
 
389
+ predict_btn = gr.Button("Predict Interaction", variant="primary")
390
 
391
  with gr.Column():
392
  output = gr.Textbox(
393
  label="Interaction Prediction",
394
+ lines=2,
395
  interactive=False
396
  )
397
 
398
  predict_btn.click(fn=lambda x: predict_interaction(x, dataset_db, fallback_db), inputs=drug_input, outputs=output)
399
 
400
+ # Add examples
401
+ gr.Examples(
402
+ examples=[
403
+ ["Warfarin, Aspirin"],
404
+ ["St John's Wort, Morphine"],
405
+ ["Yohimbe, Khat"],
406
+ ["Cannabis, Valerian"],
407
+ ["Turmeric, Ginger"],
408
+ ["Kava, Ashwagandha"]
409
+ ],
410
+ inputs=drug_input
411
+ )
412
 
413
  if __name__ == "__main__":
414
  demo.launch()