File size: 19,456 Bytes
d35b5b6
2213189
914e5a1
2213189
 
 
 
07c450c
2213189
 
07c450c
2213189
 
 
796e4f0
ec53fe0
2213189
ec53fe0
 
2213189
 
 
796e4f0
2213189
796e4f0
2213189
b1f52a5
0ad090a
 
796e4f0
 
2213189
 
796e4f0
 
 
 
 
 
6f46f3e
796e4f0
 
 
 
 
 
 
6f46f3e
 
 
 
 
 
 
 
796e4f0
2213189
 
 
 
 
 
 
 
 
 
 
 
ec53fe0
2213189
 
796e4f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2213189
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec53fe0
2213189
 
 
796e4f0
2213189
796e4f0
 
 
2213189
 
 
b1f52a5
2213189
 
 
796e4f0
 
b1f52a5
2213189
 
 
796e4f0
6f46f3e
2213189
6f46f3e
 
 
0ad090a
2213189
6f46f3e
 
 
 
2213189
0ad090a
2213189
6f46f3e
 
 
0ad090a
6f46f3e
 
 
 
 
2213189
 
 
 
796e4f0
0ad090a
 
 
 
ec53fe0
2213189
796e4f0
 
 
ec53fe0
 
b1f52a5
ec53fe0
 
 
796e4f0
 
 
0ad090a
ec53fe0
 
0ad090a
ec53fe0
0ad090a
796e4f0
ec53fe0
 
2e162a8
 
 
 
 
 
796e4f0
ec53fe0
 
796e4f0
 
2213189
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
796e4f0
2213189
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
796e4f0
2213189
 
796e4f0
 
2213189
796e4f0
 
 
 
 
276129d
2213189
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1f52a5
2213189
e69190c
2213189
 
 
 
 
 
 
b1f52a5
 
2213189
 
 
 
 
b1f52a5
2213189
 
 
 
 
 
 
796e4f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec53fe0
796e4f0
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
import streamlit as st
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel
from rdkit import Chem
from rdkit.Chem import Draw
from fpdf import FPDF
import tempfile
import time
import requests
import xml.etree.ElementTree as ET
import json
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from typing import Optional, Dict, List, Any
import os
import logging

# Setup logging
logging.basicConfig(level=logging.ERROR) #Log only errors

# API Endpoints (Centralized Configuration)
API_ENDPOINTS = {
    "clinical_trials": "https://clinicaltrials.gov/api/v2/studies",
    "pubchem": "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/{}/JSON",
     "pubmed": "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi",
    "who_drugs": "https://health-products.canada.ca/api/drug/product",
    #"ema_reports": "https://www.ema.europa.eu/api/search/medicines", #Removed due to 403
    "fda_drug_approval": "https://api.fda.gov/drug/label.json", # Updated this to use base API
    "faers_adverse_events": "https://api.fda.gov/drug/event.json", # Updated this to use base API
    "pharmgkb": "https://api.pharmgkb.org/v1/data/variant/{}/clinicalAnnotations",
     "bioportal": "https://data.bioontology.org/ontologies"
}

#Email addresses
#Email addresses
if "PUB_EMAIL" in st.secrets:
    PUBMED_EMAIL = st.secrets["PUB_EMAIL"]
else:
    PUBMED_EMAIL = None
    st.error("PubMed email not found in secrets. Please add the PUB_EMAIL to secrets.")
CLINICALTRIALS_EMAIL = PUBMED_EMAIL

# Retrieve the BioPortal API Key from secrets
if "BIOPORTAL_API_KEY" in st.secrets:
    BIOPORTAL_API_KEY = st.secrets["BIOPORTAL_API_KEY"]
else:
    BIOPORTAL_API_KEY = None
    st.error("BioPortal API key not found in secrets. Please add the BIOPORTAL_API_KEY to secrets.")

# Retrieve the OpenFDA API Key from secrets
if "OPENFDA_KEY" in st.secrets:
    OPENFDA_KEY = st.secrets["OPENFDA_KEY"]
