Download app.py from shim5/mirrors: direct link, hf CLI and curl.
- Browser
- Download file 29.5 kB
-
https://huggingface.co/spaces/shim5/mirrors/resolve/main/app.py
- Command line
-
hf download hf://spaces/shim5/mirrors/app.py
-
curl -L -o app.py https://huggingface.co/spaces/shim5/mirrors/resolve/main/app.py
29.5 kB
| # -*- coding: utf-8 -*- | |
| """ | |
| ืืจืืืช (Mirrors) - Hebrew Self-Reflective AI Agent | |
| Main application file with Gradio interface | |
| """ | |
| import gradio as gr | |
| import torch | |
| from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline | |
| import logging | |
| import sys | |
| from typing import List, Tuple, Optional | |
| import os | |
| import random | |
| # Import our custom modules | |
| from prompt_engineering import ( | |
| DEFAULT_PARTS, | |
| get_system_prompt, | |
| get_initial_prompts, | |
| get_part_selection_text | |
| ) | |
| from conversation_manager import ConversationManager, ConversationState | |
| # Configure logging | |
| logging.basicConfig(level=logging.INFO) | |
| logger = logging.getLogger(__name__) | |
| class MirautrApp: | |
| """Main application class for ืืจืืืช""" | |
| def __init__(self): | |
| self.model = None | |
| self.tokenizer = None | |
| self.generator = None | |
| self.conversation_manager = ConversationManager() | |
| self.model_available = False | |
| self.setup_model() | |
| def setup_model(self): | |
| """Initialize a Hebrew-capable model with proper fallback""" | |
| try: | |
| # Check environment | |
| is_hf_spaces = os.getenv("SPACE_ID") is not None | |
| is_test_mode = os.getenv("FORCE_LIGHT_MODEL") is not None | |
| logger.info(f"Environment: HF_Spaces={is_hf_spaces}, Test_Mode={is_test_mode}") | |
| # Try to load a model that can handle Hebrew | |
| model_name = None | |
| if is_test_mode: | |
| # For testing, use a small model but focus on template responses | |
| logger.info("Test mode - will use template-based responses primarily") | |
| self.model_available = False | |
| return | |
| elif is_hf_spaces: | |
| # For HF Spaces, try a lightweight multilingual model | |
| try: | |
| model_name = "microsoft/DialoGPT-small" # Start simple, can upgrade later | |
| logger.info(f"HF Spaces: Attempting to load {model_name}") | |
| except: | |
| logger.info("HF Spaces: Model loading failed, using template responses") | |
| self.model_available = False | |
| return | |
| else: | |
| # For local, try better models | |
| possible_models = [ | |
| "microsoft/DialoGPT-medium", # Better conversational model | |
| "microsoft/DialoGPT-small" # Fallback | |
| ] | |
| for model in possible_models: | |
| try: | |
| model_name = model | |
| logger.info(f"Local: Attempting to load {model_name}") | |
| break | |
| except: | |
| continue | |
| if not model_name: | |
| logger.info("Local: No suitable model found, using template responses") | |
| self.model_available = False | |
| return | |
| # Load the model | |
| if model_name: | |
| self.tokenizer = AutoTokenizer.from_pretrained(model_name) | |
| if self.tokenizer.pad_token is None: | |
| self.tokenizer.pad_token = self.tokenizer.eos_token | |
| # Use CPU for stability across environments | |
| self.model = AutoModelForCausalLM.from_pretrained( | |
| model_name, | |
| torch_dtype=torch.float32, | |
| low_cpu_mem_usage=True | |
| ) | |
| self.generator = pipeline( | |
| "text-generation", | |
| model=self.model, | |
| tokenizer=self.tokenizer, | |
| max_new_tokens=50, | |
| temperature=0.7, | |
| do_sample=True, | |
| pad_token_id=self.tokenizer.pad_token_id, | |
| return_full_text=False | |
| ) | |
| self.model_available = True | |
| logger.info(f"Model loaded successfully: {model_name}") | |
| except Exception as e: | |
| logger.warning(f"Model loading failed: {e}") | |
| logger.info("Falling back to template-based responses") | |
| self.model_available = False | |
| def generate_persona_response(self, user_message: str, conversation_state: ConversationState) -> str: | |
| """ | |
| Generate persona-based response using templates with personality variations | |
| This is our primary response system that always works | |
| """ | |
| part_info = DEFAULT_PARTS.get(conversation_state.selected_part, {}) | |
| persona_name = conversation_state.persona_name or part_info.get("default_persona_name", "ืืืง ืคื ืืื") | |
| # Get conversation context for more personalized responses | |
| recent_context = "" | |
| if conversation_state.conversation_history: | |
| # Get last few exchanges for context | |
| last_messages = conversation_state.conversation_history[-4:] # Last 2 exchanges | |
| recent_context = " ".join([msg["content"] for msg in last_messages]) | |
| # Generate contextual responses based on part type | |
| if conversation_state.selected_part == "ืืงืื ืืืืงืืจืชื": | |
| responses = [ | |
| f"ืื ื {persona_name}, ืืงืื ืืืืงืืจืชื ืฉืื. ืฉืืขืชื ืื ืฉืืืจืช ืขื '{user_message}' - ืื ื ืืืฉื ืฉืฆืจืื ืืืืื ืืช ืื ืืืชืจ ืืขืืืง. ืื ืืืืช ืขืืื ืืืืืจื ืืืืฉืืืช ืืืื?", | |
| f"ืื ื {persona_name}. ืื ืฉืืืจืช ืืขืืจืจ ืื ืฉืืืืช. '{user_message}' - ืืื ืืื ืื ืืืืช ืืืฆื ืืืื? ืืืื ืืฉ ืืื ืืืจืื ืฉืืชื ืื ืจืืื?", | |
| f"ืื {persona_name} ืืืืจ. ืื ื ืฉืืืข ืืืชื ืืืืจ '{user_message}', ืืื ืื ื ืืจืืืฉ ืฉืื ืื ื ืฆืจืืืื ืืืืืช ืืืชืจ ืืืงืืจืชืืื ืืื. ืื ืืชื ืื ืืกืคืจ ืืขืฆืื?", | |
| f"ืื ื {persona_name}, ืืื ื ืืื ืืื ืืขืืืจ ืื ืืจืืืช ืืช ืืชืืื ื ืืืืื. ืื ืฉืืืจืช ืขื '{user_message}' - ืื ืจืง ืืฆื ืืืกืืคืืจ, ืื? ืืืื ื ื ืืคืืจ ืขืืืง ืืืชืจ." | |
| ] | |
| elif conversation_state.selected_part == "ืืืื/ื ืืคื ืืืืช": | |
| responses = [ | |
| f"ืื ื {persona_name}, ืืืื/ื ืืคื ืืืืช ืฉืื. ืื ืฉืืืจืช ืขื '{user_message}' ืืืจื ืื ืืืจืืืฉ... ืงืฆืช ืคืืืข. ืืชื ืืืืช ืฉืืืข ืืืชื ืขืืฉืื?", | |
| f"ืื {persona_name}. '{user_message}' - ืื ืืืืื ืืืชื ืงืฆืช. ืื ื ืฆืจืื ืืืขืช ืฉืืื ืืืื ืืกืืจ. ืืชื ืืืื ืืืจืืืข ืืืชื?", | |
| f"ืื ื {persona_name}, ืืืืง ืืฆืขืืจ ืฉืื. ืื ืฉืืืจืช ื ืืืข ืืื ืฉืื. '{user_message}' - ืื ื ืืจืืืฉ ืฉืืฉ ืืื ืืฉืื ืืฉืื ืฉืื ื ืฆืจืื ืืืืื.", | |
| f"ืื {persona_name} ืืืืจ ืืฉืงื. ืื ื ืฉืืืข ืืช '{user_message}' ืืื ืืขืืจืจ ืื ืจืืฉืืช. ืืื ืื ืืืื ืืืฉืื ืขื ืื? ืื ื ืงืฆืช ืืจื." | |
| ] | |
| elif conversation_state.selected_part == "ืืืจืฆื": | |
| responses = [ | |
| f"ืื ื {persona_name}, ืืืจืฆื ืฉืื. ืฉืืขืชื ืืช '{user_message}' ืืื ื ืจืืฆื ืืืืื ืฉืืืื ืืืื ืืกืืจ ืขื ืื. ืืื ืื ืื ื ืืืืืื ืืคืชืืจ ืืช ืื ืืฆืืจื ืฉืชืจืฆื ืืช ืืืื?", | |
| f"ืื {persona_name}. ืื ืฉืืืจืช ืขื '{user_message}' ืืืจื ืื ืืืืื - ืืื ืื ืืืื ืืคืืืข ืืืืฉืื? ืืืื ื ื ืืฆื ืืจื ืขืืื ื ืืืชืจ ืืืชืืืื ืขื ืื.", | |
| f"ืื ื {persona_name}, ืืื ื ืจืืฆื ืฉืืืื ืืืื ืืจืืฆืื ืืื. '{user_message}' - ืื ื ืฉืืข ืืื ืืฉืื ืฉืืืื ืืืฆืืจ ืืชื. ืืื ื ืืื ืืขืฉืืช ืืช ืื ืืฆืืจื ืฉืืืื ืืืืื?", | |
| f"ืื {persona_name} ืืืืจ. ืื ื ืฉืืืข ืืช '{user_message}' ืืืื ืื ื ืืืฉื - ืื ืืืจืื ืืืืื ืขื ืื? ืืืื ื ื ืืืื ืฉืื ืื ื ืื ืคืืืขืื ืืืฃ ืืื." | |
| ] | |
| elif conversation_state.selected_part == "ืืืื": | |
| responses = [ | |
| f"ืื ื {persona_name}, ืืืื ืฉืื. '{user_message}' - ืื ื ืืขืจืื ืืช ืืืฆื. ืืื ืื ืืืื? ืื ื ืืื ืืื ืืฉืืืจ ืขืืื ืืื ืื ืฉืืืื ืืคืืืข ืื.", | |
| f"ืื {persona_name}. ืฉืืขืชื ืื ืฉืืืจืช ืขื '{user_message}' ืืื ื ืืื ืืืื ื ืืช. ืื ืืืืืืื ืืื? ืืื ืื ื ืืืื ืืืื ืขืืื ืืื ืืืชืจ?", | |
| f"ืื ื {persona_name}, ืืฉืืืจ ืฉืื. ืื ืฉืืืจืช ืืขืืจืจ ืื ืืช ืืืื ืกืืื ืงืืื ืืืื ืืื. '{user_message}' - ืืืื ื ื ืืืื ืฉืืชื ืืืง ืืกืคืืง ืืืชืืืื ืขื ืื.", | |
| f"ืื {persona_name} ืืืืจ. ืื ื ืฉืืืข ืืช '{user_message}' ืืื ื ืืืฉื ืขื ืืกืืจืืืืืช ืืื ื. ืื ืื ืื ื ืฆืจืืืื ืืขืฉืืช ืืื ืฉืชืืื ืืืื?" | |
| ] | |
| elif conversation_state.selected_part == "ืื ืื ืข/ืช": | |
| responses = [ | |
| f"ืื ื {persona_name}, ืื ืื ืข/ืช ืฉืื. ืื ืฉืืืจืช ืขื '{user_message}' ืืืจื ืื ืืจืฆืืช ืืืืกืื ืงืฆืช. ืืืื... ืื ืืืืืื ืืืชืืืื ืขื ืื ืขืืฉืื?", | |
| f"ืื {persona_name}. '{user_message}' - ืื ื ืฉืืข ืืืจืื ืืืคืืื. ืืื ืืฉ ืืจื ืืืืื ืข ืืื? ืืคืขืืื ืขืืืฃ ืื ืืืืื ืก ืืืฆืืื ืงืฉืื.", | |
| f"ืื ื {persona_name}, ืืื ื ืืจืืืฉ ืงืฆืช ืืจืื ื'{user_message}'. ืืืื ื ื ืืืืจ ืืื ืืืจ ืื? ืืืื ืขืืฉืื ืื ืื ืืืื ืืืชืืื.", | |
| f"ืื {persona_name} ืืืืจ ืืืืืจืืช. ืื ืฉืืืจืช ืืขืืจืจ ืื ืจืฆืื ืืืจืื. '{user_message}' - ืืื ืืืืช ืฆืจืื ืืืชืืืื ืขื ืื ืขืืฉืื?" | |
| ] | |
| else: | |
| responses = [ | |
| f"ืื ื {persona_name}, ืืืง ืคื ืืื ืฉืื. ืฉืืขืชื ืืช '{user_message}' ืืื ื ืืื ืืื ืืฉืืื ืืืชื ืขื ืื. ืื ืขืื ืืชื ืืจืืืฉ ืืืื ืืืฆื ืืื?", | |
| f"ืื {persona_name}. ืื ืฉืืืจืช ืืขื ืืื ืืืชื. '{user_message}' - ืืืื ื ื ืืงืืจ ืืช ืื ืืื ืื ืืื ืื ืื ืืืืจ ืขืืื.", | |
| f"ืื ื {persona_name}, ืืื ื ืจืืฆื ืืืืื ืืืชื ืืื ืืืชืจ. '{user_message}' - ืืื ืื ืืฉืคืืข ืขืืื ืืจืื ืืจืืฉืืช?", | |
| f"ืื {persona_name} ืืืืจ. ืื ื ืฉืืืข ืืช '{user_message}' ืืื ื ืกืงืจื ืืืขืช ืืืชืจ. ืื ืขืื ืืฉ ืื ืื ืืฉื ืืื?" | |
| ] | |
| # Select response based on context or randomly | |
| if "ืคืื" in user_message or "ืืจืื" in user_message: | |
| # Choose responses that address fear/anxiety | |
| selected_response = responses[1] if len(responses) > 1 else responses[0] | |
| elif "ืืขืก" in user_message or "ืืจืืืฉ ืจืข" in user_message: | |
| # Choose responses that address anger/negative feelings | |
| selected_response = responses[2] if len(responses) > 2 else responses[0] | |
| else: | |
| # Choose randomly for variety | |
| selected_response = random.choice(responses) | |
| # Add user context if relevant | |
| if conversation_state.user_context and len(conversation_state.conversation_history) < 4: | |
| selected_response += f" ืืืืจ ืฉืืืจืช ืืืชืืื: {conversation_state.user_context[:100]}..." | |
| return selected_response | |
| def generate_response(self, user_message: str, conversation_state: ConversationState) -> str: | |
| """ | |
| Generate AI response - uses persona templates as primary with optional model enhancement | |
| """ | |
| try: | |
| if not conversation_state.selected_part: | |
| return "ืื ื ืฆืจืื ืฉืชืืืจ ืืืง ืคื ืืื ืืื ืืฉืืื ืืืชื." | |
| # Always generate persona-based response first (our reliable system) | |
| persona_response = self.generate_persona_response(user_message, conversation_state) | |
| # If model is available, try to enhance the response (but don't depend on it) | |
| if self.model_available and self.generator: | |
| try: | |
| # Create a simple English prompt for the model to add conversational flow | |
| english_prompt = f"User said they feel: {user_message[:50]}. Respond supportively in 1-2 sentences:" | |
| model_output = self.generator(english_prompt, max_new_tokens=30, temperature=0.7) | |
| if model_output and len(model_output) > 0: | |
| # Extract any useful emotional tone or structure, but keep Hebrew content | |
| model_text = model_output[0]["generated_text"].strip() | |
| # Don't replace our Hebrew response, just use model for emotional context | |
| logger.info(f"Model provided contextual input: {model_text[:50]}...") | |
| except Exception as model_error: | |
| logger.warning(f"Model enhancement failed: {model_error}") | |
| # Continue with persona response only | |
| # Always return the Hebrew persona response | |
| return persona_response | |
| except Exception as e: | |
| logger.error(f"Error generating response: {e}") | |
| return "ืกืืืื, ืืืื ื ื ื ืกื ืฉืื. ืืื ืืชื ืืจืืืฉ ืขืืฉืื?" | |
| def create_main_interface(self): | |
| """Create the main Gradio interface""" | |
| # Custom CSS for Hebrew support | |
| css = """ | |
| .rtl { | |
| direction: rtl; | |
| text-align: right; | |
| } | |
| .hebrew-text { | |
| font-family: 'Segoe UI', Tahoma, Arial, sans-serif; | |
| direction: rtl; | |
| text-align: right; | |
| } | |
| .welcome-text { | |
| font-size: 24px; | |
| font-weight: bold; | |
| color: #2c5aa0; | |
| margin: 20px 0; | |
| } | |
| """ | |
| with gr.Blocks(css=css, title="ืืจืืืช - ืืจืื ืืืฉื ืืฉืื ืคื ืืื", theme=gr.themes.Soft()) as demo: | |
| # Session state | |
| conversation_state = gr.State(self.conversation_manager.create_new_session()) | |
| # Header | |
| status_message = "๐ค ืืขืจืืช ืชืืืืืช ืืืชืืืช ืืืฉืืช ืคืขืืื" if not self.model_available else "๐ค ืืขืจืืช ืืืื ืขื ืืืื AI ืคืขืืื" | |
| gr.HTML(f""" | |
| <div class="hebrew-text welcome-text" style="text-align: center;"> | |
| ๐ช ืืจืืืช: ืืจืื ืืืฉื ืืฉืื ืคื ืืื ืืืคืชื ืขื ืขืฆืื ๐ช | |
| </div> | |
| <div class="hebrew-text" style="text-align: center; margin-bottom: 20px;"> | |
| ืืงืื ืืืื ืืฉืืื ืขื ืืืืงืื ืืฉืื ืื ืฉื ืขืฆืื ืืืคืชื ืืื ื ืขืฆืืืช ืขืืืงื ืืืชืจ | |
| </div> | |
| <div style="background-color: #e8f5e8; border: 1px solid #4caf50; padding: 10px; margin: 10px 0; border-radius: 5px; text-align: center;"> | |
| <strong>{status_message}</strong> | |
| </div> | |
| """) | |
| # Main interface areas | |
| with gr.Column(): | |
| # Step 1: Initial context gathering | |
| with gr.Group(visible=True) as initial_step: | |
| gr.Markdown("## ืฉืื 1: ืกืคืจ/ืกืคืจื ืขื ืขืฆืื", elem_classes=["hebrew-text"]) | |
| initial_prompts = get_initial_prompts() | |
| initial_choice = gr.Radio( | |
| choices=[ | |
| ("ืชืืจ/ืชืืจื ืืช ืขืฆืื ืืืื", "describe_self"), | |
| ("ืืื ืืชื ืืืฉื ืฉืืืจืื ืจืืืื ืืืชื?", "self_perception"), | |
| ("ืืืื ืืชืืจ ืืชื ืืืื ืขืืฉืื ืืืืื?", "current_challenge") | |
| ], | |
| label="ืืืจ/ืืืจื ื ืืฉื ืืฉืืชืืฃ:", | |
| elem_classes=["hebrew-text"] | |
| ) | |
| user_context_input = gr.Textbox( | |
| label="ืกืคืจ/ืกืคืจื ืืืื ืืฉืคืืื:", | |
| placeholder="ืืชืื/ืืชืื ืืื ืืช ืืืืฉืืืช ืฉืื...", | |
| lines=4, | |
| elem_classes=["hebrew-text"] | |
| ) | |
| continue_to_parts = gr.Button("ืืืฉื ืืืืืจืช ืืืง ืคื ืืื", variant="primary") | |
| # Step 2: Part selection | |
| with gr.Group(visible=False) as parts_step: | |
| gr.Markdown("## ืฉืื 2: ืืืจ/ืืืจื ืืืง ืคื ืืื ืืฉืืื", elem_classes=["hebrew-text"]) | |
| part_selection = gr.Radio( | |
| choices=[ | |
| ("ืืงืื ืืืืงืืจืชื - ืืืืง ืฉืื ืกื ืืืื ืขืืื ืขื ืืื ืืืงืืจืช ืืืืืื ื", "ืืงืื ืืืืงืืจืชื"), | |
| ("ืืืื/ื ืืคื ืืืืช - ืืืืง ืืคืืืข, ืืฆืขืืจ ืืืืืืชื ืฉืื", "ืืืื/ื ืืคื ืืืืช"), | |
| ("ืืืจืฆื - ืืืืง ืฉืจืืฆื ืฉืืืื ืืืื ืืจืืฆืื", "ืืืจืฆื"), | |
| ("ืืืื - ืืืืง ืืืืง ืฉืืื ืขืืื ืืคื ื ืคืืืขืืช", "ืืืื"), | |
| ("ืื ืื ืข/ืช - ืืืืง ืฉืืขืืืฃ ืืืืื ืข ืืืฆืืื ืืืชืืจืื", "ืื ืื ืข/ืช") | |
| ], | |
| label="ืืืื ืืืง ืคื ืืื ืชืจืฆื ืืคืืืฉ?", | |
| elem_classes=["hebrew-text"] | |
| ) | |
| # Customization options | |
| with gr.Accordion("ืืชืืื ืืืฉืืช (ืืืคืฆืืื ืื)", open=False): | |
| persona_name = gr.Textbox( | |
| label="ืฉื ืืืืง ืืื:", | |
| placeholder="ืืืฉื: ืื ื, ืืืื, ืืื...", | |
| elem_classes=["hebrew-text"] | |
| ) | |
| persona_age = gr.Textbox( | |
| label="ืืื ืื ืชืงืืคืช ืืืื:", | |
| placeholder="ืืืฉื: ืืื/ื, ืืชืืืจ/ืช, ืืืืจ/ืช...", | |
| elem_classes=["hebrew-text"] | |
| ) | |
| persona_style = gr.Textbox( | |
| label="ืกืื ืื ืืืืืจ ืืืืื:", | |
| placeholder="ืืืฉื: ืจืืืฉ, ืจืฆืื ื, ืืฉืขืฉืข...", | |
| elem_classes=["hebrew-text"] | |
| ) | |
| start_conversation = gr.Button("ืืชืื ืฉืืื", variant="primary") | |
| # Step 3: Conversation interface | |
| with gr.Group(visible=False) as conversation_step: | |
| gr.Markdown("## ืฉืืื ืขื ืืืืง ืืคื ืืื ืฉืื", elem_classes=["hebrew-text"]) | |
| current_part_display = gr.Markdown("", elem_classes=["hebrew-text"]) | |
| # Chat interface | |
| with gr.Row(): | |
| with gr.Column(scale=4): | |
| chatbot = gr.Chatbot( | |
| height=400, | |
| label="ืืฉืืื ืฉืื", | |
| elem_classes=["hebrew-text"], | |
| rtl=True | |
| ) | |
| msg_input = gr.Textbox( | |
| label="ืืืืืขื ืฉืื:", | |
| placeholder="ืืชืื/ืืชืื ืืช ืืืืฉืืืช ืฉืื ืืื...", | |
| lines=2, | |
| elem_classes=["hebrew-text"] | |
| ) | |
| with gr.Row(): | |
| send_btn = gr.Button("ืฉืื", variant="primary") | |
| clear_btn = gr.Button("ื ืงื ืฉืืื") | |
| with gr.Column(scale=1): | |
| gr.Markdown("### ืคืขืืืืช ื ืืกืคืืช", elem_classes=["hebrew-text"]) | |
| change_part_btn = gr.Button("ืืืืฃ ืืืง ืคื ืืื") | |
| restart_btn = gr.Button("ืืชืื ืืืืฉ") | |
| # Event handlers | |
| def process_initial_context(choice, context, state): | |
| """Process initial context and move to part selection""" | |
| if not choice or not context.strip(): | |
| gr.Warning("ืื ื ืืืจ ื ืืฉื ืืืชื ืืฉืื ืืื ืืืืฉืื") | |
| return state, gr.update(), gr.update(visible=True), gr.update(visible=False), gr.update(visible=False) | |
| state = self.conversation_manager.set_initial_context(state, choice, context) | |
| return ( | |
| state, | |
| gr.update(), | |
| gr.update(visible=False), | |
| gr.update(visible=True), | |
| gr.update(visible=False) | |
| ) | |
| def start_chat(part, p_name, p_age, p_style, state): | |
| """Start the conversation with selected part""" | |
| if not part: | |
| gr.Warning("ืื ื ืืืจ ืืืง ืคื ืืื ืืื ืืืชืืื") | |
| return state, gr.update(), gr.update(visible=False), gr.update(visible=True), gr.update(visible=False), gr.update() | |
| state = self.conversation_manager.set_selected_part( | |
| state, part, p_name.strip() if p_name else None, | |
| p_age.strip() if p_age else None, p_style.strip() if p_style else None | |
| ) | |
| part_info = DEFAULT_PARTS.get(part, {}) | |
| display_name = (p_name.strip() if p_name else None) or part_info.get("default_persona_name", "ืืืง ืคื ืืื") | |
| display_text = f"๐ฃ๏ธ ืืขืช ืืชื ืืชืฉืืื ืขื: **{display_name}** ({part})" | |
| return ( | |
| state, | |
| display_text, | |
| gr.update(visible=False), | |
| gr.update(visible=False), | |
| gr.update(visible=True), | |
| [] | |
| ) | |
| def handle_message(message, history, state): | |
| """Handle user message and generate response""" | |
| if not message.strip(): | |
| return "", history, state | |
| # Generate response | |
| response = self.generate_response(message, state) | |
| # Update conversation state | |
| state = self.conversation_manager.add_to_history(state, message, response) | |
| # Update history for display | |
| history.append([message, response]) | |
| return "", history, state | |
| def clear_conversation(state): | |
| """Clear conversation history""" | |
| state = self.conversation_manager.clear_conversation(state) | |
| return [], state | |
| def change_part(): | |
| """Return to part selection""" | |
| return ( | |
| gr.update(visible=False), | |
| gr.update(visible=True), | |
| gr.update(visible=False) | |
| ) | |
| def restart_completely(): | |
| """Restart the entire session""" | |
| new_state = self.conversation_manager.create_new_session() | |
| return ( | |
| new_state, | |
| gr.update(visible=True), | |
| gr.update(visible=False), | |
| gr.update(visible=False), | |
| [], | |
| "", | |
| "", | |
| None, | |
| None, | |
| "", | |
| "", | |
| "" | |
| ) | |
| # Wire up event handlers | |
| continue_to_parts.click( | |
| fn=process_initial_context, | |
| inputs=[initial_choice, user_context_input, conversation_state], | |
| outputs=[conversation_state, current_part_display, initial_step, parts_step, conversation_step] | |
| ) | |
| start_conversation.click( | |
| fn=start_chat, | |
| inputs=[part_selection, persona_name, persona_age, persona_style, conversation_state], | |
| outputs=[conversation_state, current_part_display, initial_step, parts_step, conversation_step, chatbot] | |
| ) | |
| # Chat message handling | |
| msg_input.submit( | |
| fn=handle_message, | |
| inputs=[msg_input, chatbot, conversation_state], | |
| outputs=[msg_input, chatbot, conversation_state] | |
| ) | |
| send_btn.click( | |
| fn=handle_message, | |
| inputs=[msg_input, chatbot, conversation_state], | |
| outputs=[msg_input, chatbot, conversation_state] | |
| ) | |
| clear_btn.click( | |
| fn=clear_conversation, | |
| inputs=[conversation_state], | |
| outputs=[chatbot, conversation_state] | |
| ) | |
| change_part_btn.click( | |
| fn=change_part, | |
| outputs=[conversation_step, parts_step, initial_step] | |
| ) | |
| restart_btn.click( | |
| fn=restart_completely, | |
| outputs=[conversation_state, initial_step, parts_step, conversation_step, chatbot, | |
| user_context_input, current_part_display, initial_choice, part_selection, | |
| persona_name, persona_age, persona_style] | |
| ) | |
| return demo | |
| def main(): | |
| """Main function to launch the application""" | |
| logger.info("Starting ืืจืืืช application...") | |
| try: | |
| app = MirautrApp() | |
| demo = app.create_main_interface() | |
| # Check environment | |
| is_hf_spaces = os.getenv("SPACE_ID") is not None | |
| logger.info(f"Launching app... HF Spaces: {is_hf_spaces}") | |
| # Unified launch configuration for both environments | |
| # This ensures identical experience in both local and HF Spaces | |
| launch_config = { | |
| "show_error": True, | |
| "show_api": False, # Disable API docs to avoid schema issues | |
| "favicon_path": None, | |
| "auth": None, | |
| "enable_queue": False, # Disable queue to prevent schema issues | |
| "max_threads": 1 # Limit threads for stability | |
| } | |
| if is_hf_spaces: | |
| # HF Spaces specific settings | |
| logger.info("Configuring for HF Spaces deployment") | |
| launch_config.update({ | |
| "server_name": "0.0.0.0", | |
| "server_port": 7860, | |
| "share": False, # HF Spaces handles public access | |
| "quiet": True | |
| }) | |
| else: | |
| # Local development settings | |
| logger.info("Configuring for local development") | |
| # Try to find an available port | |
| default_port = int(os.getenv("GRADIO_SERVER_PORT", "7861")) | |
| available_port = default_port | |
| # Check if port is available, if not find next available | |
| import socket | |
| for port_try in range(default_port, default_port + 10): | |
| try: | |
| with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: | |
| s.bind(('127.0.0.1', port_try)) | |
| available_port = port_try | |
| break | |
| except OSError: | |
| continue | |
| logger.info(f"Using port {available_port} for local development") | |
| launch_config.update({ | |
| "server_name": "127.0.0.1", | |
| "server_port": available_port, | |
| "share": True, # Enable share for local testing to avoid localhost issues | |
| "inbrowser": True, # Auto-open browser | |
| "quiet": False | |
| }) | |
| demo.launch(**launch_config) | |
| except Exception as e: | |
| logger.error(f"Failed to start application: {e}") | |
| raise | |
| if __name__ == "__main__": | |
| main() |