cryogenic22 commited on
Commit
88eab90
·
verified ·
1 Parent(s): ea2851d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +19 -318
app.py CHANGED
@@ -2,8 +2,7 @@
2
  Pharmaceutical Analytics Agentic AI Demo - Streamlit App
3
 
4
  This is the main Streamlit application for the pharmaceutical analytics demo.
5
- It includes initialization steps that would normally be in main.py to support
6
- running directly on Hugging Face Spaces.
7
 
8
  Usage (on Hugging Face):
9
  The app runs automatically
@@ -13,34 +12,17 @@ Usage (locally):
13
  """
14
 
15
  import streamlit as st
16
- import pandas as pd
17
- import numpy as np
18
- import matplotlib.pyplot as plt
19
- import seaborn as sns
20
  import os
21
- import json
22
- import time
23
  import sys
 
24
  from datetime import datetime
25
- import sqlite3
26
- import plotly.express as px
27
- import plotly.graph_objects as go
28
- import networkx as nx
29
- from pyvis.network import Network
30
- import tempfile
31
- import base64
32
- from PIL import Image
33
- from io import BytesIO
34
- import uuid
35
- import threading
36
- import queue
37
-
38
- # Import diagnostics module
39
- from updated_diagnostics import render_diagnostics_tab
40
 
41
  # Add current directory to path to ensure module imports work
42
  sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))
43
 
 
 
 
44
  # Initialize environment
45
  def setup_environment():
46
  """Setup the demo environment"""
@@ -121,72 +103,6 @@ st.set_page_config(
121
  initial_sidebar_state="expanded"
122
  )
123
 
124
- # Initialize session state for workflow
125
- if "workflow_state" not in st.session_state:
126
- st.session_state.workflow_state = None
127
-
128
- if "workflow_thread" not in st.session_state:
129
- st.session_state.workflow_thread = None
130
-
131
- if "status_queue" not in st.session_state:
132
- st.session_state.status_queue = queue.Queue()
133
-
134
- if "logs" not in st.session_state:
135
- st.session_state.logs = []
136
-
137
- if "current_step" not in st.session_state:
138
- st.session_state.current_step = None
139
-
140
- if "alert_submitted" not in st.session_state:
141
- st.session_state.alert_submitted = False
142
-
143
- if "show_sql" not in st.session_state:
144
- st.session_state.show_sql = False
145
-
146
- if "show_code" not in st.session_state:
147
- st.session_state.show_code = False
148
-
149
- if "environment_ready" not in st.session_state:
150
- st.session_state.environment_ready = False
151
-
152
- if "agents_loaded" not in st.session_state:
153
- st.session_state.agents_loaded = False
154
-
155
- if "initialization_attempted" not in st.session_state:
156
- st.session_state.initialization_attempted = False
157
-
158
- if "active_tab" not in st.session_state:
159
- st.session_state.active_tab = "Main"
160
-
161
- # Run workflow in separate thread
162
- def run_workflow_thread(workflow, alert):
163
- try:
164
- # Update status
165
- st.session_state.status_queue.put(("info", "Planning analysis approach..."))
166
- st.session_state.current_step = "planning"
167
-
168
- # Run the workflow with more detailed logging
169
- print(f"Starting workflow with alert: {alert}")
170
- result = workflow.run_workflow(alert)
171
- print("Workflow completed successfully")
172
-
173
- # Store the result
174
- st.session_state.workflow_state = result
175
-
176
- # Update status
177
- st.session_state.status_queue.put(("success", "Analysis complete!"))
178
- st.session_state.current_step = "complete"
179
- except Exception as e:
180
- import traceback
181
- error_details = f"Error in workflow: {str(e)}\n{traceback.format_exc()}"
182
- print(error_details)
183
- st.session_state.status_queue.put(("error", f"Error: {str(e)}"))
184
- st.session_state.current_step = "error"
185
- # Add to error details for debugging
186
- if "error_details" not in st.session_state:
187
- st.session_state.error_details = []
188
- st.session_state.error_details.append(error_details)
189
-
190
  # Main application header
191
  st.title("🔮 Agentic Pharmaceutical Analytics Platform")
192
  st.markdown("### Automated Analytics Workflow for Pharmaceutical Brand Leaders")
@@ -210,7 +126,7 @@ with st.sidebar:
210
  st.success("✓ Claude API key found")
211
 
212
  # Setup environment if not already done
213
- if not st.session_state.environment_ready:
214
  st.session_state.environment_ready = setup_environment()
215
  if not st.session_state.environment_ready:
216
  st.error("Environment setup failed. Check error messages above.")
@@ -218,7 +134,7 @@ with st.sidebar:
218
  st.stop()
219
 
220
  # Initialize agents if environment is ready
221
- if st.session_state.environment_ready and not st.session_state.agents_loaded:
222
  st.markdown("### Initializing agents...")
223
  agents_loaded, agents_or_error = initialize_agents()
224
  st.session_state.agents_loaded = agents_loaded
@@ -232,13 +148,13 @@ with st.sidebar:
232
  st.info("Try refreshing the page or check logs.")
233
  # Don't stop here, allow diagnostics tab to run
234
 
235
- # Debug options (only show if environment and agents are ready)
236
- if st.session_state.environment_ready:
237
  st.subheader("Debug Options")
238
- show_sql = st.checkbox("Show Generated SQL", value=st.session_state.show_sql)
239
  st.session_state.show_sql = show_sql
240
 
241
- show_code = st.checkbox("Show Generated Python", value=st.session_state.show_code)
242
  st.session_state.show_code = show_code
243
 
244
  # Explanation
@@ -257,238 +173,23 @@ with st.sidebar:
257
  """)
