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()