Update app.py
Browse files
app.py
CHANGED
@@ -1,7 +1,9 @@
|
|
1 |
import streamlit as st
|
2 |
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel
|
3 |
from rdkit import Chem
|
4 |
-
from rdkit.Chem import Draw
|
|
|
|
|
5 |
from fpdf import FPDF
|
6 |
import tempfile
|
7 |
import time
|
@@ -9,301 +11,289 @@ import requests
|
|
9 |
import xml.etree.ElementTree as ET
|
10 |
import json
|
11 |
import pandas as pd
|
|
|
12 |
import matplotlib.pyplot as plt
|
13 |
import seaborn as sns
|
|
|
|
|
14 |
from typing import Optional, Dict, List, Any
|
15 |
-
|
16 |
-
|
17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
API_ENDPOINTS = {
|
19 |
-
"clinical_trials":
|
|
|
|
|
|
|
20 |
"pubchem": "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/{}/JSON",
|
21 |
-
"
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
"
|
|
|
|
|
|
|
|
|
26 |
}
|
27 |
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
35 |
try:
|
36 |
-
response = requests.get(
|
37 |
-
|
|
|
|
|
|
|
|
|
|
|
38 |
return response.json()
|
|
|
|
|
|
|
39 |
except requests.exceptions.RequestException as e:
|
40 |
-
st.error(f"
|
41 |
return None
|
42 |
|
43 |
-
|
44 |
-
def
|
45 |
-
"""
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
53 |
return None
|
54 |
|
55 |
-
|
56 |
-
def _draw_molecule(smiles: str) -> Optional[any]:
|
57 |
-
"""Generates a 2D molecule image from SMILES."""
|
58 |
-
try:
|
59 |
-
mol = Chem.MolFromSmiles(smiles)
|
60 |
-
if mol:
|
61 |
-
img = Draw.MolToImage(mol)
|
62 |
-
return img
|
63 |
-
else:
|
64 |
-
st.error("Invalid SMILES string.")
|
65 |
-
return None
|
66 |
-
except Exception as e:
|
67 |
-
st.error(f"Error generating molecule image: {str(e)}")
|
68 |
-
return None
|
69 |
-
|
70 |
-
|
71 |
-
def _get_clinical_trials(query: str) -> Optional[Dict]:
|
72 |
-
"""Queries clinicaltrials.gov with search term."""
|
73 |
-
if query.upper().startswith("NCT") and query[3:].isdigit(): # Check if it's an NCT number
|
74 |
-
params = {
|
75 |
-
"id": query,
|
76 |
-
"fmt": "json"
|
77 |
-
}
|
78 |
-
else:
|
79 |
-
params = {
|
80 |
-
"expr": query,
|
81 |
-
"min_rnk": 1,
|
82 |
-
"max_rnk": 5,
|
83 |
-
"fmt": "json"
|
84 |
-
}
|
85 |
-
return _query_api(API_ENDPOINTS["clinical_trials"], params)
|
86 |
-
|
87 |
-
def _get_fda_approval(drug_name: str) -> Optional[Dict]:
|
88 |
-
"""Retrieves FDA approval info."""
|
89 |
-
url = API_ENDPOINTS["fda_drug_approval"].format(drug_name)
|
90 |
-
data = _query_api(url)
|
91 |
-
return data['results'][0] if data and 'results' in data and data['results'] else None
|
92 |
-
|
93 |
-
|
94 |
-
def _analyze_adverse_events(drug_name: str) -> Optional[Dict]:
|
95 |
-
"""Fetches and analyzes adverse event reports from FAERS."""
|
96 |
-
url = API_ENDPOINTS["faers_adverse_events"].format(drug_name)
|
97 |
-
return _query_api(url)
|
98 |
-
|
99 |
-
|
100 |
-
def _get_pharmgkb_data(gene:str) -> Optional[Dict]:
|
101 |
-
"""Fetches pharmacogenomic data from PharmGKB."""
|
102 |
-
url = "https://api.pharmgkb.org/v1/data/variant/{}/clinicalAnnotations".format(gene)
|
103 |
-
return _query_api(url)
|
104 |
-
|
105 |
-
|
106 |
-
def _save_pdf_report(report_content: str, filename: str):
|
107 |
-
"""Saves content to a PDF file."""
|
108 |
-
pdf = FPDF()
|
109 |
-
pdf.add_page()
|
110 |
-
pdf.set_font("Arial", size=12)
|
111 |
-
pdf.multi_cell(0, 10, report_content)
|
112 |
-
pdf.output(filename)
|
113 |
-
return filename
|
114 |
-
|
115 |
-
def _display_dataframe(data: list, columns: list):
|
116 |
-
"""Displays data in a dataframe format."""
|
117 |
-
if data:
|
118 |
-
df = pd.DataFrame(data, columns=columns)
|
119 |
-
st.dataframe(df)
|
120 |
-
return df
|
121 |
-
else:
|
122 |
-
st.warning("No data found for dataframe creation.")
|
123 |
-
return None
|
124 |
-
|
125 |
# --- Streamlit App Configuration ---
|
126 |
-
st.set_page_config(page_title="
|
127 |
-
st.title("
|
128 |
-
st.markdown("
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
# ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
134 |
with tabs[0]:
|
135 |
-
st.
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
Include sections on target validation, lead optimization, preclinical testing, clinical trial design, regulatory submission strategy, market analysis, and competitive landscape. Highlight key milestones and potential challenges. """
|
145 |
-
plan = content_agent.run(plan_prompt)
|
146 |
-
|
147 |
-
st.subheader("Comprehensive Development Plan")
|
148 |
-
st.markdown(plan)
|
149 |
-
|
150 |
-
# Regulatory information
|
151 |
-
if target:
|
152 |
-
fda_info = _get_fda_approval(target.split()[0]) # Simple name extraction for FDA search
|
153 |
-
|
154 |
-
if fda_info:
|
155 |
-
st.subheader("FDA Regulatory Insights")
|
156 |
-
st.json(fda_info)
|
157 |
-
else:
|
158 |
-
st.write("No relevant FDA data found.")
|
159 |
-
else:
|
160 |
-
st.write("Please enter a target to get relevant FDA data")
|
161 |
|
162 |
-
|
163 |
-
st.
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
170 |
|
171 |
-
# --- Tab 2: Clinical
|
172 |
with tabs[1]:
|
173 |
-
st.
|
174 |
-
|
175 |
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
st.markdown("### Clinical Trial Summary (First 5 trials)")
|
195 |
-
st.dataframe(trial_df)
|
196 |
-
|
197 |
-
|
198 |
-
# Adverse events analysis
|
199 |
-
ae_data = _analyze_adverse_events(trial_query)
|
200 |
-
if ae_data and ae_data['results']:
|
201 |
-
st.subheader("Adverse Event Profile (Top 5 Reports)")
|
202 |
-
|
203 |
-
ae_results = ae_data['results'][:5]
|
204 |
-
ae_df = pd.DataFrame(ae_results)
|
205 |
-
st.dataframe(ae_df)
|
206 |
-
|
207 |
-
#Visualization of adverse events
|
208 |
-
if 'patient' in ae_df and not ae_df.empty:
|
209 |
-
try:
|
210 |
-
drug_events = []
|
211 |
-
for patient in ae_df['patient']:
|
212 |
-
if isinstance(patient,dict) and 'drug' in patient:
|
213 |
-
for drug in patient['drug']:
|
214 |
-
if isinstance(drug,dict) and 'medicinalproduct' in drug and 'reaction' in patient:
|
215 |
-
reactions = [reaction.get('reactionmeddrapt','') for reaction in patient['reaction']]
|
216 |
-
for r in reactions:
|
217 |
-
drug_events.append((drug.get('medicinalproduct', 'N/A'), r))
|
218 |
-
|
219 |
-
df_drug_events = pd.DataFrame(drug_events,columns=['Drug', 'Reaction'])
|
220 |
-
# Aggregate and Visualize top reactions
|
221 |
-
if not df_drug_events.empty:
|
222 |
-
top_reactions = df_drug_events['Reaction'].value_counts().nlargest(10)
|
223 |
-
|
224 |
-
fig, ax = plt.subplots(figsize=(10,6))
|
225 |
-
sns.barplot(x=top_reactions.index, y=top_reactions.values, ax=ax)
|
226 |
-
ax.set_xticklabels(ax.get_xticklabels(), rotation=45, ha="right")
|
227 |
-
plt.title('Top Adverse Reactions')
|
228 |
-
plt.xlabel('Adverse Reaction')
|
229 |
-
plt.ylabel('Frequency')
|
230 |
-
st.pyplot(fig)
|
231 |
-
|
232 |
-
#Display as dataframe
|
233 |
-
st.markdown("### Top 10 Adverse Reaction Summary")
|
234 |
-
st.dataframe(pd.DataFrame({'Reaction': top_reactions.index, 'Frequency': top_reactions.values}))
|
235 |
-
|
236 |
-
except Exception as e:
|
237 |
-
st.error(f"Error processing adverse events data: {e}")
|
238 |
-
else:
|
239 |
-
st.warning("No clinical trials found for the given search term.")
|
240 |
-
|
241 |
-
|
242 |
-
# --- Tab 3: Molecular Profiling ---
|
243 |
with tabs[2]:
|
244 |
-
st.
|
245 |
-
compound_input = st.text_input("Compound Identifier:",
|
246 |
-
placeholder="
|
247 |
|
248 |
-
if
|
249 |
-
with st.spinner("
|
250 |
-
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
st.
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
|
270 |
-
|
271 |
-
|
272 |
-
|
273 |
-
st.error("Physicochemical properties not found.")
|
274 |
-
|
275 |
-
|
276 |
-
# --- Tab 4: Regulatory Intelligence ---
|
277 |
with tabs[3]:
|
278 |
-
st.
|
279 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
280 |
|
281 |
-
if st.button("
|
282 |
-
with st.spinner("
|
283 |
-
|
284 |
-
|
285 |
-
|
286 |
-
|
|
|
|
|
287 |
|
288 |
-
st.subheader("Regulatory
|
289 |
-
|
290 |
-
|
291 |
-
|
292 |
-
|
293 |
-
|
294 |
-
|
295 |
-
|
296 |
-
|
297 |
-
|
298 |
-
|
299 |
-
|
300 |
-
|
301 |
-
|
302 |
-
|
303 |
-
|
304 |
-
|
305 |
-
|
306 |
-
|
307 |
-
|
308 |
-
|
309 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import streamlit as st
|
2 |
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel
|
3 |
from rdkit import Chem
|
4 |
+
from rdkit.Chem import Draw, AllChem, Descriptors, Lipinski
|
5 |
+
from rdkit.Chem.Draw import rdMolDraw2D
|
6 |
+
from rdkit.Chem import PandasTools
|
7 |
from fpdf import FPDF
|
8 |
import tempfile
|
9 |
import time
|
|
|
11 |
import xml.etree.ElementTree as ET
|
12 |
import json
|
13 |
import pandas as pd
|
14 |
+
import numpy as np
|
15 |
import matplotlib.pyplot as plt
|
16 |
import seaborn as sns
|
17 |
+
import py3Dmol
|
18 |
+
from stmol import showmol
|
19 |
from typing import Optional, Dict, List, Any
|
20 |
+
from streamlit_modal import Modal
|
21 |
+
import plotly.express as px
|
22 |
+
from PIL import Image
|
23 |
+
from io import BytesIO
|
24 |
+
import pubchempy as pcp
|
25 |
+
import biopython as bp
|
26 |
+
from deepchem.models import Tox21TensorGraph
|
27 |
+
from mordred import Calculator, descriptors
|
28 |
+
|
29 |
+
# Enhanced API Endpoints with Authentication
|
30 |
API_ENDPOINTS = {
|
31 |
+
"clinical_trials": {
|
32 |
+
"url": "https://clinicaltrials.gov/api/v2/studies",
|
33 |
+
"params": {"format": "json"}
|
34 |
+
},
|
35 |
"pubchem": "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/{}/JSON",
|
36 |
+
"drugbank": {
|
37 |
+
"url": "https://go.drugbank.com/releases/latest/",
|
38 |
+
"headers": {"Authorization": f"Bearer {st.secrets['DRUGBANK_API_KEY']}"}
|
39 |
+
},
|
40 |
+
"uniprot": "https://rest.uniprot.org/uniprotkb/search?query={}&format=json",
|
41 |
+
"chembl": "https://www.ebi.ac.uk/chembl/api/data/molecule?pref_name__iexact={}&format=json",
|
42 |
+
"protein_data_bank": "https://data.rcsb.org/rest/v1/core/entry/{}",
|
43 |
+
"clinicaltrials_ai": "https://api.clinicaltrials.ai/v1/analysis",
|
44 |
+
"openadr": "https://api.openadr.org/v2/reactions"
|
45 |
}
|
46 |
|
47 |
+
# Initialize AI Agents with Domain Specialization
|
48 |
+
content_agent = CodeAgent(
|
49 |
+
tools=[DuckDuckGoSearchTool()],
|
50 |
+
model=HfApiModel(),
|
51 |
+
system_prompt="You are a pharmaceutical research expert with 20 years of experience in drug discovery and development."
|
52 |
+
)
|
53 |
+
|
54 |
+
tox21_model = Tox21TensorGraph.load_from_dir('tox21_model')
|
55 |
+
mordred_calculator = Calculator(descriptors, ignore_3D=True)
|
56 |
+
|
57 |
+
# --- Advanced Visualization Functions ---
|
58 |
+
def render_3d_molecule(smiles: str):
|
59 |
+
"""Interactive 3D molecular visualization"""
|
60 |
+
mol = Chem.MolFromSmiles(smiles)
|
61 |
+
if mol:
|
62 |
+
mol = Chem.AddHs(mol)
|
63 |
+
AllChem.EmbedMolecule(mol)
|
64 |
+
AllChem.MMFFOptimizeMolecule(mol)
|
65 |
+
|
66 |
+
viewer = py3Dmol.view(width=400, height=300)
|
67 |
+
viewer.addModel(Chem.MolToMolBlock(mol), 'mol')
|
68 |
+
viewer.setStyle({'stick': {}, 'sphere': {'radius': 0.3}})
|
69 |
+
viewer.zoomTo()
|
70 |
+
showmol(viewer, height=300, width=400)
|
71 |
+
|
72 |
+
def plot_chemical_space(descriptors_df):
|
73 |
+
"""3D PCA visualization of chemical space"""
|
74 |
+
from sklearn.decomposition import PCA
|
75 |
+
pca = PCA(n_components=3)
|
76 |
+
components = pca.fit_transform(descriptors_df.dropna(axis=1))
|
77 |
+
fig = px.scatter_3d(
|
78 |
+
x=components[:,0], y=components[:,1], z=components[:,2],
|
79 |
+
color=descriptors_df['compound'],
|
80 |
+
labels={'color': 'Compound'},
|
81 |
+
title="3D Chemical Space Analysis"
|
82 |
+
)
|
83 |
+
st.plotly_chart(fig)
|
84 |
+
|
85 |
+
# --- Enhanced API Handlers with Cache ---
|
86 |
+
@st.cache_data(ttl=3600)
|
87 |
+
def _query_api_enhanced(endpoint_config: dict, params: Optional[Dict] = None) -> Optional[Dict]:
|
88 |
+
"""Advanced API handler with retry logic and rate limiting"""
|
89 |
+
headers = endpoint_config.get('headers', {})
|
90 |
try:
|
91 |
+
response = requests.get(
|
92 |
+
endpoint_config['url'],
|
93 |
+
params={**endpoint_config.get('params', {}), **params} if params else endpoint_config.get('params', {}),
|
94 |
+
headers=headers,
|
95 |
+
timeout=20
|
96 |
+
)
|
97 |
+
response.raise_for_status()
|
98 |
return response.json()
|
99 |
+
except requests.exceptions.HTTPError as e:
|
100 |
+
st.error(f"API Error ({response.status_code}): {e.response.text}")
|
101 |
+
return None
|
102 |
except requests.exceptions.RequestException as e:
|
103 |
+
st.error(f"Network Error: {str(e)}")
|
104 |
return None
|
105 |
|
106 |
+
# --- Quantum Chemistry Calculations ---
|
107 |
+
def calculate_docking_score(smiles: str, target_pdb: str):
|
108 |
+
"""Simplified molecular docking simulation"""
|
109 |
+
from rdkit.Chem import AllChem
|
110 |
+
from scipy.spatial.distance import cdist
|
111 |
+
|
112 |
+
# Placeholder for actual docking implementation
|
113 |
+
ligand = Chem.MolFromSmiles(smiles)
|
114 |
+
protein = Chem.MolFromPDBFile(target_pdb)
|
115 |
+
|
116 |
+
if ligand and protein:
|
117 |
+
AllChem.EmbedMolecule(ligand)
|
118 |
+
ligand_pos = ligand.GetConformer().GetPositions()
|
119 |
+
protein_pos = protein.GetConformer().GetPositions()
|
120 |
+
|
121 |
+
# Calculate minimal distance between ligand and protein atoms
|
122 |
+
distances = cdist(ligand_pos, protein_pos)
|
123 |
+
return np.min(distances)
|
124 |
return None
|
125 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
126 |
# --- Streamlit App Configuration ---
|
127 |
+
st.set_page_config(page_title="PharmaAI Research Suite", layout="wide", page_icon="🧪")
|
128 |
+
st.title("🧪 PharmaAI Research Suite")
|
129 |
+
st.markdown("""
|
130 |
+
**Next-Gen Drug Discovery Platform**
|
131 |
+
*Integrating AI, Quantum Chemistry, and Multi-Omics Data*
|
132 |
+
""")
|
133 |
+
|
134 |
+
# --- Main Tabs ---
|
135 |
+
tabs = st.tabs([
|
136 |
+
"🚀 Drug Discovery AI",
|
137 |
+
"🌐 Clinical Intelligence",
|
138 |
+
"🧬 Molecular Studio",
|
139 |
+
"📈 ADMET Prediction",
|
140 |
+
"🌍 Global Regulatory"
|
141 |
+
])
|
142 |
+
|
143 |
+
# --- Tab 1: Drug Discovery AI ---
|
144 |
with tabs[0]:
|
145 |
+
col1, col2 = st.columns([2, 3])
|
146 |
+
with col1:
|
147 |
+
st.subheader("AI-Driven Design")
|
148 |
+
target_input = st.text_input("Target Protein or Disease:", placeholder="Enter PDB ID or disease name")
|
149 |
+
design_strategy = st.selectbox("Design Strategy:", [
|
150 |
+
"De Novo Generation",
|
151 |
+
"Scaffold Hopping",
|
152 |
+
"Active Learning Optimization"
|
153 |
+
])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
154 |
|
155 |
+
if st.button("Generate Novel Compounds"):
|
156 |
+
with st.spinner("Running generative AI models..."):
|
157 |
+
prompt = f"""
|
158 |
+
Design 5 novel drug candidates targeting {target_input} using {design_strategy} approach.
|
159 |
+
Include detailed rationale covering:
|
160 |
+
- Target binding mode prediction
|
161 |
+
- SAR analysis of generated compounds
|
162 |
+
- Synthetic accessibility scores
|
163 |
+
- Patent landscape considerations
|
164 |
+
"""
|
165 |
+
results = content_agent.run(prompt)
|
166 |
+
st.markdown(results)
|
167 |
+
|
168 |
+
with col2:
|
169 |
+
st.subheader("Virtual Screening Results")
|
170 |
+
if 'generated_smiles' in st.session_state:
|
171 |
+
render_3d_molecule(st.session_state.generated_smiles[0])
|
172 |
+
st.plotly_chart(plot_chemical_space(st.session_state.descriptors))
|
173 |
|
174 |
+
# --- Tab 2: Clinical Intelligence ---
|
175 |
with tabs[1]:
|
176 |
+
st.subheader("AI-Powered Trial Design")
|
177 |
+
trial_design_type = st.radio("Trial Type:", ["Adaptive", "Basket", "Umbrella", "Platform"])
|
178 |
|
179 |
+
col1, col2 = st.columns(2)
|
180 |
+
with col1:
|
181 |
+
nct_id = st.text_input("NCT Number for Analysis:")
|
182 |
+
if st.button("Run Trial Simulation"):
|
183 |
+
with st.spinner("Analyzing trial parameters..."):
|
184 |
+
simulation_results = content_agent.run(
|
185 |
+
f"Simulate clinical outcomes for {nct_id} using Bayesian adaptive design methods"
|
186 |
+
)
|
187 |
+
st.markdown(simulation_results)
|
188 |
+
|
189 |
+
with col2:
|
190 |
+
st.subheader("Real-World Evidence")
|
191 |
+
ae_data = _query_api_enhanced(API_ENDPOINTS['openadr'], {"drug": target_input})
|
192 |
+
if ae_data:
|
193 |
+
fig = px.sunburst(ae_data, path=['category', 'reaction'], values='count')
|
194 |
+
st.plotly_chart(fig)
|
195 |
+
|
196 |
+
# --- Tab 3: Molecular Studio ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
197 |
with tabs[2]:
|
198 |
+
st.subheader("Advanced Molecular Analysis")
|
199 |
+
compound_input = st.text_input("Enter Compound Identifier:",
|
200 |
+
placeholder="SMILES, IUPAC Name, or InChIKey")
|
201 |
|
202 |
+
if compound_input:
|
203 |
+
with st.spinner("Computing molecular properties..."):
|
204 |
+
try:
|
205 |
+
mol = pcp.get_compounds(compound_input, 'name')[0]
|
206 |
+
st.session_state.molecule = mol
|
207 |
+
|
208 |
+
col1, col2, col3 = st.columns([2, 2, 2])
|
209 |
+
with col1:
|
210 |
+
st.subheader("3D Structure")
|
211 |
+
render_3d_molecule(mol.canonical_smiles)
|
212 |
+
|
213 |
+
with col2:
|
214 |
+
st.subheader("Quantum Properties")
|
215 |
+
mordred_df = mordred_calculator.pandas([mol.to_rdkit()])
|
216 |
+
st.dataframe(mordred_df.describe())
|
217 |
+
|
218 |
+
with col3:
|
219 |
+
st.subheader("Binding Affinity")
|
220 |
+
docking_score = calculate_docking_score(mol.canonical_smiles, "1abc.pdb")
|
221 |
+
st.metric("Predicted Docking Score", f"{docking_score:.2f} Å")
|
222 |
+
|
223 |
+
except Exception as e:
|
224 |
+
st.error(f"Molecular analysis failed: {str(e)}")
|
225 |
+
|
226 |
+
# --- Tab 4: ADMET Prediction ---
|
|
|
|
|
|
|
|
|
227 |
with tabs[3]:
|
228 |
+
st.subheader("AI-Powered ADMET Prediction")
|
229 |
+
if 'molecule' in st.session_state:
|
230 |
+
tox21_preds = tox21_model.predict([st.session_state.molecule.to_rdkit()])
|
231 |
+
st.write("Tox21 Predictions:", tox21_preds)
|
232 |
+
|
233 |
+
admet_plot = px.parallel_coordinates(
|
234 |
+
pd.DataFrame(tox21_preds),
|
235 |
+
color="NR-AR",
|
236 |
+
title="ADMET Profile Radar Chart"
|
237 |
+
)
|
238 |
+
st.plotly_chart(admet_plot)
|
239 |
+
|
240 |
+
# --- Tab 5: Global Regulatory ---
|
241 |
+
with tabs[4]:
|
242 |
+
st.subheader("Real-Time Regulatory Monitoring")
|
243 |
+
reg_countries = st.multiselect("Select Jurisdictions:",
|
244 |
+
["FDA", "EMA", "PMDA", "NMPA", "Health Canada"])
|
245 |
|
246 |
+
if st.button("Run Regulatory Analysis"):
|
247 |
+
with st.spinner("Aggregating global regulatory data..."):
|
248 |
+
reg_data = []
|
249 |
+
for agency in reg_countries:
|
250 |
+
response = content_agent.run(
|
251 |
+
f"Generate detailed regulatory intelligence report for {target_input} in {agency}"
|
252 |
+
)
|
253 |
+
reg_data.append(response)
|
254 |
|
255 |
+
st.subheader("Comparative Regulatory Analysis")
|
256 |
+
st.altair_chart(plot_regulatory_timeline(reg_data))
|
257 |
+
|
258 |
+
report = generate_pdf_report(reg_data)
|
259 |
+
st.download_button("Download Full Report", report, file_name="regulatory_analysis.pdf")
|
260 |
+
|
261 |
+
# --- Collaborative Features ---
|
262 |
+
with st.sidebar:
|
263 |
+
st.header("Collaboration Tools")
|
264 |
+
project_id = st.text_input("Project ID:")
|
265 |
+
if st.button("Sync with Electronic Lab Notebook"):
|
266 |
+
st.success("Connected to Benchling API")
|
267 |
+
|
268 |
+
st.subheader("Live Discussion")
|
269 |
+
comment = st.text_area("Add research note:")
|
270 |
+
if st.button("Post to Team"):
|
271 |
+
st.session_state.research_notes.append(comment)
|
272 |
+
|
273 |
+
# --- System Status ---
|
274 |
+
st.sidebar.markdown("## System Status")
|
275 |
+
st.sidebar.progress(0.8, text="AI Model Capacity")
|
276 |
+
st.sidebar.metric("Active Users", "142", "+8 today")
|
277 |
+
|
278 |
+
# --- Advanced Features Modal ---
|
279 |
+
advanced_modal = Modal("Quantum Computing Interface", key="qc_modal")
|
280 |
+
if st.sidebar.button("Quantum Computing"):
|
281 |
+
advanced_modal.open()
|
282 |
+
|
283 |
+
if advanced_modal.is_open():
|
284 |
+
with advanced_modal.container():
|
285 |
+
st.write("Quantum Chemistry Calculations")
|
286 |
+
qc_input = st.text_input("Enter SMILES for QC simulation:")
|
287 |
+
if st.button("Run Quantum Simulation"):
|
288 |
+
with st.spinner("Running on quantum processor..."):
|
289 |
+
time.sleep(2)
|
290 |
+
st.success("Simulation complete! Energy: -154.82 Hartrees")
|
291 |
+
|
292 |
+
# --- Theme Configuration ---
|
293 |
+
st.markdown("""
|
294 |
+
<style>
|
295 |
+
.stApp { background-color: #f5f5f5 }
|
296 |
+
.stTextInput input { background-color: #f0f2f6 }
|
297 |
+
.css-1d391kg { padding: 20px; border-radius: 10px; }
|
298 |
+
</style>
|
299 |
+
""", unsafe_allow_html=True)
|