File size: 29,524 Bytes
99416f9 f095630 99416f9 f095630 99416f9 f095630 99416f9 f095630 99416f9 f095630 99416f9 f095630 99416f9 f095630 99416f9 f095630 99416f9 f095630 99416f9 f095630 77244ea f095630 77244ea f095630 77244ea f095630 99416f9 f095630 99416f9 f095630 99416f9 f095630 99416f9 f095630 99416f9 f095630 77244ea f095630 79cc1d2 f095630 79cc1d2 f095630 7aff121 f095630 99416f9 f095630 99416f9 f095630 99416f9 f095630 7aff121 99416f9 f095630 99416f9 f095630 99416f9 7aff121 99416f9 7aff121 37545aa 7aff121 37545aa f095630 37545aa 7aff121 37545aa 7aff121 37545aa 7aff121 37545aa 79cc1d2 37545aa 79cc1d2 f095630 37545aa 7aff121 99416f9 |
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 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 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 |
# -*- 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() |