VEDAGI1 commited on
Commit
dc12e99
·
verified ·
1 Parent(s): bb96579

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +336 -363
app.py CHANGED
@@ -22,16 +22,25 @@ import regex as re2
22
  import re
23
 
24
  from langchain_cohere import ChatCohere # noqa: F401
25
-
26
  from settings import (
27
  GENERAL_CONVERSATION_PROMPT,
28
  COHERE_MODEL_PRIMARY,
29
- COHERE_TIMEOUT_S, # noqa: F401
30
- USE_OPEN_FALLBACKS # noqa: F401
31
  )
 
 
 
 
32
  # Try to import optional HIPAA flags; fall back to safe defaults if not defined.
33
  try:
34
- from settings import PHI_MODE, PERSIST_HISTORY, HISTORY_TTL_DAYS, REDACT_BEFORE_LLM, ALLOW_EXTERNAL_PHI
 
 
 
 
 
 
35
  except Exception:
36
  PHI_MODE = False
37
  PERSIST_HISTORY = True
@@ -39,13 +48,8 @@ except Exception:
39
  REDACT_BEFORE_LLM = False
40
  ALLOW_EXTERNAL_PHI = True
41
 
42
- from audit_log import log_event
43
- from privacy import safety_filter, refusal_reply
44
- from llm_router import cohere_chat, _co_client, cohere_embed
45
-
46
 
47
  # ---------------------- Helpers (analysis logic selectively improved) ----------------------
48
-
49
  def load_markdown_text(filepath: str) -> str:
50
  try:
51
  with open(filepath, "r", encoding="utf-8") as f:
@@ -72,6 +76,7 @@ PHI_PATTERNS = [
72
  (re.compile(r"\b\d{5}(-\d{4})?\b"), "[REDACTED_ZIP]"),
73
  ]
74
 
 
75
  def redact_phi(text: str) -> str:
76
  if not isinstance(text, str):
77
  return text
@@ -80,6 +85,7 @@ def redact_phi(text: str) -> str:
80
  t = pat.sub(repl, t)
81
  return t
82
 
 
83
  def safe_log(event_name: str, meta: dict | None = None):
84
  # Avoid logging raw PHI or payloads
85
  try:
@@ -97,7 +103,7 @@ def _create_python_script(user_scenario: str, schema_context: str) -> str:
97
  The AI first creates a step-by-step plan, then writes code to execute it.
98
  This ensures the analysis is logical, correctly aggregated, and aligned with the user's goal.
99
  """
100
- prompt_for_coder = f"""\
101
  You are an expert-level Python data scientist acting as a consultant. Your task is to analyze data to answer a user's business request.
102
 
103
  --- USER'S SCENARIO ---
@@ -111,31 +117,33 @@ You are an expert-level Python data scientist acting as a consultant. Your task
111
  You must follow a rigorous two-step process:
112
 
113
  **Step 1: Create a Detailed Analysis Plan.**
114
- First, think step-by-step. Deconstruct the user's request into a clear, logical plan. The plan must identify the key metrics, necessary data manipulations (cleaning, grouping, aggregation), and the final outputs required.
 
 
115
  - **CRITICAL for aggregation:** If the user asks for analysis by category (e.g., "specialty," "department"), you MUST identify the correct high-level categorical column for grouping. DO NOT aggregate by granular, free-text procedure descriptions unless explicitly asked. Your goal is to find meaningful, strategic trends.
116
 
117
  **Step 2: Write the Python Script.**
118
  Based on your plan, write a complete Python script.
119
 
120
  CRITICAL SCRIPTING RULES:
121
- 1. **NO FILE READING:** The data is already loaded into a list of pandas DataFrames called `dfs`. You MUST use this variable. Do not include `pd.read_csv`.
122
- 2. **STRICTLY JSON OUTPUT:** The script's ONLY output to stdout MUST be a single, well-structured JSON object containing all the raw data findings from your plan.
123
- 3. **ROBUST DATA CLEANING:** Before performing calculations, clean data robustly. Convert numeric columns to numbers using `pd.to_numeric(..., errors='coerce')`. Handle missing values (`NaN`) appropriately (e.g., by excluding them from averages).
124
- 4. **JSON SERIALIZATION:** Ensure all data in the final dictionary is JSON-serializable. Use `.item()` for single numpy values and `.tolist()` for arrays/series.
125
 
126
  Now, provide your response in the following format:
127
 
128
  **ANALYSIS PLAN:**