258
 
259
  # Restart button
260
- if st.session_state.workflow_state is not None:
261
  if st.button("Restart Demo"):
262
  st.session_state.workflow_state = None
263
  st.session_state.workflow_thread = None
264
  st.session_state.logs = []
265
  st.session_state.current_step = None
266
  st.session_state.alert_submitted = False
 
267
  st.rerun()
268
 
269
- # Tab selection
270
- tab1, tab2 = st.tabs(["Main App", "Diagnostics"])
271
-
272
- with tab1:
273
- # Only show main app if environment is ready
274
- if not st.session_state.environment_ready:
275
- st.info("Setting up environment. Please wait...")
276
- else:
277
- # Main screen
278
- if st.session_state.workflow_state is None:
279
- # Alert input section
280
- st.header("📱 Incoming Alert")
281
-
282
- col1, col2 = st.columns([3, 1])
283
-
284
- with col1:
285
- # Dropdown for alert selection
286
- alert_option = st.selectbox(
287
- "Select Alert Type:",
288
- [
289
- "Sales Decline",
290
- "Market Share Loss",
291
- "Inventory Issue",
292
- "Competitor Launch",
293
- "Custom Alert"
294
- ]
295
- )
296
-
297
- # Alert templates
298
- alert_templates = {
299
- "Sales Decline": "Sales of DrugX down 15% in Northeast region over past 30 days compared to forecast.",
300
- "Market Share Loss": "Market share of DrugX decreased by 8 percentage points in the Southeast region over the last quarter.",
301
- "Inventory Issue": "Multiple stockouts of DrugX reported in Midwest distribution centers affecting 25% of pharmacies.",
302
- "Competitor Launch": "Competitor MedCorp launched similar product at 20% lower price point in Western territories.",
303
- "Custom Alert": ""
304
- }
305
-
306
- # Alert description
307
- alert_text = st.text_area(
308
- "Alert Description:",
309
- value=alert_templates[alert_option],
310
- height=100
311
- )
312
-
313
-
314
-
315
- # Submit button
316
- submit_button = st.button("Analyze Alert")
317
-
318
- if submit_button and alert_text:
319
- st.info("Starting analysis workflow...")
320
-
321
- try:
322
- # Create the workflow
323
- SalesAnalysisWorkflow = st.session_state.agents["SalesAnalysisWorkflow"]
324
- workflow = SalesAnalysisWorkflow(db_path="data/pharma_db.sqlite")
325
-
326
- # Initialize workflow state tracking
327
- if "workflow_progress" not in st.session_state:
328
- st.session_state.workflow_progress = {
329
- "started": True,
330
- "step": "planning",
331
- "completed_steps": [],
332
- "error": None
333
- }
334
-
335
- # Show current progress
336
- progress_status = st.empty()
337
- progress_status.info(f"Step: {st.session_state.workflow_progress['step']}")
338
-
339
- # Execute workflow in steps for better visibility
340
- if st.session_state.workflow_progress["step"] == "planning":
341
- try:
342
- # Execute planning step
343
- progress_status.info("Planning analysis approach...")
344
- result = workflow.run_workflow(alert_text)
345
-
346
- # Store the result
347
- st.session_state.workflow_state = result
348
- st.session_state.workflow_progress["completed_steps"].append("planning")
349
- st.session_state.workflow_progress["step"] = "complete"
350
-
351
- # Show success
352
- progress_status.success("Analysis complete!")
353
- st.rerun()
354
- except Exception as e:
355
- import traceback
356
- error_msg = f"Error in workflow: {str(e)}"
357
- st.error(error_msg)
358
- st.code(traceback.format_exc())
359
- st.session_state.workflow_progress["error"] = error_msg
360
-
361
- # If we have a completed workflow, display it
362
- if "workflow_state" in st.session_state and st.session_state.workflow_state:
363
- workflow_state = st.session_state.workflow_state
364
- if workflow_state["status"] == "complete":
365
- st.success("Analysis completed successfully!")
366
- except Exception as e:
367
- import traceback
368
- st.error(f"Error initializing workflow: {str(e)}")
369
- st.code(traceback.format_exc())
370
-
371
- with col2:
372
- st.image("https://img.icons8.com/fluency/240/000000/notification-center.png", width=150)
373
- st.markdown("**Source:** Mobile Alert System")
374
- st.markdown("**Priority:** High")
375
- st.markdown("**Time:** " + datetime.now().strftime("%Y-%m-%d %H:%M"))
376
-
377
- # Show example dashboard
378
- st.markdown("---")
379
- st.header("📊 Example Dashboard Preview")
380
-
381
- # Create sample visualization
382
- fig = px.line(
383
- pd.DataFrame({
384
- 'Month': pd.date_range(start='2023-01-01', periods=12, freq='M'),
385
- 'Sales': [1200, 1250, 1300, 1400, 1500, 1600, 1550, 1500, 1450, 1300, 1200, 1150],
386
- 'Target': [1200, 1250, 1300, 1350, 1400, 1450, 1500, 1550, 1600, 1650, 1700, 1750]
387
- }),
388
- x='Month',
389
- y=['Sales', 'Target'],
390
- title="DrugX Performance (Sample Data)",
391
- labels={"value": "Sales ($K)", "variable": "Metric"}
392
- )
393
- fig.update_layout(height=400)
394
- st.plotly_chart(fig, use_container_width=True)
395
-
396
- else:
397
- # Process status updates from thread
398
- while not st.session_state.status_queue.empty():
399
- status_type, status_message = st.session_state.status_queue.get()
400
- if status_type == "info":
401
- st.info(status_message)
402
- elif status_type == "success":
403
- st.success(status_message)
404
- elif status_type == "error":
405
- st.error(status_message)
406
-
407
- # Add to logs
408
- st.session_state.logs.append({
409
- "timestamp": datetime.now().isoformat(),
410
- "type": status_type,
411
- "message": status_message
412
- })
413
-
414
- # Get current workflow state
415
- workflow_state = st.session_state.workflow_state
416
-
417
- if workflow_state is None or workflow_state["status"] == "error":
418
- # Show error state
419
- st.error(f"Analysis failed: {workflow_state.get('error', 'Unknown error')}")
420
- if st.button("Start Over"):
421
- st.session_state.workflow_state = None
422
- st.session_state.workflow_thread = None
423
- st.session_state.logs = []
424
- st.session_state.current_step = None
425
- st.session_state.alert_submitted = False
426
- st.rerun()
427
-
428
- elif workflow_state["status"] != "complete":
429
- # Show progress
430
- current_step = st.session_state.current_step
431
-
432
- # Progress indicators
433
- st.markdown("### 🔄 Analysis in Progress")
434
-
435
- # Progress bar
436
- steps = ["planning", "data_collection", "analysis", "validation", "insights", "complete"]
437
- step_idx = steps.index(current_step) if current_step in steps else 0
438
- progress = (step_idx + 1) / len(steps)
439
-
440
- progress_bar = st.progress(progress)
441
-
442
- # Step indicators
443
- col1, col2, col3, col4, col5 = st.columns(5)
444
-
445
- with col1:
446
- check = "✅" if step_idx >= 0 else "🔄"
447
- st.markdown(f"{check} **Planning**")
448
-
449
- with col2:
450
- check = "✅" if step_idx >= 1 else "⏳"
451
- check = "🔄" if step_idx == 1 else check
452
- st.markdown(f"{check} **Data Collection**")
453
-
454
- with col3:
455
- check = "✅" if step_idx >= 2 else "⏳"
456
- check = "🔄" if step_idx == 2 else check
457
- st.markdown(f"{check} **Analysis**")
458
-
459
- with col4:
460
- check = "✅" if step_idx >= 3 else "⏳"
461
- check = "🔄" if step_idx == 3 else check
462
- st.markdown(f"{check} **Validation**")
463
-
464
- with col5:
465
- check = "✅" if step_idx >= 4 else "⏳"
466
- check = "🔄" if step_idx == 4 else check
467
- st.markdown(f"{check} **Insights**")
468
-
469
- # Show agent activity visualization based on current step
470
- st.markdown("---")
471
-
472
- # ... (rest of the agent visualization code remains unchanged)
473
-
474
- # Placeholder for log console
475
- with st.expander("View Process Log"):
476
- for log in st.session_state.logs:
477
- st.text(f"{log['timestamp']} - {log['message']}")
478
-
479
- # Auto refresh
480
- time.sleep(0.5)
481
- st.rerun()
482
-
483
- else:
484
- # Show completed analysis
485
- st.markdown("### ✅ Analysis Complete")
486
-
487
- # ... (rest of the analysis display code remains unchanged)
488
 
