Fredaaaaaa commited on
Commit
e29e5fe
Β·
verified Β·
1 Parent(s): f907abe

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +212 -0
app.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ from rdkit import Chem
4
+ from rdkit.Chem import Descriptors
5
+ import pandas as pd
6
+ from inference import DDIPredictor
7
+ import torch
8
+ import re
9
+
10
+ # Initialize your trained model
11
+ predictor = DDIPredictor(".")
12
+
13
+ def fetch_pubchem_data(drug_name):
14
+ """Fetch drug data from PubChem by name"""
15
+ try:
16
+ # First, search for the compound ID
17
+ search_url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/{drug_name}/cids/JSON"
18
+ search_response = requests.get(search_url)
19
+
20
+ if search_response.status_code != 200:
21
+ return None, f"Drug '{drug_name}' not found in PubChem"
22
+
23
+ cid = search_response.json()['IdentifierList']['CID'][0]
24
+
25
+ # Fetch compound data
26
+ compound_url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{cid}/property/CanonicalSMILES,MolecularWeight,XLogP,TPSA/JSON"
27
+ compound_response = requests.get(compound_url)
28
+
29
+ if compound_response.status_code != 200:
30
+ return None, "Failed to fetch compound data"
31
+
32
+ data = compound_response.json()['PropertyTable']['Properties'][0]
33
+
34
+ # Calculate additional properties from SMILES
35
+ mol = Chem.MolFromSmiles(data['CanonicalSMILES'])
36
+ if mol:
37
+ data['RotatableBondCount'] = Descriptors.NumRotatableBonds(mol)
38
+ data['HBondDonorCount'] = Descriptors.NumHDonors(mol)
39
+ data['HBondAcceptorCount'] = Descriptors.NumHAcceptors(mol)
40
+ data['Complexity'] = Descriptors.MolWt(mol) # Simplified complexity
41
+
42
+ return data, None
43
+
44
+ except Exception as e:
45
+ return None, f"Error fetching data: {str(e)}"
46
+
47
+ def generate_interaction_description(drug1_data, drug2_data):
48
+ """Generate a clinical-style interaction description based on molecular properties"""
49
+
50
+ descriptions = []
51
+
52
+ # Based on molecular weight difference
53
+ mw_diff = abs(drug1_data['MolecularWeight'] - drug2_data['MolecularWeight'])
54
+ if mw_diff > 500:
55
+ descriptions.append("Significant molecular size difference may affect metabolism")
56
+
57
+ # Based on lipophilicity (XLogP)
58
+ logp_diff = abs(drug1_data.get('XLogP', 0) - drug2_data.get('XLogP', 0))
59
+ if logp_diff > 3:
60
+ descriptions.append("Differing lipophilicity may influence distribution and clearance")
61
+
62
+ # Based on TPSA (polar surface area)
63
+ tpsa_diff = abs(drug1_data.get('TPSA', 0) - drug2_data.get('TPSA', 0))
64
+ if tpsa_diff > 100:
65
+ descriptions.append("Varying polar surface areas suggest different membrane permeability")
66
+
67
+ # Based on hydrogen bonding
68
+ hbond_total1 = drug1_data.get('HBondDonorCount', 0) + drug1_data.get('HBondAcceptorCount', 0)
69
+ hbond_total2 = drug2_data.get('HBondDonorCount', 0) + drug2_data.get('HBondAcceptorCount', 0)
70
+ if abs(hbond_total1 - hbond_total2) > 8:
71
+ descriptions.append("Differing hydrogen bonding capacity may affect protein binding")
72
+
73
+ # Default description if no specific features stand out
74
+ if not descriptions:
75
+ descriptions.append("Potential pharmacokinetic interaction requiring clinical evaluation")
76
+
77
+ return " ".join(descriptions)
78
+
79
+ def check_drugbank_interaction(drug1_name, drug2_name):
80
+ """Placeholder function to check DrugBank interactions (you'd need API access)"""
81
+ # This is a mock function - you'd need actual DrugBank API access
82
+ drug1_clean = drug1_name.lower().strip()
83
+ drug2_clean = drug2_name.lower().strip()
84
+
85
+ # Mock known interactions for demonstration
86
+ known_interactions = {
87
+ ('warfarin', 'aspirin'): 'Severe: Increased bleeding risk',
88
+ ('warfarin', 'ibuprofen'): 'Moderate: Increased bleeding risk',
89
+ ('simvastatin', 'clarithromycin'): 'Severe: Increased risk of myopathy',
90
+ ('digoxin', 'quinine'): 'Moderate: Increased digoxin levels',
91
+ }
92
+
93
+ # Check both orders
94
+ interaction = known_interactions.get((drug1_clean, drug2_clean)) or known_interactions.get((drug2_clean, drug1_clean))
95
+
96
+ if interaction:
97
+ return interaction
98
+ else:
99
+ return "No known interaction in mock database"
100
+
101
+ def predict_ddi(drug1_name, drug2_name):
102
+ """Main prediction function"""
103
+ try:
104
+ # Fetch data for both drugs
105
+ drug1_data, error1 = fetch_pubchem_data(drug1_name)
106
+ drug2_data, error2 = fetch_pubchem_data(drug2_name)
107
+
108
+ if error1 or error2:
109
+ return f"Error: {error1 or error2}", "", "", "", ""
110
+
111
+ # Generate interaction description
112
+ interaction_description = generate_interaction_description(drug1_data, drug2_data)
113
+
114
+ # Make prediction
115
+ result = predictor.predict(interaction_description)
116
+
117
+ # Check DrugBank (mock)
118
+ drugbank_result = check_drugbank_interaction(drug1_name, drug2_name)
119
+
120
+ # Prepare detailed output
121
+ drug1_info = f"""
122
+ **{drug1_name} Properties:**
123
+ - SMILES: {drug1_data['CanonicalSMILES']}
124
+ - Molecular Weight: {drug1_data['MolecularWeight']:.2f}
125
+ - LogP: {drug1_data.get('XLogP', 'N/A')}
126
+ - TPSA: {drug1_data.get('TPSA', 'N/A')}
127
+ - H-Bond Donors: {drug1_data.get('HBondDonorCount', 'N/A')}
128
+ - H-Bond Acceptors: {drug1_data.get('HBondAcceptorCount', 'N/A')}
129
+ """
130
+
131
+ drug2_info = f"""
132
+ **{drug2_name} Properties:**
133
+ - SMILES: {drug2_data['CanonicalSMILES']}
134
+ - Molecular Weight: {drug2_data['MolecularWeight']:.2f}
135
+ - LogP: {drug2_data.get('XLogP', 'N/A')}
136
+ - TPSA: {drug2_data.get('TPSA', 'N/A')}
137
+ - H-Bond Donors: {drug2_data.get('HBondDonorCount', 'N/A')}
138
+ - H-Bond Acceptors: {drug2_data.get('HBondAcceptorCount', 'N/A')}
139
+ """
140
+
141
+ prediction_output = f"""
142
+ **Generated Interaction Description:**
143
+ {interaction_description}
144
+
145
+ **AI Prediction:**
146
+ - Severity: **{result['prediction']}**
147
+ - Confidence: {result['confidence']:.2%}
148
+
149
+ **Probabilities:**
150
+ {', '.join([f'{k}: {v:.2%}' for k, v in result['probabilities'].items()])}
151
+ """
152
+
153
+ return prediction_output, drug1_info, drug2_info, drugbank_result, interaction_description
154
+
155
+ except Exception as e:
156
+ return f"Error: {str(e)}", "", "", "", ""
157
+
158
+ # Create Gradio interface
159
+ with gr.Blocks(title="Drug Interaction Severity Predictor", theme=gr.themes.Soft()) as demo:
160
+ gr.Markdown("# πŸ§ͺ Drug Interaction Severity Predictor")
161
+ gr.Markdown("Predict potential drug-drug interaction severity using molecular properties and AI")
162
+
163
+ with gr.Row():
164
+ with gr.Column():
165
+ drug1 = gr.Textbox(label="First Drug Name", placeholder="e.g., Warfarin, Aspirin, Simvastatin...")
166
+ drug2 = gr.Textbox(label="Second Drug Name", placeholder="e.g., Ibuprofen, Clarithromycin...")
167
+ predict_btn = gr.Button("Predict Interaction", variant="primary")
168
+
169
+ with gr.Row():
170
+ with gr.Column():
171
+ gr.Markdown("## πŸ“Š Prediction Results")
172
+ prediction_output = gr.Markdown(label="AI Prediction")
173
+
174
+ with gr.Column():
175
+ gr.Markdown("## πŸ” Drug Properties")
176
+ with gr.Tab("Drug 1"):
177
+ drug1_info = gr.Markdown()
178
+ with gr.Tab("Drug 2"):
179
+ drug2_info = gr.Markdown()
180
+
181
+ with gr.Row():
182
+ with gr.Column():
183
+ gr.Markdown("## πŸ₯ DrugBank Comparison")
184
+ drugbank_result = gr.Textbox(label="Known Interaction (Mock Data)", interactive=False)
185
+
186
+ with gr.Column():
187
+ gr.Markdown("## πŸ“ Generated Description")
188
+ interaction_description = gr.Textbox(label="AI-Generated Interaction Description", interactive=False)
189
+
190
+ # Examples
191
+ gr.Markdown("### πŸ’‘ Example Drug Pairs")
192
+ gr.Examples(
193
+ examples=[
194
+ ["Warfarin", "Aspirin"],
195
+ ["Simvastatin", "Clarithromycin"],
196
+ ["Digoxin", "Quinine"],
197
+ ["Metformin", "Ibuprofen"]
198
+ ],
199
+ inputs=[drug1, drug2],
200
+ outputs=[prediction_output, drug1_info, drug2_info, drugbank_result, interaction_description],
201
+ fn=predict_ddi,
202
+ cache_examples=True
203
+ )
204
+
205
+ predict_btn.click(
206
+ fn=predict_ddi,
207
+ inputs=[drug1, drug2],
208
+ outputs=[prediction_output, drug1_info, drug2_info, drugbank_result, interaction_description]
209
+ )
210
+
211
+ if __name__ == "__main__":
212
+ demo.launch(share=True)