129
- ```text
130
- 1. **Objective:** [Briefly state the main goal]
131
- 2. **Data Cleaning:** [Describe steps to clean and prepare the data]
132
- 3. **Analysis Step A:** [e.g., "Calculate average wait times per hospital by grouping `dfs[0]` by 'Facility' and averaging 'Surgery_Median'."]
133
- 4. **Analysis Step B:** [e.g., "Identify top 5 specialties by grouping `dfs[0]` by the 'Specialty' column and calculating the mean of 'Surgery_Median'."]
134
- 5. **Analysis Step C:** [e.g., "Determine zone-level performance by grouping by 'Zone' and comparing to the overall provincial average."]
135
- 6. **JSON Output Structure:** [Describe the keys and values of the final JSON object]
136
- PYTHON SCRIPT:
137
- code
138
- Python
139
  # Your complete Python script starts here
140
  import pandas as pd
141
  import json
@@ -147,17 +155,14 @@ import re
147
  print(json.dumps(final_data_structure, indent=4))
148
  """
149
  generated_text = cohere_chat(prompt_for_coder)
150
- # This regex is more robust for extracting the final code block
151
  match = re2.search(r"PYTHON SCRIPT:\s*python\n(.*?)", generated_text, re2.DOTALL)
152
  if match:
153
  return match.group(1).strip()
154
- code
155
- Code
156
- # Fallback if the structured format fails
157
- fallback_match = re2.search(r"```python\n(.*?)```", generated_text, re2.DOTALL)
158
  if fallback_match:
159
- return fallback_match.group(1).strip()
160
-
161
  return "print(json.dumps({'error': 'Failed to generate a valid Python script from the plan.'}))"
162
  def _generate_long_report(prompt: str) -> str:
163
  try:
@@ -179,7 +184,7 @@ IMPROVED: Generates a professional, structured report from the JSON data.
179
  The prompt guides the AI to synthesize insights in a standard consulting format,
180
  ensuring a high level of detail and actionable recommendations.
181
  """
182
- prompt_for_writer = f"""
183
  You are an expert management consultant specializing in data-driven strategy. A Python script has been executed to extract key data points based on a user's request. Your task is to synthesize this raw data into a polished, comprehensive, and actionable report.
184
  --- USER'S ORIGINAL SCENARIO ---
185
  {user_scenario}
@@ -189,26 +194,40 @@ You are an expert management consultant specializing in data-driven strategy. A
189
  --- END RAW DATA ---
190
  CRITICAL INSTRUCTIONS:
191
  You must write a final report that follows this exact structure:
192
- ### Executive Summary
 
193
  Start with a brief paragraph summarizing the core problem, key findings, and top recommendations. This should be a high-level overview for a leadership audience.
194
- ### 1. [First Key Finding, e.g., Hospitals with the Longest Wait Times]
 
 
195
  Present the relevant data in a Markdown table.
196
  Write a short narrative interpreting the data. What does it mean? Are there any outliers? Why might these facilities have long waits (e.g., specialized care, rural location, capacity issues)?
197
- ### 2. [Second Key Finding, e.g., Specialties with the Longest Wait Times]
 
 
198
  Present the relevant data in a Markdown table.
199
  Interpret the findings. Why are these specialties facing delays (e.g., specialist shortages, equipment needs)?
200
- ### 3. [Third Key Finding, e.g., Zone-Level Performance]
 
 
201
  Present the data in a table, including a comparison to a relevant average or baseline.
202
  Analyze the geographic or systemic issues this data reveals.
203
- ### 4. [Fourth Key Finding, if applicable, e.g., Geographic Distribution]
 
 
204
  Synthesize location data with the wait-time findings.
205
  Discuss the implications for patient equity, travel burdens, and access to care.
206
- ### 5. Recommendations for Resource Allocation
 
 
207
  Provide specific, actionable, and justified recommendations.
208
  Structure them by category (e.g., by facility, by specialty, by zone).
209
  For each recommendation, provide a clear rationale directly linked to the data findings above (e.g., "Allocate additional resources to Glace Bay Hospital because it is a rural facility in a high-wait zone, suggesting a capacity bottleneck.").
210
- ### Data Limitations
 
 
211
  Briefly mention any potential limitations of the analysis (e.g., missing data, use of proxies, case severity not included). This adds credibility to the report.
 
212
  Do not just repeat the JSON data. Your value is in interpreting the numbers, connecting the dots between different findings, and providing clear, data-backed strategic advice.
213
  """
214
  return _generate_long_report(prompt_for_writer)
@@ -220,383 +239,337 @@ cli = _co_client()
220
  if not cli:
221
  return "Cohere client not initialized."
222
  vecs = cohere_embed(["hello", "world"])
223
- return f"Cohere OK (model={COHERE_MODEL_PRIMARY})" if vecs else "Cohere reachable."
224
  except Exception as e:
225
  return f"Cohere ping failed: {e}"
226
  def handle(user_msg: str, files: list, yield_update) -> str:
227
  try:
228
- # Safety filter on incoming message
229
  safe_in, blocked_in, reason_in = safety_filter(user_msg, mode="input")
230
  if blocked_in:
231
  return refusal_reply(reason_in)
232
- code
233
- Code
234
- # Optional PHI redaction for prompts sent to an external LLM
235
- redacted_in = safe_in
236
- if PHI_MODE and REDACT_BEFORE_LLM:
237
- redacted_in = redact_phi(safe_in)
238
-
239
- file_paths: List[str] = [getattr(f, "name", None) or f for f in (files or [])]
240
-
241
- if file_paths:
242
- # CSV analysis path
243
- dataframes, schema_parts = [], []
244
- for i, p in enumerate(file_paths):
245
- if p.endswith(".csv"):
246
- try:
247
- df = pd.read_csv(p)
248
- except UnicodeDecodeError:
249
- df = pd.read_csv(p, encoding="latin1")
250
- dataframes.append(df)
251
-
252
- # --- IMPROVEMENT: ENRICHED SCHEMA CONTEXT ---
253
- schema_buffer = io.StringIO()
254
- df.info(buf=schema_buffer)
255
- schema_info = schema_buffer.getvalue()
256
- schema_parts.append(
257
- f"""DataFrame `dfs[{i}]` (`{os.path.basename(p)}`):
258
- Head
259
- {df.head().to_markdown()}
260
- Schema and Data Types
261
- code
262
- Code
263
- {schema_info}
264
- Summary Statistics
265
- {df.describe(include='all').to_markdown()}
266
- """
267
  )
268
- code
269
- Code
270
  if not dataframes:
271
- return "Please upload at least one CSV file."
272
-
273
- schema_context = "\n".join(schema_parts)
274
-
275
- # If external PHI is not allowed, use redacted prompt; otherwise use original
276
- prompt_for_code = redacted_in if (PHI_MODE and not ALLOW_EXTERNAL_PHI) else safe_in
277
-
278
- yield_update("""```
279
- 🧠 Generating aligned analysis script...
280
- code
281
- """)
282
  analysis_script = _create_python_script(prompt_for_code, schema_context)
283
-
284
- yield_update("""```
285
- ⚙️ Executing script to extract raw data...
286
- ```""")
287
- execution_namespace = {"dfs": dataframes, "pd": pd, "re": re, "json": json}
288
- output_buffer = io.StringIO()
289
-
290
- try:
291
- with redirect_stdout(output_buffer):
292
- exec(analysis_script, execution_namespace)
293
- raw_data_output = output_buffer.getvalue()
294
- except Exception as e:
295
- return (
296
- f"An error occurred executing the script: {e}\n\nGenerated Script:\n"
297
- f"```python\n{analysis_script}\n```"
298
- )
299
-
300
- yield_update("""```
301
- ✍️ Synthesizing final comprehensive report...
302
- ```""")
303
- writer_input = redacted_in if (PHI_MODE and not ALLOW_EXTERNAL_PHI) else safe_in
304
- final_report = _generate_final_report(writer_input, raw_data_output)
305
- return _sanitize_text(final_report)
306
- else:
307
- # Pure chat path
308
- chat_input = redacted_in if (PHI_MODE and not ALLOW_EXTERNAL_PHI) else safe_in
309
- prompt = f"{GENERAL_CONVERSATION_PROMPT}\n\nUser: {chat_input}\nAssistant:"
310
- return _sanitize_text(cohere_chat(prompt) or "How can I help further?")
311
-
312
- except Exception as e:
313
- tb = traceback.format_exc()
314
- safe_log("app_error", {"err": str(e)})
315
- return "A critical error occurred. Please contact your administrator." if PHI_MODE else f"A critical error occurred: {e}"
316
-
317
-
318
  PRIVACY_POLICY_TEXT = load_markdown_text("privacy_policy.md")
319
  TERMS_OF_SERVICE_TEXT = load_markdown_text("terms_of_service.md")
320
-
321
-
322
- # ---------------------- Sleek UI assets (CSS/JS only) ----------------------
323
-
324
  SLEEK_CSS = """
