File size: 34,959 Bytes
1642415
 
 
 
 
 
 
 
ce8069b
1642415
38eadf8
74b60b6
1642415
 
 
74b60b6
ce8069b
1642415
dbba862
1642415
74b60b6
1642415
74b60b6
1642415
74b60b6
 
 
 
 
 
1642415
 
74b60b6
 
 
1642415
74b60b6
 
1642415
 
74b60b6
 
 
1642415
74b60b6
1642415
 
 
74b60b6
dbba862
e69c269
1642415
74b60b6
1642415
 
 
 
 
 
 
 
 
 
9cee324
1642415
 
74b60b6
dbba862
1642415
 
 
74b60b6
1642415
 
 
 
 
 
 
74b60b6
1642415
 
 
 
74b60b6
1642415
 
 
 
c23c630
ce8069b
1642415
dbba862
1642415
 
 
 
 
 
74b60b6
38eadf8
74b60b6
 
38eadf8
74b60b6
 
 
 
 
 
1642415
74b60b6
 
1642415
74b60b6
 
ce8069b
74b60b6
1642415
74b60b6
 
 
 
1642415
 
74b60b6
ce8069b
1642415
 
 
 
 
ce8069b
74b60b6
 
1642415
 
 
74b60b6
1642415
 
74b60b6
 
1642415
 
c23c630
1642415
 
 
 
 
 
 
dbba862
ce8069b
74b60b6
 
 
 
 
 
 
 
 
1642415
74b60b6
ce8069b
1642415
ce8069b
 
 
 
1642415
 
 
 
 
 
 
ce8069b
 
1642415
ce8069b
 
 
1642415
 
 
 
 
 
 
 
ce8069b
 
1642415
74b60b6
 
 
 
 
 
 
 
1642415
74b60b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce8069b
9cee324
1642415
9cee324
 
 
1642415
 
9cee324
 
 
1642415
9cee324
 
 
1642415
9cee324
 
 
1642415
9cee324
 
 
1642415
9cee324
 
 
 
1642415
9cee324
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74b60b6
 
 
e69c269
1642415
 
 
9cee324
 
 
74b60b6
 
 
e69c269
74b60b6
 
e69c269
9cee324
 
e69c269
1642415
 
74b60b6
 
ce8069b
74b60b6
 
 
 
 
 
 
 
ce8069b
74b60b6
 
e69c269
25059c7
1642415
 
 
25059c7
 
e69c269
74b60b6
 
1642415
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74b60b6
9cee324
74b60b6
 
 
9cee324
74b60b6
 
9cee324
74b60b6
 
 
 
 
 
9cee324
1642415
74b60b6
 
1642415
74b60b6
 
 
 
 
 
 
 
 
 
ce8069b
 
74b60b6
 
 
 
 
 
1642415
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74b60b6
 
 
56c5b38
74b60b6
1642415
74b60b6
 
 
 
ce8069b
74b60b6
 
 
 
 
ce8069b
1642415
56c5b38
1642415
 
74b60b6
1642415
 
74b60b6
1642415
dbae96a
1642415
 
 
 
 
 
dbae96a
1642415
 
 
 
56c5b38
1642415
c23c630
1642415
ce8069b
1642415
ce8069b
1642415
 
 
 
e69c269
c23c630
 
e69c269
1642415
e69c269
 
1642415
 
e69c269
1642415
ce8069b
1642415
 
e69c269
 
9cee324
 
 
 
 
 
 
 
 
 
 
 
 
142eec4
9cee324
 
 
 
 
e69c269
 
74b60b6
 
 
 
e69c269
74b60b6
e69c269
1642415
 
 
 
 
 
 
 
 
9cee324
dbae96a
74b60b6
 
 
 
 
 
 
 
 
 
38eadf8
ce8069b
74b60b6
e69c269
 
 
74b60b6
 
e69c269
 
74b60b6
e69c269
dbae96a
74b60b6
 
 
ce8069b
 
 
 
 
74b60b6
 
ce8069b
74b60b6
 
 
 
 
 
 
ce8069b
74b60b6
ce8069b
74b60b6
 
 
 
 
 
 
 
 
 
 
 
 
 
dbae96a
74b60b6
 
 
 
dbae96a
74b60b6
ce8069b
74b60b6
dbae96a
ce8069b
 
 
 
 
38eadf8
74b60b6
 
 
 
 
 
dbae96a
ce8069b
74b60b6
 
 
 
 
 
 
e69c269
ce8069b
e69c269
 
 
ce8069b
74b60b6
 
 
ce8069b
 
 
74b60b6
 
 
 
 
dbae96a
74b60b6
 
 
 
 
e69c269
ce8069b
 
 
9cee324
74b60b6
9cee324
dbae96a
ce8069b
dbae96a
9cee324
74b60b6
 
 
9cee324
ce8069b
ee8f500
9cee324
ce8069b
a4c8210
9cee324
 
 
 
 
 
 
 
 
 