else:
    OPENFDA_KEY = None
    st.error("OpenFDA API key not found in secrets. Please add the OPENFDA_KEY to secrets.")
    
# Initialize AI Agent (Context-aware)
content_agent = CodeAgent(tools=[DuckDuckGoSearchTool()], model=HfApiModel())

# --- Utility Functions ---
def _query_api(endpoint: str, params: Optional[Dict] = None) -> Optional[Dict]:
    """Handles API requests with robust error handling."""
    try:
        response = requests.get(endpoint, params=params, timeout=15)
        response.raise_for_status()  # Raise HTTPError for bad responses (4xx or 5xx)
        return response.json()
    except requests.exceptions.RequestException as e:
        st.error(f"API request failed: {e} for endpoint {endpoint}. Please check connectivity and the endpoint.")
        logging.error(f"API request failed: {e} for endpoint {endpoint}.")
        return None

def _query_pubmed(query: str, email: Optional[str] = PUBMED_EMAIL) -> Optional[Dict]:
    """Queries PubMed with robust error handling."""
    if not email:
        st.error("PubMed email not configured.")
        return None
    
    params = {
        "db": "pubmed",
        "term": query,
        "retmax": 10,
        "retmode": "json",
        "email": email
    }
    return _query_api(API_ENDPOINTS["pubmed"], params)


def _get_pubchem_smiles(drug_name: str) -> Optional[str]:
    """Retrieves SMILES from PubChem, returns None on failure."""
    url = API_ENDPOINTS["pubchem"].format(drug_name)
    data = _query_api(url)
    if data and 'PC_Compounds' in data and data['PC_Compounds'][0]['props']:
        #Check if props exists and find SMILES value
        for prop in data['PC_Compounds'][0]['props']:
            if 'name' in prop and prop['name'] == 'Canonical SMILES':
                return prop['value']['sval']
    return None


def _draw_molecule(smiles: str) -> Optional[any]:
    """Generates a 2D molecule image from SMILES."""
    try:
        mol = Chem.MolFromSmiles(smiles)
        if mol:
            img = Draw.MolToImage(mol)
            return img
        else:
            st.error("Invalid SMILES string.")
            return None
    except Exception as e:
        st.error(f"Error generating molecule image: {str(e)}")
        logging.error(f"Error generating molecule image: {str(e)}")
        return None


def _get_clinical_trials(query: str, email:Optional[str] = CLINICALTRIALS_EMAIL) -> Optional[Dict]:
    """Queries clinicaltrials.gov with search term."""
    if not email:
        st.error("Clinical Trials email not configured.")
        return None
    if query.upper().startswith("NCT") and query[3:].isdigit():  # Check if it's an NCT number
        params = {
            "id": query,
            "fmt": "json"
        }
    else:
        params = {
            "query.term": query,
            "fmt": "json",
             "email": email
        }
    return _query_api(API_ENDPOINTS["clinical_trials"], params)


def _get_fda_approval(drug_name: str, api_key:Optional[str] = OPENFDA_KEY) -> Optional[Dict]:
    """Retrieves FDA approval info."""
    if not api_key:
         st.error("OpenFDA key not configured.")
         return None
    url = f"{API_ENDPOINTS['fda_drug_approval']}?api_key={api_key}&search=openfda.brand_name:\"{drug_name}\""
    data = _query_api(url)
    if data and 'results' in data and data['results']:
        return data['results'][0]
    else:
      return None

def _analyze_adverse_events(drug_name: str, api_key:Optional[str] = OPENFDA_KEY, limit: int = 5) -> Optional[Dict]:
    """Fetches and analyzes adverse event reports from FAERS."""
    if not api_key:
        st.error("OpenFDA key not configured.")
        return None
    url = f"{API_ENDPOINTS['faers_adverse_events']}?api_key={api_key}&search=patient.drug.medicinalproduct:\"{drug_name}\"&limit={limit}"
    data = _query_api(url)
    if data and 'results' in data:
        return data
    else:
        return None


