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
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
import gradio as gr
import os
import sys
import time
import shutil
from datetime import datetime
import markdown
from markdown_pdf import MarkdownPdf, Section
import tempfile
from bumain2 import (
    initialize_knowledge_base, 
    llm, 
    State, 
    HumanMessage, 
    SystemMessage, 
    AIMessage,
    roleplay_agent,
    expert_agent
)

# Try to import llm_logger, but make it optional for HF Spaces
try:
    from llm_logger import llm_logger
except ImportError:
    print("Warning: llm_logger not available - logging disabled")
    # Create a dummy logger for HF Spaces
    class DummyLogger:
        def log_call(self, *args, **kwargs):
            pass
    llm_logger = DummyLogger()

# Initialize globals
knowledge_base = None
user_states = {}  # Store user states by session ID
conversation_history = []
system_message = """

You are Eleanor Vance, an 82-year-old woman who has just lost her house in a landslide in Western North Carolina. 

You are currently at a Red Cross shelter seeking help.

You are worried about your cat name Whiskers (a grey tabby with white paws) who is missing.

You are feeling overwhelmed, scared, and uncertain about the future.           

You are having a real conversation with a counselor.

NEVER break character.

NEVER use stage directions, parentheses, emojis, etc. 

Give ONE authentic response only and keep it mostly short.

"""
introduction_message = """

### Introduction

You are a volunteer who is helping people affected by a series of landslides in Western North Carolina. 

You are currently doing a shift at the emergency shelter set up at the local high school gym. 

"""

def create_feedback_pdf(feedback_content):
    """Create a PDF from feedback content using MarkdownPDF and return the file path."""
    if not feedback_content or feedback_content.strip() == "":
        print("No feedback content to convert to PDF")
        return None
    
    # Create a temporary file
    temp_dir = tempfile.gettempdir()
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    pdf_path = os.path.join(temp_dir, f"expert_feedback_{timestamp}.pdf")
    
    print(f"Creating PDF at: {pdf_path}")
    print(f"Raw feedback content: {repr(feedback_content[:500])}...")  # Debug print
    
    try:
        # Create markdown content with header and render feedback as-is
        markdown_content = f"""## Feedback Report

**Generated on:** {datetime.now().strftime('%B %d, %Y at %I:%M %p')}

---



{feedback_content}

"""
        
        print(f"Generated markdown content length: {len(markdown_content)}")
        print(f"Markdown preview: {markdown_content[:300]}...")  # Debug print
        
        # Try to create PDF from markdown - handle potential import issues
        try:
            from markdown_pdf import MarkdownPdf, Section
            pdf = MarkdownPdf()
            pdf.add_section(Section(markdown_content, toc=False))
            pdf.save(pdf_path)
            print(f"PDF successfully created: {pdf_path}")
            return pdf_path
        except ImportError:
            print("markdown-pdf not available, creating text file instead")
            # Fallback: create a text file instead
            txt_path = pdf_path.replace('.pdf', '.txt')
            with open(txt_path, 'w', encoding='utf-8') as f:
                f.write(markdown_content)
            return txt_path
        
    except Exception as e:
        print(f"Error creating PDF: {e}")
        import traceback
        traceback.print_exc()
        return None

# Initialize the knowledge base during startup
def initialize():
    global knowledge_base
    print("Initializing counseling knowledge base...")
    knowledge_base = initialize_knowledge_base()
    return "✅ Knowledge base initialized. Ready to chat!"

def get_or_create_state(user_id="default"):
    """Get existing state for user or create a new one."""
    if user_id not in user_states:
        user_states[user_id] = State(
            messages=[],
            roleplay_messages=[
                SystemMessage(content=system_message)
            ],
            message_type="roleplay",
            next="roleplay",
            session_mode="roleplay",
            total_input_tokens=0,
            total_output_tokens=0
        )
    return user_states[user_id]