1642415
 
 
 
 
 
74b60b6
e69c269
74b60b6
9cee324
74b60b6
c23c630
 
e69c269
74b60b6
9cee324
74b60b6
dbae96a
 
1642415
 
 
 
 
 
 
ce8069b
74b60b6
 
 
 
 
 
e69c269
74b60b6
ce8069b
74b60b6
c23c630
 
74b60b6
 
 
 
1642415
74b60b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38eadf8
ce8069b
74b60b6
ce8069b
74b60b6
ce8069b
 
 
74b60b6
 
 
 
dbae96a
 
74b60b6
 
 
 
c23c630
9cee324
 
 
 
 
 
 
 
 
 
 
c23c630
e69c269
c23c630
74b60b6
c23c630
1642415
9cee324
1642415
9cee324
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1642415
c23c630
e69c269
 
c23c630
 
dbba862
 
c23c630
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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
#!/usr/bin/env python3
"""
Eternity POC v5.2 - Enhanced Avatar Chat with OpenAI API and Audio I/O
- Fixed OpenAI API integration
- Added browser-based audio input (no PyAudio dependency)
- Improved error handling and debugging
"""

import os
import re
import asyncio
import tempfile
import requests
import gradio as gr
import edge_tts
from datetime import datetime

class KnowledgeBase:
    def __init__(self):
        self.documents = {}
        self.conversation_history = []
        self.llm_preference = "openai"  # Default to OpenAI
        
        # Sample personas with detailed backgrounds
        self.sample_personas = {
            "peter_mernok": {
                "name": "Péter",
                "age": "28",
                "personality": "professzionális",
                "voice": "hu-HU-TamasNeural",
                "background": "Szoftverfejlesztő mérnök vagyok, aki mesterséges intelligenciával és webes alkalmazásokkal foglalkozik. Budapesten élek, és imádom a technológiai kihívásokat.",
                "style": "Technikai, precíz, de barátságos kommunikáció. Szeretek részletekbe menni és praktikus megoldásokat javasolni."
            },
            "anna_tanar": {
                "name": "Anna",
                "age": "35",
                "personality": "barátságos",
                "voice": "hu-HU-NoemiNeural",
                "background": "Matematika és fizika tanár vagyok egy budapesti gimnáziumban. Imádom a diákjaimat és a tudás átadását. Szabadidőmben olvasok és túrázok.",
                "style": "Türelmes, magyarázó jellegű kommunikáció. Szeretek példákkal illusztrálni és kérdéseket feltenni."
            },
            "zsolti_epitomunkás": {
                "name": "Zsolti",
                "age": "42",
                "personality": "egyenes",
                "voice": "hu-HU-TamasNeural",
                "background": "Építőipari segédmunkás vagyok. Kemény munkát végzek, de becsületes ember vagyok. Szeretem a sört, a focit és a barátaimat.",
                "style": "Egyenes, őszinte kommunikáció. Nem szépítem a szót, de segítőkész vagyok."
            }
        }
        
        # Set default persona
        self.current_persona = self.sample_personas["peter_mernok"].copy()
    
    def add_document(self, name, content):
        """Add a document to the knowledge base"""
        self.documents[name] = content
        return f"✅ '{name}' dokumentum hozzáadva a tudásbázishoz!"
    
    def get_context_for_query(self, query):
        """Get relevant context from knowledge base"""
        if not self.documents:
            return "Nincs elérhető dokumentum a tudásbázisban."
        
        # Simple keyword matching for context
        relevant_docs = []
        query_lower = query.lower()
        
        for doc_name, content in self.documents.items():
            if any(word in content.lower() for word in query_lower.split()):
                relevant_docs.append(f"[{doc_name}]: {content[:200]}...")
        
        if relevant_docs:
            return "Releváns információk:\n" + "\n".join(relevant_docs)
        else:
            return "Nincs releváns információ a tudásbázisban ehhez a kérdéshez."
    
    def add_to_conversation(self, user_message, ai_response):
        """Add conversation to history"""
        self.conversation_history.append({
            "timestamp": datetime.now().isoformat(),
            "user": user_message,
            "ai": ai_response,
            "persona": self.current_persona["name"]
        })
    
    def set_llm_preference(self, preference):
        """Set LLM preference"""
        self.llm_preference = preference

# Initialize knowledge base
kb = KnowledgeBase()

