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"
{escaped_text}"
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