def _get_pharmgkb_data(gene:str) -> Optional[Dict]:
    """Fetches pharmacogenomic data from PharmGKB."""
    url = API_ENDPOINTS["pharmgkb"].format(gene)
    data = _query_api(url)
    if data and 'clinicalAnnotations' in data:
         return data
    else:
        return None

def _get_bioportal_data(ontology: str, term: str) -> Optional[Dict]:
    """Fetches data from BioPortal."""
    if not BIOPORTAL_API_KEY:
      st.error("BioPortal API key not found. Please add the BIOPORTAL_API_KEY to secrets.")
      return None
    if not term:
      st.error("Please provide a search term.")
      return None
    
    headers = {
        "Authorization": f"apikey token={BIOPORTAL_API_KEY}"
        }
    params = {
        "q": term,
        "ontologies": ontology
    }

    url = f"{API_ENDPOINTS['bioportal']}/search"
    try:
        response = requests.get(url, headers=headers, params=params, timeout=15)
        response.raise_for_status()
        data = response.json()
        if data and 'collection' in data:
            return data
        else:
            st.warning("No results found for the BioPortal query.")
            return None
    except requests.exceptions.RequestException as e:
        st.error(f"BioPortal API request failed: {e} Please check connectivity and ensure you have the correct API Key.")
        logging.error(f"BioPortal API request failed: {e}")
        return None
    
def _save_pdf_report(report_content: str, filename: str):
    """Saves content to a PDF file."""
    pdf = FPDF()
    pdf.add_page()
    pdf.set_font("Arial", size=12)
    pdf.multi_cell(0, 10, report_content)
    pdf.output(filename)
    return filename

def _display_dataframe(data: list, columns: list):
    """Displays data in a dataframe format."""
    if data:
        df = pd.DataFrame(data, columns=columns)
        st.dataframe(df)
        return df
    else:
         st.warning("No data found for dataframe creation.")
         return None

# --- Streamlit App Configuration ---
st.set_page_config(page_title="Pharma Research Expert Platform", layout="wide")
st.title("πŸ”¬ Pharma Research Expert Platform")
st.markdown("An integrated platform for drug discovery, clinical research, and regulatory affairs.")

# --- Tabs ---
tabs = st.tabs(["πŸ’Š Drug Development", "πŸ“Š Trial Analytics", "🧬 Molecular Profiling", "πŸ“œ Regulatory Intelligence", "πŸ“š Literature Search"])

# --- Tab 1: Drug Development ---
with tabs[0]:
    st.header("AI-Driven Drug Development Strategy")
    target = st.text_input("Target Disease/Pathway:", placeholder="Enter biological target or disease mechanism")
    target_gene = st.text_input("Target Gene (for pharmacogenomics)", placeholder="Enter the gene associated with target")
    strategy = st.selectbox("Development Strategy:", ["First-in-class", "Me-too", "Repurposing", "Biologic"])
    
    if st.button("Generate Development Plan"):
        with st.spinner("Analyzing target and competitive landscape..."):
            # AI-generated content with regulatory checks
            plan_prompt = f"""Develop a comprehensive drug development plan for the treatment of {target} using a {strategy} strategy.
            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. """
            plan = content_agent.run(plan_prompt)
            
            st.subheader("Comprehensive Development Plan")
            st.markdown(plan)
            
            # Regulatory information
            if target:
                fda_info = _get_fda_approval(target.split()[0])  # Simple name extraction for FDA search

                if fda_info:
                    st.subheader("FDA Regulatory Insights")
                    st.json(fda_info)
                else:
                    st.write("No relevant FDA data found.")
            else:
                st.write("Please enter a target to get relevant FDA data")
        
            # Pharmacogenomic integration
            st.subheader("Pharmacogenomic Considerations")
            pgx_data = _get_pharmgkb_data(target_gene)
            if pgx_data:
                st.write(pgx_data)
            else:
                st.write("No relevant pharmacogenomic data found.")