def get_openai_response(message, context):
    """Get response from OpenAI API with better error handling"""
    api_key = os.getenv('OPENAI_API_KEY')
    if not api_key:
        print("DEBUG: OpenAI API key not found")
        return None, "OpenAI not configured"
    
    try:
        persona = kb.current_persona
        system_prompt = f"""Te {persona['name']} vagy, {persona['age']} éves, {persona['personality']} személyiségű.

Háttér: {persona['background']}

Kommunikációs stílus: {persona['style']}

Kontextus: {context}

Válaszolj természetesen, a karakterednek megfelelően, magyarul. Legyen rövid és személyes a válaszod (maximum 2-3 mondat)."""

        headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        }
        
        payload = {
            "model": "gpt-3.5-turbo",
            "messages": [
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": message}
            ],
            "max_tokens": 300,
            "temperature": 0.7
        }
        
        print(f"DEBUG: Calling OpenAI API with message: {message[:50]}...")
        response = requests.post("https://api.openai.com/v1/chat/completions", 
                               headers=headers, json=payload, timeout=15)
        
        print(f"DEBUG: OpenAI response status: {response.status_code}")
        
        if response.status_code == 200:
            result = response.json()
            ai_response = result["choices"][0]["message"]["content"]
            print(f"DEBUG: OpenAI response received: {ai_response[:50]}...")
            return ai_response, "🤖 OpenAI GPT-3.5"
        else:
            print(f"DEBUG: OpenAI API error: {response.status_code} - {response.text}")
            return None, f"OpenAI Error: {response.status_code}"
            
    except Exception as e:
        print(f"DEBUG: OpenAI exception: {str(e)}")
        return None, f"OpenAI Error: {str(e)}"

def get_gemma_response(message, context):
    """Get response from Gemma API"""
    gemma_url = os.getenv('GEMMA_ENDPOINT_URL')
    hf_token = os.getenv('HF_TOKEN')
    
    if not gemma_url or not hf_token:
        return None, "Gemma not configured"
    
    try:
        persona = kb.current_persona
        system_prompt = f"""Te {persona['name']} vagy, {persona['age']} éves, {persona['personality']} személyiségű.

Háttér: {persona['background']}

Kommunikációs stílus: {persona['style']}

Kontextus: {context}

Válaszolj természetesen, a karakterednek megfelelően, magyarul."""

        headers = {
            "Authorization": f"Bearer {hf_token}",
            "Content-Type": "application/json"
        }
        
        payload = {
            "inputs": f"<start_of_turn>system\n{system_prompt}<end_of_turn>\n<start_of_turn>user\n{message}<end_of_turn>\n<start_of_turn>model\n",
            "parameters": {
                "max_new_tokens": 512,
                "temperature": 0.7,
                "top_p": 0.9,
                "return_full_text": False
            }
        }
        
        response = requests.post(gemma_url, headers=headers, json=payload, timeout=30)
        
        if response.status_code == 200:
            result = response.json()
            
            if isinstance(result, list) and len(result) > 0:
                if "generated_text" in result[0]:
                    return result[0]["generated_text"], "🔮 Gemma-3-12B-IT-OZA"
            elif "generated_text" in result:
                return result["generated_text"], "🔮 Gemma-3-12B-IT-OZA"
        
        return None, f"Gemma Error: {response.status_code}"
            
    except Exception as e:
        return None, f"Gemma Error: {str(e)}"

def get_fallback_response(message):
    """Rule-based fallback responses based on persona"""
    persona = kb.current_persona
    name = persona['name']
    
    message_lower = message.lower()
    
    if any(word in message_lower for word in ['szia', 'hello', 'helló', 'jó napot', 'szervusz', 'hell']):
        if name == "Zsolti":
            return f"Szia! {name} vagyok. Most jöttem haza a melóból, fáradt vagyok mint a szar. Te hogy vagy?", "📝 Alapválasz"
        elif name == "Anna":
            return f"Szia! {name} vagyok, örülök hogy beszélgethetünk! Hogy vagy?", "📝 Alapválasz"
        else:  # Péter
            return f"Szia! {name} vagyok. Szoftverfejlesztéssel foglalkozom. Miben segíthetek?", "📝 Alapválasz"
    
    elif any(word in message_lower for word in ['hogy vagy', 'mi újság', 'hogy megy']):
        if name == "Zsolti":
            return f"Hát tudod, kemény nap volt a munkán. De este megiszunk egy sört a srácokkal, úgyhogy jó lesz.", "📝 Alapválasz"
        elif name == "Anna":
            return f"Köszönöm, jól vagyok! Ma tanítottam, mindig öröm látni a diákok fejlődését.", "📝 Alapválasz"
        else:  # Péter
            return f"Jól, köszönöm! Éppen egy új projekten dolgozom. Érdekes technikai kihívások vannak benne.", "📝 Alapválasz"
    
    else:
        if name == "Zsolti":
            return f"Hát nem tudom mit mondjak erre, haver. Nem vagyok túl okos, de ha segíthetek, szólj.", "📝 Alapválasz"
        elif name == "Anna":
            return f"Érdekes kérdés! Szívesen beszélgetek erről veled. Mit gondolsz te?", "📝 Alapválasz"
        else:  # Péter
            return f"Érdekes téma! Technikai szempontból hogyan közelítenéd meg ezt a problémát?", "📝 Alapválasz"

