Fredaaaaaa commited on
Commit
74177af
Β·
verified Β·
1 Parent(s): 0f8c85b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +92 -150
app.py CHANGED
@@ -1,147 +1,112 @@
1
  import gradio as gr
2
  import requests
3
- import json
4
  from inference import DDIPredictor
5
- import re
6
 
7
- # Initialize your trained model from the Hugging Face Hub
8
  try:
9
- predictor = DDIPredictor(model_repo="Fredaaaaaa/drug_interaction_severity")
 
 
10
  except Exception as e:
11
- print(f"Failed to initialize DDIPredictor: {e}")
12
- raise
13
 
14
  def fetch_pubchem_data(drug_name):
15
- """Fetch comprehensive drug data from PubChem by name"""
16
  try:
 
 
 
17
  # First, search for the compound ID
18
  search_url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/{drug_name}/cids/JSON"
19
- search_response = requests.get(search_url, timeout=10)
20
 
21
  if search_response.status_code != 200:
22
  return None, f"Drug '{drug_name}' not found in PubChem"
23
 
24
  cid = search_response.json()['IdentifierList']['CID'][0]
25
 
26
- # Fetch comprehensive compound data
27
- properties = [
28
- 'CanonicalSMILES', 'MolecularWeight', 'XLogP', 'TPSA',
29
- 'RotatableBondCount', 'HBondDonorCount', 'HBondAcceptorCount',
30
- 'Complexity', 'Charge', 'ExactMass'
31
- ]
32
-
33
  compound_url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{cid}/property/{','.join(properties)}/JSON"
34
- compound_response = requests.get(compound_url, timeout=10)
35
 
36
  if compound_response.status_code != 200:
37
- return None, "Failed to fetch compound properties"
38
 
39
  data = compound_response.json()['PropertyTable']['Properties'][0]
40
  data['CID'] = cid
41
 
42
- # Get IUPAC name for better identification
43
- iupac_url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{cid}/property/IUPACName/JSON"
44
- iupac_response = requests.get(iupac_url, timeout=10)
45
- if iupac_response.status_code == 200:
46
- data['IUPACName'] = iupac_response.json()['PropertyTable']['Properties'][0]['IUPACName']
47
- else:
48
- data['IUPACName'] = drug_name
49
-
50
  return data, None
51
 
52
  except requests.exceptions.Timeout:
53
  return None, "PubChem API timeout - please try again"
 
 
54
  except Exception as e:
55
  return None, f"Error fetching data: {str(e)}"
56
 
57
  def generate_interaction_description(drug1_data, drug2_data):
58
- """Generate a clinical-style interaction description based on molecular properties"""
59
- descriptions = []
60
-
61
- # Molecular weight analysis
62
- mw1 = drug1_data.get('MolecularWeight', 0)
63
- mw2 = drug2_data.get('MolecularWeight', 0)
64
- mw_diff = abs(mw1 - mw2)
65
-
66
- if mw_diff > 500:
67
- descriptions.append("Significant molecular size difference may affect metabolic pathways")
68
- elif mw_diff > 200:
69
- descriptions.append("Moderate molecular size difference could influence distribution")
70
-
71
- # Lipophilicity analysis (XLogP)
72
- logp1 = drug1_data.get('XLogP', 0)
73
- logp2 = drug2_data.get('XLogP', 0)
74
- logp_diff = abs(logp1 - logp2)
75
-
76
- if logp_diff > 3:
77
- descriptions.append("Differing lipophilicity may affect membrane permeability and clearance rates")
78
- elif logp_diff > 1.5:
79
- descriptions.append("Variation in lipophilicity could influence tissue distribution")
80
-
81
- # Polar surface area analysis
82
- tpsa1 = drug1_data.get('TPSA', 0)
83
- tpsa2 = drug2_data.get('TPSA', 0)
84
- tpsa_diff = abs(tpsa1 - tpsa2)
85
-
86
- if tpsa_diff > 100:
87
- descriptions.append("Significant difference in polar surface area suggests varying bioavailability")
88
- elif tpsa_diff > 50:
89
- descriptions.append("Moderate difference in polar surface area may affect absorption")
90
-
91
- # Hydrogen bonding analysis
92
- h_donor1 = drug1_data.get('HBondDonorCount', 0)
93
- h_donor2 = drug2_data.get('HBondDonorCount', 0)
94
- h_acceptor1 = drug1_data.get('HBondAcceptorCount', 0)
95
- h_acceptor2 = drug2_data.get('HBondAcceptorCount', 0)
96
-
97
- if abs(h_donor1 - h_donor2) > 3 or abs(h_acceptor1 - h_acceptor2) > 5:
98
- descriptions.append("Differing hydrogen bonding capacity may affect protein binding and metabolism")
99
-
100
- # Rotatable bonds analysis
101
- rotatable1 = drug1_data.get('RotatableBondCount', 0)
102
- rotatable2 = drug2_data.get('RotatableBondCount', 0)
103
-
104
- if abs(rotatable1 - rotatable2) > 8:
105
- descriptions.append("Significant difference in molecular flexibility may influence receptor binding")
106
-
107
- # Default description if no specific features stand out
108
- if not descriptions:
109
- descriptions.append("Potential pharmacokinetic interaction based on molecular properties - clinical evaluation recommended")
110
-
111
- return ". ".join(descriptions) + "."
112
 