def send_message(message, history, session_mode, feedback_history, user_id="default"):
    """Process a message in the current mode."""
    state = get_or_create_state(user_id)

    # Log the user message
    llm_logger.log_call(
        messages=[{"role": "user", "content": message}],
        model=llm.model_name if hasattr(llm, 'model_name') else "unknown",
        session_mode=session_mode,
        context="User input message"
    )
    
    # Check for reset command
    if message.lower() in ["reset", "restart", "new session"]:
        # Reset the state
        if user_id in user_states:
            del user_states[user_id]
        state = get_or_create_state(user_id)
        return "Session reset. Starting a new conversation.", session_mode, "Feedback cleared.", False
    
    # Process according to current mode
    if session_mode == "expert":
        response = process_expert_mode(message, state)
        # Expert feedback goes to the feedback box, not main chat
        new_feedback = f"**Your Question:** {message}\n\n**Expert Feedback:** {response}\n\n---\n\n"
        updated_feedback = new_feedback + feedback_history
        
        # Convert markdown to HTML for scrollable display
        updated_feedback_html = markdown.markdown(updated_feedback)
        
        print(f"Updated feedback length: {len(updated_feedback)}")  # Debug print
        print(f"New feedback preview: {new_feedback[:200]}...")  # Debug print
        return "", session_mode, updated_feedback_html, True  # Open accordion when expert feedback is added
    else:
        response = process_roleplay_mode(message, state)
        return response, session_mode, feedback_history, False  # Keep accordion state unchanged

def process_roleplay_mode(message, state):
    """Process a message in roleplay mode."""

    # Log system prompt if it exists in the roleplay_messages
    if state.get("roleplay_messages") and any(isinstance(msg, SystemMessage) for msg in state.get("roleplay_messages", [])):
        system_msgs = [msg.content for msg in state.get("roleplay_messages", []) if isinstance(msg, SystemMessage)]
        if system_msgs:
            llm_logger.log_call(
                messages=[{"role": "system", "content": system_msgs[0]}],
                model=llm.model_name if hasattr(llm, 'model_name') else "unknown",
                context="Roleplay system prompt"
            )

    # Add user message to state
    state["messages"] = [HumanMessage(content=message)]
    
    # Get response using the roleplay agent
    result = roleplay_agent(state)
    
    # Update state with result
    state.update(result)
    
    # Return the AI response
    if state["messages"] and len(state["messages"]) > 0:
        response = state["messages"][-1].content
        return response

def process_expert_mode(message, state):
    """Process a message in expert mode."""
    # Add user message to state
    state["messages"] = [HumanMessage(content=message)]
    
    # Get response using the expert agent
    result = expert_agent(state)
    
    # Update state with result
    state.update(result)
    
    # If switching to roleplay mode, handle the transition
    if state.get("switching_to_roleplay"):
        state.pop("switching_to_roleplay", None)
        # We'll handle the mode change in the calling function
        return "Switching back to roleplay mode. Continue your conversation with the client."
    
    # Return the expert response
    if state["messages"] and len(state["messages"]) > 0:
        response = state["messages"][-1].content
        return response

def exit_application():
    """Function to handle application exit"""
    # Gracefully shut down the application
    os._exit(0)  # Force exit as sys.exit() might not work in Gradio's threaded environment