async def generate_tts(text, voice="hu-HU-NoemiNeural"):
    """Generate TTS audio using Edge-TTS"""
    try:
        # Clean text for TTS
        clean_text = re.sub(r'[🔮🤖📝⚠️✅❌]', '', text)
        clean_text = re.sub(r'\*.*?\*', '', clean_text)  # Remove model indicators
        clean_text = clean_text.strip()
        
        if not clean_text:
            return None
            
        communicate = edge_tts.Communicate(clean_text, voice)
        
        # Create temporary file
        with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_file:
            await communicate.save(tmp_file.name)
            return tmp_file.name
    except Exception as e:
        print(f"TTS Error: {e}")
        return None

def get_ai_response_with_preference(message, context):
    """Get AI response based on LLM preference with better debugging"""
    ai_response = None
    model_used = "📝 Alapválasz"
    
    print(f"DEBUG: LLM preference: {kb.llm_preference}")
    
    if kb.llm_preference == "gemma":
        # Try Gemma first
        ai_response, model_used = get_gemma_response(message, context)
        print(f"DEBUG: Gemma response: {ai_response is not None}")
        # Fallback to OpenAI if Gemma fails
        if not ai_response:
            ai_response, model_used = get_openai_response(message, context)
            print(f"DEBUG: OpenAI fallback response: {ai_response is not None}")
    else:  # openai preference
        # Try OpenAI first
        ai_response, model_used = get_openai_response(message, context)
        print(f"DEBUG: OpenAI response: {ai_response is not None}")
        # Fallback to Gemma if OpenAI fails
        if not ai_response:
            ai_response, model_used = get_gemma_response(message, context)
            print(f"DEBUG: Gemma fallback response: {ai_response is not None}")
    
    # Final fallback to rule-based
    if not ai_response:
        ai_response, model_used = get_fallback_response(message)
        print(f"DEBUG: Using fallback response")
    
    return ai_response, model_used

def get_avatar_display(speaking=False, message=""):
    """Generate avatar display HTML"""
    persona = kb.current_persona
    name = persona['name']
    
    if name == "Péter":
        avatar_emoji = "👨‍💻"
        color = "linear-gradient(135deg, #667eea, #764ba2)"
    elif name == "Anna":
        avatar_emoji = "👩‍🏫"
        color = "linear-gradient(135deg, #FF6B6B, #4ECDC4)"
    else:  # Zsolti
        avatar_emoji = "🏗️"
        color = "linear-gradient(135deg, #8B4513, #D2691E)"
    
    animation = "animation: pulse 2s infinite;" if speaking else ""
    
    return f"""
    <div style="text-align: center; padding: 20px; background: {color}; border-radius: 15px; color: white; {animation}">
        <div style="font-size: 4em; margin-bottom: 10px;">{avatar_emoji}</div>
        <h2 style="margin: 0; font-size: 1.8em;">{name}</h2>
        <p style="margin: 5px 0; opacity: 0.9;">{persona['age']} éves • {persona['personality'].capitalize()}</p>
        <p style="margin: 10px 0; font-size: 0.9em; opacity: 0.8;">{persona['background'][:100]}...</p>
        {f'<div style="margin-top: 15px; padding: 10px; background: rgba(255,255,255,0.2); border-radius: 10px; font-style: italic;">"{message[:100]}..."</div>' if message else ''}
    </div>
    """