113
  def check_drugbank_interaction(drug1_name, drug2_name):
114
- """Mock function to simulate DrugBank interaction check"""
115
- # Convert to lowercase for case-insensitive matching
116
  drug1_clean = drug1_name.lower().strip()
117
  drug2_clean = drug2_name.lower().strip()
118
 
119
- # Expanded mock database of known interactions
120
  known_interactions = {
121
  ('warfarin', 'aspirin'): 'Severe: Increased risk of bleeding and hemorrhage',
122
  ('warfarin', 'ibuprofen'): 'Moderate: Increased risk of gastrointestinal bleeding',
123
- ('warfarin', 'simvastatin'): 'Moderate: Increased anticoagulant effect',
124
  ('simvastatin', 'clarithromycin'): 'Severe: Increased risk of myopathy and rhabdomyolysis',
125
- ('simvastatin', 'itraconazole'): 'Severe: Increased statin levels and toxicity risk',
126
  ('digoxin', 'quinine'): 'Moderate: Increased digoxin levels, risk of toxicity',
127
- ('digoxin', 'verapamil'): 'Moderate: Increased digoxin concentrations',
128
- ('lisinopril', 'ibuprofen'): 'Moderate: Reduced antihypertensive effect',
129
- ('metformin', 'contrast'): 'Severe: Risk of lactic acidosis with contrast media',
130
- ('phenytoin', 'warfarin'): 'Moderate: Altered anticoagulant effect',
131
  }
132
 
133
- # Check both orders of drug names
134
  interaction = (known_interactions.get((drug1_clean, drug2_clean)) or
135
  known_interactions.get((drug2_clean, drug1_clean)))
136
 
137
- if interaction:
138
- return interaction
139
- else:
140
- return "No known severe interaction in database (mock data)"
141
 
142
  def predict_ddi(drug1_name, drug2_name):
143
  """Main prediction function"""
144
  try:
 
 
 
145
  if not drug1_name or not drug2_name:
146
  return "Please enter both drug names", "", "", "", ""
147
 
@@ -157,50 +122,41 @@ def predict_ddi(drug1_name, drug2_name):
157
  # Generate interaction description
158
  interaction_description = generate_interaction_description(drug1_data, drug2_data)
159
 
160
- # Make prediction
161
  result = predictor.predict(interaction_description)
162
 
163
  # Check DrugBank (mock)
164
  drugbank_result = check_drugbank_interaction(drug1_name, drug2_name)
165
 
166
- # Prepare detailed output
167
  drug1_info = f"""
168
  **{drug1_name}** (PubChem CID: {drug1_data.get('CID', 'N/A')})
169
  - **IUPAC Name:** {drug1_data.get('IUPACName', 'N/A')}
170
- - **SMILES:** {drug1_data.get('CanonicalSMILES', 'N/A')}
171
  - **Molecular Weight:** {drug1_data.get('MolecularWeight', 'N/A')} g/mol
172
- - **LogP (XLogP):** {drug1_data.get('XLogP', 'N/A')}
173
  - **TPSA:** {drug1_data.get('TPSA', 'N/A')} Γ…Β²
174
- - **H-Bond Donors:** {drug1_data.get('HBondDonorCount', 'N/A')}
175
- - **H-Bond Acceptors:** {drug1_data.get('HBondAcceptorCount', 'N/A')}
176
- - **Rotatable Bonds:** {drug1_data.get('RotatableBondCount', 'N/A')}
177
- - **Complexity:** {drug1_data.get('Complexity', 'N/A')}
178
  """
179
 
