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=True): 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()