def chat_with_avatar(message, history, use_tts, persona_selection, llm_preference):
    """Main chat function with avatar"""
    if not message.strip():
        return history, "", None, get_avatar_display()
    
    print(f"DEBUG: Received message: {message}")
    print(f"DEBUG: LLM preference: {llm_preference}")
    
    # Update LLM preference
    kb.set_llm_preference(llm_preference)
    
    # Update persona if changed
    if persona_selection in kb.sample_personas:
        kb.current_persona = kb.sample_personas[persona_selection].copy()
    
    # Get context for the query
    context = kb.get_context_for_query(message)
    
    # Get AI response based on preference
    ai_response, model_used = get_ai_response_with_preference(message, context)
    
    print(f"DEBUG: Final response: {ai_response[:50]}... (Model: {model_used})")
    
    # Add to conversation history
    kb.add_to_conversation(message, ai_response)
    
    # Generate TTS if enabled
    audio_file = None
    if use_tts and ai_response:
        voice = kb.current_persona.get('voice', 'hu-HU-NoemiNeural')
        try:
            audio_file = asyncio.run(generate_tts(ai_response, voice))
        except:
            audio_file = None
    
    # Format response with model indicator
    formatted_response = f"**{model_used}**\n\n{ai_response}"
    
    # Update history with proper message format
    if history is None:
        history = []
    
    history.append({"role": "user", "content": message})
    history.append({"role": "assistant", "content": formatted_response})
    
    return history, "", audio_file, get_avatar_display(True, ai_response)

def process_audio_input(audio_file):
    """Process audio input and convert to text"""
    if audio_file is None:
        return ""
    
    try:
        # This is a placeholder - in a real implementation, you'd use speech recognition
        # For now, return a placeholder message
        return "Hangfelvétel feldolgozva (speech-to-text funkció fejlesztés alatt)"
    except Exception as e:
        print(f"Audio processing error: {e}")
        return ""

def upload_document(file, doc_name):
    """Upload and process document"""
    if file is None:
        return "❌ Nincs fájl kiválasztva!", get_knowledge_base_status()
    
    if not doc_name.strip():
        doc_name = file.name
    
    try:
        content = file.read().decode('utf-8')
        result = kb.add_document(doc_name, content)
        return result, get_knowledge_base_status()
    except Exception as e:
        return f"❌ Hiba a fájl feldolgozása során: {str(e)}", get_knowledge_base_status()

def get_knowledge_base_status():
    """Get knowledge base status"""
    if not kb.documents:
        return "📚 Tudásbázis üres\n\nNincs feltöltött dokumentum."
    
    status_lines = ["📚 Tudásbázis állapot:\n"]
    for doc_name, content in kb.documents.items():
        status_lines.append(f"• {doc_name}: {len(content)} karakter")
    
    status_lines.append(f"\n💬 Beszélgetés előzmények: {len(kb.conversation_history)} üzenet")
    
    return "\n".join(status_lines)

def load_sample_persona(persona_key):
    """Load a sample persona"""
    if persona_key in kb.sample_personas:
        persona = kb.sample_personas[persona_key]
        kb.current_persona = persona.copy()
        
        return (
            persona['name'],
            persona['age'],
            persona['personality'],
            persona['voice'],
            persona['background'],
            f"✅ {persona['name']} persona betöltve!",
            get_avatar_display()
        )
    
    return "", "", "", "", "", "❌ Hiba a persona betöltése során!", get_avatar_display()

def save_custom_persona(name, age, personality, voice, background):
    """Save custom persona"""
    if not name.strip():
        return "❌ A név megadása kötelező!", get_avatar_display()
    
    kb.current_persona = {
        'name': name.strip(),
        'age': age.strip() if age.strip() else "Nem megadott",
        'personality': personality,
        'voice': voice,
        'background': background.strip() if background.strip() else "Nincs háttér információ.",
        'style': f"{personality.capitalize()} kommunikációs stílus."
    }
    
    return f"✅ {name} persona mentve!", get_avatar_display()

def get_api_status():
    """Check API status for all services"""
    status_lines = []
    
    # Check OpenAI API
    openai_key = os.getenv('OPENAI_API_KEY')
    if openai_key:
        status_lines.append("• 🤖 OpenAI API: ✅ Beállítva")
        # Test API call
        try:
            test_response, _ = get_openai_response("test", "")
            if test_response:
                status_lines.append("• OpenAI API Test: ✅ Működik")
            else:
                status_lines.append("• OpenAI API Test: ❌ Hiba")
        except:
            status_lines.append("• OpenAI API Test: ❌ Kapcsolódási hiba")
    else:
        status_lines.append("• 🤖 OpenAI API: ❌ Nincs beállítva")
    
    # Check Gemma API
    gemma_url = os.getenv('GEMMA_ENDPOINT_URL')
    hf_token = os.getenv('HF_TOKEN')
    
    if gemma_url and hf_token:
        status_lines.append("• 🔮 Gemma-3-12B API: ✅ Konfigurálva")
        status_lines.append(f"• Gemma Endpoint URL: ✅ Beállítva")
    else:
        status_lines.append("• 🔮 Gemma-3-12B API: ❌ Nincs konfigurálva")
        status_lines.append("• Gemma Endpoint URL: ❌ Nincs beállítva")
    
    # Check HF Token
    if hf_token:
        status_lines.append("• HF Token: ✅ Beállítva")
    else:
        status_lines.append("• HF Token: ❌ Nincs beállítva")
    
    return "\n".join(status_lines)