180
  drug2_info = f"""
181
  **{drug2_name}** (PubChem CID: {drug2_data.get('CID', 'N/A')})
182
  - **IUPAC Name:** {drug2_data.get('IUPACName', 'N/A')}
183
- - **SMILES:** {drug2_data.get('CanonicalSMILES', 'N/A')}
184
  - **Molecular Weight:** {drug2_data.get('MolecularWeight', 'N/A')} g/mol
185
- - **LogP (XLogP):** {drug2_data.get('XLogP', 'N/A')}
186
  - **TPSA:** {drug2_data.get('TPSA', 'N/A')} Γ…Β²
187
- - **H-Bond Donors:** {drug2_data.get('HBondDonorCount', 'N/A')}
188
- - **H-Bond Acceptors:** {drug2_data.get('HBondAcceptorCount', 'N/A')}
189
- - **Rotatable Bonds:** {drug2_data.get('RotatableBondCount', 'N/A')}
190
- - **Complexity:** {drug2_data.get('Complexity', 'N/A')}
191
  """
192
 
193
  prediction_output = f"""
194
  ## πŸ” AI Prediction Results
195
 
196
- **Generated Interaction Description:**
197
- *"{interaction_description}"*
198
 
199
- **Prediction:**
200
- - **Severity:** **{result['prediction']}**
201
- - **Confidence:** {result['confidence']:.1%}
202
 
203
- **Probability Distribution:**
204
  {', '.join([f'{k}: {v:.1%}' for k, v in result['probabilities'].items()])}
205
  """
206
 
@@ -211,54 +167,40 @@ def predict_ddi(drug1_name, drug2_name):
211
 
212
  # Create Gradio interface
213
  with gr.Blocks(title="Drug Interaction Severity Predictor", theme=gr.themes.Soft()) as demo:
214
- gr.Markdown("# πŸ§ͺ Drug Interaction Severity Predictor")
215
- gr.Markdown("Predict potential drug-drug interaction severity using molecular properties from PubChem and AI")
216
 
217
  with gr.Row():
218
- with gr.Column(scale=1):
219
- gr.Markdown("## πŸ’Š Input Drug Names")
220
- drug1 = gr.Textbox(label="First Drug Name", placeholder="e.g., Warfarin, Aspirin, Simvastatin...")
221
- drug2 = gr.Textbox(label="Second Drug Name", placeholder="e.g., Ibuprofen, Clarithromycin, Digoxin...")
222
- predict_btn = gr.Button("πŸ”¬ Predict Interaction", variant="primary", size="lg")
223
-
224
- gr.Markdown("### πŸ’‘ Example Pairs")
225
- gr.Examples(
226
- examples=[
227
- ["Warfarin", "Aspirin"],
228
- ["Simvastatin", "Clarithromycin"],
229
- ["Digoxin", "Quinine"],
230
- ["Lisinopril", "Ibuprofen"]
231
- ],
232
- inputs=[drug1, drug2],
233
- label="Try these examples:"
234
- )
235
 
236
  with gr.Row():
237
- with gr.Column(scale=2):
238
- gr.Markdown("## πŸ“Š Prediction Results")
239
- prediction_output = gr.Markdown(label="AI Prediction")
240
-
241
- with gr.Column(scale=1):
242
- gr.Markdown("## πŸ₯ DrugBank Check")
243
- drugbank_result = gr.Textbox(label="Known Interaction (Mock Data)", interactive=False)
244
 
245
  with gr.Row():
246
  with gr.Column():
247
- gr.Markdown("## πŸ” Molecular Properties")
248
- with gr.Tab("Drug 1 Properties"):
249
- drug1_info = gr.Markdown()
250
- with gr.Tab("Drug 2 Properties"):
251
- drug2_info = gr.Markdown()
252
 
253
  with gr.Row():
254
- gr.Markdown("## πŸ“ Generated Description")
255
- interaction_description = gr.Textbox(label="AI-Generated Interaction Description", interactive=False, lines=3)
256
 
257
- predict_btn.click(
258
- fn=predict_ddi,
 
259
  inputs=[drug1, drug2],
260
- outputs=[prediction_output, drug1_info, drug2_info, drugbank_result, interaction_description]
 
 
 
 
 
 
261
  )
262
 
263
  if __name__ == "__main__":
264
- demo.launch(share=True)
 
1
  import gradio as gr
2
  import requests
3
+ import time
4
  from inference import DDIPredictor
 
5
 
6
+ # Initialize predictor with your Hugging Face repository
7
  try:
8
+ predictor = DDIPredictor("Fredaaaaaa/drug_interaction_severity")
9
+ MODEL_LOADED = True
10
+ print("βœ… Model loaded successfully from Fredaaaaaa/drug_interaction_severity")
11
  except Exception as e:
12
+ print(f"❌ Model loading failed: {e}")
13
+ MODEL_LOADED = False
14
 
15
  def fetch_pubchem_data(drug_name):
16
+ """Fetch drug data from PubChem by name"""
17
  try:
18
+ if not drug_name or not drug_name.strip():
19
+ return None, "Please enter a valid drug name"
20
+
21
  # First, search for the compound ID
22
  search_url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/{drug_name}/cids/JSON"
23
+ search_response = requests.get(search_url, timeout=15)
24
 
25
  if search_response.status_code != 200:
26
  return None, f"Drug '{drug_name}' not found in PubChem"
27
 
28
  cid = search_response.json()['IdentifierList']['CID'][0]
29
 
30
+ # Fetch compound data
31
+ properties = ['CanonicalSMILES', 'MolecularWeight', 'IUPACName', 'XLogP', 'TPSA']
 
 
 
 
 
32
  compound_url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{cid}/property/{','.join(properties)}/JSON"
33
+ compound_response = requests.get(compound_url, timeout=15)
34
 
35
  if compound_response.status_code != 200:
36
+ return None, "Failed to fetch compound data from PubChem"
37
 
38
  data = compound_response.json()['PropertyTable']['Properties'][0]
39
  data['CID'] = cid
40
 
 
 
 
 
 
 
 
 
41
  return data, None
42
 
43
  except requests.exceptions.Timeout:
44
  return None, "PubChem API timeout - please try again"
45
+ except requests.exceptions.RequestException:
46
+ return None, "Network error - please check your connection"
47
  except Exception as e:
48
  return None, f"Error fetching data: {str(e)}"
49
 
50
  def generate_interaction_description(drug1_data, drug2_data):
51
+ """Generate clinical interaction description based on molecular properties"""
52
+ try:
53
+ descriptions = []
54
+
55
+ # Molecular weight analysis
56
+ mw1 = drug1_data.get('MolecularWeight', 0)
57
+ mw2 = drug2_data.get('MolecularWeight', 0)
58
+ if mw1 and mw2:
59
+ mw_diff = abs(mw1 - mw2)
60
+ if mw_diff > 300:
61
+ descriptions.append("Significant molecular size difference may affect metabolic pathways")
62
+
63
+ # Lipophilicity analysis
64
+ logp1 = drug1_data.get('XLogP', 0)
65
+ logp2 = drug2_data.get('XLogP', 0)
66
+ if logp1 is not None and logp2 is not None:
67
+ logp_diff = abs(logp1 - logp2)
68
+ if logp_diff > 2:
69
+ descriptions.append("Differing lipophilicity may affect membrane permeability")
70
+
71
+ # Polar surface area analysis
72
+ tpsa1 = drug1_data.get('TPSA', 0)
73
+ tpsa2 = drug2_data.get('TPSA', 0)
74
+ if tpsa1 and tpsa2:
75
+ tpsa_diff = abs(tpsa1 - tpsa2)
76
+ if tpsa_diff > 80:
77
+ descriptions.append("Varying polar surface areas suggest different absorption characteristics")
78
+
79
+ if not descriptions:
80
+ descriptions.append("Potential pharmacokinetic interaction based on molecular properties")
81
+
82
+ return ". ".join(descriptions) + ". Clinical evaluation recommended."
83
+
84
+ except Exception:
85
+ return "Potential drug interaction requiring clinical assessment."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
  def check_drugbank_interaction(drug1_name, drug2_name):
88
+ """Mock function for DrugBank interaction check"""
 
89
  drug1_clean = drug1_name.lower().strip()
90
  drug2_clean = drug2_name.lower().strip()
91
 
 
92
  known_interactions = {
93
  ('warfarin', 'aspirin'): 'Severe: Increased risk of bleeding and hemorrhage',
94
  ('warfarin', 'ibuprofen'): 'Moderate: Increased risk of gastrointestinal bleeding',
 
95
  ('simvastatin', 'clarithromycin'): 'Severe: Increased risk of myopathy and rhabdomyolysis',
 
96
  ('digoxin', 'quinine'): 'Moderate: Increased digoxin levels, risk of toxicity',
 
 
 
 
97
  }
98
 
 
99
  interaction = (known_interactions.get((drug1_clean, drug2_clean)) or
100
  known_interactions.get((drug2_clean, drug1_clean)))
101
 
102
+ return interaction or "No known severe interaction in mock database"
 
 
 
103
 
104
  def predict_ddi(drug1_name, drug2_name):
105
  """Main prediction function"""
106
  try:
107
+ if not MODEL_LOADED:
108
+ return "Model not loaded properly. Please check the deployment.", "", "", "", ""
109
+
110
  if not drug1_name or not drug2_name:
111
  return "Please enter both drug names", "", "", "", ""
112
 
 
122
  # Generate interaction description
123
  interaction_description = generate_interaction_description(drug1_data, drug2_data)
124
 
125
+ # Make prediction using your hosted model
126
  result = predictor.predict(interaction_description)
127
 
128
  # Check DrugBank (mock)
129
  drugbank_result = check_drugbank_interaction(drug1_name, drug2_name)
130
 
131
+ # Prepare output
132
  drug1_info = f"""
133
  **{drug1_name}** (PubChem CID: {drug1_data.get('CID', 'N/A')})
134
  - **IUPAC Name:** {drug1_data.get('IUPACName', 'N/A')}
 
135
  - **Molecular Weight:** {drug1_data.get('MolecularWeight', 'N/A')} g/mol
136
+ - **LogP:** {drug1_data.get('XLogP', 'N/A')}
137
  - **TPSA:** {drug1_data.get('TPSA', 'N/A')} Γ…Β²
138
+ - **SMILES:** {drug1_data.get('CanonicalSMILES', 'N/A')}
 
 
 
139
  """
140
 
141
  drug2_info = f"""
142
  **{drug2_name}** (PubChem CID: {drug2_data.get('CID', 'N/A')})
143
  - **IUPAC Name:** {drug2_data.get('IUPACName', 'N/A')}
 
144
  - **Molecular Weight:** {drug2_data.get('MolecularWeight', 'N/A')} g/mol
145
+ - **LogP:** {drug2_data.get('XLogP', 'N/A')}
146
  - **TPSA:** {drug2_data.get('TPSA', 'N/A')} Γ…Β²
147
+ - **SMILES:** {drug2_data.get('CanonicalSMILES', 'N/A')}
 
 
 
148
  """
149
 
150
  prediction_output = f"""
151
  ## πŸ” AI Prediction Results
152
 
153
+ **Model Source:** Fredaaaaaa/drug_interaction_severity
154
+ **Generated Description:** {interaction_description}
155
 
156
+ **Prediction:** **{result['prediction']}**
157
+ **Confidence:** {result['confidence']:.1%}
 
158
 
159
+ **Probabilities:**
160
  {', '.join([f'{k}: {v:.1%}' for k, v in result['probabilities'].items()])}
161
  """
162
 
 
167
 
168
  # Create Gradio interface
169
  with gr.Blocks(title="Drug Interaction Severity Predictor", theme=gr.themes.Soft()) as demo:
170
+ gr.Markdown("# πŸ’Š Drug Interaction Severity Predictor")
171
+ gr.Markdown("Powered by AI model from: [Fredaaaaaa/drug_interaction_severity](https://huggingface.co/Fredaaaaaa/drug_interaction_severity)")
172
 
173
  with gr.Row():
174
+ drug1 = gr.Textbox(label="First Drug Name", placeholder="e.g., Warfarin, Aspirin...")
175
+ drug2 = gr.Textbox(label="Second Drug Name", placeholder="e.g., Ibuprofen, Clarithromycin...")
176
+
177
+ predict_btn = gr.Button("πŸ”¬ Predict Interaction", variant="primary")
 
 
 
 
 
 
 
 
 
 
 
 
 
178
 
179
  with gr.Row():
180
+ prediction_output = gr.Markdown("## πŸ“Š Prediction Results will appear here")
 
 
 
 
 
 
181
 
182
  with gr.Row():
183
  with gr.Column():
184
+ drug1_info = gr.Markdown("### πŸ’Š Drug 1 Properties")
185
+ with gr.Column():
186
+ drug2_info = gr.Markdown("### πŸ’Š Drug 2 Properties")
 
 
187
 
188
  with gr.Row():
189
+ drugbank_info = gr.Textbox(label="πŸ₯ DrugBank Comparison (Mock Data)")
190
+ interaction_desc = gr.Textbox(label="πŸ“ AI-Generated Description")
191
 
192
+ # Examples
193
+ gr.Examples(
194
+ examples=[["Warfarin", "Aspirin"], ["Simvastatin", "Clarithromycin"]],
195
  inputs=[drug1, drug2],
196
+ label="πŸ’‘ Try these examples:"
197
+ )
198
+
199
+ predict_btn.click(
200
+ predict_ddi,
201
+ [drug1, drug2],
202
+ [prediction_output, drug1_info, drug2_info, drugbank_info, interaction_desc]
203
  )
204
 
205
  if __name__ == "__main__":
206
+ demo.launch()