# --- Tab 2: Clinical Trial Analytics ---
with tabs[1]:
    st.header("Clinical Trial Landscape Analytics")
    trial_query = st.text_input("Search Clinical Trials:", placeholder="Enter condition, intervention, or NCT number")
    
    if st.button("Analyze Trial Landscape"):
        with st.spinner("Aggregating global trial data..."):
            trials = _get_clinical_trials(trial_query)
            if trials and trials['studies']:
                st.subheader("Recent Clinical Trials")
                trial_data = []
                for study in trials['studies'][:5]:
                   
                    trial_data.append({
                        "Title": study['briefTitle'],
                         "Status": study['overallStatus'],
                         "Phase": study['phase'] if 'phase' in study else 'Not Available',
                         "Enrollment": study['enrollmentCount'] if 'enrollmentCount' in study else 'Not Available'
                   })
                
                trial_df = _display_dataframe(trial_data, list(trial_data[0].keys())) if trial_data else None

                if trial_df is not None:
                    st.markdown("### Clinical Trial Summary (First 5 trials)")
                    st.dataframe(trial_df)


                    # Adverse events analysis
                    ae_data = _analyze_adverse_events(trial_query)
                    if ae_data and ae_data['results']:
                        st.subheader("Adverse Event Profile (Top 5 Reports)")
                        
                        ae_results = ae_data['results'][:5]
                        ae_df = pd.DataFrame(ae_results)
                        st.dataframe(ae_df)
                        
                        #Visualization of adverse events
                        if 'patient' in ae_df and not ae_df.empty:
                            try:
                                drug_events = []
                                for patient in ae_df['patient']:
                                    if isinstance(patient,dict) and 'drug' in patient:
                                        for drug in patient['drug']:
                                            if isinstance(drug,dict) and 'medicinalproduct' in drug and 'reaction' in patient:
                                                reactions = [reaction.get('reactionmeddrapt','') for reaction in patient['reaction']]
                                                for r in reactions:
                                                    drug_events.append((drug.get('medicinalproduct', 'N/A'), r))
                                    
                                df_drug_events = pd.DataFrame(drug_events,columns=['Drug', 'Reaction'])
                                # Aggregate and Visualize top reactions
                                if not df_drug_events.empty:
                                    top_reactions = df_drug_events['Reaction'].value_counts().nlargest(10)

                                    fig, ax = plt.subplots(figsize=(10,6))
                                    sns.barplot(x=top_reactions.index, y=top_reactions.values, ax=ax)
                                    ax.set_xticklabels(ax.get_xticklabels(), rotation=45, ha="right")
                                    plt.title('Top Adverse Reactions')
                                    plt.xlabel('Adverse Reaction')
                                    plt.ylabel('Frequency')
                                    st.pyplot(fig)

                                    #Display as dataframe
                                    st.markdown("### Top 10 Adverse Reaction Summary")
                                    st.dataframe(pd.DataFrame({'Reaction': top_reactions.index, 'Frequency': top_reactions.values}))

                            except Exception as e:
                                st.error(f"Error processing adverse events data: {e}")
            else:
                st.warning("No clinical trials found for the given search term.")


# --- Tab 3: Molecular Profiling ---
with tabs[2]:
    st.header("Advanced Molecular Profiling")
    compound_input = st.text_input("Compound Identifier:", 
                                 placeholder="Enter drug name, SMILES, or INN")
    
    if st.button("Analyze Compound"):
        with st.spinner("Querying global databases..."):
            # SMILES resolution
            smiles = compound_input if Chem.MolFromSmiles(compound_input) else _get_pubchem_smiles(compound_input)
            
            if smiles:
                img = _draw_molecule(smiles)
                if img:
                    st.image(img, caption="2D Structure")
            else:
                st.error("Compound structure not found in databases.")

            # PubChem properties
            pubchem_data = _query_api(API_ENDPOINTS["pubchem"].format(compound_input))
            if pubchem_data and 'PC_Compounds' in pubchem_data and pubchem_data['PC_Compounds']:
                st.subheader("Physicochemical Properties")
                props = pubchem_data['PC_Compounds'][0]['props']
                mw = next((prop['value']['sval'] for prop in props if 'name' in prop and prop['name'] == 'Molecular Weight'), 'N/A')
                logp = next((prop['value']['sval'] for prop in props if 'name' in prop and prop['name'] == 'LogP'), 'N/A')

                st.write(f"""
                    Molecular Weight: {mw}
                    LogP: {logp}
                    """)
            else:
                st.error("Physicochemical properties not found.")


