Spaces:
Runtime error
Runtime error
File size: 7,369 Bytes
6b7b839 88eab90 6b7b839 1f3e394 6b7b839 88eab90 1f3e394 6b7b839 88eab90 b99baab 6d6c35e b99baab 6d6c35e b99baab 6d6c35e b99baab 1f3e394 6b7b839 88eab90 6b7b839 1f3e394 6b7b839 88eab90 6b7b839 6d6c35e 1f3e394 88eab90 6b7b839 88eab90 6b7b839 88eab90 6b7b839 1f3e394 88eab90 1f3e394 88eab90 1aa6589 1f3e394 88eab90 6d6c35e 88eab90 1f3e394 6d6c35e | 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 | """
Pharmaceutical Analytics Agentic AI Demo - Streamlit App
This is the main Streamlit application for the pharmaceutical analytics demo.
It initializes the environment and delegates page rendering to the page manager.
Usage (on Hugging Face):
The app runs automatically
Usage (locally):
streamlit run app.py
"""
import streamlit as st
import os
import sys
import time
from datetime import datetime
# Add current directory to path to ensure module imports work
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))
# Import page manager for modular UI
from page_manager import render_page
# Initialize environment
def setup_environment():
"""Setup the demo environment"""
st.sidebar.markdown("### Setting up environment...")
# Create directories
os.makedirs("data", exist_ok=True)
os.makedirs("agents", exist_ok=True)
os.makedirs("workflows", exist_ok=True)
os.makedirs("utils", exist_ok=True)
# Check for database file
db_path = "data/pharma_db.sqlite"
if not os.path.exists(db_path):
if st.session_state.get("initialization_attempted", False):
st.sidebar.warning("Previous initialization attempt failed. Check logs.")
return False
st.sidebar.info("Database not found. Generating synthetic data...")
st.session_state.initialization_attempted = True
try:
# Import needed modules
from data.schema import create_schema
from data.seed_data import create_seed_data
# Create schema first
create_schema(db_path)
st.sidebar.info("โ Database schema created")
# Add seed data
create_seed_data(db_path)
st.sidebar.info("โ Seed data created")
# Generate full synthetic dataset
from data.data_generator import generate_all_data
generate_all_data()
st.sidebar.success("โ Synthetic data generated successfully")
return True
except Exception as e:
st.sidebar.error(f"Error setting up environment: {e}")
return False
else:
st.sidebar.success("โ Database found")
return True
# Import our agents and workflow
@st.cache_resource
def initialize_agents():
"""Initialize agents and return status"""
try:
# We'll only import these modules when needed
from agents.planning_agent import PlanningAgent, AnalysisPlan
from agents.data_agent import DataAgent, DataRequest, DataSource
from agents.analytics_agent import AnalyticsAgent, AnalysisRequest, AnalysisResult
from agents.qa_agent import QAAgent, ValidationRequest, ValidationResult
from agents.insights_agent import InsightsAgent, InsightRequest, InsightCard
from workflows.sales_analysis import SalesAnalysisWorkflow, WorkflowState
return True, {
"PlanningAgent": PlanningAgent,
"DataAgent": DataAgent,
"AnalyticsAgent": AnalyticsAgent,
"QAAgent": QAAgent,
"InsightsAgent": InsightsAgent,
"SalesAnalysisWorkflow": SalesAnalysisWorkflow
}
except Exception as e:
return False, str(e)
# Configure Streamlit page
st.set_page_config(
page_title="Pharmaceutical Analytics AI",
page_icon="๐",
layout="wide",
initial_sidebar_state="expanded"
)
# Main application header
st.title("๐ฎ Agentic Pharmaceutical Analytics Platform")
st.markdown("### Automated Analytics Workflow for Pharmaceutical Brand Leaders")
# Sidebar for configuration and API key
with st.sidebar:
st.header("๐ Configuration")
# API key check and environment setup
api_key = os.getenv("ANTHROPIC_API_KEY")
if not api_key:
api_key = st.text_input("Enter Claude API Key:", type="password")
if api_key:
os.environ["ANTHROPIC_API_KEY"] = api_key
st.success("API key set successfully!")
else:
st.warning("Please enter your Claude API key to continue.")
st.info("For Hugging Face Spaces, add ANTHROPIC_API_KEY to the Secrets tab.")
st.stop()
else:
st.success("โ Claude API key found")
# Setup environment if not already done
if not st.session_state.get("environment_ready", False):
st.session_state.environment_ready = setup_environment()
if not st.session_state.environment_ready:
st.error("Environment setup failed. Check error messages above.")
st.info("You might need to restart the app or check if you have sufficient permissions.")
st.stop()
# Initialize agents if environment is ready
if st.session_state.environment_ready and not st.session_state.get("agents_loaded", False):
st.markdown("### Initializing agents...")
agents_loaded, agents_or_error = initialize_agents()
st.session_state.agents_loaded = agents_loaded
if agents_loaded:
st.success("โ All agents initialized successfully")
# Store agents in session state
st.session_state.agents = agents_or_error
else:
st.error(f"Failed to initialize agents: {agents_or_error}")
st.info("Try refreshing the page or check logs.")
# Don't stop here, allow diagnostics tab to run
# Debug options (only show if environment is ready)
if st.session_state.get("environment_ready", False):
st.subheader("Debug Options")
show_sql = st.checkbox("Show Generated SQL", value=st.session_state.get("show_sql", False))
st.session_state.show_sql = show_sql
show_code = st.checkbox("Show Generated Python", value=st.session_state.get("show_code", False))
st.session_state.show_code = show_code
# Explanation
st.markdown("---")
st.subheader("About This Demo")
st.markdown("""
This platform demonstrates how agentic AI can transform pharmaceutical analytics:
1. **Planning Agent**: Decomposes the problem and plans the analysis
2. **Data Agent**: Translates natural language to SQL and builds data pipelines
3. **Analytics Agent**: Performs statistical analysis and modeling
4. **QA Agent**: Validates results for accuracy and relevance
5. **Insights Agent**: Creates visualizations and actionable insights
All steps are automated with agents collaborating to deliver insights in minutes rather than days.
""")
# Restart button
if st.session_state.get("workflow_state") is not None:
if st.button("Restart Demo"):
st.session_state.workflow_state = None
st.session_state.workflow_thread = None
st.session_state.logs = []
st.session_state.current_step = None
st.session_state.alert_submitted = False
st.session_state.active_page = "main"
st.rerun()
# Only show main app if environment is ready
if not st.session_state.get("environment_ready", False):
st.info("Setting up environment and initializing agents. Please wait...")
st.stop()
# Render the appropriate page based on session state
render_page()
# Run the app
if __name__ == "__main__":
pass |