File size: 8,998 Bytes
17f3ad3
 
 
 
 
be1b5d2
 
17f3ad3
 
be1b5d2
17f3ad3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be1b5d2
61eaa9c
 
 
be1b5d2
 
 
17f3ad3
 
61eaa9c
 
 
 
 
17f3ad3
 
 
 
 
be1b5d2
17f3ad3
 
 
 
 
61eaa9c
 
 
17f3ad3
 
 
 
61eaa9c
 
be1b5d2
 
17f3ad3
61eaa9c
be1b5d2
61eaa9c
 
 
 
 
 
 
 
17f3ad3
be1b5d2
61eaa9c
 
 
 
17f3ad3
 
 
 
 
 
 
 
 
61eaa9c
17f3ad3
 
61eaa9c
 
 
17f3ad3
61eaa9c
 
 
 
 
 
 
17f3ad3
 
 
 
 
 
be1b5d2
17f3ad3
be1b5d2
 
 
61eaa9c
 
be1b5d2
 
61eaa9c
be1b5d2
 
 
 
 
 
 
 
17f3ad3
 
61eaa9c
17f3ad3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61eaa9c
17f3ad3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61eaa9c
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

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"<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>"
    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)