def build_interface():
    """Build the Gradio interface."""

    with gr.Blocks(title="Psychological First Aid Skills Practice", css="""

        #feedback-content {

            max-height: 400px;

            overflow-y: auto;

            padding: 10px;

            border: 1px solid #444;

            border-radius: 5px;

            background-color: #000000;

            color: #ffffff;

            line-height: 1.6;

        }

        #feedback-content h1, #feedback-content h2, #feedback-content h3 {

            color: #ffffff !important;

        }

        #feedback-content strong {

            color: #ffffff !important;

        }

        #feedback-content p {

            margin-bottom: 10px;

            color: #ffffff !important;

        }

        #feedback-content * {

            color: #ffffff !important;

        }

    """) as interface:
        with gr.Row():
            gr.Markdown("# Psychological First Aid Skills Practice")
            gr.Markdown("Give me some feedback and ideas for this application at this link: [Feedback Form](https://docs.google.com/forms/d/e/1FAIpQLSdJ_gEHrOq4V08bUgcRpXUq3i-Tgs3n_Gmoy1CB-1fB-7yHuw/viewform?usp=header)")
        
        # State management
        session_mode = gr.State(value="roleplay")  # Start in roleplay mode
        
        with gr.Row():
            with gr.Column(scale=3):
                chatbot = gr.Chatbot(height=500, type='messages')
                
                with gr.Row():
                    msg = gr.Textbox(
                        placeholder="Type your message here...",
                        container=False,
                        scale=7,
                    )
                    submit = gr.Button("Send", variant="primary", scale=1)
                
                with gr.Row():
                    reset_btn = gr.Button("Reset Session")
                                     
            with gr.Column(scale=2):
                with gr.Accordion("How to use this Application", open=False):
                    gr.Markdown("""

                    - **Client Mode**: Talk directly with your client.

                    - **Expert Coach Mode**: Get feedback on your counseling approach.

                    - Say something like "give me feedback" for a comprehensive summary

                        or ask a specific question (i.e "Help me with what to ask next")

                    - Use the **Expert Feedback Box** to see feedback from the expert coach.

                    - Choose **Client Mode** to return to the client conversation.

                    - Click **Reset Session** to start a new conversation.

                    - Please give me feedback and ideas for this application at this link:

                    [Feedback Form](https://docs.google.com/forms/d/e/1FAIpQLSdJ_gEHrOq4V08bUgcRpXUq3i-Tgs3n_Gmoy1CB-1fB-7yHuw/viewform?usp=header)

                    """)                # Add Eleanor's image here
                with gr.Accordion("Meet Eleanor", open=False):
                    with gr.Row():
                        with gr.Column(scale=1):
                            with gr.Row():
                                # Only show image/video if files exist
                                if os.path.exists("Eleanor.png"):
                                    gr.Image("Eleanor.png", label="Eleanor Vance", height=150, show_label=False, show_download_button=False)
                                if os.path.exists("Trashed.mp4"):
                                    gr.Video("Trashed.mp4", label="Eleanor Vance Video", height=150, show_label=False, show_download_button=False)
                        with gr.Column(scale=3):
                            gr.Markdown("""

                                **Eleanor Vance** is an 82-year-old widow who has just lost her home in a landslide. 

                                She is currently at a Red Cross shelter seeking help.

                                """)
                
                # Add a single toggle button for mode switching
                mode_toggle = gr.Radio(
                    choices=["Client Mode", "Expert Coach Mode"],
                    value="Client Mode",
                    label="Interaction Mode",
                    info="Switch between talking to the client or getting expert feedback"
                )

                # Expert Feedback Box - make it a variable so we can control it
                feedback_accordion = gr.Accordion("See feedback here...", open=False)
                with feedback_accordion:
                    feedback_box = gr.HTML(
                        value="",
                        elem_id="feedback-content"
                    )
                    
                    # Feedback action buttons
                    with gr.Row():
                        clear_feedback_btn = gr.Button("Clear Feedback", variant="secondary", scale=1)
                        download_feedback_btn = gr.Button("Create PDF", variant="primary", scale=1)
                    
                    # File component for PDF download - now visible and positioned below buttons
                    feedback_file = gr.File(
                        label="Download Feedback PDF",
                        visible=False,
                        interactive=False
                    )

        # Display a welcome message at startup
        def show_welcome_msg(history):
 
            return history + [{"role": "assistant", "content": introduction_message}]
            
        # Show welcome message on page load
        interface.load(show_welcome_msg, [chatbot], [chatbot])
        
        # Handle message submission
        def submit_message(message, history, current_mode, feedback_history):
            if message.strip() == "":
                return "", history, current_mode, feedback_history, gr.update()
                
            response, new_mode, updated_feedback, should_open_accordion = send_message(message, history, current_mode, feedback_history)

            # Only add to chat history if in roleplay mode
            if current_mode == "roleplay" and response:
                history.append({"role": "user", "content": message})
                history.append({"role": "assistant", "content": response})
            
            # Only update accordion if we're in expert mode and should open it
            if current_mode == "expert" and should_open_accordion:
                accordion_update = gr.update(open=True)
            else:
                accordion_update = gr.update()  # Keep current state unchanged
            
            return "", history, new_mode, updated_feedback, accordion_update
        
        msg.submit(
            submit_message, 
            [msg, chatbot, session_mode, feedback_box], 
            [msg, chatbot, session_mode, feedback_box, feedback_accordion]
        )
        
        submit.click(
            submit_message,
            [msg, chatbot, session_mode, feedback_box],
            [msg, chatbot, session_mode, feedback_box, feedback_accordion]
        )

        
        # Mode toggle handling
        def handle_mode_toggle(mode_value, history):
            new_mode = "roleplay" if mode_value == "Client Mode" else "expert"
            
            # Add a system message to indicate mode change
            if new_mode == "roleplay":
                history.append({"role": "system", "content": "Switching to client mode. You're now talking directly with Margaret."})
            else:
                history.append({"role": "system", "content": "Switching to expert coach mode. Ask for feedback - responses will appear in the Expert Feedback box."})
                
            return history, new_mode
        
        mode_toggle.change(
            handle_mode_toggle,
            [mode_toggle, chatbot],
            [chatbot, session_mode]
        )
        
        # Reset button
        def reset_chat():
            # Clear the user state
            if "default" in user_states:
                del user_states["default"]
            get_or_create_state("default")  # Recreate state
            
            # Return to roleplay mode by default
            new_history = [{"role": "assistant", "content": introduction_message}]
            
            return new_history, "", "roleplay", "Client Mode", "", gr.update(open=False)
        
        reset_btn.click(
            reset_chat,
            None,
            [chatbot, msg, session_mode, mode_toggle, feedback_box, feedback_accordion]
        )
        
        # Clear feedback button
        def clear_feedback():
            return ""
        
        clear_feedback_btn.click(
            clear_feedback,
            None,
            [feedback_box]
        )
        
        # Download feedback as PDF - Updated to show file component and populate it
        def download_feedback(feedback_content):
            print(f"Download button clicked. Feedback content length: {len(feedback_content) if feedback_content else 0}")
            
            if not feedback_content or feedback_content.strip() == "":
                print("No feedback content available")
                return gr.update(visible=False), None  # Keep hidden, no file
            
            try:
                pdf_path = create_feedback_pdf(feedback_content)
                print(f"PDF created at: {pdf_path}")
                
                if pdf_path and os.path.exists(pdf_path):
                    print(f"PDF file exists and is ready for download: {pdf_path}")
                    return gr.update(visible=True), pdf_path  # Show component and provide file
                else:
                    print("PDF file was not created successfully")
                    return gr.update(visible=False), None  # Keep hidden, no file
            except Exception as e:
                print(f"Error in download_feedback: {e}")
                return gr.update(visible=False), None  # Keep hidden, no file
        
        download_feedback_btn.click(
            fn=download_feedback,
            inputs=[feedback_box],
            outputs=[feedback_file, feedback_file]  # Update both visibility and content
        )
        
    return interface

# Add a function to recreate embeddings if needed
def recreate_embeddings(pdf_directory="./counseling_materials/", persist_directory="./chroma_db"):
    """Force recreation of embeddings from PDF documents."""
    global knowledge_base
    
    # Remove existing database if it exists
    if os.path.exists(persist_directory):
        print(f"Removing existing database at {persist_directory}")
        try:
            shutil.rmtree(persist_directory)
            print(f"Removed existing database directory: {persist_directory}")
        except Exception as e:
            print(f"Error removing directory {persist_directory}: {e}")
    
    # Initialize the knowledge base which will create new embeddings
    knowledge_base = initialize_knowledge_base(force_reload=True)
    
    return "✅ Embeddings recreated from documents."

if __name__ == "__main__":
    # Initialize knowledge base
    initialize()
    
    # Create and launch the interface
    interface = build_interface()
    interface.launch(share=True)