# --- Tab 4: Regulatory Intelligence ---
with tabs[3]:
    st.header("Global Regulatory Monitoring")
    drug_name = st.text_input("Drug Product:", placeholder="Enter generic or brand name")
    
    if st.button("Generate Regulatory Report"):
        with st.spinner("Compiling global regulatory status..."):
            # Multi-regional checks
            fda = _get_fda_approval(drug_name)
           # ema = _query_api(API_ENDPOINTS["ema_reports"], {"search": drug_name}) #Removed EMA due to 403 error
            who = _query_api(API_ENDPOINTS["who_drugs"], {"name": drug_name})
            
            st.subheader("Regulatory Status")
            col1, col2, col3 = st.columns(3)
            with col1:
                st.markdown("**FDA Status**")
                st.write(fda['openfda']['brand_name'][0] if fda and 'openfda' in fda and 'brand_name' in fda['openfda'] else "Not approved")
            with col2:
                st.markdown("**EMA Status**")
                #st.write(ema['results'][0]['currentStatus'] if ema and 'results' in ema and ema['results'] else "Not approved") #Removed EMA due to 403 error
                st.write("Not Available")
            with col3:
                st.markdown("**WHO Essential Medicine**")
                st.write("Yes" if who else "No")

        # Save the information to a PDF report
        regulatory_content = f"### Regulatory Report\n\nFDA Status: {fda['openfda']['brand_name'][0] if fda and 'openfda' in fda and 'brand_name' in fda['openfda'] else 'Not Approved'}\n\nEMA Status: {'Not Available'}\n\nWHO Essential Medicine: {'Yes' if who else 'No'}"
        report_file = _save_pdf_report(regulatory_content, f"{drug_name}_regulatory_report.pdf")
        if report_file:
            with open(report_file, "rb") as file:
                st.download_button(
                        label="Download Regulatory Report (PDF)",
                        data=file,
                        file_name=f"{drug_name}_regulatory_report.pdf",
                        mime="application/pdf")

# --- Tab 5: Literature Search ---
with tabs[4]:
    st.header("Literature Search")
    search_term = st.text_input("Enter search query for PubMed:", placeholder="e.g., Alzheimer's disease genetics")
    if st.button("Search PubMed"):
        with st.spinner("Searching PubMed..."):
            pubmed_data = _query_pubmed(search_term)
            if pubmed_data and 'esearchresult' in pubmed_data and 'idlist' in pubmed_data['esearchresult'] and pubmed_data['esearchresult']['idlist']:
                st.subheader("PubMed Search Results")
                st.write(f"Found {len(pubmed_data['esearchresult']['idlist'])} results for '{search_term}':")
                for article_id in pubmed_data['esearchresult']['idlist']:
                  st.write(f"- PMID: {article_id}")
            else:
                st.write("No results found for that term.")

    st.header("Ontology Search")
    ontology_search_term = st.text_input("Enter Search query for Ontology:", placeholder="Enter disease or ontology")
    ontology_select = st.selectbox("Select Ontology", ["MESH","NCIT","GO", "SNOMEDCT"])
    if st.button("Search BioPortal"):
        with st.spinner("Searching Ontology..."):
            bioportal_data = _get_bioportal_data(ontology_select, ontology_search_term)
            if bioportal_data and 'collection' in bioportal_data:
                st.subheader(f"BioPortal Search Results for {ontology_select}")
                for result in bioportal_data['collection']:
                    st.write(f"- {result['prefLabel']} ({result['@id']})")
            else:
                st.write("No results found")