mirrors / app.py
Shim
.
f095630
Raw History Blame Contribute Delete
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()