sales_analytics / app.py
cryogenic22's picture
Update app.py
88eab90 verified
"""
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