Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,16 +1,15 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
import requests
|
| 3 |
import time
|
| 4 |
-
from inference import DDIPredictor
|
| 5 |
|
| 6 |
-
#
|
| 7 |
try:
|
| 8 |
-
predictor
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 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"""
|
|
@@ -18,188 +17,108 @@ def fetch_pubchem_data(drug_name):
|
|
| 18 |
if not drug_name or not drug_name.strip():
|
| 19 |
return None, "Please enter a valid drug name"
|
| 20 |
|
| 21 |
-
#
|
| 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=
|
| 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 |
-
|
| 32 |
-
|
| 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
|
| 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
|
| 49 |
|
| 50 |
def generate_interaction_description(drug1_data, drug2_data):
|
| 51 |
-
"""Generate
|
| 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
|
| 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
|
| 81 |
|
| 82 |
return ". ".join(descriptions) + ". Clinical evaluation recommended."
|
| 83 |
-
|
| 84 |
-
|
| 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
|
| 109 |
|
| 110 |
if not drug1_name or not drug2_name:
|
| 111 |
-
return "Please enter both drug names", "", "", ""
|
| 112 |
|
| 113 |
-
# Fetch data
|
| 114 |
drug1_data, error1 = fetch_pubchem_data(drug1_name)
|
| 115 |
drug2_data, error2 = fetch_pubchem_data(drug2_name)
|
| 116 |
|
| 117 |
-
if error1:
|
| 118 |
-
return f"Error
|
| 119 |
-
if error2:
|
| 120 |
-
return f"Error with {drug2_name}: {error2}", "", "", "", ""
|
| 121 |
|
| 122 |
-
# Generate
|
| 123 |
interaction_description = generate_interaction_description(drug1_data, drug2_data)
|
| 124 |
|
| 125 |
-
# Make prediction
|
| 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 |
-
|
| 133 |
-
**{drug1_name}
|
| 134 |
-
|
| 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 |
-
|
| 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 |
|
| 163 |
-
return prediction_output,
|
| 164 |
|
| 165 |
except Exception as e:
|
| 166 |
-
return f"Error: {str(e)}", "", "", ""
|
| 167 |
|
| 168 |
-
# Create
|
| 169 |
-
with gr.Blocks(title="Drug Interaction
|
| 170 |
-
gr.Markdown("# 💊 Drug Interaction
|
| 171 |
-
gr.Markdown("
|
| 172 |
|
| 173 |
with gr.Row():
|
| 174 |
-
drug1 = gr.Textbox(label="
|
| 175 |
-
drug2 = gr.Textbox(label="
|
| 176 |
|
| 177 |
-
predict_btn = gr.Button("
|
| 178 |
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 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 |
-
[
|
| 203 |
)
|
| 204 |
|
| 205 |
if __name__ == "__main__":
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import requests
|
| 3 |
import time
|
|
|
|
| 4 |
|
| 5 |
+
# Try to import the predictor
|
| 6 |
try:
|
| 7 |
+
from inference import predictor, MODEL_LOADED
|
| 8 |
+
print("✅ Inference module imported successfully")
|
| 9 |
+
except ImportError as e:
|
| 10 |
+
print(f"❌ Failed to import inference: {e}")
|
|
|
|
| 11 |
MODEL_LOADED = False
|
| 12 |
+
predictor = None
|
| 13 |
|
| 14 |
def fetch_pubchem_data(drug_name):
|
| 15 |
"""Fetch drug data from PubChem by name"""
|
|
|
|
| 17 |
if not drug_name or not drug_name.strip():
|
| 18 |
return None, "Please enter a valid drug name"
|
| 19 |
|
| 20 |
+
# Search for compound ID
|
| 21 |
search_url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/{drug_name}/cids/JSON"
|
| 22 |
+
search_response = requests.get(search_url, timeout=10)
|
| 23 |
|
| 24 |
if search_response.status_code != 200:
|
| 25 |
return None, f"Drug '{drug_name}' not found in PubChem"
|
| 26 |
|
| 27 |
cid = search_response.json()['IdentifierList']['CID'][0]
|
| 28 |
|
| 29 |
+
# Fetch basic compound data
|
| 30 |
+
compound_url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{cid}/property/CanonicalSMILES,MolecularWeight,IUPACName/JSON"
|
| 31 |
+
compound_response = requests.get(compound_url, timeout=10)
|
|
|
|
| 32 |
|
| 33 |
if compound_response.status_code != 200:
|
| 34 |
+
return None, "Failed to fetch compound data"
|
| 35 |
|
| 36 |
data = compound_response.json()['PropertyTable']['Properties'][0]
|
| 37 |
data['CID'] = cid
|
| 38 |
|
| 39 |
return data, None
|
| 40 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
except Exception as e:
|
| 42 |
+
return None, f"Error: {str(e)}"
|
| 43 |
|
| 44 |
def generate_interaction_description(drug1_data, drug2_data):
|
| 45 |
+
"""Generate interaction description"""
|
| 46 |
try:
|
| 47 |
descriptions = []
|
| 48 |
|
|
|
|
| 49 |
mw1 = drug1_data.get('MolecularWeight', 0)
|
| 50 |
mw2 = drug2_data.get('MolecularWeight', 0)
|
| 51 |
if mw1 and mw2:
|
| 52 |
mw_diff = abs(mw1 - mw2)
|
| 53 |
if mw_diff > 300:
|
| 54 |
+
descriptions.append("Significant molecular size difference")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
if not descriptions:
|
| 57 |
+
descriptions.append("Potential drug interaction")
|
| 58 |
|
| 59 |
return ". ".join(descriptions) + ". Clinical evaluation recommended."
|
| 60 |
+
except:
|
| 61 |
+
return "Potential drug interaction requiring assessment."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
def predict_ddi(drug1_name, drug2_name):
|
| 64 |
"""Main prediction function"""
|
| 65 |
try:
|
| 66 |
+
if not MODEL_LOADED or predictor is None:
|
| 67 |
+
return "Model not loaded. Please check requirements.txt", "", "", ""
|
| 68 |
|
| 69 |
if not drug1_name or not drug2_name:
|
| 70 |
+
return "Please enter both drug names", "", "", ""
|
| 71 |
|
| 72 |
+
# Fetch drug data
|
| 73 |
drug1_data, error1 = fetch_pubchem_data(drug1_name)
|
| 74 |
drug2_data, error2 = fetch_pubchem_data(drug2_name)
|
| 75 |
|
| 76 |
+
if error1 or error2:
|
| 77 |
+
return f"Error: {error1 or error2}", "", "", ""
|
|
|
|
|
|
|
| 78 |
|
| 79 |
+
# Generate description
|
| 80 |
interaction_description = generate_interaction_description(drug1_data, drug2_data)
|
| 81 |
|
| 82 |
+
# Make prediction
|
| 83 |
result = predictor.predict(interaction_description)
|
| 84 |
|
|
|
|
|
|
|
|
|
|
| 85 |
# Prepare output
|
| 86 |
+
drug_info = f"""
|
| 87 |
+
**{drug1_name}**: MW={drug1_data.get('MolecularWeight', 'N/A')} g/mol
|
| 88 |
+
**{drug2_name}**: MW={drug2_data.get('MolecularWeight', 'N/A')} g/mol
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
"""
|
| 90 |
|
| 91 |
prediction_output = f"""
|
| 92 |
+
**Prediction:** {result['prediction']}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
**Confidence:** {result['confidence']:.1%}
|
| 94 |
+
**Description:** {interaction_description}
|
|
|
|
|
|
|
| 95 |
"""
|
| 96 |
|
| 97 |
+
return prediction_output, drug_info, interaction_description, "✅ Success"
|
| 98 |
|
| 99 |
except Exception as e:
|
| 100 |
+
return f"Error: {str(e)}", "", "", ""
|
| 101 |
|
| 102 |
+
# Create simple interface
|
| 103 |
+
with gr.Blocks(title="Drug Interaction Predictor") as demo:
|
| 104 |
+
gr.Markdown("# 💊 Drug Interaction Predictor")
|
| 105 |
+
gr.Markdown("Model: Fredaaaaaa/drug_interaction_severity")
|
| 106 |
|
| 107 |
with gr.Row():
|
| 108 |
+
drug1 = gr.Textbox(label="Drug 1", placeholder="e.g., Aspirin")
|
| 109 |
+
drug2 = gr.Textbox(label="Drug 2", placeholder="e.g., Warfarin")
|
| 110 |
|
| 111 |
+
predict_btn = gr.Button("Predict", variant="primary")
|
| 112 |
|
| 113 |
+
output = gr.Markdown("## Results will appear here")
|
| 114 |
+
drug_info = gr.Markdown()
|
| 115 |
+
interaction_desc = gr.Textbox(label="Generated Description")
|
| 116 |
+
status = gr.Textbox(label="Status")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
predict_btn.click(
|
| 119 |
predict_ddi,
|
| 120 |
[drug1, drug2],
|
| 121 |
+
[output, drug_info, interaction_desc, status]
|
| 122 |
)
|
| 123 |
|
| 124 |
if __name__ == "__main__":
|