import gradio as gr import html from src.interface.session_manager import SimplifiedSessionData from src.interface.stats_handlers import get_conversation_stats from src.interface.enhanced_display_integration import create_enhanced_display_integration from src.core.improved_classification_prompt_manager import ImprovedClassificationPromptManager def handle_message(message: str, history, session: SimplifiedSessionData): """Handle user message with enhanced display formatting.""" if session is None: session = SimplifiedSessionData() session.update_activity() # Apply per-session model overrides (if configured in Model Settings) custom_models = getattr(session, 'custom_models', None) if custom_models: session.app_instance.set_model_overrides(custom_models) else: session.app_instance.set_model_overrides({}) # Apply per-session prompt overrides (if configured in Edit Prompts) custom_prompts = getattr(session, 'custom_prompts', None) if custom_prompts: session.app_instance.set_prompt_overrides(custom_prompts) else: session.app_instance.set_prompt_overrides({}) # Store previous spiritual state to detect transitions previous_state = session.app_instance.spiritual_state.spiritual_state # Initialize enhanced display integration enhanced_display = create_enhanced_display_integration() new_history, status = session.app_instance.process_message(message, history) # Check if we just transitioned to RED state (consent was given) current_state = session.app_instance.spiritual_state.spiritual_state consent_just_given = (previous_state.value == "awaiting_consent" and current_state.value == "red") # Get updated conversation stats stats = get_conversation_stats(session) # Check for provider summary (RED flag case) provider_summary_text = "" coherent_summary_text = "" show_provider_panel = False last_summary = session.app_instance.get_last_provider_summary() # Debug logging print(f"DEBUG: last_summary exists: {last_summary is not None}") print(f"DEBUG: consent_just_given: {consent_just_given}") print(f"DEBUG: previous_state: {previous_state.value}, current_state: {current_state.value}") if last_summary: print(f"DEBUG: summary patient: {last_summary.patient_name}") print(f"DEBUG: summary indicators: {last_summary.indicators}") # Use the same approach as get_status function 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: print(f"DEBUG: About to generate coherent summary...") coherent_summary_text = session.app_instance.provider_summary_generator.format_coherent_paragraph(last_summary) print(f"DEBUG: coherent summary generated: {len(coherent_summary_text) if coherent_summary_text else 0} chars") if coherent_summary_text: print(f"DEBUG: coherent summary preview: {coherent_summary_text[:200]}...") else: print(f"DEBUG: coherent summary is empty or None") # Fallback: create a simple test summary coherent_summary_text = f"TEST SUMMARY: {last_summary.patient_name or 'Patient'} is experiencing distress indicators: {', '.join(last_summary.indicators or ['general distress'])}. This is a test to verify the UI is working." print(f"DEBUG: Using fallback test summary: {coherent_summary_text[:100]}...") except Exception as e: print(f"DEBUG: Error generating coherent summary: {e}") import traceback traceback.print_exc() # Fallback: create a simple test summary coherent_summary_text = f"ERROR FALLBACK: Unable to generate summary. Error: {str(e)}" show_provider_panel = True print(f"DEBUG: formatted summary length: {len(provider_summary_text)}") print(f"DEBUG: show_provider_panel: {show_provider_panel}") else: print("DEBUG: No provider summary found") # Debug: print what we're returning print(f"DEBUG RETURN: show_panel={show_provider_panel}, text_len={len(provider_summary_text)}") print(f"DEBUG RETURN: coherent_summary_text length={len(coherent_summary_text) if coherent_summary_text else 0}") if provider_summary_text: print(f"DEBUG RETURN: first 100 chars: {provider_summary_text[:100]}") if coherent_summary_text: print(f"DEBUG RETURN: coherent first 100 chars: {coherent_summary_text[:100]}") print(f"DEBUG RETURN: coherent FULL TEXT: {coherent_summary_text}") # Enhanced display formatting - use same approach as get_status if provider_summary_text: import html escaped_text = html.escape(provider_summary_text) html_content = f"
{escaped_text}"
else:
html_content = ""
# Use gr.update for both visibility and value
if not provider_summary_text:
provider_summary_text = ""
html_content = ""
# Generate status message for provider summary with enhanced formatting
if show_provider_panel and provider_summary_text:
# Get the last assessment for enhanced status display
last_assessment = session.app_instance.spiritual_state.last_assessment
if last_assessment:
# Use simple text format instead of HTML badge for Markdown compatibility
classification_text = f"🔴 **{last_assessment.state.value.upper()} FLAG**"
status_msg = f"""**🔴 Provider Summary Generated**
{classification_text}
**Patient:** {session.app_instance.patient_info.get('name', 'Test Patient')}
**Indicators:** {len(session.app_instance.get_last_provider_summary().indicators) if session.app_instance.get_last_provider_summary() else 0} 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:
status_msg = f"""**🔴 Provider Summary Generated**
**Patient:** {session.app_instance.patient_info.get('name', 'Test Patient')}
**Classification:** 🔴 **RED FLAG**
**Indicators:** {len(session.app_instance.get_last_provider_summary().indicators) if session.app_instance.get_last_provider_summary() else 0} 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:
status_msg = "No provider summary available"
return (
new_history,
status,
session,
"",
stats,
gr.update(visible=show_provider_panel), # provider_summary_content visibility
status_msg, # provider_summary_status content
gr.update(value=html_content, visible=True) if show_provider_panel else gr.update(visible=False), # provider_summary_display content
coherent_summary_text if coherent_summary_text else "" # coherent_summary_display content - try direct value
)
def handle_clear(session: SimplifiedSessionData):
"""
Handle clear chat button.
Resets entire session including:
- Chat history
- Spiritual monitoring state
- Provider summary panel (hides and clears content)
- Conversation statistics
"""
if session is None:
session = SimplifiedSessionData()
session.update_activity()
new_history, status = session.app_instance.reset_session()
# Hide and clear provider summary panel
return (
new_history, # Clear chat history
status, # Reset status
session, # Updated session
gr.update(visible=False), # Hide provider_summary_content group
"No provider summary available", # Clear provider_summary_status
"", # Clear provider_summary_display HTML
"" # Clear coherent_summary_display - direct value
)
def send_example(example_text: str, history, session: SimplifiedSessionData):
"""Send example message."""
return handle_message(example_text, history, session)
def send_example_with_stats(example_text: str, history, session: SimplifiedSessionData):
"""Send example message and return stats."""
# Assuming this was supposed to be similar to send_example but returning different things?
# In the original file, it calls handle_message which returns 9 items.
# We should match the return signature if this is used by a button.
return handle_message(example_text, history, session)