489
- with tab2:
490
- # Render diagnostics tab
491
- render_diagnostics_tab()
492
 
493
  # Run the app
494
  if __name__ == "__main__":
 
2
  Pharmaceutical Analytics Agentic AI Demo - Streamlit App
3
 
4
  This is the main Streamlit application for the pharmaceutical analytics demo.
5
+ It initializes the environment and delegates page rendering to the page manager.
 
6
 
7
  Usage (on Hugging Face):
8
  The app runs automatically
 
12
  """
13
 
14
  import streamlit as st
 
 
 
 
15
  import os
 
 
16
  import sys
17
+ import time
18
  from datetime import datetime
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
  # Add current directory to path to ensure module imports work
21
  sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))
22
 
23
+ # Import page manager for modular UI
24
+ from page_manager import render_page
25
+
26
  # Initialize environment
27
  def setup_environment():
28
  """Setup the demo environment"""
 
103
  initial_sidebar_state="expanded"
104
  )
105
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
  # Main application header
107
  st.title("🔮 Agentic Pharmaceutical Analytics Platform")
108
  st.markdown("### Automated Analytics Workflow for Pharmaceutical Brand Leaders")
 
126
  st.success("✓ Claude API key found")
127
 
128
  # Setup environment if not already done
129
+ if not st.session_state.get("environment_ready", False):
130
  st.session_state.environment_ready = setup_environment()
131
  if not st.session_state.environment_ready:
132
  st.error("Environment setup failed. Check error messages above.")
 
134
  st.stop()
135
 
136
  # Initialize agents if environment is ready
137
+ if st.session_state.environment_ready and not st.session_state.get("agents_loaded", False):
138
  st.markdown("### Initializing agents...")
139
  agents_loaded, agents_or_error = initialize_agents()
140
  st.session_state.agents_loaded = agents_loaded
 
148
  st.info("Try refreshing the page or check logs.")
149
  # Don't stop here, allow diagnostics tab to run
150
 
151
+ # Debug options (only show if environment is ready)
152
+ if st.session_state.get("environment_ready", False):
153
  st.subheader("Debug Options")
154
+ show_sql = st.checkbox("Show Generated SQL", value=st.session_state.get("show_sql", False))
155
  st.session_state.show_sql = show_sql
156
 
157
+ show_code = st.checkbox("Show Generated Python", value=st.session_state.get("show_code", False))
158
  st.session_state.show_code = show_code
159
 
160
  # Explanation
 
173
  """)
174
 
175
  # Restart button
176
+ if st.session_state.get("workflow_state") is not None:
177
  if st.button("Restart Demo"):
178
  st.session_state.workflow_state = None
179
  st.session_state.workflow_thread = None
180
  st.session_state.logs = []
181
  st.session_state.current_step = None
182
  st.session_state.alert_submitted = False
183
+ st.session_state.active_page = "main"
184
  st.rerun()
185
 
186
+ # Only show main app if environment is ready
187
+ if not st.session_state.get("environment_ready", False):
188
+ st.info("Setting up environment and initializing agents. Please wait...")
189
+ st.stop()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
 
191
+ # Render the appropriate page based on session state
192
+ render_page()
 
193
 
194
  # Run the app
195
  if __name__ == "__main__":