def create_enhanced_eternity_interface():
    """Create the enhanced Eternity interface with audio support"""
    
    # Custom CSS for better styling
    css = """
    .gradio-container {
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }
    .llm-selector {
        background: linear-gradient(135deg, #667eea, #764ba2);
        padding: 15px;
        border-radius: 10px;
        color: white;
        margin-bottom: 15px;
    }
    @keyframes pulse {
        0% { transform: scale(1); }
        50% { transform: scale(1.05); }
        100% { transform: scale(1); }
    }
    """
    
    with gr.Blocks(css=css, title="Eternity POC v5.2", theme=gr.themes.Soft()) as interface:
        
        # Header
        gr.HTML("""
        <div style="text-align: center; padding: 20px; background: linear-gradient(135deg, #667eea, #764ba2); border-radius: 15px; margin-bottom: 20px; color: white;">
            <h1 style="margin: 0; font-size: 2.5em;">🎭 Eternity - Magyar Beszélő Avatar POC v5.2</h1>
            <p style="margin: 10px 0 0 0; font-size: 1.2em; opacity: 0.9;">🔮 Gemma-3-12B + 🤖 OpenAI • 🎤 Magyar TTS</p>
            <p style="margin: 5px 0 0 0; opacity: 0.8;">Hugging Face Spaces kompatibilis verzió</p>
        </div>
        """)
        
        with gr.Tabs():
            # Main Chat Tab
            with gr.Tab("💬 Beszélgetés"):
                with gr.Row():
                    with gr.Column(scale=3):
                        # Chat interface
                        chatbot = gr.Chatbot(
                            label="💬 Beszélgetés az Avatar-ral",
                            height=400,
                            type="messages",
                            avatar_images=None
                        )
                        
                        # LLM Selection
                        with gr.Group():
                            gr.HTML("""
                            <div class="llm-selector">
                                <h4 style="margin: 0 0 10px 0;">🤖 AI Modell Választás</h4>
                                <p style="margin: 0; opacity: 0.9; font-size: 0.9em;">Válaszd ki melyik AI modellt használja a rendszer</p>
                            </div>
                            """)
                            llm_selector = gr.Radio(
                                choices=[
                                    ("🔮 Gemma-3-12B-IT-OZA (Local)", "gemma"),
                                    ("🤖 OpenAI GPT-3.5 (Cloud)", "openai")
                                ],
                                value="openai",
                                label="AI Modell",
                                interactive=True
                            )
                        
                        # Text Input
                        with gr.Row():
                            msg_input = gr.Textbox(
                                placeholder="Írj egy üzenetet...",
                                label="Üzenet",
                                scale=4,
                                container=False
                            )
                            send_btn = gr.Button("📤 Küldés", scale=1, variant="primary")
                        
                        # Audio Input
                        with gr.Row():
                            audio_input = gr.Audio(
                                label="🎤 Hangfelvétel (beszélj a mikrofonba)",
                                sources=["microphone"],
                                type="filepath"
                            )
                            process_audio_btn = gr.Button("🎤 Hang feldolgozása", variant="secondary")
                        
                        # Settings
                        with gr.Row():
                            use_tts = gr.Checkbox(label="🗣️ Beszélő avatar (TTS)", value=True)
                            persona_selector = gr.Dropdown(
                                choices=[
                                    ("Péter - Mérnök (alapértelmezett)", "peter_mernok"),
                                    ("Anna - Tanár", "anna_tanar"), 
                                    ("Zsolti - Építőmunkás", "zsolti_epitomunkás")
                                ],
                                value="peter_mernok",
                                label="👤 Persona választás",
                                scale=2
                            )
                        
                        audio_output = gr.Audio(label="🔊 Avatar hangja", autoplay=True)
                    
                    with gr.Column(scale=1):
                        avatar_display = gr.HTML(
                            value=get_avatar_display(),
                            label="🎭 Avatar megjelenítés"
                        )
            
            # Persona Setup Tab  
            with gr.Tab("👤 Persona Beállítás"):
                gr.HTML("""
                <div style="text-align: center; padding: 15px; background: linear-gradient(135deg, #4ECDC4, #44A08D); border-radius: 10px; margin-bottom: 20px; color: white;">
                    <h2 style="margin: 0;">👤 Avatar Persona Beállítások</h2>
                    <p style="margin: 5px 0 0 0; opacity: 0.9;">Válassz mintapersonát vagy hozz létre egyedi karaktert</p>
                </div>
                """)
                
                with gr.Row():
                    with gr.Column():
                        gr.HTML("<h3>🎭 Mintapersonák</h3>")
                        
                        sample_persona_dropdown = gr.Dropdown(
                            choices=[
                                ("Péter - Szoftverfejlesztő mérnök (alapértelmezett)", "peter_mernok"),
                                ("Anna - Matematika és fizika tanár", "anna_tanar"),
                                ("Zsolti - Építőipari segédmunkás", "zsolti_epitomunkás")
                            ],
                            label="Válassz mintapersonát",
                            value="peter_mernok"
                        )
                        
                        load_sample_btn = gr.Button("📥 Mintapersona Betöltése", variant="secondary")
                        
                        # Sample persona details display
                        with gr.Group():
                            gr.HTML("<h4>📋 Persona Részletek:</h4>")
                            sample_details = gr.HTML("""
                            <div style="padding: 15px; background: linear-gradient(135deg, #667eea, #764ba2); border-radius: 10px; color: white;">
                                <h4>👨‍💻 Péter - Szoftverfejlesztő (Alapértelmezett)</h4>
                                <p><strong>Kor:</strong> 28 éves</p>
                                <p><strong>Személyiség:</strong> Professzionális, analitikus</p>
                                <p><strong>Háttér:</strong> Budapesti szoftverfejlesztő, AI és webes alkalmazások szakértője</p>
                                <p><strong>Stílus:</strong> Technikai, precíz, de barátságos kommunikáció</p>
                            </div>
                            """)
                    
                    with gr.Column():
                        gr.HTML("<h3>⚙️ Egyedi Persona</h3>")
                        
                        persona_name = gr.Textbox(label="👤 Név", value="Péter")
                        persona_age = gr.Textbox(label="🎂 Kor", value="28")
                        persona_personality = gr.Dropdown(
                            choices=["barátságos", "professzionális", "humoros", "bölcs", "energikus", "egyenes"],
                            label="🎭 Személyiség",
                            value="professzionális"
                        )
                        persona_voice = gr.Dropdown(
                            choices=[
                                ("Női hang (Noémi)", "hu-HU-NoemiNeural"),
                                ("Férfi hang (Tamás)", "hu-HU-TamasNeural")
                            ],
                            label="🗣️ TTS Hang",
                            value="hu-HU-TamasNeural"
                        )
                        persona_background = gr.Textbox(
                            label="📖 Háttér",
                            lines=4,
                            value="Szoftverfejlesztő mérnök vagyok, aki mesterséges intelligenciával és webes alkalmazásokkal foglalkozik..."
                        )
                        
                        save_persona_btn = gr.Button("💾 Persona Mentése", variant="primary")
                        persona_status = gr.Textbox(label="📊 Állapot", value="✅ Péter persona aktív!")
                        
                        current_avatar_display = gr.HTML(
                            value=get_avatar_display(),
                            label="🎭 Jelenlegi Avatar"
                        )
            
            # Knowledge Base Tab
            with gr.Tab("📚 Tudásbázis & AI API"):
                with gr.Row():
                    with gr.Column():
                        gr.HTML("""
                        <div style="text-align: center; padding: 15px; background: linear-gradient(135deg, #FF6B6B, #4ECDC4); border-radius: 10px; margin-bottom: 20px; color: white;">
                            <h2 style="margin: 0;">📚 Tudásbázis Kezelés</h2>
                            <p style="margin: 5px 0 0 0; opacity: 0.9;">Dokumentumok feltöltése és AI API státusz</p>
                        </div>
                        """)
                        
                        # Document upload
                        doc_file = gr.File(label="📄 Dokumentum feltöltése", file_types=[".txt", ".md"])
                        doc_name = gr.Textbox(label="📝 Dokumentum neve", placeholder="pl. eletrajz")
                        upload_btn = gr.Button("📤 Feltöltés", variant="secondary")
                        upload_status = gr.Textbox(label="📊 Feltöltés állapot")
                        
                        # Knowledge base status
                        kb_status = gr.Textbox(
                            label="📚 Tudásbázis állapot",
                            value=get_knowledge_base_status(),
                            lines=4
                        )
                    
                    with gr.Column():
                        gr.HTML("""
                        <div style="text-align: center; padding: 15px; background: linear-gradient(135deg, #8B4513, #D2691E); border-radius: 10px; margin-bottom: 20px; color: white;">
                            <h2 style="margin: 0;">🔧 AI API Státusz</h2>
                            <p style="margin: 5px 0 0 0; opacity: 0.9;">Modellek és szolgáltatások ellenőrzése</p>
                        </div>
                        """)
                        
                        # API status
                        api_status = gr.Textbox(
                            label="🔧 API Állapot",
                            value=get_api_status(),
                            lines=12
                        )
                        
                        refresh_btn = gr.Button("🔄 Frissítés", variant="secondary")
        
        # Event handlers
        def handle_chat(message, history, use_tts, persona_selection, llm_preference):
            if history is None:
                history = []
            
            updated_history, _, audio_file, avatar_display = chat_with_avatar(
                message, history, use_tts, persona_selection, llm_preference
            )
            
            return updated_history, "", audio_file, avatar_display
        
        def handle_audio_input(audio_file):
            if audio_file:
                text = process_audio_input(audio_file)
                return text
            return ""
        
        # Chat events
        send_btn.click(
            handle_chat,
            inputs=[msg_input, chatbot, use_tts, persona_selector, llm_selector],
            outputs=[chatbot, msg_input, audio_output, avatar_display]
        )
        
        msg_input.submit(
            handle_chat,
            inputs=[msg_input, chatbot, use_tts, persona_selector, llm_selector],
            outputs=[chatbot, msg_input, audio_output, avatar_display]
        )
        
        # Audio input processing
        process_audio_btn.click(
            handle_audio_input,
            inputs=[audio_input],
            outputs=[msg_input]
        )
        
        # Persona events
        load_sample_btn.click(
            load_sample_persona,
            inputs=[sample_persona_dropdown],
            outputs=[persona_name, persona_age, persona_personality, persona_voice, persona_background, persona_status, current_avatar_display]
        )
        
        save_persona_btn.click(
            save_custom_persona,
            inputs=[persona_name, persona_age, persona_personality, persona_voice, persona_background],
            outputs=[persona_status, current_avatar_display]
        )
        
        # Update sample details when dropdown changes
        def update_sample_details(persona_key):
            if persona_key in kb.sample_personas:
                persona = kb.sample_personas[persona_key]
                
                if persona_key == "peter_mernok":
                    color = "linear-gradient(135deg, #667eea, #764ba2)"
                    icon = "👨‍💻"
                elif persona_key == "anna_tanar":
                    color = "linear-gradient(135deg, #FF6B6B, #4ECDC4)"
                    icon = "👩‍🏫"
                else:  # zsolti
                    color = "linear-gradient(135deg, #8B4513, #D2691E)"
                    icon = "🏗️"
                
                return f"""
                <div style="padding: 15px; background: {color}; border-radius: 10px; color: white;">
                    <h4>{icon} {persona['name']} - {persona_key.split('_')[1].capitalize()}</h4>
                    <p><strong>Kor:</strong> {persona['age']} éves</p>
                    <p><strong>Személyiség:</strong> {persona['personality'].capitalize()}</p>
                    <p><strong>Háttér:</strong> {persona['background'][:100]}...</p>
                    <p><strong>Stílus:</strong> {persona['style']}</p>
                </div>
                """
            return ""
        
        sample_persona_dropdown.change(
            update_sample_details,
            inputs=[sample_persona_dropdown],
            outputs=[sample_details]
        )
        
        # Knowledge base events
        upload_btn.click(
            upload_document,
            inputs=[doc_file, doc_name],
            outputs=[upload_status, kb_status]
        )
        
        # API status refresh
        refresh_btn.click(
            lambda: get_api_status(),
            outputs=[api_status]
        )
        
        # LLM preference change
        def update_llm_preference(preference):
            kb.set_llm_preference(preference)
            return get_api_status()
        
        llm_selector.change(
            update_llm_preference,
            inputs=[llm_selector],
            outputs=[api_status]
        )
    
    return interface

# Create and launch the interface
if __name__ == "__main__":
    print("🎭 Eternity POC v5.2 - Enhanced with Audio I/O")
    print("🔮 Gemma-3-12B-IT-OZA + 🤖 OpenAI GPT-3.5 támogatással")
    print("🎤 Hangbemenet és 🗣️ TTS rendszer aktív")
    
    # Check environment variables
    gemma_url = os.getenv('GEMMA_ENDPOINT_URL')
    hf_token = os.getenv('HF_TOKEN')
    openai_key = os.getenv('OPENAI_API_KEY')
    
    if gemma_url and hf_token:
        print("✅ Gemma-3-12B API konfigurálva")
    else:
        print("⚠️ Gemma-3-12B API nincs konfigurálva")
    
    if openai_key:
        print("✅ OpenAI API kulcs észlelve - GPT-3.5 elérhető")
    else:
        print("⚠️ OpenAI API kulcs nem található")
    
    print("🚀 Eternity POC v5.2 elindítva!")
    
    interface = create_enhanced_eternity_interface()
    interface.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False,
        show_error=True
    )