325
  /* Full-bleed, modern look */
326
  :root, body, #root, .gradio-container { height: 100%; }
327
  .gradio-container { padding: 0 !important; }
328
  .block { padding: 0 !important; }
329
-
330
  /* Header */
331
  .header {
332
- padding: 20px 28px;
333
- background: linear-gradient(135deg, #0e1726, #1d2a44 60%, #243a5e);
334
- color: #fff;
335
- display: flex; align-items: center; justify-content: space-between;
336
- gap: 16px;
337
  }
338
  .header h1 { margin: 0; font-size: 22px; letter-spacing: 0.3px; font-weight: 600; }
339
  .header .badge { font-size: 12px; opacity: 0.9; background:#ffffff22; padding:6px 10px; border-radius: 999px; }
340
-
341
  /* Main layout */
342
  .main {
343
- display: grid;
344
- grid-template-columns: 420px 1fr;
345
- gap: 16px;
346
- padding: 16px;
347
- height: calc(100vh - 72px);
348
- box-sizing: border-box;
349
  }
350
  .left, .right {
351
- background: #0b1020;
352
- color: #e9edf3;
353
- border-radius: 16px;
354
- border: 1px solid #1c2642;
355
  }
356
  .left { padding: 16px; display: flex; flex-direction: column; gap: 12px; }
357
  .right { padding: 0; display: flex; flex-direction: column; }
358
-
359
  /* Panels */
360
  .panel-title { font-size: 14px; font-weight: 600; color: #aeb8cc; margin-bottom: 6px; }
361
  .helper { font-size: 12px; color: #97a3bb; margin-bottom: 8px; }
362
-
363
  /* Sticky actions */
364
  .actions {
365
- display: flex; gap: 8px; align-items: center; justify-content: stretch;
366
  }
367
  .actions .gr-button { flex: 1; }
368
-
369
  /* Tabs full height */
370
  .right .tabs { height: 100%; display: flex; flex-direction: column; }
371
  .right .tabitem { flex: 1; display: flex; flex-direction: column; }
372
  #chatbot_container { flex: 1; }
373
  #chatbot_container .gr-chatbot { height: 100%; }
374
-
375
  /* Tiny separators */
376
  .hr { height: 1px; background: #16203b; margin: 10px 0; }
377
-
378
  /* Voice hint */
379
  .voice-hint { font-size: 12px; color:#9fb0cc; margin-top: 4px; }
380
  """
381
-
382
  VOICE_STT_HTML = """
383
  <script>
384
  let __rs_rec = null;
385
  function rs_toggle_stt(elemId){
386
- const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
387
- if (!SpeechRecognition){
388
- alert("This browser does not support Speech Recognition. Try Chrome or Edge.");
389
- return;
390
- }
391
- if (__rs_rec){ __rs_rec.stop(); __rs_rec = null; return; }
392
- __rs_rec = new SpeechRecognition();
393
- __rs_rec.lang = "en-US";
394
- __rs_rec.interimResults = true;
395
- __rs_rec.continuous = true;
396
-
397
- const box = document.querySelector(`#${elemId} textarea`);
398
- if (!box){ alert("Prompt box not found."); return; }
399
- let base = box.value || "";
400
-
401
- __rs_rec.onresult = (ev) => {
402
- let t = "";
403
- for (let i = ev.resultIndex; i < ev.results.length; i++){
404
- t += ev.results[i][0].transcript;
405
- }
406
- box.value = (base + " " + t).trim();
407
- box.dispatchEvent(new Event("input", { bubbles: true }));
408
- };
409
- __rs_rec.onend = () => { __rs_rec = null; };
410
- __rs_rec.start();
411
  }
412
  </script>
413
  """
414
-
415
-
416
- # ---------------------- Sleek UI (with fixed State wiring) ----------------------
417
-
418
  with gr.Blocks(theme=gr.themes.Soft(), css=SLEEK_CSS, fill_width=True) as demo:
419
- # Persistent in-memory history component (fixes list/_id error)
420
- assessment_history = gr.State([])
421
-
422
- # Header
423
- with gr.Row(elem_classes=["header"]):
424
- gr.Markdown("<h1>Clarity Ops Augemented Decision Support</h1>")
425
- pill = "PHI Mode ON · history off" if (PHI_MODE and not PERSIST_HISTORY) else \
426
- "PHI Mode ON" if PHI_MODE else "PHI Mode OFF"
427
- gr.Markdown(f"<span class='badge'>{pill}</span>")
428
-
429
- # Main layout
430
- with gr.Row(elem_classes=["main"]):
431
- # Left panel
432
- with gr.Column(elem_classes=["left"]):
433
- gr.Markdown("<div class='panel-title'>New Assessment</div>")
434
- gr.Markdown("<div class='helper'>Upload CSVs for analysis, or enter a prompt. Voice works in modern browsers.</div>")
435
- files_input = gr.Files(
436
- label="Upload Data Files (.csv)",
437
- file_count="multiple",
438
- type="filepath",
439
- file_types=[".csv"],
440
- )
441
- prompt_input = gr.Textbox(
442
- label="Prompt",
443
- placeholder="Paste your scenario or question here...",
444
- lines=12,
445
- elem_id="prompt_box",
446
- autofocus=True,
447
- )
448
-
449
- with gr.Row(elem_classes=["actions"]):
450
- send_btn = gr.Button("▶️ Run Analysis", variant="primary")
451
- clear_btn = gr.Button("🧹 Clear")
452
- voice_btn = gr.Button("🎙️ Voice")
453
-
454
- gr.Markdown("<div class='voice-hint'>Click Voice to start/stop dictation into the prompt box.</div>")
455
- ping_btn = gr.Button("🔌 Ping Cohere")
456
- ping_out = gr.Markdown()
457
-
458
- gr.Markdown("<div class='hr'></div>")
459
- if PHI_MODE:
460
- gr.Markdown(
461
- "⚠️ **PHI Mode:** History persistence is disabled by default. Avoid unnecessary identifiers."
462
- )
463
-
464
- with gr.Accordion("Privacy & Terms", open=False):
465
- gr.Markdown(PRIVACY_POLICY_TEXT)
466
- gr.Markdown("<div class='hr'></div>")
467
- gr.Markdown(TERMS_OF_SERVICE_TEXT)
468
-
469
- # Right panel
470
- with gr.Column(elem_classes=["right"]):
471
- with gr.Tabs(elem_classes=["tabs"]):
472
- with gr.TabItem("Current Assessment", id=0, elem_classes=["tabitem"]):
473
- with gr.Column(elem_id="chatbot_container"):
474
- chat_history_output = gr.Chatbot(label="Analysis Output", type="messages")
475
- with gr.TabItem("Assessment History", id=1, elem_classes=["tabitem"]):
476
- gr.Markdown("### Review Past Assessments")
477
- history_dropdown = gr.Dropdown(label="Select an assessment to review", choices=[])
478
- history_display = gr.Markdown(label="Selected Assessment Details")
479
-
480
- # Inject voice-to-text helper
481
- gr.HTML(VOICE_STT_HTML)
482
-
483
- # --------- Event logic (unchanged analysis flow) ----------
484
-
485
- def run_analysis_wrapper(prompt, files, chat_history_list, history_state_list):
486
- if not prompt:
487
- gr.Warning("Please enter a prompt.")
488
- yield chat_history_list, history_state_list, gr.update()
489
- return
490
-
491
- # Append user's message
492
- chat_with_user_msg = _append_msg(chat_history_list, "user", prompt)
493
-
494
- # Optional progress callback (not streaming in this UI)
495
- def dummy_update(message: str):
496
- pass
497
-
498
- # Thinking bubble
499
- thinking_message = _append_msg(
500
- chat_with_user_msg,
501
- "assistant",
502
- """```
503
- 🧠 Generating and executing analysis... Please wait.
504
- ```""",
505
- )
506
- yield thinking_message, history_state_list, gr.update()
507
-
508
- # Run analysis/chat
509
- ai_response_text = handle(prompt, files, dummy_update)
510
-
511
- # Append final assistant response
512
- final_chat = _append_msg(chat_with_user_msg, "assistant", ai_response_text)
513
- timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
514
-
515
- # Capture filenames (if any)
516
- file_names: List[str] = []
517
- if files:
518
- file_names = [
519
- os.path.basename(f.name if hasattr(f, "name") else f) for f in files
520
- ]
521
-
522
- # Build history record
523
- new_entry = {
524
- "id": timestamp,
525
- "prompt": prompt,
526
- "files": file_names,
527
- "response": ai_response_text,
528
- "chat_history": final_chat,
529
- }
530
-
531
- # Respect PHI/history flags
532
- if PERSIST_HISTORY and (not PHI_MODE or (PHI_MODE and HISTORY_TTL_DAYS > 0)):
533
- updated_history: List[Dict[str, Any]] = (history_state_list or []) + [new_entry]
534
- else:
535
- updated_history = history_state_list or []
536
-
537
- history_labels = [f"{item['id']} - {item['prompt'][:40]}..." for item in updated_history]
538
-
539
- yield final_chat, updated_history, gr.update(choices=history_labels)
540
-
541
- def view_history(selection: str, history_state_list: List[Dict[str, Any]]) -> str:
542
- if not selection or not history_state_list:
543
- return ""
544
- try:
545
- selected_id = selection.split(" - ", 1)[0]
546
- except Exception:
547
- selected_id = selection
548
-
549
- selected_assessment = next(
550
- (item for item in history_state_list if item.get("id") == selected_id), None
551
- )
552
- if not selected_assessment:
553
- return "Could not find the selected assessment."
554
-
555
- file_list = selected_assessment.get("files", [])
556
- file_list_md = "\n- ".join(file_list) if file_list else "*(no files uploaded)*"
557
-
558
- chat_entries = selected_assessment.get("chat_history", [])
559
- chat_md_lines = []
560
- for msg in chat_entries:
561
- role = msg.get("role", "").capitalize()
562
- content = msg.get("content", "")
563
- chat_md_lines.append(f"**{role}:** {content}")
564
- chat_md = "\n\n".join(chat_md_lines)
565
-
566
- return f"""### Assessment from: {selected_assessment['id']}
567
- **Files Used:**
568
- - {file_list_md}
569
- ---
570
- **Original Prompt:**
571
- > {selected_assessment['prompt']}
572
- ---
573
- **AI Generated Response:**
574
  {selected_assessment['response']}
575
- ---
576
- **Chat Transcript:**
577
  {chat_md}
578
  """
579
-
580
- # Wire events (using proper gr.State component for history)
581
- send_btn.click(
582
- run_analysis_wrapper,
583
- inputs=[prompt_input, files_input, chat_history_output, assessment_history],
584
- outputs=[chat_history_output, assessment_history, history_dropdown],
585
- )
586
- history_dropdown.change(
587
- view_history,
588
- inputs=[history_dropdown, assessment_history],
589
- outputs=[history_display],
590
- )
591
- clear_btn.click(
592
- lambda: (None, None, []),
593
- outputs=[prompt_input, files_input, chat_history_output],
594
- )
595
- ping_btn.click(ping_cohere, outputs=[ping_out])
596
- voice_btn.click(None, [], [], js="rs_toggle_stt('prompt_box')")
597
-
598
-
599
- if __name__ == "__main__":
600
- if not os.getenv("COHERE_API_KEY"):
601
- print("🔴 COHERE_API_KEY environment variable not set. Application may not function correctly.")
602
- demo.launch(server_name="0.0.0.0", server_port=int(os.getenv("PORT", "7860")))
 
22
  import re
23
 
24
  from langchain_cohere import ChatCohere # noqa: F401
 
25
  from settings import (
26
  GENERAL_CONVERSATION_PROMPT,
27
  COHERE_MODEL_PRIMARY,
28
+ COHERE_TIMEOUT_S,
29
+ USE_OPEN_FALLBACKS,
30
  )
31
+ from audit_log import log_event
32
+ from privacy import safety_filter, refusal_reply
33
+ from llm_router import cohere_chat, _co_client, cohere_embed
34
+
35
  # Try to import optional HIPAA flags; fall back to safe defaults if not defined.
36
  try:
37
+ from settings import (
38
+ PHI_MODE,
39
+ PERSIST_HISTORY,
40
+ HISTORY_TTL_DAYS,
41
+ REDACT_BEFORE_LLM,
42
+ ALLOW_EXTERNAL_PHI,
43
+ )
44
  except Exception:
45
  PHI_MODE = False
46
  PERSIST_HISTORY = True
 
48
  REDACT_BEFORE_LLM = False
49
  ALLOW_EXTERNAL_PHI = True
50
 
 
 
 
 
51
 
52
  # ---------------------- Helpers (analysis logic selectively improved) ----------------------
 
53
  def load_markdown_text(filepath: str) -> str:
54
  try:
55
  with open(filepath, "r", encoding="utf-8") as f:
 
76
  (re.compile(r"\b\d{5}(-\d{4})?\b"), "[REDACTED_ZIP]"),
77
  ]
78
 
79
+
80
  def redact_phi(text: str) -> str:
81
  if not isinstance(text, str):
82
  return text
 
85
  t = pat.sub(repl, t)
86
  return t
87
 
88
+
89
  def safe_log(event_name: str, meta: dict | None = None):
90
  # Avoid logging raw PHI or payloads
91
  try:
 
103
  The AI first creates a step-by-step plan, then writes code to execute it.
104
  This ensures the analysis is logical, correctly aggregated, and aligned with the user's goal.
105
  """
106
+ prompt_for_coder = f"""\
107
  You are an expert-level Python data scientist acting as a consultant. Your task is to analyze data to answer a user's business request.
108
 
109
  --- USER'S SCENARIO ---
 
117
  You must follow a rigorous two-step process:
118
 
119
  **Step 1: Create a Detailed Analysis Plan.**
120
+ First, think step-by-step. Deconstruct the user's request into a clear, logical plan.
121
+ The plan must identify the key metrics, necessary data manipulations (cleaning, grouping, aggregation), and the final outputs required.
122
+
123
  - **CRITICAL for aggregation:** If the user asks for analysis by category (e.g., "specialty," "department"), you MUST identify the correct high-level categorical column for grouping. DO NOT aggregate by granular, free-text procedure descriptions unless explicitly asked. Your goal is to find meaningful, strategic trends.
124
 
125
  **Step 2: Write the Python Script.**
126
  Based on your plan, write a complete Python script.
127
 
128
  CRITICAL SCRIPTING RULES:
129
+ 1. **NO FILE READING:** The data is already loaded into a list of pandas DataFrames called `dfs`. You MUST use this variable. Do not include `pd.read_csv`.
130
+ 2. **STRICTLY JSON OUTPUT:** The script's ONLY output to stdout MUST be a single, well-structured JSON object containing all the raw data findings from your plan.
131
+ 3. **ROBUST DATA CLEANING:** Before performing calculations, clean data robustly. Convert numeric columns to numbers using `pd.to_numeric(..., errors='coerce')`. Handle missing values (`NaN`) appropriately (e.g., by excluding them from averages).
132
+ 4. **JSON SERIALIZATION:** Ensure all data in the final dictionary is JSON-serializable. Use `.item()` for single numpy values and `.tolist()` for arrays/series.
133
 
134
  Now, provide your response in the following format:
135
 
136
  **ANALYSIS PLAN:**
137
+
138
+ Objective: [Briefly state the main goal]
139
+ Data Cleaning: [Describe steps to clean and prepare the data]
140
+ Analysis Step A: [e.g., "Calculate average wait times per hospital by grouping dfs[0] by 'Facility' and averaging 'Surgery_Median'."]
141
+ Analysis Step B: [e.g., "Identify top 5 specialties by grouping dfs[0] by the 'Specialty' column and calculating the mean of 'Surgery_Median'."]
142
+ Analysis Step C: [e.g., "Determine zone-level performance by grouping by 'Zone' and comparing to the overall provincial average."]
143
+ JSON Output Structure: [Describe the keys and values of the final JSON object]
144
+
145
+ text**PYTHON SCRIPT:**
146
+ ```python
147
  # Your complete Python script starts here
148
  import pandas as pd
149
  import json
 
155
  print(json.dumps(final_data_structure, indent=4))
156
  """
157
  generated_text = cohere_chat(prompt_for_coder)
158
+ This regex is more robust for extracting the final code block
159
  match = re2.search(r"PYTHON SCRIPT:\s*python\n(.*?)", generated_text, re2.DOTALL)
160
  if match:
161
  return match.group(1).strip()
162
+ Fallback if the structured format fails
163
+ fallback_match = re2.search(r"python\n(.*?)", generated_text, re2.DOTALL)
 
 
164
  if fallback_match:
165
+ return fallback_match.group(1).strip()
 
166
  return "print(json.dumps({'error': 'Failed to generate a valid Python script from the plan.'}))"
167
  def _generate_long_report(prompt: str) -> str:
168
  try:
 
184
  The prompt guides the AI to synthesize insights in a standard consulting format,
185
  ensuring a high level of detail and actionable recommendations.
186
  """
187
+ prompt_for_writer = f"""\
188
  You are an expert management consultant specializing in data-driven strategy. A Python script has been executed to extract key data points based on a user's request. Your task is to synthesize this raw data into a polished, comprehensive, and actionable report.
189
  --- USER'S ORIGINAL SCENARIO ---
190
  {user_scenario}
 
194
  --- END RAW DATA ---
195
  CRITICAL INSTRUCTIONS:
196
  You must write a final report that follows this exact structure:
197
+ Executive Summary
198
+
199
  Start with a brief paragraph summarizing the core problem, key findings, and top recommendations. This should be a high-level overview for a leadership audience.
200
+
201
+ 1. [First Key Finding, e.g., Hospitals with the Longest Wait Times]
202
+
203
  Present the relevant data in a Markdown table.
204
  Write a short narrative interpreting the data. What does it mean? Are there any outliers? Why might these facilities have long waits (e.g., specialized care, rural location, capacity issues)?
205
+
206
+ 2. [Second Key Finding, e.g., Specialties with the Longest Wait Times]
207
+
208
  Present the relevant data in a Markdown table.
209
  Interpret the findings. Why are these specialties facing delays (e.g., specialist shortages, equipment needs)?
210
+
211
+ 3. [Third Key Finding, e.g., Zone-Level Performance]
212
+
213
  Present the data in a table, including a comparison to a relevant average or baseline.
214
  Analyze the geographic or systemic issues this data reveals.
215
+
216
+ 4. [Fourth Key Finding, if applicable, e.g., Geographic Distribution]
217
+
218
  Synthesize location data with the wait-time findings.
219
  Discuss the implications for patient equity, travel burdens, and access to care.
220
+
221
+ 5. Recommendations for Resource Allocation
222
+
223
  Provide specific, actionable, and justified recommendations.
224
  Structure them by category (e.g., by facility, by specialty, by zone).
225
  For each recommendation, provide a clear rationale directly linked to the data findings above (e.g., "Allocate additional resources to Glace Bay Hospital because it is a rural facility in a high-wait zone, suggesting a capacity bottleneck.").
226
+
227
+ Data Limitations
228
+
229
  Briefly mention any potential limitations of the analysis (e.g., missing data, use of proxies, case severity not included). This adds credibility to the report.
230
+
231
  Do not just repeat the JSON data. Your value is in interpreting the numbers, connecting the dots between different findings, and providing clear, data-backed strategic advice.
232
  """
233
  return _generate_long_report(prompt_for_writer)
 
239
  if not cli:
240
  return "Cohere client not initialized."
241
  vecs = cohere_embed(["hello", "world"])
242
+ return f"Cohere OK (model={COHERE_MODEL_PRIMARY})" if vecs else "Cohere reachable."
243
  except Exception as e:
244
  return f"Cohere ping failed: {e}"
245
  def handle(user_msg: str, files: list, yield_update) -> str:
246
  try:
247
+ Safety filter on incoming message
248
  safe_in, blocked_in, reason_in = safety_filter(user_msg, mode="input")
249
  if blocked_in:
250
  return refusal_reply(reason_in)
251
+ Optional PHI redaction for prompts sent to an external LLM
252
+ redacted_in = safe_in
253
+ if PHI_MODE and REDACT_BEFORE_LLM:
254
+ redacted_in = redact_phi(safe_in)
255
+ file_paths: List[str] = [
256
+ getattr(f, "name", None) or f for f in (files or [])
257
+ ]
258
+ if file_paths:
259
+ CSV analysis path
260
+ dataframes, schema_parts = [], []
261
+ for i, p in enumerate(file_paths):
262
+ if p.endswith(".csv"):
263
+ try:
264
+ df = pd.read_csv(p)
265
+ except UnicodeDecodeError:
266
+ df = pd.read_csv(p, encoding="latin1")
267
+ dataframes.append(df)
268
+ --- IMPROVEMENT: ENRICHED SCHEMA CONTEXT ---
269
+ schema_buffer = io.StringIO()
270
+ df.info(buf=schema_buffer)
271
+ schema_info = schema_buffer.getvalue()
272
+ schema_parts.append(
273
+ f"""DataFrame dfs[{i}] ({os.path.basename(p)}):\n\nHead\n{df.head().to_markdown()}\n\nSchema and Data Types\n\n{schema_info}\n\n\nSummary Statistics\n{df.describe(include='all').to_markdown()}\n"""
 
 
 
 
 
 
 
 
 
 
 
 
274
  )
 
 
275
  if not dataframes:
276
+ return "Please upload at least one CSV file."
277
+ schema_context = "\n".join(schema_parts)
278
+ If external PHI is not allowed, use redacted prompt; otherwise use original
279
+ prompt_for_code = (
280
+ redacted_in if (PHI_MODE and not ALLOW_EXTERNAL_PHI) else safe_in
281
+ )
282
+ yield_update("Generating aligned analysis script...")
 
 
 
 
283
  analysis_script = _create_python_script(prompt_for_code, schema_context)
284
+ yield_update("Executing script to extract raw data...")
285
+ execution_namespace = {"dfs": dataframes, "pd": pd, "re": re, "json": json}
286
+ output_buffer = io.StringIO()
287
+ try:
288
+ with redirect_stdout(output_buffer):
289
+ exec(analysis_script, execution_namespace)
290
+ raw_data_output = output_buffer.getvalue()
291
+ except Exception as e:
292
+ return (
293
+ f"An error occurred executing the script: {e}\n\nGenerated Script:\n"
294
+ f"python\n{analysis_script}\n"
295
+ )
296
+ yield_update("Synthesizing final comprehensive report...")
297
+ writer_input = (
298
+ redacted_in if (PHI_MODE and not ALLOW_EXTERNAL_PHI) else safe_in
299
+ )
300
+ final_report = _generate_final_report(writer_input, raw_data_output)
301
+ return _sanitize_text(final_report)
302
+ else:
303
+ Pure chat path
304
+ chat_input = (
305
+ redacted_in if (PHI_MODE and not ALLOW_EXTERNAL_PHI) else safe_in
306
+ )
307
+ prompt = f"{GENERAL_CONVERSATION_PROMPT}\n\nUser: {chat_input}\nAssistant:"
308
+ return _sanitize_text(cohere_chat(prompt) or "How can I help further?")
309
+ except Exception as e:
310
+ tb = traceback.format_exc()
311
+ safe_log("app_error", {"err": str(e)})
312
+ return "A critical error occurred. Please contact your administrator." if PHI_MODE else f"A critical error occurred: {e}"
 
 
 
 
 
 
313
  PRIVACY_POLICY_TEXT = load_markdown_text("privacy_policy.md")
314
  TERMS_OF_SERVICE_TEXT = load_markdown_text("terms_of_service.md")
315
+ ---------------------- Sleek UI assets (CSS/JS only) ----------------------
 
 
 
316
  SLEEK_CSS = """
317
  /* Full-bleed, modern look */
318
  :root, body, #root, .gradio-container { height: 100%; }
319
  .gradio-container { padding: 0 !important; }
320
  .block { padding: 0 !important; }
 
321
  /* Header */
322
  .header {
323
+ padding: 20px 28px;
324
+ background: linear-gradient(135deg, #0e1726, #1d2a44 60%, #243a5e);
325
+ color: #fff;
326
+ display: flex; align-items: center; justify-content: space-between;
327
+ gap: 16px;
328
  }
329
  .header h1 { margin: 0; font-size: 22px; letter-spacing: 0.3px; font-weight: 600; }
330
  .header .badge { font-size: 12px; opacity: 0.9; background:#ffffff22; padding:6px 10px; border-radius: 999px; }
 
331
  /* Main layout */
332
  .main {
333
+ display: grid;
334
+ grid-template-columns: 420px 1fr;
335
+ gap: 16px;
336
+ padding: 16px;
337
+ height: calc(100vh - 72px);
338
+ box-sizing: border-box;
339
  }
340
  .left, .right {
341
+ background: #0b1020;
342
+ color: #e9edf3;
343
+ border-radius: 16px;
344
+ border: 1px solid #1c2642;
345
  }
346
  .left { padding: 16px; display: flex; flex-direction: column; gap: 12px; }
347
  .right { padding: 0; display: flex; flex-direction: column; }
 
348
  /* Panels */
349
  .panel-title { font-size: 14px; font-weight: 600; color: #aeb8cc; margin-bottom: 6px; }
350
  .helper { font-size: 12px; color: #97a3bb; margin-bottom: 8px; }
 
351
  /* Sticky actions */
352
  .actions {
353
+ display: flex; gap: 8px; align-items: center; justify-content: stretch;
354
  }
355
  .actions .gr-button { flex: 1; }
 
356
  /* Tabs full height */
357
  .right .tabs { height: 100%; display: flex; flex-direction: column; }
358
  .right .tabitem { flex: 1; display: flex; flex-direction: column; }
359
  #chatbot_container { flex: 1; }
360
  #chatbot_container .gr-chatbot { height: 100%; }
 
361
  /* Tiny separators */
362
  .hr { height: 1px; background: #16203b; margin: 10px 0; }
 
363
  /* Voice hint */
364
  .voice-hint { font-size: 12px; color:#9fb0cc; margin-top: 4px; }
365
  """
 
366
  VOICE_STT_HTML = """
367
  <script>
368
  let __rs_rec = null;
369
  function rs_toggle_stt(elemId){
370
+ const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
371
+ if (!SpeechRecognition){
372
+ alert("This browser does not support Speech Recognition. Try Chrome or Edge.");
373
+ return;
374
+ }
375
+ if (__rs_rec){ __rs_rec.stop(); __rs_rec = null; return; }
376
+ __rs_rec = new SpeechRecognition();
377
+ __rs_rec.lang = "en-US";
378
+ __rs_rec.interimResults = true;
379
+ __rs_rec.continuous = true;
380
+
381
+ const box = document.querySelector(`#${elemId} textarea`);
382
+ if (!box){ alert("Prompt box not found."); return; }
383
+ let base = box.value || "";
384
+
385
+ __rs_rec.onresult = (ev) => {
386
+ let t = "";
387
+ for (let i = ev.resultIndex; i < ev.results.length; i++){
388
+ t += ev.results[i][0].transcript;
389
+ }
390
+ box.value = (base + " " + t).trim();
391
+ box.dispatchEvent(new Event("input", { bubbles: true }));
392
+ };
393
+ __rs_rec.onend = () => { __rs_rec = null; };
394
+ __rs_rec.start();
395
  }
396
  </script>
397
  """
398
+ ---------------------- Sleek UI (with fixed State wiring) ----------------------
 
 
 
399
  with gr.Blocks(theme=gr.themes.Soft(), css=SLEEK_CSS, fill_width=True) as demo:
400
+ Persistent in-memory history component (fixes list/_id error)
401
+ assessment_history = gr.State([])
402
+ Header
403
+ with gr.Row(elem_classes=["header"]):
404
+ gr.Markdown("Clarity Ops Augmented Decision Support")
405
+ pill = (
406
+ "PHI Mode ON · history off"
407
+ if (PHI_MODE and not PERSIST_HISTORY)
408
+ else "PHI Mode ON"
409
+ if PHI_MODE
410
+ else "PHI Mode OFF"
411
+ )
412
+ gr.Markdown(f"{pill}")
413
+ Main layout
414
+ with gr.Row(elem_classes=["main"]):
415
+ Left panel
416
+ with gr.Column(elem_classes=["left"]):
417
+ gr.Markdown("New Assessment")
418
+ gr.Markdown(
419
+ "Upload CSVs for analysis, or enter a prompt. Voice works in modern browsers."
420
+ )
421
+ files_input = gr.Files(
422
+ label="Upload Data Files (.csv)",
423
+ file_count="multiple",
424
+ type="filepath",
425
+ file_types=[".csv"],
426
+ )
427
+ prompt_input = gr.Textbox(
428
+ label="Prompt",
429
+ placeholder="Paste your scenario or question here...",
430
+ lines=12,
431
+ elem_id="prompt_box",
432
+ autofocus=True,
433
+ )
434
+ with gr.Row(elem_classes=["actions"]):
435
+ send_btn = gr.Button("Run Analysis", variant="primary")
436
+ clear_btn = gr.Button("Clear")
437
+ voice_btn = gr.Button("Voice")
438
+ gr.Markdown(
439
+ "Click Voice to start/stop dictation into the prompt box."
440
+ )
441
+ ping_btn = gr.Button("Ping Cohere")
442
+ ping_out = gr.Markdown()
443
+ gr.Markdown("")
444
+ if PHI_MODE:
445
+ gr.Markdown(
446
+ "Warning: PHI Mode: History persistence is disabled by default. Avoid unnecessary identifiers."
447
+ )
448
+ with gr.Accordion("Privacy & Terms", open=False):
449
+ gr.Markdown(PRIVACY_POLICY_TEXT)
450
+ gr.Markdown("")
451
+ gr.Markdown(TERMS_OF_SERVICE_TEXT)
452
+ Right panel
453
+ with gr.Column(elem_classes=["right"]):
454
+ with gr.Tabs(elem_classes=["tabs"]):
455
+ with gr.TabItem("Current Assessment", id=0, elem_classes=["tabitem"]):
456
+ with gr.Column(elem_id="chatbot_container"):
457
+ chat_history_output = gr.Chatbot(
458
+ label="Analysis Output", type="messages"
459
+ )
460
+ with gr.TabItem("Assessment History", id=1, elem_classes=["tabitem"]):
461
+ gr.Markdown("### Review Past Assessments")
462
+ history_dropdown = gr.Dropdown(
463
+ label="Select an assessment to review", choices=[]
464
+ )
465
+ history_display = gr.Markdown(label="Selected Assessment Details")
466
+ Inject voice-to-text helper
467
+ gr.HTML(VOICE_STT_HTML)
468
+ --------- Event logic (unchanged analysis flow) ----------
469
+ def run_analysis_wrapper(
470
+ prompt, files, chat_history_list, history_state_list
471
+ ):
472
+ if not prompt:
473
+ gr.Warning("Please enter a prompt.")
474
+ yield chat_history_list, history_state_list, gr.update()
475
+ return
476
+ Append user's message
477
+ chat_with_user_msg = _append_msg(chat_history_list, "user", prompt)
478
+ Thinking bubble
479
+ thinking_message = _append_msg(
480
+ chat_with_user_msg,
481
+ "assistant",
482
+ "Generating and executing analysis... Please wait.",
483
+ )
484
+ yield thinking_message, history_state_list, gr.update()
485
+ Run analysis/chat
486
+ def dummy_update(message: str):
487
+ pass
488
+ ai_response_text = handle(prompt, files, dummy_update)
489
+ Append final assistant response
490
+ final_chat = _append_msg(chat_with_user_msg, "assistant", ai_response_text)
491
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
492
+ Capture filenames (if any)
493
+ file_names: List[str] = []
494
+ if files:
495
+ file_names = [
496
+ os.path.basename(f.name if hasattr(f, "name") else f) for f in files
497
+ ]
498
+ Build history record
499
+ new_entry = {
500
+ "id": timestamp,
501
+ "prompt": prompt,
502
+ "files": file_names,
503
+ "response": ai_response_text,
504
+ "chat_history": final_chat,
505
+ }
506
+ Respect PHI/history flags
507
+ if PERSIST_HISTORY and (not PHI_MODE or (PHI_MODE and HISTORY_TTL_DAYS > 0)):
508
+ updated_history: List[Dict[str, Any]] = (history_state_list or []) + [
509
+ new_entry
510
+ ]
511
+ else:
512
+ updated_history = history_state_list or []
513
+ history_labels = [
514
+ f"{item['id']} - {item['prompt'][:40]}..."
515
+ for item in updated_history
516
+ ]
517
+ yield final_chat, updated_history, gr.update(choices=history_labels)
518
+ def view_history(selection: str, history_state_list: List[Dict[str, Any]]) -> str:
519
+ if not selection or not history_state_list:
520
+ return ""
521
+ try:
522
+ selected_id = selection.split(" - ", 1)[0]
523
+ except Exception:
524
+ selected_id = selection
525
+ selected_assessment = next(
526
+ (item for item in history_state_list if item.get("id") == selected_id), None
527
+ )
528
+ if not selected_assessment:
529
+ return "Could not find the selected assessment."
530
+ file_list = selected_assessment.get("files", [])
531
+ file_list_md = "\n- ".join(file_list) if file_list else "(no files uploaded)"
532
+ chat_entries = selected_assessment.get("chat_history", [])
533
+ chat_md_lines = []
534
+ for msg in chat_entries:
535
+ role = msg.get("role", "").capitalize()
536
+ content = msg.get("content", "")
537
+ chat_md_lines.append(f"{role}: {content}")
538
+ chat_md = "\n\n".join(chat_md_lines)
539
+ return f"""### Assessment from: {selected_assessment['id']}
540
+ Files Used:
541
+
542
+ {file_list_md}
543
+
544
+
545
+ Original Prompt:
546
+ {selected_assessment['prompt']}
547
+
548
+ AI Generated Response:
 
 
 
 
 
 
549
  {selected_assessment['response']}
550
+ Chat Transcript:
 
551
  {chat_md}
552
  """
553
+ Wire events (using proper gr.State component for history)
554
+ send_btn.click(
555
+ run_analysis_wrapper,
556
+ inputs=[prompt_input, files_input, chat_history_output, assessment_history],
557
+ outputs=[chat_history_output, assessment_history, history_dropdown],
558
+ )
559
+ history_dropdown.change(
560
+ view_history,
561
+ inputs=[history_dropdown, assessment_history],
562
+ outputs=[history_display],
563
+ )
564
+ clear_btn.click(
565
+ lambda: (None, None, []),
566
+ outputs=[prompt_input, files_input, chat_history_output],
567
+ )
568
+ ping_btn.click(ping_cohere, outputs=[ping_out])
569
+ voice_btn.click(None, [], [], js="rs_toggle_stt('prompt_box')")
570
+ if name == "main":
571
+ if not os.getenv("COHERE_API_KEY"):
572
+ print(
573
+ "COHERE_API_KEY environment variable not set. Application may not function correctly."
574
+ )
575
+ demo.launch(server_name="0.0.0.0", server_port=int(os.getenv("PORT", "7860")))