File size: 22,465 Bytes
347e5b4 92ff582 c734a36 d35b5b6 300a38a 07c450c 92ff582 347e5b4 92ff582 347e5b4 300a38a 92ff582 347e5b4 92ff582 300a38a 347e5b4 92ff582 b294de4 0d4f109 300a38a 0d4f109 347e5b4 300a38a 347e5b4 300a38a 347e5b4 92ff582 347e5b4 300a38a 92ff582 0d4f109 300a38a 347e5b4 300a38a 347e5b4 300a38a 347e5b4 300a38a 347e5b4 300a38a c734a36 92ff582 c734a36 92ff582 347e5b4 300a38a 347e5b4 300a38a 347e5b4 300a38a 347e5b4 300a38a 347e5b4 300a38a 347e5b4 300a38a 347e5b4 300a38a 347e5b4 300a38a 347e5b4 300a38a 92ff582 347e5b4 92ff582 347e5b4 92ff582 347e5b4 300a38a 347e5b4 300a38a 347e5b4 300a38a 347e5b4 92ff582 347e5b4 92ff582 347e5b4 300a38a 347e5b4 300a38a 347e5b4 c88dd17 c734a36 92ff582 c734a36 92ff582 347e5b4 92ff582 300a38a 347e5b4 92ff582 347e5b4 300a38a 347e5b4 300a38a 347e5b4 300a38a 347e5b4 300a38a 347e5b4 300a38a 347e5b4 300a38a 347e5b4 300a38a 347e5b4 300a38a 347e5b4 300a38a 347e5b4 300a38a 347e5b4 300a38a 92ff582 347e5b4 92ff582 300a38a 347e5b4 300a38a 347e5b4 300a38a 92ff582 347e5b4 300a38a 347e5b4 300a38a 347e5b4 300a38a 347e5b4 c4afc76 c734a36 92ff582 c734a36 92ff582 347e5b4 92ff582 300a38a 347e5b4 92ff582 347e5b4 92ff582 347e5b4 c734a36 347e5b4 c734a36 0d096e5 300a38a 347e5b4 300a38a 347e5b4 c734a36 347e5b4 92ff582 347e5b4 300a38a 347e5b4 c734a36 92ff582 0d096e5 347e5b4 92ff582 347e5b4 92ff582 347e5b4 0d096e5 92ff582 300a38a 92ff582 300a38a 92ff582 347e5b4 92ff582 347e5b4 92ff582 300a38a 347e5b4 92ff582 300a38a 347e5b4 92ff582 300a38a 347e5b4 92ff582 347e5b4 92ff582 347e5b4 92ff582 347e5b4 92ff582 347e5b4 92ff582 347e5b4 92ff582 347e5b4 92ff582 300a38a 347e5b4 92ff582 347e5b4 92ff582 347e5b4 92ff582 300a38a 347e5b4 300a38a 347e5b4 92ff582 347e5b4 92ff582 347e5b4 92ff582 347e5b4 92ff582 347e5b4 62a6d51 c734a36 0d096e5 347e5b4 |
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 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 |
# -----------------------------
# IMPORTS & CONFIGURATION
# -----------------------------
import streamlit as st
import requests
from rdkit import Chem
from rdkit.Chem import Draw
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from fpdf import FPDF
import tempfile
import logging
import os
import plotly.graph_objects as go
import networkx as nx
from typing import Optional, Dict, List, Any, Tuple
from openai import OpenAI
# Advanced logging configuration: capturing detailed operational logs for debugging and audit trails.
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("pris_debug.log", mode='w'),
logging.StreamHandler()
]
)
logger = logging.getLogger("PRIS")
# -----------------------------
# GLOBAL CONSTANTS
# -----------------------------
API_ENDPOINTS: Dict[str, str] = {
# Clinical Data Services
"clinical_trials": "https://clinicaltrials.gov/api/v2/studies",
"fda_drug_approval": "https://api.fda.gov/drug/label.json",
"faers_adverse_events": "https://api.fda.gov/drug/event.json",
# Chemical & Biological Data
"pubchem": "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/{}/JSON",
"pubmed": "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi",
# Pharmacogenomics Resources
"pharmgkb_variant_clinical_annotations": "https://api.pharmgkb.org/v1/data/variant/{}/clinicalAnnotations",
"pharmgkb_gene": "https://api.pharmgkb.org/v1/data/gene/{}",
"pharmgkb_gene_variants": "https://api.pharmgkb.org/v1/data/gene/{}/variants",
# Semantic Medical Resources
"bioportal_search": "https://data.bioontology.org/search",
# Drug Classification Systems
"rxnorm_rxcui": "https://rxnav.nlm.nih.gov/REST/rxcui.json",
"rxnorm_properties": "https://rxnav.nlm.nih.gov/REST/rxcui/{}/properties.json",
"rxclass_by_drug": "https://rxnav.nlm.nih.gov/REST/class/byDrugName.json"
}
DEFAULT_HEADERS: Dict[str, str] = {
"User-Agent": "PharmaResearchIntelligenceSuite/1.0 (Professional Use)",
"Accept": "application/json"
}
# -----------------------------
# SECRETS MANAGEMENT
# -----------------------------
class APIConfigurationError(Exception):
"""Custom exception for missing or misconfigured API credentials."""
pass
try:
# Retrieve API credentials from the secure Streamlit secrets store.
OPENAI_API_KEY: str = st.secrets["OPENAI_API_KEY"]
BIOPORTAL_API_KEY: str = st.secrets["BIOPORTAL_API_KEY"]
PUB_EMAIL: str = st.secrets["PUB_EMAIL"]
OPENFDA_KEY: str = st.secrets["OPENFDA_KEY"]
# Ensure that all essential API keys are present.
if not all([OPENAI_API_KEY, BIOPORTAL_API_KEY, PUB_EMAIL, OPENFDA_KEY]):
raise APIConfigurationError("One or more required API credentials are missing.")
except (KeyError, APIConfigurationError) as e:
st.error(f"Critical configuration error: {str(e)}")
logger.critical(f"Configuration error: {str(e)}")
st.stop()
# -----------------------------
# CORE INFRASTRUCTURE
# -----------------------------
class PharmaResearchEngine:
"""
Core engine for integrating and analyzing pharmaceutical data.
This engine provides utility functions for API requests and chemical data extraction,
facilitating the seamless integration of multi-omics and clinical datasets.
"""
def __init__(self) -> None:
# Initialize the OpenAI client with the provided API key.
self.openai_client = OpenAI(api_key=OPENAI_API_KEY)
logger.info("PharmaResearchEngine initialized with OpenAI client.")
@staticmethod
def api_request(endpoint: str,
params: Optional[Dict[str, Any]] = None,
headers: Optional[Dict[str, str]] = None) -> Optional[Dict[str, Any]]:
"""
Perform a resilient API GET request.
Args:
endpoint (str): The URL endpoint for the API.
params (Optional[Dict[str, Any]]): Query parameters to be included in the request.
headers (Optional[Dict[str, str]]): Additional headers to include in the request.
Returns:
Optional[Dict[str, Any]]: JSON response from the API, or None if an error occurs.
"""
try:
logger.debug(f"Requesting data from {endpoint} with params: {params}")
response = requests.get(
endpoint,
params=params,
headers={**DEFAULT_HEADERS, **(headers or {})},
timeout=(3.05, 15)
)
response.raise_for_status()
logger.info(f"Successful API request to {endpoint}")
return response.json()
except requests.exceptions.HTTPError as http_err:
logger.error(f"HTTP Error {http_err.response.status_code} for {endpoint}: {http_err}")
st.error(f"API HTTP Error: {http_err.response.status_code} - {http_err.response.reason}")
except Exception as e:
logger.error(f"Network error during API request to {endpoint}: {str(e)}")
st.error(f"Network error: {str(e)}")
return None
def get_compound_profile(self, identifier: str) -> Optional[Dict[str, str]]:
"""
Retrieve a comprehensive chemical profile for a given compound.
This method queries the PubChem API using a provided identifier (name or SMILES)
and extracts key molecular properties.
Args:
identifier (str): The compound name or SMILES string.
Returns:
Optional[Dict[str, str]]: A dictionary containing molecular formula, IUPAC name,
canonical SMILES, molecular weight, and LogP. Returns None if data is unavailable.
"""
formatted_endpoint = API_ENDPOINTS["pubchem"].format(identifier)
logger.info(f"Fetching compound profile from PubChem for identifier: {identifier}")
pubchem_data = self.api_request(formatted_endpoint)
if not pubchem_data or not pubchem_data.get("PC_Compounds"):
logger.warning("No compound data found in PubChem response.")
return None
compound = pubchem_data["PC_Compounds"][0]
profile = {
'molecular_formula': self._extract_property(compound, 'Molecular Formula'),
'iupac_name': self._extract_property(compound, 'IUPAC Name'),
'canonical_smiles': self._extract_property(compound, 'Canonical SMILES'),
'molecular_weight': self._extract_property(compound, 'Molecular Weight'),
'logp': self._extract_property(compound, 'LogP')
}
logger.debug(f"Extracted compound profile: {profile}")
return profile
def _extract_property(self, compound: Dict[str, Any], prop_name: str) -> str:
"""
Helper function to extract a specific property from PubChem compound data.
Args:
compound (Dict[str, Any]): The compound data dictionary from PubChem.
prop_name (str): The name of the property to extract.
Returns:
str: The extracted property value as a string, or "N/A" if not found.
"""
for prop in compound.get("props", []):
if prop.get("urn", {}).get("label") == prop_name:
# Attempt to return the string value regardless of underlying type.
return str(prop["value"].get("sval", "N/A"))
logger.debug(f"Property '{prop_name}' not found for compound.")
return "N/A"
# -----------------------------
# INTELLIGENCE MODULES
# -----------------------------
class ClinicalIntelligence:
"""
Module for analyzing clinical trial landscapes and regulatory data.
This class encapsulates methods for retrieving and processing clinical trial data
and FDA drug approval information.
"""
def __init__(self) -> None:
self.engine = PharmaResearchEngine()
logger.info("ClinicalIntelligence module initialized.")
def get_trial_landscape(self, query: str) -> List[Dict[str, Any]]:
"""
Analyze the clinical trial landscape for a specified query.
Args:
query (str): A search term (condition, intervention, or NCT number) for clinical trials.
Returns:
List[Dict[str, Any]]: A list of dictionaries representing the top clinical trials.
"""
# Determine appropriate parameters based on query format.
params = {"query.term": query, "retmax": 10} if not query.startswith("NCT") else {"id": query}
logger.info(f"Fetching clinical trials with query: {query}")
trials = self.engine.api_request(API_ENDPOINTS["clinical_trials"], params=params)
# Safely extract and return up to the first 5 trials.
trial_list = trials.get("studies", [])[:5] if trials else []
logger.debug(f"Retrieved {len(trial_list)} clinical trials for query '{query}'")
return trial_list
def get_fda_approval(self, drug_name: str) -> Optional[Dict[str, Any]]:
"""
Retrieve FDA approval information for a specified drug.
Args:
drug_name (str): The name of the drug to query.
Returns:
Optional[Dict[str, Any]]: A dictionary containing FDA approval details or None if unavailable.
"""
if not OPENFDA_KEY:
st.error("OpenFDA API key not configured.")
logger.error("Missing OpenFDA API key.")
return None
params: Dict[str, Any] = {
"api_key": OPENFDA_KEY,
"search": f'openfda.brand_name:"{drug_name}"',
"limit": 1
}
logger.info(f"Fetching FDA approval data for drug: {drug_name}")
data = self.engine.api_request(API_ENDPOINTS["fda_drug_approval"], params=params)
if data and data.get("results"):
logger.debug(f"FDA approval data retrieved for drug: {drug_name}")
return data["results"][0]
logger.warning(f"No FDA approval data found for drug: {drug_name}")
return None
class AIDrugInnovator:
"""
AI-Driven Drug Development Strategist powered by GPT-4.
This module leverages advanced language models to generate innovative drug development
strategies tailored to specific targets and therapeutic paradigms.
"""
def __init__(self) -> None:
self.engine = PharmaResearchEngine()
logger.info("AIDrugInnovator module initialized with GPT-4 integration.")
def generate_strategy(self, target: str, strategy: str) -> str:
"""
Generate an AI-driven development strategy.
Constructs a detailed prompt for GPT-4 to generate a strategic plan including
target validation, lead optimization, clinical trial design, regulatory analysis,
and commercial potential assessment.
Args:
target (str): The target disease, pathway, or biological entity.
strategy (str): The desired development paradigm (e.g., "First-in-class").
Returns:
str: A formatted strategic blueprint in Markdown.
"""
prompt: str = (
f"As Chief Scientific Officer at a leading pharmaceutical company, "
f"develop a {strategy} development strategy for the target: {target}.\n\n"
"Include the following sections:\n"
"- **Target Validation Approach:** Describe methods to confirm the target's role in the disease.\n"
"- **Lead Optimization Tactics:** Outline strategies for refining lead compounds.\n"
"- **Clinical Trial Design:** Propose innovative trial designs and endpoints.\n"
"- **Regulatory Pathway Analysis:** Evaluate the regulatory strategy and compliance roadmap.\n"
"- **Commercial Potential Assessment:** Analyze market opportunity and competitive landscape.\n\n"
"Please format your response in Markdown with clear, well-defined sections."
)
logger.info(f"Generating AI strategy for target: {target} using paradigm: {strategy}")
try:
response = self.engine.openai_client.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": prompt}],
temperature=0.7,
max_tokens=1500
)
generated_strategy = response.choices[0].message.content
logger.debug("AI strategy generation successful.")
return generated_strategy
except Exception as e:
logger.error(f"Error during AI strategy generation: {str(e)}")
return "Strategy generation failed. Please check API configuration and try again."
# -----------------------------
# STREAMLIT INTERFACE
# -----------------------------
class PharmaResearchInterface:
"""
User Interface for the Pharma Research Intelligence Suite.
This class configures and renders the Streamlit application, providing an interactive
environment for exploring drug innovation, clinical trial analytics, compound profiling,
regulatory insights, and AI-driven strategy generation.
"""
def __init__(self) -> None:
self.clinical_intel = ClinicalIntelligence()
self.ai_innovator = AIDrugInnovator()
self._configure_page()
logger.info("PharmaResearchInterface initialized and page configured.")
def _configure_page(self) -> None:
"""
Configure the Streamlit page settings and apply custom CSS styles.
"""
st.set_page_config(
page_title="PRIS - Pharma Research Intelligence Suite",
layout="wide",
initial_sidebar_state="expanded"
)
st.markdown("""
<style>
.main {background-color: #f9f9f9; padding: 20px;}
.stAlert {padding: 20px; border: 1px solid #e0e0e0; border-radius: 5px; background-color: #fff;}
.reportview-container .markdown-text-container {font-family: 'Arial', sans-serif; line-height: 1.6;}
</style>
""", unsafe_allow_html=True)
logger.info("Streamlit page configuration completed.")
def render(self) -> None:
"""
Render the complete Streamlit user interface with multiple functional tabs.
"""
st.title("Pharma Research Intelligence Suite")
self._render_navigation()
logger.info("User interface rendered successfully.")
def _render_navigation(self) -> None:
"""
Create a dynamic, tab-based navigation layout for different modules.
"""
tabs = st.tabs([
"π Drug Innovation",
"π Trial Analytics",
"π§ͺ Compound Profiler",
"π Regulatory Hub",
"π€ AI Strategist"
])
with tabs[0]:
self._drug_innovation()
with tabs[1]:
self._trial_analytics()
with tabs[2]:
self._compound_profiler()
with tabs[3]:
self._regulatory_hub()
with tabs[4]:
self._ai_strategist()
def _drug_innovation(self) -> None:
"""
Render the drug innovation module that generates AI-powered development strategies.
"""
st.header("AI-Powered Drug Innovation Engine")
col1, col2 = st.columns([1, 3])
with col1:
target = st.text_input("Target Pathobiology:", placeholder="e.g., EGFR mutant NSCLC")
strategy = st.selectbox("Development Paradigm:",
["First-in-class", "Fast-follower", "Biologic", "ADC", "Gene Therapy"])
if st.button("Generate Development Blueprint"):
with st.spinner("Formulating strategic plan..."):
blueprint = self.ai_innovator.generate_strategy(target, strategy)
st.markdown(blueprint, unsafe_allow_html=True)
logger.info("Drug innovation strategy generated and displayed.")
def _trial_analytics(self) -> None:
"""
Render the clinical trial analytics module to explore current trial landscapes.
"""
st.header("Clinical Trial Landscape Analysis")
trial_query = st.text_input("Search Clinical Trials:", placeholder="Enter condition, intervention, or NCT number")
if st.button("Analyze Trial Landscape"):
with st.spinner("Fetching trial data..."):
trials = self.clinical_intel.get_trial_landscape(trial_query)
if trials:
st.subheader("Top 5 Clinical Trials")
trial_data: List[Dict[str, Any]] = []
for study in trials:
trial_data.append({
"Title": study.get("protocolSection", {}).get("identificationModule", {}).get("briefTitle", "N/A"),
"Status": study.get("protocolSection", {}).get("statusModule", {}).get("overallStatus", "N/A"),
"Phase": study.get("protocolSection", {}).get("designModule", {}).get("phases", ["N/A"])[0],
"Enrollment": study.get("protocolSection", {}).get("designModule", {}).get("enrollmentInfo", {}).get("count", "N/A")
})
# Display the clinical trial data in a table.
df = pd.DataFrame(trial_data)
st.dataframe(df)
# Generate and display a bar chart of trial phase distribution.
st.subheader("Trial Phase Distribution")
phase_counts = df["Phase"].value_counts()
fig, ax = plt.subplots()
sns.barplot(x=phase_counts.index, y=phase_counts.values, ax=ax)
ax.set_xlabel("Trial Phase")
ax.set_ylabel("Number of Trials")
st.pyplot(fig)
logger.info("Clinical trial analytics displayed successfully.")
else:
st.warning("No clinical trials found for the query.")
logger.warning("No clinical trial data returned from API.")
def _compound_profiler(self) -> None:
"""
Render the multi-omics compound profiler module for in-depth chemical analysis.
"""
st.header("Multi-Omics Compound Profiler")
compound = st.text_input("Analyze Compound:", placeholder="Enter drug name or SMILES")
if compound:
with st.spinner("Decoding molecular profile..."):
profile = PharmaResearchEngine().get_compound_profile(compound)
if profile:
col1, col2 = st.columns(2)
with col1:
st.subheader("Structural Insights")
mol = Chem.MolFromSmiles(profile['canonical_smiles'])
if mol:
# Generate and display the 2D molecular structure image.
img = Draw.MolToImage(mol, size=(400, 300))
st.image(img, caption="2D Molecular Structure")
else:
st.warning("Unable to render molecular structure from SMILES.")
logger.warning("RDKit failed to create molecule from SMILES.")
with col2:
st.subheader("Physicochemical Profile")
st.metric("Molecular Weight", profile['molecular_weight'])
st.metric("LogP", profile['logp'])
st.metric("IUPAC Name", profile['iupac_name'])
st.code(f"SMILES: {profile['canonical_smiles']}")
logger.info("Compound profile details rendered.")
else:
st.warning("No compound data available. Please verify the input.")
logger.warning("Compound profiler did not return any data.")
def _regulatory_hub(self) -> None:
"""
Render the regulatory intelligence hub module for accessing FDA and regulatory data.
"""
st.header("Regulatory Intelligence Hub")
st.write("Access detailed insights into FDA approvals and regulatory pathways.")
drug_name = st.text_input("Enter Drug Name for Regulatory Analysis:", placeholder="e.g., aspirin")
if st.button("Fetch Regulatory Data"):
with st.spinner("Retrieving regulatory information..."):
fda_data = self.clinical_intel.get_fda_approval(drug_name)
if fda_data:
st.subheader("FDA Approval Details")
st.json(fda_data)
logger.info("FDA regulatory data displayed.")
else:
st.warning("No FDA data found for the specified drug.")
logger.warning("FDA regulatory data retrieval returned no results.")
def _ai_strategist(self) -> None:
"""
Render the AI strategist module for generating innovative drug development strategies.
"""
st.header("AI Drug Development Strategist")
st.write("Utilize GPT-4 to craft cutting-edge drug development strategies.")
target = st.text_input("Enter Target Disease or Pathway:", placeholder="e.g., KRAS G12C mutation")
if st.button("Generate AI Strategy"):
with st.spinner("Generating AI-driven strategy..."):
strategy = self.ai_innovator.generate_strategy(target, "First-in-class")
st.markdown(strategy, unsafe_allow_html=True)
logger.info("AI-driven strategy generated and displayed.")
# -----------------------------
# MAIN EXECUTION
# -----------------------------
if __name__ == "__main__":
try:
interface = PharmaResearchInterface()
interface.render()
logger.info("PRIS application launched successfully.")
except Exception as e:
logger.critical(f"Unexpected error during application launch: {str(e)}")
st.error(f"Application failed to start due to an unexpected error: {str(e)}")
|