mgbam commited on
Commit
0d4f109
·
verified ·
1 Parent(s): f036b96

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +183 -128
app.py CHANGED
@@ -3,15 +3,15 @@
3
  # -----------------------------
4
  import streamlit as st
5
  import requests
 
 
6
  import pandas as pd
7
  import matplotlib.pyplot as plt
8
  import seaborn as sns
9
  import logging
10
  import re
11
- import time
12
- from rdkit import Chem
13
- from rdkit.Chem import Draw
14
- from bs4 import BeautifulSoup # For future scraping implementations if needed
15
 
16
  # Configure advanced logging for full traceability and diagnostics
17
  logging.basicConfig(
@@ -22,79 +22,109 @@ logging.basicConfig(
22
  logger = logging.getLogger("PRIS")
23
 
24
  # -----------------------------
25
- # FALLBACK / SCRAPED DATA
26
  # -----------------------------
27
- # Fallback data for compound profiling (e.g., scraped or cached data)
28
- FALLBACK_COMPOUND_DATA = {
29
- "aspirin": {
30
- "molecular_formula": "C9H8O4",
31
- "iupac_name": "2-acetoxybenzoic acid",
32
- "canonical_smiles": "CC(=O)OC1=CC=CC=C1C(=O)O", # Valid SMILES for Aspirin
33
- "molecular_weight": "180.16",
34
- "logp": "N/A"
35
- }
36
  }
37
 
38
- # Fallback clinical trial data (e.g., sample scraped data)
39
- FALLBACK_CLINICAL_DATA = {
40
- "nct1": [
41
- {
42
- "Title": "A Study of Novel Therapeutics in Diabetes",
43
- "Status": "Completed",
44
- "Phase": "Phase II",
45
- "Enrollment": "120"
46
- }
47
- ]
48
  }
49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  # -----------------------------
51
  # CORE INFRASTRUCTURE
52
  # -----------------------------
53
  class PharmaResearchEngine:
54
- """
55
- Core engine for integrating pharmaceutical datasets using fallback/scraped data.
56
- No external APIs are required; fallback data is used instead.
57
- """
58
 
59
  def __init__(self):
60
- # In a production environment, this is where an AI client would be initialized.
61
- pass
62
-
63
- def api_request(self, endpoint: str, params: dict = None, headers: dict = None) -> dict:
 
 
64
  """
65
- Dummy API request handler. In this implementation, live API calls are bypassed.
66
- Instead, the method always returns an empty dictionary.
67
  """
68
- logger.info(f"Simulated API request to {endpoint} with params {params}")
69
- # Simulate a network delay
70
- time.sleep(0.5)
71
- return {} # Always empty because no API is actually used
 
 
 
 
 
 
 
 
 
 
 
 
72
 
73
- def get_compound_profile(self, identifier: str) -> dict:
74
  """
75
- Retrieve a comprehensive compound profile.
76
- This function first checks if the input is valid, then returns fallback data.
77
  """
78
  if not self._is_valid_compound_input(identifier):
79
  msg = (f"The input '{identifier}' appears to reference a disease term rather than a chemical compound. "
80
  "For disease-related inquiries, please use the Clinical Trial Analytics module.")
81
  logger.warning(msg)
82
  st.error(msg)
83
- return {}
84
 
85
- # Attempt simulated API call (which in this case does nothing)
86
- pubchem_data = self.api_request("https://pubchem.fakeendpoint/rest/pug/compound/name/{}/JSON".format(identifier))
87
-
88
- # If no data is returned from API simulation, use fallback scraped data
89
- if identifier.lower() in FALLBACK_COMPOUND_DATA:
90
- logger.info(f"Using fallback data for compound '{identifier}'.")
91
- return FALLBACK_COMPOUND_DATA[identifier.lower()]
92
- else:
93
- logger.warning(f"No compound data found for '{identifier}'.")
94
  st.error("No compound data found. Please verify your input (e.g., check for typos or use a recognized compound name).")
95
- return {}
 
 
 
 
 
 
 
 
 
96
 
97
- def _is_valid_compound_input(self, user_input: str) -> bool:
 
 
 
 
 
 
 
 
98
  """
99
  Determines whether the user input is a valid chemical compound identifier.
100
  Accepts both conventional compound names and SMILES strings.
@@ -106,11 +136,11 @@ class PharmaResearchEngine:
106
  if any(term in input_lower for term in disease_terms):
107
  return False
108
 
109
- # Check for SMILES-specific characters (e.g., '=', '(', ')', '#')
110
  if re.search(r"[=\(\)#]", user_input):
111
  return True
112
 
113
- # If input is alphanumeric (with spaces or hyphens), assume it's a valid compound name.
114
  if re.match(r'^[A-Za-z0-9\s\-]+$', user_input):
115
  return True
116
 
@@ -121,79 +151,94 @@ class PharmaResearchEngine:
121
  # -----------------------------
122
  class ClinicalIntelligence:
123
  """
124
- Module for clinical trial and regulatory intelligence using fallback data.
 
125
  """
126
 
127
  def __init__(self):
128
  self.engine = PharmaResearchEngine()
129
 
130
- def get_trial_landscape(self, query: str) -> list:
131
- """
132
- Retrieve clinical trial information using fallback data.
133
- If the query matches a known identifier, return fallback data.
134
- """
135
- # Simulate API call (which always fails in this offline mode)
136
- trials = self.engine.api_request("https://clinicaltrials.fakeendpoint/api", params={"query": query})
137
-
138
- # Use fallback data if the query (e.g., "nct1") exists in our fallback dataset.
139
- key = query.lower().strip()
140
- if key in FALLBACK_CLINICAL_DATA:
141
- logger.info(f"Using fallback clinical trial data for query '{query}'.")
142
- return FALLBACK_CLINICAL_DATA[key]
143
- else:
144
- logger.error(f"No clinical trial data available for query '{query}'.")
145
  st.error("Failed to retrieve clinical trials. Please try a different query or check your network connection.")
146
  return []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
 
148
  class AIDrugInnovator:
149
  """
150
- Simulated AI module for generating drug development strategies.
151
- In this offline mode, a pre-defined strategy is returned.
152
  """
153
 
154
  def __init__(self):
155
  self.engine = PharmaResearchEngine()
156
 
157
  def generate_strategy(self, target: str, strategy: str) -> str:
158
- """
159
- Return a robust, pre-defined strategic blueprint for drug development.
160
- """
161
- # Here, we simulate the GPT-4 response with a comprehensive text.
162
- simulated_response = f"""
163
- # First-in-Class Strategy for {target.title()}
 
164
 
165
- ## Target Validation Approach
166
- - **Literature Review:** Perform an exhaustive review to understand the molecular underpinnings of {target}.
167
- - **Preclinical Models:** Validate targets using state-of-the-art in vitro and in vivo models.
168
- - **Omics Integration:** Leverage genomic, proteomic, and metabolomic data to pinpoint actionable targets.
169
- - **Collaborative Research:** Engage with leading academic and clinical institutions for validation.
170
 
171
- ## Lead Optimization Tactics
172
- - **Chemical Optimization:** Refine lead compounds to improve potency, selectivity, and pharmacokinetic profiles.
173
- - **High-Throughput Screening:** Utilize cutting-edge assays for iterative lead refinement.
174
- - **In Vivo Efficacy:** Conduct rigorous animal studies to assess efficacy and safety.
175
- - **Patent Strategy:** Secure intellectual property with comprehensive patent landscaping.
 
176
 
177
- ## Clinical Trial Design
178
- - **Phase I:** Safety and dosage trials with a focus on pharmacodynamics.
179
- - **Phase II:** Efficacy and side-effect profiling in an expanded cohort.
180
- - **Phase III:** Large-scale trials comparing with the current standard of care.
181
- - **Phase IV:** Post-marketing surveillance for long-term outcomes.
182
- - **Adaptive Designs:** Employ adaptive and basket trial designs to optimize trial efficiency.
183
 
184
- ## Regulatory Pathway Analysis
185
- - **Pre-IND Consultation:** Early engagement with regulatory bodies to align on requirements.
186
- - **IND Preparation:** Develop robust IND submissions incorporating all preclinical data.
187
- - **Continuous Dialogue:** Maintain proactive communication with regulators throughout development.
188
- - **Expedited Programs:** Explore Fast Track and Breakthrough Therapy designations.
189
 
190
- ## Commercial Potential Assessment
191
- - **Market Research:** Conduct deep-dive analyses into market size, competition, and unmet needs.
192
- - **Patient Segmentation:** Identify target patient populations for tailored therapeutic approaches.
193
- - **Pricing & Reimbursement:** Develop dynamic pricing strategies and secure payer alignment.
194
- - **Go-To-Market:** Formulate a comprehensive multi-channel marketing strategy.
195
- """
196
- return simulated_response
 
 
 
 
 
 
197
 
198
  # -----------------------------
199
  # STREAMLIT INTERFACE
@@ -201,13 +246,12 @@ class AIDrugInnovator:
201
  class PharmaResearchInterface:
202
  """
203
  Next-generation Streamlit interface for the Pharma Research Intelligence Suite.
204
- Uses fallback and scraped data to simulate a fully operational research platform.
205
  """
206
 
207
  def __init__(self):
208
  self.clinical_intel = ClinicalIntelligence()
209
  self.ai_innovator = AIDrugInnovator()
210
- self.engine = PharmaResearchEngine()
211
  self._configure_page()
212
 
213
  def _configure_page(self):
@@ -218,8 +262,8 @@ class PharmaResearchInterface:
218
  )
219
  st.markdown("""
220
  <style>
221
- .main {background-color: #f0f2f6; padding: 20px;}
222
- .stAlert {padding: 20px; font-size: 1.1em;}
223
  .reportview-container .markdown-text-container {font-family: 'Helvetica Neue', Arial, sans-serif}
224
  </style>
225
  """, unsafe_allow_html=True)
@@ -252,7 +296,8 @@ class PharmaResearchInterface:
252
  col1, col2 = st.columns([1, 3])
253
  with col1:
254
  target = st.text_input("Target Pathobiology:", placeholder="e.g., EGFR mutant NSCLC")
255
- strategy = st.selectbox("Development Paradigm:", ["First-in-class", "Fast-follower", "Biologic", "ADC", "Gene Therapy"])
 
256
  if st.button("Generate Development Blueprint"):
257
  with st.spinner("Formulating strategic plan..."):
258
  blueprint = self.ai_innovator.generate_strategy(target, strategy)
@@ -265,8 +310,20 @@ class PharmaResearchInterface:
265
  with st.spinner("Fetching trial data..."):
266
  trials = self.clinical_intel.get_trial_landscape(trial_query)
267
  if trials:
268
- st.subheader("Top Clinical Trials")
269
- df = pd.DataFrame(trials)
 
 
 
 
 
 
 
 
 
 
 
 
270
  st.dataframe(df)
271
  st.subheader("Trial Phase Distribution")
272
  phase_counts = df["Phase"].value_counts()
@@ -283,13 +340,13 @@ class PharmaResearchInterface:
283
  compound = st.text_input("Analyze Compound:", placeholder="Enter drug name or SMILES (e.g., Aspirin, CC(=O)OC1=CC=CC=C1C(=O)O)")
284
  if st.button("Profile Compound"):
285
  with st.spinner("Decoding molecular profile..."):
286
- profile = self.engine.get_compound_profile(compound)
287
  if profile:
288
  col1, col2 = st.columns(2)
289
  with col1:
290
  st.subheader("Structural Insights")
291
  smiles = profile.get('canonical_smiles', '')
292
- mol = Chem.MolFromSmiles(smiles) if smiles and smiles != "N/A" else None
293
  if mol:
294
  img = Draw.MolToImage(mol, size=(400, 300))
295
  st.image(img, caption="2D Molecular Structure")
@@ -306,22 +363,20 @@ class PharmaResearchInterface:
306
 
307
  def _regulatory_hub(self):
308
  st.header("Regulatory Intelligence Hub")
309
- st.write("Gain insights into FDA approvals and regulatory pathways (using local sample data).")
310
  drug_name = st.text_input("Enter Drug Name for Regulatory Analysis:", placeholder="e.g., Aspirin")
311
  if st.button("Fetch Regulatory Data"):
312
- # Since no API is available, we simulate regulatory data.
313
- sample_regulatory_data = {
314
- "drug_name": drug_name,
315
- "approval_status": "Approved",
316
- "approval_date": "1985-07-01",
317
- "label": "Sample regulatory label information."
318
- }
319
- st.subheader("FDA Approval Details")
320
- st.json(sample_regulatory_data)
321
 
322
  def _ai_strategist(self):
323
  st.header("AI Drug Development Strategist")
324
- st.write("Leverage simulated GPT-4 to generate cutting-edge drug development strategies.")
325
  target = st.text_input("Enter Target Disease or Pathway:", placeholder="e.g., KRAS G12C mutation")
326
  if st.button("Generate AI Strategy"):
327
  with st.spinner("Generating AI-driven strategy..."):
@@ -333,4 +388,4 @@ class PharmaResearchInterface:
333
  # -----------------------------
334
  if __name__ == "__main__":
335
  interface = PharmaResearchInterface()
336
- interface.render()
 
3
  # -----------------------------
4
  import streamlit as st
5
  import requests
6
+ from rdkit import Chem
7
+ from rdkit.Chem import Draw
8
  import pandas as pd
9
  import matplotlib.pyplot as plt
10
  import seaborn as sns
11
  import logging
12
  import re
13
+ from typing import Optional, Dict, List, Any
14
+ from openai import OpenAI
 
 
15
 
16
  # Configure advanced logging for full traceability and diagnostics
17
  logging.basicConfig(
 
22
  logger = logging.getLogger("PRIS")
23
 
24
  # -----------------------------
25
+ # GLOBAL CONSTANTS
26
  # -----------------------------
27
+ API_ENDPOINTS = {
28
+ "clinical_trials": "https://clinicaltrials.gov/api/v2/studies",
29
+ "fda_drug_approval": "https://api.fda.gov/drug/label.json",
30
+ "pubchem": "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/{}/JSON",
31
+ # ... other endpoints omitted for brevity ...
 
 
 
 
32
  }
33
 
34
+ DEFAULT_HEADERS = {
35
+ "User-Agent": "PharmaResearchIntelligenceSuite/1.0 (Professional Use)",
36
+ "Accept": "application/json"
 
 
 
 
 
 
 
37
  }
38
 
39
+ # -----------------------------
40
+ # SECRETS MANAGEMENT
41
+ # -----------------------------
42
+ class APIConfigurationError(Exception):
43
+ """Custom exception for missing API configurations."""
44
+ pass
45
+
46
+ try:
47
+ OPENAI_API_KEY = st.secrets["OPENAI_API_KEY"]
48
+ BIOPORTAL_API_KEY = st.secrets["BIOPORTAL_API_KEY"]
49
+ PUB_EMAIL = st.secrets["PUB_EMAIL"]
50
+ OPENFDA_KEY = st.secrets["OPENFDA_KEY"]
51
+
52
+ if not all([OPENAI_API_KEY, BIOPORTAL_API_KEY, PUB_EMAIL, OPENFDA_KEY]):
53
+ raise APIConfigurationError("One or more required API credentials are missing.")
54
+ except (KeyError, APIConfigurationError) as e:
55
+ st.error(f"Critical configuration error: {str(e)}")
56
+ st.stop()
57
+
58
  # -----------------------------
59
  # CORE INFRASTRUCTURE
60
  # -----------------------------
61
  class PharmaResearchEngine:
62
+ """Core engine for integrating diverse pharmaceutical datasets and performing advanced analyses."""
 
 
 
63
 
64
  def __init__(self):
65
+ self.openai_client = OpenAI(api_key=OPENAI_API_KEY)
66
+
67
+ @staticmethod
68
+ def api_request(endpoint: str,
69
+ params: Optional[Dict] = None,
70
+ headers: Optional[Dict] = None) -> Optional[Dict]:
71
  """
72
+ Enterprise-grade API request handler with detailed error logging.
 
73
  """
74
+ try:
75
+ response = requests.get(
76
+ endpoint,
77
+ params=params,
78
+ headers={**DEFAULT_HEADERS, **(headers or {})},
79
+ timeout=(3.05, 15)
80
+ )
81
+ response.raise_for_status() # Raises HTTPError for 4xx/5xx responses
82
+ return response.json()
83
+ except requests.exceptions.HTTPError as e:
84
+ logger.error(f"HTTP Error {e.response.status_code} for {endpoint} with params {params}")
85
+ st.error(f"API Error: {e.response.status_code} - {e.response.reason}")
86
+ except Exception as e:
87
+ logger.error(f"Network error for {endpoint}: {str(e)}")
88
+ st.error(f"Network error: {str(e)}")
89
+ return None
90
 
91
+ def get_compound_profile(self, identifier: str) -> Optional[Dict]:
92
  """
93
+ Retrieve comprehensive chemical profile data from PubChem for a given compound.
94
+ Accepts both common compound names and SMILES strings.
95
  """
96
  if not self._is_valid_compound_input(identifier):
97
  msg = (f"The input '{identifier}' appears to reference a disease term rather than a chemical compound. "
98
  "For disease-related inquiries, please use the Clinical Trial Analytics module.")
99
  logger.warning(msg)
100
  st.error(msg)
101
+ return None
102
 
103
+ pubchem_url = API_ENDPOINTS["pubchem"].format(identifier)
104
+ pubchem_data = self.api_request(pubchem_url)
105
+ if not pubchem_data or not pubchem_data.get("PC_Compounds"):
106
+ logger.warning(f"No compound data returned for identifier: {identifier}")
 
 
 
 
 
107
  st.error("No compound data found. Please verify your input (e.g., check for typos or use a recognized compound name).")
108
+ return None
109
+
110
+ compound = pubchem_data["PC_Compounds"][0]
111
+ return {
112
+ 'molecular_formula': self._extract_property(compound, 'Molecular Formula'),
113
+ 'iupac_name': self._extract_property(compound, 'IUPAC Name'),
114
+ 'canonical_smiles': self._extract_property(compound, 'Canonical SMILES'),
115
+ 'molecular_weight': self._extract_property(compound, 'Molecular Weight'),
116
+ 'logp': self._extract_property(compound, 'LogP')
117
+ }
118
 
119
+ def _extract_property(self, compound: Dict, prop_name: str) -> str:
120
+ """Helper to extract a specific property from PubChem compound data."""
121
+ for prop in compound.get("props", []):
122
+ if prop.get("urn", {}).get("label") == prop_name:
123
+ return prop["value"].get("sval", "N/A")
124
+ return "N/A"
125
+
126
+ @staticmethod
127
+ def _is_valid_compound_input(user_input: str) -> bool:
128
  """
129
  Determines whether the user input is a valid chemical compound identifier.
130
  Accepts both conventional compound names and SMILES strings.
 
136
  if any(term in input_lower for term in disease_terms):
137
  return False
138
 
139
+ # If the input contains characters common in SMILES (e.g., '=', '(', ')', '#'), treat as SMILES.
140
  if re.search(r"[=\(\)#]", user_input):
141
  return True
142
 
143
+ # Otherwise, if input is alphanumeric with spaces or hyphens, assume it's a valid compound name.
144
  if re.match(r'^[A-Za-z0-9\s\-]+$', user_input):
145
  return True
146
 
 
151
  # -----------------------------
152
  class ClinicalIntelligence:
153
  """
154
+ Module for clinical trial and regulatory intelligence.
155
+ Provides deep insights into trial landscapes and FDA approval data.
156
  """
157
 
158
  def __init__(self):
159
  self.engine = PharmaResearchEngine()
160
 
161
+ def get_trial_landscape(self, query: str) -> List[Dict]:
162
+ params = {"query.term": query, "retmax": 10} if not query.startswith("NCT") else {"id": query}
163
+ trials = self.engine.api_request(API_ENDPOINTS["clinical_trials"], params=params)
164
+ if trials is None:
165
+ logger.error(f"Clinical trial API returned no data for query: {query}")
 
 
 
 
 
 
 
 
 
 
166
  st.error("Failed to retrieve clinical trials. Please try a different query or check your network connection.")
167
  return []
168
+ return trials.get("studies", [])[:5]
169
+
170
+ def get_fda_approval(self, drug_name: str) -> Optional[Dict]:
171
+ if not OPENFDA_KEY:
172
+ st.error("OpenFDA API key not configured.")
173
+ return None
174
+
175
+ params = {
176
+ "api_key": OPENFDA_KEY,
177
+ "search": f'openfda.brand_name:"{drug_name}"',
178
+ "limit": 1
179
+ }
180
+ data = self.engine.api_request(API_ENDPOINTS["fda_drug_approval"], params=params)
181
+ if data and data.get("results"):
182
+ return data["results"][0]
183
+ logger.warning(f"No FDA data found for drug: {drug_name}")
184
+ st.error("No FDA regulatory data found for the specified drug.")
185
+ return None
186
 
187
  class AIDrugInnovator:
188
  """
189
+ GPT-4 powered module for generating advanced, cutting-edge drug development strategies.
 
190
  """
191
 
192
  def __init__(self):
193
  self.engine = PharmaResearchEngine()
194
 
195
  def generate_strategy(self, target: str, strategy: str) -> str:
196
+ prompt = f"""As the Chief Scientific Officer at a leading pharmaceutical company, please develop a {strategy} strategy for the target: {target}.
197
+
198
+ **Target Validation Approach**
199
+ - Perform an exhaustive literature review to understand the molecular basis of the disease.
200
+ - Validate targets using in vitro and in vivo models.
201
+ - Integrate genomic and proteomic data to identify actionable targets.
202
+ - Collaborate with top-tier academic and clinical institutions.
203
 
204
+ **Lead Optimization Tactics**
205
+ - Conduct chemical optimization to improve potency, selectivity, and pharmacokinetic properties.
206
+ - Utilize high-throughput screening and biological assays for iterative lead refinement.
207
+ - Perform rigorous in vivo efficacy and safety evaluations.
208
+ - Secure intellectual property through comprehensive patent landscaping.
209
 
210
+ **Clinical Trial Design**
211
+ - Initiate Phase I trials focused on safety and dosage determination.
212
+ - Scale to Phase II for efficacy and side-effect profiling in a broader patient cohort.
213
+ - Execute large-scale Phase III trials to validate clinical benefits against current standards of care.
214
+ - Plan for Phase IV post-marketing surveillance for long-term outcome assessment.
215
+ - Incorporate adaptive trial designs to enhance responsiveness and efficiency.
216
 
217
+ **Regulatory Pathway Analysis**
218
+ - Engage in early pre-IND consultations with regulatory authorities.
219
+ - Prepare robust IND submissions incorporating comprehensive preclinical data.
220
+ - Maintain continuous dialogue with regulators throughout clinical development.
221
+ - Strategize for expedited review pathways (e.g., Fast Track, Breakthrough Therapy).
 
222
 
223
+ **Commercial Potential Assessment**
224
+ - Conduct detailed market research to understand the competitive landscape and unmet needs.
225
+ - Segment patient populations to tailor therapeutic approaches.
226
+ - Devise dynamic pricing and reimbursement strategies aligned with payer requirements.
227
+ - Formulate a comprehensive go-to-market plan leveraging multi-channel marketing strategies.
228
 
229
+ Please format your response in Markdown with clear section headers."""
230
+ try:
231
+ response = self.engine.openai_client.chat.completions.create(
232
+ model="gpt-4",
233
+ messages=[{"role": "user", "content": prompt}],
234
+ temperature=0.7,
235
+ max_tokens=1500
236
+ )
237
+ return response.choices[0].message.content
238
+ except Exception as e:
239
+ logger.error(f"AI Strategy Generation Error: {str(e)}")
240
+ st.error("Failed to generate strategy. Please check the API configuration or try again later.")
241
+ return "Strategy generation failed due to an internal error."
242
 
243
  # -----------------------------
244
  # STREAMLIT INTERFACE
 
246
  class PharmaResearchInterface:
247
  """
248
  Next-generation Streamlit interface for the Pharma Research Intelligence Suite.
249
+ Provides an integrated, intuitive dashboard for advanced pharmaceutical data analytics and AI-driven strategy generation.
250
  """
251
 
252
  def __init__(self):
253
  self.clinical_intel = ClinicalIntelligence()
254
  self.ai_innovator = AIDrugInnovator()
 
255
  self._configure_page()
256
 
257
  def _configure_page(self):
 
262
  )
263
  st.markdown("""
264
  <style>
265
+ .main {background-color: #f0f2f6;}
266
+ .stAlert {padding: 20px;}
267
  .reportview-container .markdown-text-container {font-family: 'Helvetica Neue', Arial, sans-serif}
268
  </style>
269
  """, unsafe_allow_html=True)
 
296
  col1, col2 = st.columns([1, 3])
297
  with col1:
298
  target = st.text_input("Target Pathobiology:", placeholder="e.g., EGFR mutant NSCLC")
299
+ strategy = st.selectbox("Development Paradigm:",
300
+ ["First-in-class", "Fast-follower", "Biologic", "ADC", "Gene Therapy"])
301
  if st.button("Generate Development Blueprint"):
302
  with st.spinner("Formulating strategic plan..."):
303
  blueprint = self.ai_innovator.generate_strategy(target, strategy)
 
310
  with st.spinner("Fetching trial data..."):
311
  trials = self.clinical_intel.get_trial_landscape(trial_query)
312
  if trials:
313
+ st.subheader("Top 5 Clinical Trials")
314
+ trial_data = []
315
+ for study in trials:
316
+ title = study.get("protocolSection", {}).get("identificationModule", {}).get("briefTitle", "N/A")
317
+ status = study.get("protocolSection", {}).get("statusModule", {}).get("overallStatus", "N/A")
318
+ phase = study.get("protocolSection", {}).get("designModule", {}).get("phases", ["N/A"])[0]
319
+ enrollment = study.get("protocolSection", {}).get("designModule", {}).get("enrollmentInfo", {}).get("count", "N/A")
320
+ trial_data.append({
321
+ "Title": title,
322
+ "Status": status,
323
+ "Phase": phase,
324
+ "Enrollment": enrollment
325
+ })
326
+ df = pd.DataFrame(trial_data)
327
  st.dataframe(df)
328
  st.subheader("Trial Phase Distribution")
329
  phase_counts = df["Phase"].value_counts()
 
340
  compound = st.text_input("Analyze Compound:", placeholder="Enter drug name or SMILES (e.g., Aspirin, CC(=O)OC1=CC=CC=C1C(=O)O)")
341
  if st.button("Profile Compound"):
342
  with st.spinner("Decoding molecular profile..."):
343
+ profile = PharmaResearchEngine().get_compound_profile(compound)
344
  if profile:
345
  col1, col2 = st.columns(2)
346
  with col1:
347
  st.subheader("Structural Insights")
348
  smiles = profile.get('canonical_smiles', '')
349
+ mol = Chem.MolFromSmiles(smiles) if smiles != "N/A" else None
350
  if mol:
351
  img = Draw.MolToImage(mol, size=(400, 300))
352
  st.image(img, caption="2D Molecular Structure")
 
363
 
364
  def _regulatory_hub(self):
365
  st.header("Regulatory Intelligence Hub")
366
+ st.write("Gain insights into FDA approvals and regulatory pathways.")
367
  drug_name = st.text_input("Enter Drug Name for Regulatory Analysis:", placeholder="e.g., Aspirin")
368
  if st.button("Fetch Regulatory Data"):
369
+ with st.spinner("Retrieving regulatory information..."):
370
+ fda_data = self.clinical_intel.get_fda_approval(drug_name)
371
+ if fda_data:
372
+ st.subheader("FDA Approval Details")
373
+ st.json(fda_data)
374
+ else:
375
+ st.warning("No FDA regulatory data found for the specified drug.")
 
 
376
 
377
  def _ai_strategist(self):
378
  st.header("AI Drug Development Strategist")
379
+ st.write("Leverage GPT-4 to generate cutting-edge drug development strategies.")
380
  target = st.text_input("Enter Target Disease or Pathway:", placeholder="e.g., KRAS G12C mutation")
381
  if st.button("Generate AI Strategy"):
382
  with st.spinner("Generating AI-driven strategy..."):
 
388
  # -----------------------------
389
  if __name__ == "__main__":
390
  interface = PharmaResearchInterface()
391
+ interface.render()