Spaces:
Sleeping
Sleeping
File size: 7,670 Bytes
17f3ad3 be1b5d2 17f3ad3 be1b5d2 17f3ad3 be1b5d2 61eaa9c 17f3ad3 be1b5d2 61eaa9c 17f3ad3 61eaa9c 17f3ad3 61eaa9c 17f3ad3 be1b5d2 17f3ad3 be1b5d2 17f3ad3 be1b5d2 17f3ad3 be1b5d2 17f3ad3 be1b5d2 17f3ad3 be1b5d2 17f3ad3 be1b5d2 17f3ad3 |
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 |
import gradio as gr
import json
import csv
import os
from datetime import datetime
from src.interface.session_manager import SimplifiedSessionData
def get_conversation_stats(session: SimplifiedSessionData):
"""Get conversation statistics."""
if session is None or not hasattr(session.app_instance, 'conversation_logger'):
return "No conversation yet"
try:
summary = session.app_instance.get_conversation_summary()
if not summary or summary.get('total_exchanges', 0) == 0:
return "No conversation yet"
stats_text = f"""**📊 Conversation Statistics**
**Messages:** {summary['total_exchanges']} exchanges
**Duration:** {summary['session_duration_minutes']} minutes
**Classifications:**
🟢 Green: {summary['classification_counts']['green']} ({summary['classification_percentages']['green']}%)
🟡 Yellow: {summary['classification_counts']['yellow']} ({summary['classification_percentages']['yellow']}%)
🔴 Red: {summary['classification_counts']['red']} ({summary['classification_percentages']['red']}%)
**Average Confidence:** {summary['average_confidence']}
**Top Indicators:**"""
for indicator, count in list(summary['top_indicators'].items())[:3]:
stats_text += f"\n• {indicator}: {count}"
return stats_text
except Exception as e:
return f"Error getting stats: {str(e)}"
def download_conversation_json(session: SimplifiedSessionData):
"""Download conversation as JSON."""
if session is None or not hasattr(session.app_instance, 'conversation_logger'):
return None
try:
log_path = session.app_instance.get_conversation_log_path()
return log_path
except Exception as e:
print(f"Error downloading JSON: {e}")
return None
def download_conversation_csv(session: SimplifiedSessionData):
"""Download conversation as CSV."""
if session is None or not hasattr(session.app_instance, 'conversation_logger'):
return None
try:
csv_path = session.app_instance.export_conversation_csv()
return csv_path
except Exception as e:
print(f"Error downloading CSV: {e}")
return None
def get_status(session: SimplifiedSessionData):
"""Get current status and stats."""
if session is None:
return "❌ Session not initialized", "No stats", gr.update(visible=False), "No provider summary available", "", ""
session.update_activity()
status_info = session.app_instance._get_status_info()
# Get stats
stats_text = get_conversation_stats(session)
# Check for provider summary
last_summary = session.app_instance.get_last_provider_summary()
show_provider_panel = last_summary is not None
provider_summary_text = ""
coherent_summary_text = ""
if last_summary:
provider_summary_text = session.app_instance.provider_summary_generator.format_for_display(last_summary)
# Generate medical brain summary (NEW - Requirements 2.1-2.8)
try:
coherent_summary_text = session.app_instance.provider_summary_generator.format_coherent_paragraph(last_summary)
print(f"DEBUG get_status: coherent summary generated: {len(coherent_summary_text) if coherent_summary_text else 0} chars")
if not coherent_summary_text:
# Fallback for testing
coherent_summary_text = f"FALLBACK: {last_summary.patient_name or 'Patient'} summary for testing"
except Exception as e:
print(f"Error generating coherent summary in get_status: {e}")
coherent_summary_text = f"ERROR: {str(e)}"
if provider_summary_text:
import html
escaped_text = html.escape(provider_summary_text)
html_content = f"<pre style='white-space: pre-wrap; font-family: monospace; font-size: 11px; background: #fffbeb; padding: 10px; border-radius: 8px; max-height: 400px; overflow-y: auto;'>{escaped_text}</pre>"
status_msg = f"""**🔴 Provider Summary Generated**
**Patient:** {session.app_instance.patient_info.get('name', 'Test Patient')}
**Classification:** RED FLAG
**Indicators:** {len(last_summary.indicators)} distress indicators detected
**Summary Length:** {len(provider_summary_text)} characters
Use the **Download Summary** button below to access the complete provider summary for the spiritual care team."""
else:
html_content = ""
status_msg = "No provider summary available"
return (
status_info,
stats_text,
gr.update(visible=show_provider_panel),
status_msg,
html_content,
coherent_summary_text if coherent_summary_text else "" # Direct value instead of gr.update
)
def download_provider_summary(session: SimplifiedSessionData):
"""Download provider summary as text file."""
if session is None:
return None
last_summary = session.app_instance.get_last_provider_summary()
if not last_summary:
return None
try:
# Generate filename
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
patient_name = session.app_instance.patient_info.get('name', 'Patient').replace(" ", "_")
filename = f"provider_summary_{patient_name}_{timestamp}.txt"
# Format content
content = session.app_instance.provider_summary_generator.format_for_display(last_summary)
# Save to temp file
path = os.path.join(os.getcwd(), "exports", filename)
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w", encoding="utf-8") as f:
f.write(content)
return path
except Exception as e:
print(f"Error downloading provider summary: {e}")
return None
def clear_provider_summary():
"""Clear provider summary panel."""
return (
gr.update(visible=False),
"No provider summary available",
"",
"" # Direct empty string
)
def regenerate_coherent_summary(session: SimplifiedSessionData):
"""Regenerate medical brain summary."""
if session is None:
return ""
last_summary = session.app_instance.get_last_provider_summary()
if not last_summary:
return ""
try:
coherent_text = session.app_instance.provider_summary_generator.format_coherent_paragraph(last_summary)
return coherent_text or "Error generating coherent summary"
except Exception as e:
return f"Error: {str(e)}"
def download_coherent_summary(session: SimplifiedSessionData):
"""Download coherent summary as text file."""
if session is None:
return None
last_summary = session.app_instance.get_last_provider_summary()
if not last_summary:
return None
try:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
patient_name = session.app_instance.patient_info.get('name', 'Patient').replace(" ", "_")
filename = f"coherent_summary_{patient_name}_{timestamp}.txt"
# Generate coherent summary
coherent_text = session.app_instance.provider_summary_generator.format_coherent_paragraph(last_summary)
path = os.path.join(os.getcwd(), "exports", filename)
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w", encoding="utf-8") as f:
f.write(coherent_text)
return path
except Exception as e:
print(f"Error downloading coherent summary: {e}")
return None
|