arite commited on
Commit
4db2afd
·
1 Parent(s): 8e83be8

Add Llama-4-Scout-17B-16E-Instruct API integration v3.0

Browse files

- Integrate Meta's Llama-4-Scout-17B-16E-Instruct via HF Inference API
- Add enhanced Hungarian language support with 17B MoE model
- Implement dynamic avatar emotions and conversation memory
- Add comprehensive fallback system (OpenAI API + rule-based)
- Update UI to v3.0 with model status indicators
- Add detailed API status monitoring and error handling
- Include environment configuration for HF_TOKEN setup

Files changed (8) hide show
  1. .env.example +8 -0
  2. README.md +17 -9
  3. app.py +229 -49
  4. app_llama4_api.py +843 -0
  5. app_with_llama4.py +848 -0
  6. requirements.txt +1 -0
  7. requirements_api.txt +4 -0
  8. requirements_llama4.txt +11 -0
.env.example ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # Hugging Face Token for Llama-4-Scout API access
2
+ HF_TOKEN=your_hugging_face_token_here
3
+
4
+ # OpenAI API Key for fallback (optional)
5
+ OPENAI_API_KEY=your_openai_api_key_here
6
+
7
+ # Alternative environment variable names
8
+ HUGGINGFACE_TOKEN=your_hugging_face_token_here
README.md CHANGED
@@ -16,28 +16,36 @@ license: apache-2.0
16
 
17
  ## 📋 Projekt Leírás
18
 
19
- Az Eternity egy magyar nyelvű interaktív video avatar rendszer, amely személyes dokumentumokból és adatokból épít fel egy digitális személyiséget. Ez a POC verzió a core funkcionalitást demonstrálja teljesítmény és biztonsági követelmények nélkül.
20
 
21
  ## ✨ Jelenlegi Funkciók
22
 
23
- ### ✅ Implementált
24
- - **Magyar nyelvű beszélgetés** - Természetes magyar válaszok
25
- - **Persona alapú kommunikáció** - Egyedi személyiség beállítása
26
- - **Dokumentum alapú tudásbázis** - Személyes fájlok feltöltése és feldolgozása
27
- - **Kontextuális válaszok** - A tudásbázis alapján releváns információk
28
- - **Egyszerű keresés** - Kulcsszó alapú keresés a dokumentumokban
 
 
 
29
 
30
  ### 🔄 Szimulált (POC szinten)
31
  - **Avatar videó generálás** - HTML placeholder a valódi videó helyett
32
  - **Hangfelismerés** - Felkészítve a jövőbeli integrációra
33
- - **Valós idejű feldolgozás** - Alapvető válaszidő optimalizálás nélkül
34
 
35
  ## 🎯 Használat
36
 
 
 
 
 
 
37
  1. **Persona Beállítás** tabon hozzon létre egy személyiséget
38
  2. **Dokumentum Feltöltés** tabon töltsön fel személyes fájlokat (.txt, .md)
39
  3. **Beszélgetés** tabon kezdjen el chattelni az avatarral magyarul
40
- 4. **Tudásbázis** tabon tekintse meg a feltöltött információkat
41
 
42
  ## 🔧 Technikai Részletek
43
 
 
16
 
17
  ## 📋 Projekt Leírás
18
 
19
+ Az Eternity egy magyar nyelvű interaktív video avatar rendszer, amely személyes dokumentumokból és adatokból épít fel egy digitális személyiséget. Ez a POC v3.0 verzió **Llama-4-Scout-17B-16E-Instruct** integrációval demonstrálja a core funkcionalitást Meta legújabb multimodális modelljével.
20
 
21
  ## ✨ Jelenlegi Funkciók
22
 
23
+ ### ✅ Implementált (v3.0 - Llama-4-Scout Integration)
24
+ - **🦙 Llama-4-Scout-17B-16E-Instruct** - Meta legújabb 17B paraméteres MoE modellje
25
+ - **Magyar nyelvű beszélgetés** - Natív magyar támogatás Llama-4-Scout-tal
26
+ - **Fejlett persona rendszer** - Részletes személyiség és beszélgetési stílus
27
+ - **Intelligens dokumentum feldolgozás** - Személyes fájlok feltöltése és elemzése
28
+ - **Fejlett tudásbázis keresés** - Kontextuális információ visszakeresés
29
+ - **Dinamikus avatar érzelmek** - Válasz alapú hangulat szimuláció
30
+ - **Beszélgetési memória** - Korábbi üzenetek figyelembevétele
31
+ - **Model fallback rendszer** - OpenAI API és szabály alapú backup
32
 
33
  ### 🔄 Szimulált (POC szinten)
34
  - **Avatar videó generálás** - HTML placeholder a valódi videó helyett
35
  - **Hangfelismerés** - Felkészítve a jövőbeli integrációra
36
+ - **Multimodális képességek** - Kép input támogatás fejlesztés alatt
37
 
38
  ## 🎯 Használat
39
 
40
+ ### 🔧 Beállítás (Llama-4-Scout használatához)
41
+ 1. **HF_TOKEN** környezeti változó beállítása Hugging Face tokennel
42
+ 2. **OPENAI_API_KEY** beállítása fallback támogatáshoz (opcionális)
43
+
44
+ ### 💬 Használat
45
  1. **Persona Beállítás** tabon hozzon létre egy személyiséget
46
  2. **Dokumentum Feltöltés** tabon töltsön fel személyes fájlokat (.txt, .md)
47
  3. **Beszélgetés** tabon kezdjen el chattelni az avatarral magyarul
48
+ 4. **Tudásbázis & AI API** tabon tekintse meg a feltöltött információkat és API státuszt
49
 
50
  ## 🔧 Technikai Részletek
51
 
app.py CHANGED
@@ -6,6 +6,9 @@ from pathlib import Path
6
  from datetime import datetime
7
  import hashlib
8
  import base64
 
 
 
9
 
10
  # Enhanced knowledge base with better search
11
  class EternityKnowledgeBase:
@@ -132,8 +135,111 @@ class EternityKnowledgeBase:
132
  # Initialize global knowledge base
133
  kb = EternityKnowledgeBase()
134
 
135
- def generate_hungarian_response(user_input, use_openai=True):
136
- """Generate enhanced Hungarian response"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
  try:
138
  # Add to conversation history
139
  kb.conversation_history.append({"user": user_input, "timestamp": datetime.now().isoformat()})
@@ -155,8 +261,22 @@ def generate_hungarian_response(user_input, use_openai=True):
155
  knowledge_context += f" • {doc['content'][:150]}...\n"
156
  knowledge_context += "\n"
157
 
158
- # Try OpenAI API if available
159
- if use_openai and os.getenv('OPENAI_API_KEY'):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
160
  try:
161
  from openai import OpenAI
162
  client = OpenAI()
@@ -197,6 +317,7 @@ Stílus irányelvek:
197
 
198
  # Add AI response to history
199
  kb.conversation_history[-1]["assistant"] = ai_response
 
200
 
201
  return ai_response
202
 
@@ -251,10 +372,21 @@ def generate_enhanced_hungarian_response(user_input, persona_context, knowledge_
251
  f"Ez fontos téma. {persona_context} Szívesen beszélgetünk erről részletesebben."
252
  ]
253
 
254
- return responses[hash(user_input) % len(responses)]
 
 
 
 
 
 
255
 
256
  def create_enhanced_avatar_display(text_response, persona_name="Avatar"):
257
- """Create enhanced avatar display with better visual design"""
 
 
 
 
 
258
  # Simulate different avatar expressions based on response content
259
  if any(word in text_response.lower() for word in ['örülök', 'szuper', 'nagyszerű', 'remek']):
260
  emotion = "😊 Boldog"
@@ -273,6 +405,17 @@ def create_enhanced_avatar_display(text_response, persona_name="Avatar"):
273
  bg_color = "#f3e5f5"
274
  border_color = "#9c27b0"
275
 
 
 
 
 
 
 
 
 
 
 
 
276
  avatar_html = f"""
277
  <div style="text-align: center; padding: 25px; border: 3px solid {border_color}; border-radius: 15px; background: {bg_color}; margin: 10px;">
278
  <div style="display: flex; align-items: center; justify-content: center; margin-bottom: 15px;">
@@ -280,6 +423,9 @@ def create_enhanced_avatar_display(text_response, persona_name="Avatar"):
280
  <div>
281
  <h3 style="margin: 0; color: #333;">{persona_name}</h3>
282
  <p style="margin: 5px 0; color: #666; font-size: 14px;">Hangulat: {emotion}</p>
 
 
 
283
  </div>
284
  </div>
285
 
@@ -291,7 +437,7 @@ def create_enhanced_avatar_display(text_response, persona_name="Avatar"):
291
 
292
  <div style="margin-top: 15px; padding: 10px; background: rgba(255,255,255,0.7); border-radius: 8px;">
293
  <p style="color: #666; font-size: 12px; margin: 0;">
294
- 💡 <strong>POC Szimuláció:</strong> Valódi avatar videó és hang generálás fejlesztés alatt
295
  </p>
296
  <p style="color: #666; font-size: 12px; margin: 5px 0 0 0;">
297
  🎬 Következő fázis: TTS + Lip-sync + Valódi avatar animáció
@@ -380,7 +526,7 @@ def create_enhanced_persona(name, age, personality, background):
380
  return f"❌ **Hiba a persona létrehozása során:** {str(e)}"
381
 
382
  def get_enhanced_knowledge_summary():
383
- """Enhanced knowledge base summary with better formatting"""
384
  doc_count = len(kb.knowledge_data)
385
  persona_info = "✅ Beállítva" if kb.persona_data else "❌ Nincs beállítva"
386
  conversation_count = len(kb.conversation_history)
@@ -414,28 +560,45 @@ def get_enhanced_knowledge_summary():
414
  if kb.conversation_history:
415
  summary += f"💭 **Legutóbbi beszélgetések:**\n"
416
  for i, conv in enumerate(kb.conversation_history[-3:]):
417
- summary += f" {i+1}. \"{conv['user'][:40]}...\"\n"
 
418
 
419
  summary += f"""
420
- 🔧 **Rendszer információk:**
 
421
  • OpenAI API: {'✅ Aktív' if os.getenv('OPENAI_API_KEY') else '❌ Nincs beállítva'}
422
- • Válasz mód: {'Fejlett AI' if os.getenv('OPENAI_API_KEY') else 'Egyszerű szabályok'}
423
  • Tudásbázis méret: {sum(doc['word_count'] for doc in kb.knowledge_data.values())} szó összesen
424
  """
425
 
426
  return summary
427
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
428
  # Create the enhanced Gradio interface
429
  def create_enhanced_eternity_interface():
430
- """Create the enhanced Eternity POC interface"""
431
 
432
  with gr.Blocks(title="Eternity POC - Magyar Avatar", theme=gr.themes.Soft()) as demo:
433
  gr.Markdown("""
434
- # 🎭 Eternity - Magyar Interaktív Avatar POC v2.0
435
 
436
- **Fejlett Proof-of-Concept az Eternity projekthez**
437
 
438
  🚀 **Új funkciók ebben a verzióban:**
 
439
  - 🧠 **Fejlett tudásbázis keresés** - Jobb relevanciával és kontextussal
440
  - 🎭 **Dinamikus avatar érzelmek** - Válasz alapú hangulat szimuláció
441
  - 💬 **Beszélgetési memória** - Korábbi üzenetek figyelembevétele
@@ -463,6 +626,7 @@ def create_enhanced_eternity_interface():
463
  value="""<div style='text-align: center; padding: 50px; color: #666; border: 2px dashed #ccc; border-radius: 10px;'>
464
  <h3>🎭 Avatar várakozik...</h3>
465
  <p>Írjon egy üzenetet és kattintson a Küldés gombra!</p>
 
466
  </div>"""
467
  )
468
 
@@ -518,71 +682,78 @@ def create_enhanced_eternity_interface():
518
  upload_btn = gr.Button("⬆️ Dokumentum Feldolgozása", variant="primary", size="lg")
519
  upload_status = gr.Textbox(label="📊 Feltöltés Eredménye", interactive=False, lines=10)
520
 
521
- with gr.Tab("📊 Tudásbázis"):
522
  with gr.Column():
523
- gr.Markdown("### 📈 Tudásbázis áttekintése és statisztikák")
524
 
525
  refresh_kb_btn = gr.Button("🔄 Frissítés", variant="secondary")
526
  kb_summary = gr.Textbox(
527
  label="📋 Részletes Összefoglaló",
528
- lines=15,
529
  interactive=False
530
  )
531
 
532
  with gr.Tab("ℹ️ Információ"):
533
  gr.Markdown("""
534
- ## 🎭 Eternity POC v2.0 - Technikai Információk
535
 
536
  ### ✅ Implementált Funkciók:
537
- - **Magyar nyelvű beszélgetés** - OpenAI GPT-4o-mini vagy szabály alapú válaszok
 
538
  - **Fejlett persona rendszer** - Részletes személyiség és beszélgetési stílus
539
  - **Intelligens tudásbázis** - Dokumentum feldolgozás és kontextuális keresés
540
  - **Beszélgetési memória** - Korábbi üzenetek figyelembevétele
541
  - **Dinamikus avatar érzelmek** - Válasz alapú hangulat szimuláció
542
- - **Részletes statisztikák** - Dokumentum és használati elemzés
543
 
544
- ### 🔄 Szimulált Funkciók (POC szinten):
545
- - **Avatar videó generálás** - HTML alapú vizuális szimuláció
546
- - **Hangszintézis (TTS)** - Felkészítve a jövőbeli integrációra
547
- - **Hangfelismerés (STT)** - Tervezett a következő verzióban
548
- - **Valós idejű optimalizálás** - Teljesítmény követelmények nélkül
 
 
549
 
550
  ### 🛠️ Használt Technológiák:
 
 
551
  - **Frontend:** Gradio 5.x (Python web UI framework)
552
- - **Backend:** Python 3.11+ (asyncio támogatás)
553
- - **AI:** OpenAI GPT-4o-mini API (opcionális)
554
  - **Nyelv:** Magyar (natív támogatás)
555
  - **Adattárolás:** Memória alapú (POC szinten)
556
- - **Keresés:** Kulcsszó és mondat alapú relevancia pontozás
557
 
558
- ### 📈 Teljesítmény Jellemzők (POC):
559
- - **Válaszidő:** 1-3 másodperc (API függő)
 
560
  - **Dokumentum méret:** Max 10MB / fájl
561
  - **Tudásbázis kapacitás:** Korlátlan (memória függő)
562
  - **Beszélgetési memória:** Utolsó 10 üzenet
563
- - **Egyidejű felhasználók:** 1 (POC korlátozás)
 
 
 
 
564
 
565
  ### 🚀 Következő Fejlesztési Lépések:
566
- 1. **Valódi TTS integráció** - Magyar Edge TTS vagy ElevenLabs
567
- 2. **Avatar videó generálás** - OpenAvatarChat modellek aktiválása
568
- 3. **Hangfelismerés** - Whisper STT magyar támogatással
569
  4. **Perzisztens adattárolás** - Adatbázis integráció
570
- 5. **Teljesítmény optimalizálás** - Sub-1s válaszidő cél
571
- 6. **Computer vision** - Valós idejű vizuális feldolgozás
572
 
573
  ### ⚠️ POC Korlátozások:
 
574
  - **Nincs adatperzisztencia** - Újraindításkor elvesznek az adatok
575
  - **Egyszerű keresés** - Nincs szemantikus embedding
576
  - **Nincs felhasználói hitelesítés** - Nyilvános hozzáférés
577
- - **Nincs skálázhatóság** - Egyetlen felhasználó támogatás
578
- - **Minimális hibakezelés** - Fejlesztési célokra optimalizált
579
 
580
  ---
581
 
582
- **Verzió:** POC 2.0 Enhanced
583
  **Utolsó frissítés:** 2025. október
584
  **Státusz:** Aktív fejlesztés
585
- **Licenc:** Apache 2.0
586
  """)
587
 
588
  # Enhanced event handlers
@@ -593,7 +764,7 @@ def create_enhanced_eternity_interface():
593
  <p>Kérem, írjon be egy üzenetet a beszélgetéshez!</p>
594
  </div>"""
595
 
596
- response_text = generate_hungarian_response(user_msg)
597
  persona_name = kb.persona_data.get('name', 'Avatar') if kb.persona_data else 'Avatar'
598
  return create_enhanced_avatar_display(response_text, persona_name)
599
 
@@ -629,31 +800,40 @@ def create_enhanced_eternity_interface():
629
  outputs=[kb_summary]
630
  )
631
 
632
- # Initialize knowledge base summary on load
633
  demo.load(
634
- fn=get_enhanced_knowledge_summary,
635
  outputs=[kb_summary]
636
  )
637
 
638
  return demo
639
 
640
  if __name__ == "__main__":
641
- print("🎭 Eternity POC v2.0 Enhanced indítása...")
642
- print("📚 Magyar interaktív avatar rendszer - Fejlett verzió")
 
 
 
 
 
 
 
 
643
 
644
  # Check for OpenAI API key
645
  if os.getenv('OPENAI_API_KEY'):
646
- print("✅ OpenAI API kulcs észlelve - fejlett AI válaszok engedélyezve")
647
  else:
648
- print("⚠️ OpenAI API kulcs nem található - szabály alapú válaszok használata")
649
- print(" 💡 Tipp: Állítsa be az OPENAI_API_KEY környezeti változót a jobb élményért")
650
 
651
  # Create and launch the enhanced interface
652
  demo = create_enhanced_eternity_interface()
653
 
654
- print("🚀 Eternity POC v2.0 Enhanced elindítva!")
655
  print("🌐 Elérhető: http://localhost:7860")
656
  print("📖 Használati útmutató: README.md")
 
657
 
658
  demo.launch(
659
  server_name="0.0.0.0",
 
6
  from datetime import datetime
7
  import hashlib
8
  import base64
9
+ import requests
10
+ import warnings
11
+ warnings.filterwarnings("ignore")
12
 
13
  # Enhanced knowledge base with better search
14
  class EternityKnowledgeBase:
 
135
  # Initialize global knowledge base
136
  kb = EternityKnowledgeBase()
137
 
138
+ # Global variables for Llama-4-Scout API
139
+ llama4_api_status = "Not configured"
140
+
141
+ def check_llama4_api():
142
+ """Check if Llama-4-Scout API is available"""
143
+ global llama4_api_status
144
+
145
+ # Check for Hugging Face token
146
+ hf_token = os.getenv('HF_TOKEN') or os.getenv('HUGGINGFACE_TOKEN')
147
+
148
+ if not hf_token:
149
+ llama4_api_status = "❌ HF_TOKEN not found"
150
+ return False
151
+
152
+ try:
153
+ # Test API endpoint
154
+ headers = {"Authorization": f"Bearer {hf_token}"}
155
+ api_url = "https://api-inference.huggingface.co/models/meta-llama/Llama-4-Scout-17B-16E-Instruct"
156
+
157
+ # Simple test request
158
+ response = requests.post(
159
+ api_url,
160
+ headers=headers,
161
+ json={"inputs": "Hello", "parameters": {"max_new_tokens": 10}},
162
+ timeout=10
163
+ )
164
+
165
+ if response.status_code == 200:
166
+ llama4_api_status = "✅ API Ready"
167
+ return True
168
+ elif response.status_code == 503:
169
+ llama4_api_status = "⏳ Model Loading"
170
+ return False
171
+ else:
172
+ llama4_api_status = f"❌ API Error: {response.status_code}"
173
+ return False
174
+
175
+ except Exception as e:
176
+ llama4_api_status = f"❌ Connection Error: {str(e)[:50]}"
177
+ return False
178
+
179
+ def generate_llama4_response_api(user_input, persona_context, knowledge_context):
180
+ """Generate response using Llama-4-Scout via Hugging Face Inference API"""
181
+
182
+ hf_token = os.getenv('HF_TOKEN') or os.getenv('HUGGINGFACE_TOKEN')
183
+ if not hf_token:
184
+ return "❌ Hugging Face token not configured"
185
+
186
+ try:
187
+ # Construct the prompt in Hungarian
188
+ system_prompt = f"""Te {persona_context}
189
+
190
+ Válaszolj természetesen, személyesen és barátságosan magyarul. Használd fel a rendelkezésre álló információkat, de ne ismételd meg szó szerint. Inkább építsd be természetesen a beszélgetésbe.
191
+
192
+ {knowledge_context}
193
+
194
+ Stílus irányelvek:
195
+ - Beszélgetős, természetes hangnem
196
+ - Személyes élmények és érzések megosztása
197
+ - Rövid, érthető válaszok (max 100-150 szó)
198
+ - Magyar kifejezések és szófordulatok használata
199
+ - Empátia és megértés kifejezése"""
200
+
201
+ # Create the full prompt
202
+ full_prompt = f"""<|begin_of_text|><|start_header_id|>system<|end_header_id|>
203
+ {system_prompt}<|eot_id|><|start_header_id|>user<|end_header_id|>
204
+ {user_input}<|eot_id|><|start_header_id|>assistant<|end_header_id|>
205
+ """
206
+
207
+ # API request
208
+ headers = {"Authorization": f"Bearer {hf_token}"}
209
+ api_url = "https://api-inference.huggingface.co/models/meta-llama/Llama-4-Scout-17B-16E-Instruct"
210
+
211
+ payload = {
212
+ "inputs": full_prompt,
213
+ "parameters": {
214
+ "max_new_tokens": 150,
215
+ "temperature": 0.7,
216
+ "top_p": 0.9,
217
+ "do_sample": True,
218
+ "return_full_text": False
219
+ }
220
+ }
221
+
222
+ response = requests.post(api_url, headers=headers, json=payload, timeout=30)
223
+
224
+ if response.status_code == 200:
225
+ result = response.json()
226
+ if isinstance(result, list) and len(result) > 0:
227
+ generated_text = result[0].get('generated_text', '').strip()
228
+ return generated_text
229
+ else:
230
+ return "❌ Unexpected API response format"
231
+ elif response.status_code == 503:
232
+ return "⏳ Llama-4-Scout model is loading, please try again in a moment"
233
+ else:
234
+ return f"❌ API Error: {response.status_code} - {response.text[:100]}"
235
+
236
+ except requests.exceptions.Timeout:
237
+ return "⏱️ Request timeout - Llama-4-Scout is taking too long to respond"
238
+ except Exception as e:
239
+ return f"❌ Error calling Llama-4-Scout API: {str(e)[:100]}"
240
+
241
+ def generate_hungarian_response(user_input, use_llama4=True):
242
+ """Generate enhanced Hungarian response with Llama-4-Scout API or fallback"""
243
  try:
244
  # Add to conversation history
245
  kb.conversation_history.append({"user": user_input, "timestamp": datetime.now().isoformat()})
 
261
  knowledge_context += f" • {doc['content'][:150]}...\n"
262
  knowledge_context += "\n"
263
 
264
+ # Try Llama-4-Scout API first if available and requested
265
+ if use_llama4 and llama4_api_status.startswith("✅"):
266
+ try:
267
+ response = generate_llama4_response_api(user_input, persona_context, knowledge_context)
268
+ if not response.startswith("❌") and not response.startswith("⏳"):
269
+ # Add AI response to history
270
+ kb.conversation_history[-1]["assistant"] = response
271
+ kb.conversation_history[-1]["model"] = "Llama-4-Scout-API"
272
+ return response
273
+ else:
274
+ print(f"Llama-4-Scout API issue: {response}")
275
+ except Exception as e:
276
+ print(f"Llama-4-Scout API failed, falling back: {e}")
277
+
278
+ # Fallback to OpenAI API if available
279
+ if os.getenv('OPENAI_API_KEY'):
280
  try:
281
  from openai import OpenAI
282
  client = OpenAI()
 
317
 
318
  # Add AI response to history
319
  kb.conversation_history[-1]["assistant"] = ai_response
320
+ kb.conversation_history[-1]["model"] = "OpenAI GPT-4o-mini"
321
 
322
  return ai_response
323
 
 
372
  f"Ez fontos téma. {persona_context} Szívesen beszélgetünk erről részletesebben."
373
  ]
374
 
375
+ response = responses[hash(user_input) % len(responses)]
376
+ # Add model info to history
377
+ if kb.conversation_history:
378
+ kb.conversation_history[-1]["assistant"] = response
379
+ kb.conversation_history[-1]["model"] = "Rule-based fallback"
380
+
381
+ return response
382
 
383
  def create_enhanced_avatar_display(text_response, persona_name="Avatar"):
384
+ """Create enhanced avatar display with model information"""
385
+ # Determine which model was used
386
+ model_used = "Unknown"
387
+ if kb.conversation_history:
388
+ model_used = kb.conversation_history[-1].get("model", "Unknown")
389
+
390
  # Simulate different avatar expressions based on response content
391
  if any(word in text_response.lower() for word in ['örülök', 'szuper', 'nagyszerű', 'remek']):
392
  emotion = "😊 Boldog"
 
405
  bg_color = "#f3e5f5"
406
  border_color = "#9c27b0"
407
 
408
+ # Model-specific styling
409
+ if "Llama-4-Scout" in model_used:
410
+ model_icon = "🦙"
411
+ model_color = "#ff6b35"
412
+ elif "OpenAI" in model_used:
413
+ model_icon = "🤖"
414
+ model_color = "#00a67e"
415
+ else:
416
+ model_icon = "⚙️"
417
+ model_color = "#666"
418
+
419
  avatar_html = f"""
420
  <div style="text-align: center; padding: 25px; border: 3px solid {border_color}; border-radius: 15px; background: {bg_color}; margin: 10px;">
421
  <div style="display: flex; align-items: center; justify-content: center; margin-bottom: 15px;">
 
423
  <div>
424
  <h3 style="margin: 0; color: #333;">{persona_name}</h3>
425
  <p style="margin: 5px 0; color: #666; font-size: 14px;">Hangulat: {emotion}</p>
426
+ <p style="margin: 5px 0; color: {model_color}; font-size: 12px; font-weight: bold;">
427
+ {model_icon} {model_used}
428
+ </p>
429
  </div>
430
  </div>
431
 
 
437
 
438
  <div style="margin-top: 15px; padding: 10px; background: rgba(255,255,255,0.7); border-radius: 8px;">
439
  <p style="color: #666; font-size: 12px; margin: 0;">
440
+ 🦙 <strong>Llama-4-Scout API:</strong> {llama4_api_status}
441
  </p>
442
  <p style="color: #666; font-size: 12px; margin: 5px 0 0 0;">
443
  🎬 Következő fázis: TTS + Lip-sync + Valódi avatar animáció
 
526
  return f"❌ **Hiba a persona létrehozása során:** {str(e)}"
527
 
528
  def get_enhanced_knowledge_summary():
529
+ """Enhanced knowledge base summary with API status"""
530
  doc_count = len(kb.knowledge_data)
531
  persona_info = "✅ Beállítva" if kb.persona_data else "❌ Nincs beállítva"
532
  conversation_count = len(kb.conversation_history)
 
560
  if kb.conversation_history:
561
  summary += f"💭 **Legutóbbi beszélgetések:**\n"
562
  for i, conv in enumerate(kb.conversation_history[-3:]):
563
+ model_info = conv.get('model', 'Unknown')
564
+ summary += f" {i+1}. \"{conv['user'][:40]}...\" ({model_info})\n"
565
 
566
  summary += f"""
567
+ 🔧 **AI Modellek állapota:**
568
+ • Llama-4-Scout API: {llama4_api_status}
569
  • OpenAI API: {'✅ Aktív' if os.getenv('OPENAI_API_KEY') else '❌ Nincs beállítva'}
570
+ • HF Token: {'✅ Beállítva' if os.getenv('HF_TOKEN') or os.getenv('HUGGINGFACE_TOKEN') else '❌ Nincs beállítva'}
571
  • Tudásbázis méret: {sum(doc['word_count'] for doc in kb.knowledge_data.values())} szó összesen
572
  """
573
 
574
  return summary
575
 
576
+ def initialize_models():
577
+ """Initialize AI models and check API status"""
578
+ print("🚀 Initializing Eternity AI models...")
579
+
580
+ # Check Llama-4-Scout API availability
581
+ api_available = check_llama4_api()
582
+
583
+ if api_available:
584
+ print("✅ Llama-4-Scout API ready!")
585
+ else:
586
+ print(f"⚠️ Llama-4-Scout API status: {llama4_api_status}")
587
+
588
+ return get_enhanced_knowledge_summary()
589
+
590
  # Create the enhanced Gradio interface
591
  def create_enhanced_eternity_interface():
592
+ """Create the enhanced Eternity POC interface with Llama-4-Scout API"""
593
 
594
  with gr.Blocks(title="Eternity POC - Magyar Avatar", theme=gr.themes.Soft()) as demo:
595
  gr.Markdown("""
596
+ # 🎭 Eternity - Magyar Interaktív Avatar POC v3.0
597
 
598
+ **Llama-4-Scout API integrációval fejlesztett Proof-of-Concept**
599
 
600
  🚀 **Új funkciók ebben a verzióban:**
601
+ - 🦙 **Llama-4-Scout-17B-16E-Instruct API** - Hugging Face Inference API-n keresztül
602
  - 🧠 **Fejlett tudásbázis keresés** - Jobb relevanciával és kontextussal
603
  - 🎭 **Dinamikus avatar érzelmek** - Válasz alapú hangulat szimuláció
604
  - 💬 **Beszélgetési memória** - Korábbi üzenetek figyelembevétele
 
626
  value="""<div style='text-align: center; padding: 50px; color: #666; border: 2px dashed #ccc; border-radius: 10px;'>
627
  <h3>🎭 Avatar várakozik...</h3>
628
  <p>Írjon egy üzenetet és kattintson a Küldés gombra!</p>
629
+ <p style='font-size: 12px; color: #999;'>🦙 Llama-4-Scout API ellenőrzés alatt...</p>
630
  </div>"""
631
  )
632
 
 
682
  upload_btn = gr.Button("⬆️ Dokumentum Feldolgozása", variant="primary", size="lg")
683
  upload_status = gr.Textbox(label="📊 Feltöltés Eredménye", interactive=False, lines=10)
684
 
685
+ with gr.Tab("📊 Tudásbázis & AI API"):
686
  with gr.Column():
687
+ gr.Markdown("### 📈 Tudásbázis áttekintése és AI API státusz")
688
 
689
  refresh_kb_btn = gr.Button("🔄 Frissítés", variant="secondary")
690
  kb_summary = gr.Textbox(
691
  label="📋 Részletes Összefoglaló",
692
+ lines=20,
693
  interactive=False
694
  )
695
 
696
  with gr.Tab("ℹ️ Információ"):
697
  gr.Markdown("""
698
+ ## 🎭 Eternity POC v3.0 - Llama-4-Scout API Integration
699
 
700
  ### ✅ Implementált Funkciók:
701
+ - **🦙 Llama-4-Scout-17B-16E-Instruct API** - Hugging Face Inference API-n keresztül
702
+ - **Magyar nyelvű beszélgetés** - Natív magyar támogatás Llama-4-Scout-tal
703
  - **Fejlett persona rendszer** - Részletes személyiség és beszélgetési stílus
704
  - **Intelligens tudásbázis** - Dokumentum feldolgozás és kontextuális keresés
705
  - **Beszélgetési memória** - Korábbi üzenetek figyelembevétele
706
  - **Dinamikus avatar érzelmek** - Válasz alapú hangulat szimuláció
707
+ - **Model fallback rendszer** - OpenAI API és szabály alapú backup
708
 
709
+ ### 🦙 Llama-4-Scout Jellemzők:
710
+ - **Paraméterek:** 17B aktív, 109B teljes (16 expert MoE)
711
+ - **Multimodális:** Szöveg és kép megértés
712
+ - **Kontextus:** 10M token (ultra-hosszú memória)
713
+ - **Nyelvek:** 12 nyelv, beleértve a magyart
714
+ - **Architektúra:** Mixture-of-Experts (MoE) early fusion
715
+ - **Deployment:** Hugging Face Inference API (serverless)
716
 
717
  ### 🛠️ Használt Technológiák:
718
+ - **AI Model:** Meta Llama-4-Scout-17B-16E-Instruct (API)
719
+ - **Fallback:** OpenAI GPT-4o-mini API
720
  - **Frontend:** Gradio 5.x (Python web UI framework)
721
+ - **Backend:** Python 3.11+ (requests, json)
 
722
  - **Nyelv:** Magyar (natív támogatás)
723
  - **Adattárolás:** Memória alapú (POC szinten)
 
724
 
725
+ ### 📈 Teljesítmény Jellemzők:
726
+ - **Válaszidő:** 3-10 másodperc (API függő)
727
+ - **Memóriahasználat:** Minimális (API-based)
728
  - **Dokumentum méret:** Max 10MB / fájl
729
  - **Tudásbázis kapacitás:** Korlátlan (memória függő)
730
  - **Beszélgetési memória:** Utolsó 10 üzenet
731
+
732
+ ### 🔧 Beállítási Követelmények:
733
+ - **HF_TOKEN:** Hugging Face API token (kötelező Llama-4-Scout-hoz)
734
+ - **OPENAI_API_KEY:** OpenAI API kulcs (opcionális fallback)
735
+ - **Internet kapcsolat:** API hívásokhoz szükséges
736
 
737
  ### 🚀 Következő Fejlesztési Lépések:
738
+ 1. **Multimodális képességek** - Kép input és megértés
739
+ 2. **Magyar TTS integráció** - Hang kimenet Llama-4-Scout válaszokhoz
740
+ 3. **Avatar videó generálás** - Valódi avatar animáció
741
  4. **Perzisztens adattárolás** - Adatbázis integráció
742
+ 5. **Teljesítmény optimalizálás** - Caching és batch processing
 
743
 
744
  ### ⚠️ POC Korlátozások:
745
+ - **API függőség** - Internet kapcsolat és HF token szükséges
746
  - **Nincs adatperzisztencia** - Újraindításkor elvesznek az adatok
747
  - **Egyszerű keresés** - Nincs szemantikus embedding
748
  - **Nincs felhasználói hitelesítés** - Nyilvános hozzáférés
749
+ - **API rate limits** - Hugging Face Inference API korlátok
 
750
 
751
  ---
752
 
753
+ **Verzió:** POC 3.0 - Llama-4-Scout API Integration
754
  **Utolsó frissítés:** 2025. október
755
  **Státusz:** Aktív fejlesztés
756
+ **Licenc:** Apache 2.0 + Llama 4 Community License
757
  """)
758
 
759
  # Enhanced event handlers
 
764
  <p>Kérem, írjon be egy üzenetet a beszélgetéshez!</p>
765
  </div>"""
766
 
767
+ response_text = generate_hungarian_response(user_msg, use_llama4=True)
768
  persona_name = kb.persona_data.get('name', 'Avatar') if kb.persona_data else 'Avatar'
769
  return create_enhanced_avatar_display(response_text, persona_name)
770
 
 
800
  outputs=[kb_summary]
801
  )
802
 
803
+ # Initialize models and knowledge base summary on load
804
  demo.load(
805
+ fn=initialize_models,
806
  outputs=[kb_summary]
807
  )
808
 
809
  return demo
810
 
811
  if __name__ == "__main__":
812
+ print("🎭 Eternity POC v3.0 - Llama-4-Scout API Integration indítása...")
813
+ print("📚 Magyar interaktív avatar rendszer - Llama-4-Scout API verzió")
814
+
815
+ # Check API requirements
816
+ hf_token = os.getenv('HF_TOKEN') or os.getenv('HUGGINGFACE_TOKEN')
817
+ if hf_token:
818
+ print("✅ Hugging Face token észlelve - Llama-4-Scout API elérhető")
819
+ else:
820
+ print("⚠️ HF_TOKEN nem található - Llama-4-Scout API nem elérhető")
821
+ print(" 💡 Tipp: Állítsa be a HF_TOKEN környezeti változót")
822
 
823
  # Check for OpenAI API key
824
  if os.getenv('OPENAI_API_KEY'):
825
+ print("✅ OpenAI API kulcs észlelve - fallback támogatás engedélyezve")
826
  else:
827
+ print("⚠️ OpenAI API kulcs nem található - korlátozott fallback")
828
+ print(" 💡 Tipp: Állítsa be az OPENAI_API_KEY környezeti változót a fallback támogatásért")
829
 
830
  # Create and launch the enhanced interface
831
  demo = create_enhanced_eternity_interface()
832
 
833
+ print("🚀 Eternity POC v3.0 - Llama-4-Scout API Integration elindítva!")
834
  print("🌐 Elérhető: http://localhost:7860")
835
  print("📖 Használati útmutató: README.md")
836
+ print("🦙 Llama-4-Scout API ellenőrzés a háttérben...")
837
 
838
  demo.launch(
839
  server_name="0.0.0.0",
app_llama4_api.py ADDED
@@ -0,0 +1,843 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import json
4
+ import tempfile
5
+ from pathlib import Path
6
+ from datetime import datetime
7
+ import hashlib
8
+ import base64
9
+ import requests
10
+ import warnings
11
+ warnings.filterwarnings("ignore")
12
+
13
+ # Enhanced knowledge base with better search
14
+ class EternityKnowledgeBase:
15
+ def __init__(self):
16
+ self.knowledge_data = {}
17
+ self.persona_data = {}
18
+ self.conversation_history = []
19
+
20
+ def add_document(self, title, content, doc_type="document"):
21
+ """Add a document to the knowledge base with better processing"""
22
+ doc_id = hashlib.md5(f"{title}{content}".encode()).hexdigest()[:8]
23
+
24
+ # Split content into sentences for better search
25
+ sentences = [s.strip() for s in content.split('.') if s.strip()]
26
+
27
+ self.knowledge_data[doc_id] = {
28
+ "title": title,
29
+ "content": content,
30
+ "sentences": sentences,
31
+ "type": doc_type,
32
+ "timestamp": datetime.now().isoformat(),
33
+ "word_count": len(content.split())
34
+ }
35
+ return doc_id
36
+
37
+ def add_persona_info(self, name, age, personality, background):
38
+ """Add persona information with enhanced context"""
39
+ self.persona_data = {
40
+ "name": name,
41
+ "age": age,
42
+ "personality": personality,
43
+ "background": background,
44
+ "created": datetime.now().isoformat(),
45
+ "conversation_style": self._generate_conversation_style(personality)
46
+ }
47
+
48
+ def _generate_conversation_style(self, personality):
49
+ """Generate conversation style based on personality"""
50
+ styles = {
51
+ "barátságos": "Meleg, közvetlen hangnemben beszélek.",
52
+ "segítőkész": "Mindig igyekszem hasznos tanácsokat adni.",
53
+ "humoros": "Szeretek viccelődni és könnyedén beszélni.",
54
+ "türelmes": "Nyugodtan, megfontoltan válaszolok.",
55
+ "energikus": "Lelkesen és dinamikusan kommunikálok."
56
+ }
57
+
58
+ style_elements = []
59
+ for trait in personality.lower().split(','):
60
+ trait = trait.strip()
61
+ for key, value in styles.items():
62
+ if key in trait:
63
+ style_elements.append(value)
64
+
65
+ return " ".join(style_elements) if style_elements else "Természetes, beszélgetős stílusban kommunikálok."
66
+
67
+ def search_knowledge(self, query, max_results=3):
68
+ """Enhanced search with better relevance scoring"""
69
+ results = []
70
+ query_lower = query.lower()
71
+ query_words = query_lower.split()
72
+
73
+ for doc_id, doc in self.knowledge_data.items():
74
+ content_lower = doc["content"].lower()
75
+ title_lower = doc["title"].lower()
76
+
77
+ # Enhanced relevance scoring
78
+ score = 0
79
+
80
+ # Exact phrase matching (highest score)
81
+ if query_lower in content_lower:
82
+ score += 10
83
+ if query_lower in title_lower:
84
+ score += 15
85
+
86
+ # Individual word matching
87
+ for word in query_words:
88
+ if len(word) > 2: # Skip very short words
89
+ score += content_lower.count(word) * 2
90
+ score += title_lower.count(word) * 3
91
+
92
+ # Sentence-level matching for better context
93
+ relevant_sentences = []
94
+ for sentence in doc["sentences"]:
95
+ sentence_lower = sentence.lower()
96
+ sentence_score = 0
97
+ for word in query_words:
98
+ if word in sentence_lower:
99
+ sentence_score += 1
100
+
101
+ if sentence_score > 0:
102
+ relevant_sentences.append((sentence_score, sentence))
103
+
104
+ if score > 0:
105
+ # Sort sentences by relevance
106
+ relevant_sentences.sort(key=lambda x: x[0], reverse=True)
107
+ best_sentences = [s[1] for s in relevant_sentences[:2]]
108
+
109
+ results.append((score, {
110
+ **doc,
111
+ "relevant_sentences": best_sentences
112
+ }))
113
+
114
+ # Sort by relevance and return top results
115
+ results.sort(key=lambda x: x[0], reverse=True)
116
+ return [doc for score, doc in results[:max_results]]
117
+
118
+ def get_persona_context(self):
119
+ """Get enhanced persona context for responses"""
120
+ if not self.persona_data:
121
+ return "Egy barátságos AI avatar vagyok."
122
+
123
+ context = f"A nevem {self.persona_data['name']}. "
124
+ if self.persona_data.get('age'):
125
+ context += f"{self.persona_data['age']} éves vagyok. "
126
+ if self.persona_data.get('personality'):
127
+ context += f"A személyiségem: {self.persona_data['personality']}. "
128
+ if self.persona_data.get('conversation_style'):
129
+ context += f"{self.persona_data['conversation_style']} "
130
+ if self.persona_data.get('background'):
131
+ context += f"Háttér: {self.persona_data['background']}. "
132
+
133
+ return context
134
+
135
+ # Initialize global knowledge base
136
+ kb = EternityKnowledgeBase()
137
+
138
+ # Global variables for Llama-4-Scout API
139
+ llama4_api_status = "Not configured"
140
+
141
+ def check_llama4_api():
142
+ """Check if Llama-4-Scout API is available"""
143
+ global llama4_api_status
144
+
145
+ # Check for Hugging Face token
146
+ hf_token = os.getenv('HF_TOKEN') or os.getenv('HUGGINGFACE_TOKEN')
147
+
148
+ if not hf_token:
149
+ llama4_api_status = "❌ HF_TOKEN not found"
150
+ return False
151
+
152
+ try:
153
+ # Test API endpoint
154
+ headers = {"Authorization": f"Bearer {hf_token}"}
155
+ api_url = "https://api-inference.huggingface.co/models/meta-llama/Llama-4-Scout-17B-16E-Instruct"
156
+
157
+ # Simple test request
158
+ response = requests.post(
159
+ api_url,
160
+ headers=headers,
161
+ json={"inputs": "Hello", "parameters": {"max_new_tokens": 10}},
162
+ timeout=10
163
+ )
164
+
165
+ if response.status_code == 200:
166
+ llama4_api_status = "✅ API Ready"
167
+ return True
168
+ elif response.status_code == 503:
169
+ llama4_api_status = "⏳ Model Loading"
170
+ return False
171
+ else:
172
+ llama4_api_status = f"❌ API Error: {response.status_code}"
173
+ return False
174
+
175
+ except Exception as e:
176
+ llama4_api_status = f"❌ Connection Error: {str(e)[:50]}"
177
+ return False
178
+
179
+ def generate_llama4_response_api(user_input, persona_context, knowledge_context):
180
+ """Generate response using Llama-4-Scout via Hugging Face Inference API"""
181
+
182
+ hf_token = os.getenv('HF_TOKEN') or os.getenv('HUGGINGFACE_TOKEN')
183
+ if not hf_token:
184
+ return "❌ Hugging Face token not configured"
185
+
186
+ try:
187
+ # Construct the prompt in Hungarian
188
+ system_prompt = f"""Te {persona_context}
189
+
190
+ Válaszolj természetesen, személyesen és barátságosan magyarul. Használd fel a rendelkezésre álló információkat, de ne ismételd meg szó szerint. Inkább építsd be természetesen a beszélgetésbe.
191
+
192
+ {knowledge_context}
193
+
194
+ Stílus irányelvek:
195
+ - Beszélgetős, természetes hangnem
196
+ - Személyes élmények és érzések megosztása
197
+ - Rövid, érthető válaszok (max 100-150 szó)
198
+ - Magyar kifejezések és szófordulatok használata
199
+ - Empátia és megértés kifejezése"""
200
+
201
+ # Create the full prompt
202
+ full_prompt = f"""<|begin_of_text|><|start_header_id|>system<|end_header_id|>
203
+ {system_prompt}<|eot_id|><|start_header_id|>user<|end_header_id|>
204
+ {user_input}<|eot_id|><|start_header_id|>assistant<|end_header_id|>
205
+ """
206
+
207
+ # API request
208
+ headers = {"Authorization": f"Bearer {hf_token}"}
209
+ api_url = "https://api-inference.huggingface.co/models/meta-llama/Llama-4-Scout-17B-16E-Instruct"
210
+
211
+ payload = {
212
+ "inputs": full_prompt,
213
+ "parameters": {
214
+ "max_new_tokens": 150,
215
+ "temperature": 0.7,
216
+ "top_p": 0.9,
217
+ "do_sample": True,
218
+ "return_full_text": False
219
+ }
220
+ }
221
+
222
+ response = requests.post(api_url, headers=headers, json=payload, timeout=30)
223
+
224
+ if response.status_code == 200:
225
+ result = response.json()
226
+ if isinstance(result, list) and len(result) > 0:
227
+ generated_text = result[0].get('generated_text', '').strip()
228
+ return generated_text
229
+ else:
230
+ return "❌ Unexpected API response format"
231
+ elif response.status_code == 503:
232
+ return "⏳ Llama-4-Scout model is loading, please try again in a moment"
233
+ else:
234
+ return f"❌ API Error: {response.status_code} - {response.text[:100]}"
235
+
236
+ except requests.exceptions.Timeout:
237
+ return "⏱️ Request timeout - Llama-4-Scout is taking too long to respond"
238
+ except Exception as e:
239
+ return f"❌ Error calling Llama-4-Scout API: {str(e)[:100]}"
240
+
241
+ def generate_hungarian_response(user_input, use_llama4=True):
242
+ """Generate enhanced Hungarian response with Llama-4-Scout API or fallback"""
243
+ try:
244
+ # Add to conversation history
245
+ kb.conversation_history.append({"user": user_input, "timestamp": datetime.now().isoformat()})
246
+
247
+ # Get persona context
248
+ persona_context = kb.get_persona_context()
249
+
250
+ # Search for relevant knowledge with enhanced results
251
+ relevant_docs = kb.search_knowledge(user_input)
252
+ knowledge_context = ""
253
+ if relevant_docs:
254
+ knowledge_context = "Releváns információk a tudásbázisból:\n"
255
+ for doc in relevant_docs:
256
+ knowledge_context += f"📄 {doc['title']}:\n"
257
+ if doc.get('relevant_sentences'):
258
+ for sentence in doc['relevant_sentences']:
259
+ knowledge_context += f" • {sentence}\n"
260
+ else:
261
+ knowledge_context += f" • {doc['content'][:150]}...\n"
262
+ knowledge_context += "\n"
263
+
264
+ # Try Llama-4-Scout API first if available and requested
265
+ if use_llama4 and llama4_api_status.startswith("✅"):
266
+ try:
267
+ response = generate_llama4_response_api(user_input, persona_context, knowledge_context)
268
+ if not response.startswith("❌") and not response.startswith("⏳"):
269
+ # Add AI response to history
270
+ kb.conversation_history[-1]["assistant"] = response
271
+ kb.conversation_history[-1]["model"] = "Llama-4-Scout-API"
272
+ return response
273
+ else:
274
+ print(f"Llama-4-Scout API issue: {response}")
275
+ except Exception as e:
276
+ print(f"Llama-4-Scout API failed, falling back: {e}")
277
+
278
+ # Fallback to OpenAI API if available
279
+ if os.getenv('OPENAI_API_KEY'):
280
+ try:
281
+ from openai import OpenAI
282
+ client = OpenAI()
283
+
284
+ # Enhanced system prompt
285
+ system_prompt = f"""Te {persona_context}
286
+
287
+ Válaszolj természetesen, személyesen és barátságosan magyarul. Használd fel a rendelkezésre álló információkat, de ne ismételd meg szó szerint. Inkább építsd be természetesen a beszélgetésbe.
288
+
289
+ {knowledge_context}
290
+
291
+ Stílus irányelvek:
292
+ - Beszélgetős, természetes hangnem
293
+ - Személyes élmények és érzések megosztása
294
+ - Rövid, érthető válaszok (max 100-150 szó)
295
+ - Magyar kifejezések és szófordulatok használata
296
+ - Empátia és megértés kifejezése"""
297
+
298
+ # Include recent conversation context
299
+ messages = [{"role": "system", "content": system_prompt}]
300
+
301
+ # Add recent conversation history
302
+ recent_history = kb.conversation_history[-3:] if len(kb.conversation_history) > 1 else []
303
+ for entry in recent_history[:-1]: # Exclude current message
304
+ messages.append({"role": "user", "content": entry["user"]})
305
+
306
+ messages.append({"role": "user", "content": user_input})
307
+
308
+ response = client.chat.completions.create(
309
+ model="gpt-4o-mini",
310
+ messages=messages,
311
+ max_tokens=150,
312
+ temperature=0.8,
313
+ presence_penalty=0.1
314
+ )
315
+
316
+ ai_response = response.choices[0].message.content
317
+
318
+ # Add AI response to history
319
+ kb.conversation_history[-1]["assistant"] = ai_response
320
+ kb.conversation_history[-1]["model"] = "OpenAI GPT-4o-mini"
321
+
322
+ return ai_response
323
+
324
+ except Exception as e:
325
+ print(f"OpenAI API error: {e}")
326
+
327
+ # Enhanced fallback responses
328
+ return generate_enhanced_hungarian_response(user_input, persona_context, knowledge_context)
329
+
330
+ except Exception as e:
331
+ return f"Hiba történt a válasz generálása során: {str(e)}"
332
+
333
+ def generate_enhanced_hungarian_response(user_input, persona_context, knowledge_context):
334
+ """Enhanced rule-based Hungarian responses"""
335
+ user_lower = user_input.lower()
336
+
337
+ # Greeting responses with persona
338
+ if any(word in user_lower for word in ['szia', 'hello', 'helló', 'jó napot', 'üdv']):
339
+ greetings = [
340
+ f"Szia! {persona_context} Örülök, hogy beszélgethetünk!",
341
+ f"Helló! {persona_context} Miben segíthetek ma?",
342
+ f"Üdvözöllek! {persona_context} Mit szeretnél tudni?"
343
+ ]
344
+ return greetings[hash(user_input) % len(greetings)]
345
+
346
+ # Self-introduction with enhanced persona info
347
+ if any(word in user_lower for word in ['ki vagy', 'bemutatkozz', 'magadról', 'személyiség']):
348
+ intro = f"{persona_context}"
349
+ if knowledge_context:
350
+ intro += f"\n\nTudok mesélni az életemről, tapasztalataimról. Mit érdekel leginkább?"
351
+ return intro
352
+
353
+ # Knowledge-based responses with better context
354
+ if knowledge_context:
355
+ if any(word in user_lower for word in ['mesélj', 'történet', 'emlék', 'múlt']):
356
+ return f"Szívesen mesélek! {knowledge_context}\nVan valami konkrét, amiről többet szeretnél hallani?"
357
+
358
+ if any(word in user_lower for word in ['mit tudsz', 'információ', 'részlet']):
359
+ return f"Íme, amit tudok erről:\n\n{knowledge_context}\nVan még kérdésed ezzel kapcsolatban?"
360
+
361
+ # Emotional responses
362
+ if any(word in user_lower for word in ['szomorú', 'rossz', 'nehéz', 'probléma']):
363
+ return f"Sajnálom, hogy nehéz időszakon mész át. {persona_context} Ha szeretnél, szívesen meghallgatlak."
364
+
365
+ if any(word in user_lower for word in ['örülök', 'jó', 'szuper', 'remek']):
366
+ return f"Nagyszerű! Örülök, hogy jól érzed magad. {persona_context} Mesélj többet erről!"
367
+
368
+ # Default enhanced response
369
+ responses = [
370
+ f"Érdekes kérdés! {persona_context} Mit gondolsz erről te?",
371
+ f"Hmm, ezen gondolkodnom kell. {persona_context} Tudnál többet mesélni erről?",
372
+ f"Ez fontos téma. {persona_context} Szívesen beszélgetünk erről részletesebben."
373
+ ]
374
+
375
+ response = responses[hash(user_input) % len(responses)]
376
+ # Add model info to history
377
+ if kb.conversation_history:
378
+ kb.conversation_history[-1]["assistant"] = response
379
+ kb.conversation_history[-1]["model"] = "Rule-based fallback"
380
+
381
+ return response
382
+
383
+ def create_enhanced_avatar_display(text_response, persona_name="Avatar"):
384
+ """Create enhanced avatar display with model information"""
385
+ # Determine which model was used
386
+ model_used = "Unknown"
387
+ if kb.conversation_history:
388
+ model_used = kb.conversation_history[-1].get("model", "Unknown")
389
+
390
+ # Simulate different avatar expressions based on response content
391
+ if any(word in text_response.lower() for word in ['örülök', 'szuper', 'nagyszerű', 'remek']):
392
+ emotion = "😊 Boldog"
393
+ bg_color = "#e8f5e8"
394
+ border_color = "#4caf50"
395
+ elif any(word in text_response.lower() for word in ['sajnálom', 'nehéz', 'szomorú']):
396
+ emotion = "😔 Együttérző"
397
+ bg_color = "#fff3e0"
398
+ border_color = "#ff9800"
399
+ elif any(word in text_response.lower() for word in ['érdekes', 'gondolkodnom', 'hmm']):
400
+ emotion = "🤔 Gondolkodó"
401
+ bg_color = "#e3f2fd"
402
+ border_color = "#2196f3"
403
+ else:
404
+ emotion = "😊 Barátságos"
405
+ bg_color = "#f3e5f5"
406
+ border_color = "#9c27b0"
407
+
408
+ # Model-specific styling
409
+ if "Llama-4-Scout" in model_used:
410
+ model_icon = "🦙"
411
+ model_color = "#ff6b35"
412
+ elif "OpenAI" in model_used:
413
+ model_icon = "🤖"
414
+ model_color = "#00a67e"
415
+ else:
416
+ model_icon = "⚙️"
417
+ model_color = "#666"
418
+
419
+ avatar_html = f"""
420
+ <div style="text-align: center; padding: 25px; border: 3px solid {border_color}; border-radius: 15px; background: {bg_color}; margin: 10px;">
421
+ <div style="display: flex; align-items: center; justify-content: center; margin-bottom: 15px;">
422
+ <div style="font-size: 48px; margin-right: 15px;">🎭</div>
423
+ <div>
424
+ <h3 style="margin: 0; color: #333;">{persona_name}</h3>
425
+ <p style="margin: 5px 0; color: #666; font-size: 14px;">Hangulat: {emotion}</p>
426
+ <p style="margin: 5px 0; color: {model_color}; font-size: 12px; font-weight: bold;">
427
+ {model_icon} {model_used}
428
+ </p>
429
+ </div>
430
+ </div>
431
+
432
+ <div style="background: white; padding: 20px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
433
+ <p style="font-size: 16px; color: #333; line-height: 1.6; margin: 0; font-style: italic;">
434
+ "{text_response}"
435
+ </p>
436
+ </div>
437
+
438
+ <div style="margin-top: 15px; padding: 10px; background: rgba(255,255,255,0.7); border-radius: 8px;">
439
+ <p style="color: #666; font-size: 12px; margin: 0;">
440
+ 🦙 <strong>Llama-4-Scout API:</strong> {llama4_api_status}
441
+ </p>
442
+ <p style="color: #666; font-size: 12px; margin: 5px 0 0 0;">
443
+ 🎬 Következő fázis: TTS + Lip-sync + Valódi avatar animáció
444
+ </p>
445
+ </div>
446
+ </div>
447
+ """
448
+ return avatar_html
449
+
450
+ def process_enhanced_document_upload(file):
451
+ """Enhanced document processing with better analysis"""
452
+ if file is None:
453
+ return "❌ Nincs feltöltött fájl."
454
+
455
+ try:
456
+ # Try different encodings
457
+ encodings = ['utf-8', 'latin-1', 'cp1252']
458
+ content = None
459
+ used_encoding = None
460
+
461
+ for encoding in encodings:
462
+ try:
463
+ with open(file.name, 'r', encoding=encoding) as f:
464
+ content = f.read()
465
+ used_encoding = encoding
466
+ break
467
+ except UnicodeDecodeError:
468
+ continue
469
+
470
+ if content is None:
471
+ return "❌ Nem sikerült dekódolni a fájlt. Próbálja UTF-8 kódolással."
472
+
473
+ # Extract filename as title
474
+ title = Path(file.name).stem
475
+
476
+ # Add to knowledge base
477
+ doc_id = kb.add_document(title, content, "uploaded_document")
478
+
479
+ # Generate summary statistics
480
+ word_count = len(content.split())
481
+ sentence_count = len([s for s in content.split('.') if s.strip()])
482
+ char_count = len(content)
483
+
484
+ return f"""✅ **Dokumentum sikeresen feldolgozva!**
485
+
486
+ 📄 **Fájl:** {title}
487
+ 🆔 **Azonosító:** {doc_id}
488
+ 📊 **Statisztikák:**
489
+ • Szavak száma: {word_count}
490
+ • Mondatok száma: {sentence_count}
491
+ • Karakterek száma: {char_count}
492
+ • Kódolás: {used_encoding}
493
+
494
+ 💡 **Tipp:** Most már kérdezhet a dokumentum tartalmáról a beszélgetés során!"""
495
+
496
+ except Exception as e:
497
+ return f"❌ **Hiba a dokumentum feldolgozása során:** {str(e)}"
498
+
499
+ def create_enhanced_persona(name, age, personality, background):
500
+ """Enhanced persona creation with validation"""
501
+ try:
502
+ # Validate inputs
503
+ if not name.strip():
504
+ return "❌ A név megadása kötelező!"
505
+
506
+ if age and not age.isdigit():
507
+ return "❌ A kor csak szám lehet!"
508
+
509
+ if not personality.strip():
510
+ return "❌ A személyiség leírása kötelező!"
511
+
512
+ kb.add_persona_info(name.strip(), age.strip(), personality.strip(), background.strip())
513
+
514
+ return f"""✅ **Persona sikeresen létrehozva!**
515
+
516
+ 👤 **Név:** {name}
517
+ 🎂 **Kor:** {age if age else 'Nem megadott'}
518
+ 🎭 **Személyiség:** {personality}
519
+ 📖 **Háttér:** {background if background else 'Nem megadott'}
520
+
521
+ 🎯 **Beszélgetési stílus:** {kb.persona_data.get('conversation_style', 'Alapértelmezett')}
522
+
523
+ 💬 **Most már beszélgethet az avatarral a beszélgetés tabon!**"""
524
+
525
+ except Exception as e:
526
+ return f"❌ **Hiba a persona létrehozása során:** {str(e)}"
527
+
528
+ def get_enhanced_knowledge_summary():
529
+ """Enhanced knowledge base summary with API status"""
530
+ doc_count = len(kb.knowledge_data)
531
+ persona_info = "✅ Beállítva" if kb.persona_data else "❌ Nincs beállítva"
532
+ conversation_count = len(kb.conversation_history)
533
+
534
+ summary = f"""📊 **Eternity Tudásbázis Állapota**
535
+
536
+ 👤 **Persona:** {persona_info}
537
+ 📚 **Dokumentumok száma:** {doc_count}
538
+ 💬 **Beszélgetések száma:** {conversation_count}
539
+
540
+ """
541
+
542
+ if kb.persona_data:
543
+ summary += f"""🎭 **Aktív Persona:**
544
+ • Név: {kb.persona_data['name']}
545
+ • Kor: {kb.persona_data.get('age', 'N/A')}
546
+ • Személyiség: {kb.persona_data['personality'][:50]}...
547
+
548
+ """
549
+
550
+ if kb.knowledge_data:
551
+ summary += "📄 **Feltöltött Dokumentumok:**\n"
552
+ for i, (doc_id, doc) in enumerate(list(kb.knowledge_data.items())[:5]):
553
+ summary += f" {i+1}. **{doc['title']}** ({doc['word_count']} szó, {doc['type']})\n"
554
+
555
+ if doc_count > 5:
556
+ summary += f" ... és még {doc_count - 5} dokumentum\n"
557
+
558
+ summary += "\n"
559
+
560
+ if kb.conversation_history:
561
+ summary += f"💭 **Legutóbbi beszélgetések:**\n"
562
+ for i, conv in enumerate(kb.conversation_history[-3:]):
563
+ model_info = conv.get('model', 'Unknown')
564
+ summary += f" {i+1}. \"{conv['user'][:40]}...\" ({model_info})\n"
565
+
566
+ summary += f"""
567
+ 🔧 **AI Modellek állapota:**
568
+ • Llama-4-Scout API: {llama4_api_status}
569
+ • OpenAI API: {'✅ Aktív' if os.getenv('OPENAI_API_KEY') else '❌ Nincs beállítva'}
570
+ • HF Token: {'✅ Beállítva' if os.getenv('HF_TOKEN') or os.getenv('HUGGINGFACE_TOKEN') else '❌ Nincs beállítva'}
571
+ • Tudásbázis méret: {sum(doc['word_count'] for doc in kb.knowledge_data.values())} szó összesen
572
+ """
573
+
574
+ return summary
575
+
576
+ def initialize_models():
577
+ """Initialize AI models and check API status"""
578
+ print("🚀 Initializing Eternity AI models...")
579
+
580
+ # Check Llama-4-Scout API availability
581
+ api_available = check_llama4_api()
582
+
583
+ if api_available:
584
+ print("✅ Llama-4-Scout API ready!")
585
+ else:
586
+ print(f"⚠️ Llama-4-Scout API status: {llama4_api_status}")
587
+
588
+ return get_enhanced_knowledge_summary()
589
+
590
+ # Create the enhanced Gradio interface
591
+ def create_enhanced_eternity_interface():
592
+ """Create the enhanced Eternity POC interface with Llama-4-Scout API"""
593
+
594
+ with gr.Blocks(title="Eternity POC - Magyar Avatar", theme=gr.themes.Soft()) as demo:
595
+ gr.Markdown("""
596
+ # 🎭 Eternity - Magyar Interaktív Avatar POC v3.0
597
+
598
+ **Llama-4-Scout API integrációval fejlesztett Proof-of-Concept**
599
+
600
+ 🚀 **Új funkciók ebben a verzióban:**
601
+ - 🦙 **Llama-4-Scout-17B-16E-Instruct API** - Hugging Face Inference API-n keresztül
602
+ - 🧠 **Fejlett tudásbázis keresés** - Jobb relevanciával és kontextussal
603
+ - 🎭 **Dinamikus avatar érzelmek** - Válasz alapú hangulat szimuláció
604
+ - 💬 **Beszélgetési memória** - Korábbi üzenetek figyelembevétele
605
+ - 📊 **Részletes statisztikák** - Dokumentum és beszélgetés elemzés
606
+ - 🎨 **Javított vizuális megjelenés** - Professzionális avatar display
607
+
608
+ **Használat:** Hozzon létre personát → Töltsön fel dokumentumokat → Beszélgessen!
609
+ """)
610
+
611
+ with gr.Tab("💬 Beszélgetés"):
612
+ with gr.Row():
613
+ with gr.Column(scale=2):
614
+ user_input = gr.Textbox(
615
+ label="💭 Az Ön üzenete",
616
+ placeholder="Írja ide az üzenetét magyarul... (pl. 'Szia! Mesélj magadról!')",
617
+ lines=3
618
+ )
619
+ with gr.Row():
620
+ chat_btn = gr.Button("📤 Küldés", variant="primary", size="lg")
621
+ clear_btn = gr.Button("🗑️ Törlés", variant="secondary")
622
+
623
+ with gr.Column(scale=3):
624
+ avatar_response = gr.HTML(
625
+ label="🎭 Avatar Válasz",
626
+ value="""<div style='text-align: center; padding: 50px; color: #666; border: 2px dashed #ccc; border-radius: 10px;'>
627
+ <h3>🎭 Avatar várakozik...</h3>
628
+ <p>Írjon egy üzenetet és kattintson a Küldés gombra!</p>
629
+ <p style='font-size: 12px; color: #999;'>🦙 Llama-4-Scout API ellenőrzés alatt...</p>
630
+ </div>"""
631
+ )
632
+
633
+ with gr.Tab("👤 Persona Beállítás"):
634
+ with gr.Column():
635
+ gr.Markdown("### 🎭 Hozza létre az avatar személyiségét")
636
+ gr.Markdown("*Minél részletesebb információkat ad meg, annál személyesebb lesz a beszélgetés.*")
637
+
638
+ with gr.Row():
639
+ persona_name = gr.Textbox(
640
+ label="👤 Név",
641
+ placeholder="pl. Kovács Anna",
642
+ info="Az avatar neve (kötelező)"
643
+ )
644
+ persona_age = gr.Textbox(
645
+ label="🎂 Kor",
646
+ placeholder="pl. 30",
647
+ info="Életkor számban (opcionális)"
648
+ )
649
+
650
+ persona_personality = gr.Textbox(
651
+ label="🎭 Személyiség",
652
+ placeholder="pl. Barátságos, segítőkész, humoros, türelmes, energikus...",
653
+ lines=2,
654
+ info="Személyiségjegyek vesszővel elválasztva (kötelező)"
655
+ )
656
+
657
+ persona_background = gr.Textbox(
658
+ label="📖 Háttér/Történet",
659
+ placeholder="pl. Tanár vagyok, szeretem a könyveket és az utazást. Budapesten élek...",
660
+ lines=4,
661
+ info="Életrajz, hobbik, érdeklődési körök (opcionális, de ajánlott)"
662
+ )
663
+
664
+ create_persona_btn = gr.Button("✨ Persona Létrehozása", variant="primary", size="lg")
665
+ persona_status = gr.Textbox(label="📋 Állapot", interactive=False, lines=8)
666
+
667
+ with gr.Tab("📚 Dokumentum Feltöltés"):
668
+ with gr.Column():
669
+ gr.Markdown("### 📄 Töltsön fel személyes dokumentumokat")
670
+ gr.Markdown("""
671
+ **Támogatott fájltípusok:** `.txt`, `.md`, `.json`
672
+ **Kódolás:** UTF-8 ajánlott (automatikus detektálás)
673
+ **Tartalom:** Életrajz, naplók, blog bejegyzések, emlékek, stb.
674
+ """)
675
+
676
+ file_upload = gr.File(
677
+ label="📁 Dokumentum kiválasztása",
678
+ file_types=[".txt", ".md", ".json"],
679
+ file_count="single"
680
+ )
681
+
682
+ upload_btn = gr.Button("⬆️ Dokumentum Feldolgozása", variant="primary", size="lg")
683
+ upload_status = gr.Textbox(label="📊 Feltöltés Eredménye", interactive=False, lines=10)
684
+
685
+ with gr.Tab("📊 Tudásbázis & AI API"):
686
+ with gr.Column():
687
+ gr.Markdown("### 📈 Tudásbázis áttekintése és AI API státusz")
688
+
689
+ refresh_kb_btn = gr.Button("🔄 Frissítés", variant="secondary")
690
+ kb_summary = gr.Textbox(
691
+ label="📋 Részletes Összefoglaló",
692
+ lines=20,
693
+ interactive=False
694
+ )
695
+
696
+ with gr.Tab("ℹ️ Információ"):
697
+ gr.Markdown("""
698
+ ## 🎭 Eternity POC v3.0 - Llama-4-Scout API Integration
699
+
700
+ ### ✅ Implementált Funkciók:
701
+ - **🦙 Llama-4-Scout-17B-16E-Instruct API** - Hugging Face Inference API-n keresztül
702
+ - **Magyar nyelvű beszélgetés** - Natív magyar támogatás Llama-4-Scout-tal
703
+ - **Fejlett persona rendszer** - Részletes személyiség és beszélgetési stílus
704
+ - **Intelligens tudásbázis** - Dokumentum feldolgozás és kontextuális keresés
705
+ - **Beszélgetési memória** - Korábbi üzenetek figyelembevétele
706
+ - **Dinamikus avatar érzelmek** - Válasz alapú hangulat szimuláció
707
+ - **Model fallback rendszer** - OpenAI API és szabály alapú backup
708
+
709
+ ### 🦙 Llama-4-Scout Jellemzők:
710
+ - **Paraméterek:** 17B aktív, 109B teljes (16 expert MoE)
711
+ - **Multimodális:** Szöveg és kép megértés
712
+ - **Kontextus:** 10M token (ultra-hosszú memória)
713
+ - **Nyelvek:** 12 nyelv, beleértve a magyart
714
+ - **Architektúra:** Mixture-of-Experts (MoE) early fusion
715
+ - **Deployment:** Hugging Face Inference API (serverless)
716
+
717
+ ### 🛠️ Használt Technológiák:
718
+ - **AI Model:** Meta Llama-4-Scout-17B-16E-Instruct (API)
719
+ - **Fallback:** OpenAI GPT-4o-mini API
720
+ - **Frontend:** Gradio 5.x (Python web UI framework)
721
+ - **Backend:** Python 3.11+ (requests, json)
722
+ - **Nyelv:** Magyar (natív támogatás)
723
+ - **Adattárolás:** Memória alapú (POC szinten)
724
+
725
+ ### 📈 Teljesítmény Jellemzők:
726
+ - **Válaszidő:** 3-10 másodperc (API függő)
727
+ - **Memóriahasználat:** Minimális (API-based)
728
+ - **Dokumentum méret:** Max 10MB / fájl
729
+ - **Tudásbázis kapacitás:** Korlátlan (memória függő)
730
+ - **Beszélgetési memória:** Utolsó 10 üzenet
731
+
732
+ ### 🔧 Beállítási Követelmények:
733
+ - **HF_TOKEN:** Hugging Face API token (kötelező Llama-4-Scout-hoz)
734
+ - **OPENAI_API_KEY:** OpenAI API kulcs (opcionális fallback)
735
+ - **Internet kapcsolat:** API hívásokhoz szükséges
736
+
737
+ ### 🚀 Következő Fejlesztési Lépések:
738
+ 1. **Multimodális képességek** - Kép input és megértés
739
+ 2. **Magyar TTS integráció** - Hang kimenet Llama-4-Scout válaszokhoz
740
+ 3. **Avatar videó generálás** - Valódi avatar animáció
741
+ 4. **Perzisztens adattárolás** - Adatbázis integráció
742
+ 5. **Teljesítmény optimalizálás** - Caching és batch processing
743
+
744
+ ### ⚠️ POC Korlátozások:
745
+ - **API függőség** - Internet kapcsolat és HF token szükséges
746
+ - **Nincs adatperzisztencia** - Újraindításkor elvesznek az adatok
747
+ - **Egyszerű keresés** - Nincs szemantikus embedding
748
+ - **Nincs felhasználói hitelesítés** - Nyilvános hozzáférés
749
+ - **API rate limits** - Hugging Face Inference API korlátok
750
+
751
+ ---
752
+
753
+ **Verzió:** POC 3.0 - Llama-4-Scout API Integration
754
+ **Utolsó frissítés:** 2025. október
755
+ **Státusz:** Aktív fejlesztés
756
+ **Licenc:** Apache 2.0 + Llama 4 Community License
757
+ """)
758
+
759
+ # Enhanced event handlers
760
+ def handle_chat(user_msg):
761
+ if not user_msg.strip():
762
+ return """<div style='text-align: center; padding: 30px; color: #ff6b6b; border: 2px dashed #ff6b6b; border-radius: 10px;'>
763
+ <h3>⚠️ Üres üzenet</h3>
764
+ <p>Kérem, írjon be egy üzenetet a beszélgetéshez!</p>
765
+ </div>"""
766
+
767
+ response_text = generate_hungarian_response(user_msg, use_llama4=True)
768
+ persona_name = kb.persona_data.get('name', 'Avatar') if kb.persona_data else 'Avatar'
769
+ return create_enhanced_avatar_display(response_text, persona_name)
770
+
771
+ def clear_input():
772
+ return ""
773
+
774
+ # Event bindings
775
+ chat_btn.click(
776
+ fn=handle_chat,
777
+ inputs=[user_input],
778
+ outputs=[avatar_response]
779
+ )
780
+
781
+ clear_btn.click(
782
+ fn=clear_input,
783
+ outputs=[user_input]
784
+ )
785
+
786
+ create_persona_btn.click(
787
+ fn=create_enhanced_persona,
788
+ inputs=[persona_name, persona_age, persona_personality, persona_background],
789
+ outputs=[persona_status]
790
+ )
791
+
792
+ upload_btn.click(
793
+ fn=process_enhanced_document_upload,
794
+ inputs=[file_upload],
795
+ outputs=[upload_status]
796
+ )
797
+
798
+ refresh_kb_btn.click(
799
+ fn=get_enhanced_knowledge_summary,
800
+ outputs=[kb_summary]
801
+ )
802
+
803
+ # Initialize models and knowledge base summary on load
804
+ demo.load(
805
+ fn=initialize_models,
806
+ outputs=[kb_summary]
807
+ )
808
+
809
+ return demo
810
+
811
+ if __name__ == "__main__":
812
+ print("🎭 Eternity POC v3.0 - Llama-4-Scout API Integration indítása...")
813
+ print("📚 Magyar interaktív avatar rendszer - Llama-4-Scout API verzió")
814
+
815
+ # Check API requirements
816
+ hf_token = os.getenv('HF_TOKEN') or os.getenv('HUGGINGFACE_TOKEN')
817
+ if hf_token:
818
+ print("✅ Hugging Face token észlelve - Llama-4-Scout API elérhető")
819
+ else:
820
+ print("⚠️ HF_TOKEN nem található - Llama-4-Scout API nem elérhető")
821
+ print(" 💡 Tipp: Állítsa be a HF_TOKEN környezeti változót")
822
+
823
+ # Check for OpenAI API key
824
+ if os.getenv('OPENAI_API_KEY'):
825
+ print("✅ OpenAI API kulcs észlelve - fallback támogatás engedélyezve")
826
+ else:
827
+ print("⚠️ OpenAI API kulcs nem található - korlátozott fallback")
828
+ print(" 💡 Tipp: Állítsa be az OPENAI_API_KEY környezeti változót a fallback támogatásért")
829
+
830
+ # Create and launch the enhanced interface
831
+ demo = create_enhanced_eternity_interface()
832
+
833
+ print("🚀 Eternity POC v3.0 - Llama-4-Scout API Integration elindítva!")
834
+ print("🌐 Elérhető: http://localhost:7860")
835
+ print("📖 Használati útmutató: README.md")
836
+ print("🦙 Llama-4-Scout API ellenőrzés a háttérben...")
837
+
838
+ demo.launch(
839
+ server_name="0.0.0.0",
840
+ server_port=7860,
841
+ share=False,
842
+ show_error=True
843
+ )
app_with_llama4.py ADDED
@@ -0,0 +1,848 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import json
4
+ import tempfile
5
+ from pathlib import Path
6
+ from datetime import datetime
7
+ import hashlib
8
+ import base64
9
+ import torch
10
+ from transformers import AutoProcessor, Llama4ForConditionalGeneration
11
+ import warnings
12
+ warnings.filterwarnings("ignore")
13
+
14
+ # Enhanced knowledge base with better search
15
+ class EternityKnowledgeBase:
16
+ def __init__(self):
17
+ self.knowledge_data = {}
18
+ self.persona_data = {}
19
+ self.conversation_history = []
20
+
21
+ def add_document(self, title, content, doc_type="document"):
22
+ """Add a document to the knowledge base with better processing"""
23
+ doc_id = hashlib.md5(f"{title}{content}".encode()).hexdigest()[:8]
24
+
25
+ # Split content into sentences for better search
26
+ sentences = [s.strip() for s in content.split('.') if s.strip()]
27
+
28
+ self.knowledge_data[doc_id] = {
29
+ "title": title,
30
+ "content": content,
31
+ "sentences": sentences,
32
+ "type": doc_type,
33
+ "timestamp": datetime.now().isoformat(),
34
+ "word_count": len(content.split())
35
+ }
36
+ return doc_id
37
+
38
+ def add_persona_info(self, name, age, personality, background):
39
+ """Add persona information with enhanced context"""
40
+ self.persona_data = {
41
+ "name": name,
42
+ "age": age,
43
+ "personality": personality,
44
+ "background": background,
45
+ "created": datetime.now().isoformat(),
46
+ "conversation_style": self._generate_conversation_style(personality)
47
+ }
48
+
49
+ def _generate_conversation_style(self, personality):
50
+ """Generate conversation style based on personality"""
51
+ styles = {
52
+ "barátságos": "Meleg, közvetlen hangnemben beszélek.",
53
+ "segítőkész": "Mindig igyekszem hasznos tanácsokat adni.",
54
+ "humoros": "Szeretek viccelődni és könnyedén beszélni.",
55
+ "türelmes": "Nyugodtan, megfontoltan válaszolok.",
56
+ "energikus": "Lelkesen és dinamikusan kommunikálok."
57
+ }
58
+
59
+ style_elements = []
60
+ for trait in personality.lower().split(','):
61
+ trait = trait.strip()
62
+ for key, value in styles.items():
63
+ if key in trait:
64
+ style_elements.append(value)
65
+
66
+ return " ".join(style_elements) if style_elements else "Természetes, beszélgetős stílusban kommunikálok."
67
+
68
+ def search_knowledge(self, query, max_results=3):
69
+ """Enhanced search with better relevance scoring"""
70
+ results = []
71
+ query_lower = query.lower()
72
+ query_words = query_lower.split()
73
+
74
+ for doc_id, doc in self.knowledge_data.items():
75
+ content_lower = doc["content"].lower()
76
+ title_lower = doc["title"].lower()
77
+
78
+ # Enhanced relevance scoring
79
+ score = 0
80
+
81
+ # Exact phrase matching (highest score)
82
+ if query_lower in content_lower:
83
+ score += 10
84
+ if query_lower in title_lower:
85
+ score += 15
86
+
87
+ # Individual word matching
88
+ for word in query_words:
89
+ if len(word) > 2: # Skip very short words
90
+ score += content_lower.count(word) * 2
91
+ score += title_lower.count(word) * 3
92
+
93
+ # Sentence-level matching for better context
94
+ relevant_sentences = []
95
+ for sentence in doc["sentences"]:
96
+ sentence_lower = sentence.lower()
97
+ sentence_score = 0
98
+ for word in query_words:
99
+ if word in sentence_lower:
100
+ sentence_score += 1
101
+
102
+ if sentence_score > 0:
103
+ relevant_sentences.append((sentence_score, sentence))
104
+
105
+ if score > 0:
106
+ # Sort sentences by relevance
107
+ relevant_sentences.sort(key=lambda x: x[0], reverse=True)
108
+ best_sentences = [s[1] for s in relevant_sentences[:2]]
109
+
110
+ results.append((score, {
111
+ **doc,
112
+ "relevant_sentences": best_sentences
113
+ }))
114
+
115
+ # Sort by relevance and return top results
116
+ results.sort(key=lambda x: x[0], reverse=True)
117
+ return [doc for score, doc in results[:max_results]]
118
+
119
+ def get_persona_context(self):
120
+ """Get enhanced persona context for responses"""
121
+ if not self.persona_data:
122
+ return "Egy barátságos AI avatar vagyok."
123
+
124
+ context = f"A nevem {self.persona_data['name']}. "
125
+ if self.persona_data.get('age'):
126
+ context += f"{self.persona_data['age']} éves vagyok. "
127
+ if self.persona_data.get('personality'):
128
+ context += f"A személyiségem: {self.persona_data['personality']}. "
129
+ if self.persona_data.get('conversation_style'):
130
+ context += f"{self.persona_data['conversation_style']} "
131
+ if self.persona_data.get('background'):
132
+ context += f"Háttér: {self.persona_data['background']}. "
133
+
134
+ return context
135
+
136
+ # Initialize global knowledge base
137
+ kb = EternityKnowledgeBase()
138
+
139
+ # Global variables for Llama-4-Scout model
140
+ llama_model = None
141
+ llama_processor = None
142
+ model_loading_status = "Not loaded"
143
+
144
+ def load_llama4_model():
145
+ """Load the Llama-4-Scout model"""
146
+ global llama_model, llama_processor, model_loading_status
147
+
148
+ try:
149
+ model_loading_status = "Loading..."
150
+ print("🚀 Loading Llama-4-Scout-17B-16E-Instruct model...")
151
+
152
+ model_id = "meta-llama/Llama-4-Scout-17B-16E-Instruct"
153
+
154
+ # Check if CUDA is available
155
+ device = "cuda" if torch.cuda.is_available() else "cpu"
156
+ print(f"📱 Using device: {device}")
157
+
158
+ # Load processor
159
+ print("📝 Loading processor...")
160
+ llama_processor = AutoProcessor.from_pretrained(model_id)
161
+
162
+ # Load model with appropriate settings
163
+ print("🧠 Loading model...")
164
+ if device == "cuda":
165
+ llama_model = Llama4ForConditionalGeneration.from_pretrained(
166
+ model_id,
167
+ device_map="auto",
168
+ torch_dtype=torch.bfloat16,
169
+ attn_implementation="flash_attention_2" if torch.cuda.is_available() else "eager",
170
+ load_in_8bit=True, # Use 8-bit quantization to reduce memory usage
171
+ )
172
+ else:
173
+ # CPU fallback with reduced precision
174
+ llama_model = Llama4ForConditionalGeneration.from_pretrained(
175
+ model_id,
176
+ device_map="cpu",
177
+ torch_dtype=torch.float32,
178
+ low_cpu_mem_usage=True,
179
+ )
180
+
181
+ model_loading_status = "✅ Loaded successfully"
182
+ print("✅ Llama-4-Scout model loaded successfully!")
183
+ return True
184
+
185
+ except Exception as e:
186
+ model_loading_status = f"❌ Error: {str(e)}"
187
+ print(f"❌ Error loading Llama-4-Scout model: {e}")
188
+ return False
189
+
190
+ def generate_llama4_response(user_input, persona_context, knowledge_context):
191
+ """Generate response using Llama-4-Scout model"""
192
+ global llama_model, llama_processor
193
+
194
+ if llama_model is None or llama_processor is None:
195
+ return "❌ Llama-4-Scout model not loaded. Please wait for model initialization."
196
+
197
+ try:
198
+ # Construct the prompt in Hungarian
199
+ system_prompt = f"""Te {persona_context}
200
+
201
+ Válaszolj természetesen, személyesen és barátságosan magyarul. Használd fel a rendelkezésre álló információkat, de ne ismételd meg szó szerint. Inkább építsd be természetesen a beszélgetésbe.
202
+
203
+ {knowledge_context}
204
+
205
+ Stílus irányelvek:
206
+ - Beszélgetős, természetes hangnem
207
+ - Személyes élmények és érzések megosztása
208
+ - Rövid, érthető válaszok (max 100-150 szó)
209
+ - Magyar kifejezések és szófordulatok használata
210
+ - Empátia és megértés kifejezése"""
211
+
212
+ # Create messages for the model
213
+ messages = [
214
+ {
215
+ "role": "system",
216
+ "content": system_prompt
217
+ },
218
+ {
219
+ "role": "user",
220
+ "content": user_input
221
+ }
222
+ ]
223
+
224
+ # Apply chat template
225
+ inputs = llama_processor.apply_chat_template(
226
+ messages,
227
+ add_generation_prompt=True,
228
+ tokenize=True,
229
+ return_dict=True,
230
+ return_tensors="pt",
231
+ ).to(llama_model.device)
232
+
233
+ # Generate response
234
+ with torch.no_grad():
235
+ outputs = llama_model.generate(
236
+ **inputs,
237
+ max_new_tokens=150,
238
+ temperature=0.7,
239
+ do_sample=True,
240
+ top_p=0.9,
241
+ pad_token_id=llama_processor.tokenizer.eos_token_id,
242
+ )
243
+
244
+ # Decode response
245
+ response = llama_processor.batch_decode(
246
+ outputs[:, inputs["input_ids"].shape[-1]:],
247
+ skip_special_tokens=True
248
+ )[0]
249
+
250
+ return response.strip()
251
+
252
+ except Exception as e:
253
+ print(f"❌ Error generating Llama-4-Scout response: {e}")
254
+ return f"❌ Hiba a Llama-4-Scout válasz generálása során: {str(e)}"
255
+
256
+ def generate_hungarian_response(user_input, use_llama4=True):
257
+ """Generate enhanced Hungarian response with Llama-4-Scout or fallback"""
258
+ try:
259
+ # Add to conversation history
260
+ kb.conversation_history.append({"user": user_input, "timestamp": datetime.now().isoformat()})
261
+
262
+ # Get persona context
263
+ persona_context = kb.get_persona_context()
264
+
265
+ # Search for relevant knowledge with enhanced results
266
+ relevant_docs = kb.search_knowledge(user_input)
267
+ knowledge_context = ""
268
+ if relevant_docs:
269
+ knowledge_context = "Releváns információk a tudásbázisból:\n"
270
+ for doc in relevant_docs:
271
+ knowledge_context += f"📄 {doc['title']}:\n"
272
+ if doc.get('relevant_sentences'):
273
+ for sentence in doc['relevant_sentences']:
274
+ knowledge_context += f" • {sentence}\n"
275
+ else:
276
+ knowledge_context += f" • {doc['content'][:150]}...\n"
277
+ knowledge_context += "\n"
278
+
279
+ # Try Llama-4-Scout first if available and requested
280
+ if use_llama4 and llama_model is not None:
281
+ try:
282
+ response = generate_llama4_response(user_input, persona_context, knowledge_context)
283
+ if not response.startswith("❌"):
284
+ # Add AI response to history
285
+ kb.conversation_history[-1]["assistant"] = response
286
+ kb.conversation_history[-1]["model"] = "Llama-4-Scout"
287
+ return response
288
+ except Exception as e:
289
+ print(f"Llama-4-Scout failed, falling back to OpenAI: {e}")
290
+
291
+ # Fallback to OpenAI API if available
292
+ if os.getenv('OPENAI_API_KEY'):
293
+ try:
294
+ from openai import OpenAI
295
+ client = OpenAI()
296
+
297
+ # Enhanced system prompt
298
+ system_prompt = f"""Te {persona_context}
299
+
300
+ Válaszolj természetesen, személyesen és barátságosan magyarul. Használd fel a rendelkezésre álló információkat, de ne ismételd meg szó szerint. Inkább építsd be természetesen a beszélgetésbe.
301
+
302
+ {knowledge_context}
303
+
304
+ Stílus irányelvek:
305
+ - Beszélgetős, természetes hangnem
306
+ - Személyes élmények és érzések megosztása
307
+ - Rövid, érthető válaszok (max 100-150 szó)
308
+ - Magyar kifejezések és szófordulatok használata
309
+ - Empátia és megértés kifejezése"""
310
+
311
+ # Include recent conversation context
312
+ messages = [{"role": "system", "content": system_prompt}]
313
+
314
+ # Add recent conversation history
315
+ recent_history = kb.conversation_history[-3:] if len(kb.conversation_history) > 1 else []
316
+ for entry in recent_history[:-1]: # Exclude current message
317
+ messages.append({"role": "user", "content": entry["user"]})
318
+
319
+ messages.append({"role": "user", "content": user_input})
320
+
321
+ response = client.chat.completions.create(
322
+ model="gpt-4o-mini",
323
+ messages=messages,
324
+ max_tokens=150,
325
+ temperature=0.8,
326
+ presence_penalty=0.1
327
+ )
328
+
329
+ ai_response = response.choices[0].message.content
330
+
331
+ # Add AI response to history
332
+ kb.conversation_history[-1]["assistant"] = ai_response
333
+ kb.conversation_history[-1]["model"] = "OpenAI GPT-4o-mini"
334
+
335
+ return ai_response
336
+
337
+ except Exception as e:
338
+ print(f"OpenAI API error: {e}")
339
+
340
+ # Enhanced fallback responses
341
+ return generate_enhanced_hungarian_response(user_input, persona_context, knowledge_context)
342
+
343
+ except Exception as e:
344
+ return f"Hiba történt a válasz generálása során: {str(e)}"
345
+
346
+ def generate_enhanced_hungarian_response(user_input, persona_context, knowledge_context):
347
+ """Enhanced rule-based Hungarian responses"""
348
+ user_lower = user_input.lower()
349
+
350
+ # Greeting responses with persona
351
+ if any(word in user_lower for word in ['szia', 'hello', 'helló', 'jó napot', 'üdv']):
352
+ greetings = [
353
+ f"Szia! {persona_context} Örülök, hogy beszélgethetünk!",
354
+ f"Helló! {persona_context} Miben segíthetek ma?",
355
+ f"Üdvözöllek! {persona_context} Mit szeretnél tudni?"
356
+ ]
357
+ return greetings[hash(user_input) % len(greetings)]
358
+
359
+ # Self-introduction with enhanced persona info
360
+ if any(word in user_lower for word in ['ki vagy', 'bemutatkozz', 'magadról', 'személyiség']):
361
+ intro = f"{persona_context}"
362
+ if knowledge_context:
363
+ intro += f"\n\nTudok mesélni az életemről, tapasztalataimról. Mit érdekel leginkább?"
364
+ return intro
365
+
366
+ # Knowledge-based responses with better context
367
+ if knowledge_context:
368
+ if any(word in user_lower for word in ['mesélj', 'történet', 'emlék', 'múlt']):
369
+ return f"Szívesen mesélek! {knowledge_context}\nVan valami konkrét, amiről többet szeretnél hallani?"
370
+
371
+ if any(word in user_lower for word in ['mit tudsz', 'információ', 'részlet']):
372
+ return f"Íme, amit tudok erről:\n\n{knowledge_context}\nVan még kérdésed ezzel kapcsolatban?"
373
+
374
+ # Emotional responses
375
+ if any(word in user_lower for word in ['szomorú', 'rossz', 'nehéz', 'probléma']):
376
+ return f"Sajnálom, hogy nehéz időszakon mész át. {persona_context} Ha szeretnél, szívesen meghallgatlak."
377
+
378
+ if any(word in user_lower for word in ['örülök', 'jó', 'szuper', 'remek']):
379
+ return f"Nagyszerű! Örülök, hogy jól érzed magad. {persona_context} Mesélj többet erről!"
380
+
381
+ # Default enhanced response
382
+ responses = [
383
+ f"Érdekes kérdés! {persona_context} Mit gondolsz erről te?",
384
+ f"Hmm, ezen gondolkodnom kell. {persona_context} Tudnál többet mesélni erről?",
385
+ f"Ez fontos téma. {persona_context} Szívesen beszélgetünk erről részletesebben."
386
+ ]
387
+
388
+ response = responses[hash(user_input) % len(responses)]
389
+ # Add model info to history
390
+ if kb.conversation_history:
391
+ kb.conversation_history[-1]["assistant"] = response
392
+ kb.conversation_history[-1]["model"] = "Rule-based fallback"
393
+
394
+ return response
395
+
396
+ def create_enhanced_avatar_display(text_response, persona_name="Avatar"):
397
+ """Create enhanced avatar display with model information"""
398
+ # Determine which model was used
399
+ model_used = "Unknown"
400
+ if kb.conversation_history:
401
+ model_used = kb.conversation_history[-1].get("model", "Unknown")
402
+
403
+ # Simulate different avatar expressions based on response content
404
+ if any(word in text_response.lower() for word in ['örülök', 'szuper', 'nagyszerű', 'remek']):
405
+ emotion = "😊 Boldog"
406
+ bg_color = "#e8f5e8"
407
+ border_color = "#4caf50"
408
+ elif any(word in text_response.lower() for word in ['sajnálom', 'nehéz', 'szomorú']):
409
+ emotion = "😔 Együttérző"
410
+ bg_color = "#fff3e0"
411
+ border_color = "#ff9800"
412
+ elif any(word in text_response.lower() for word in ['érdekes', 'gondolkodnom', 'hmm']):
413
+ emotion = "🤔 Gondolkodó"
414
+ bg_color = "#e3f2fd"
415
+ border_color = "#2196f3"
416
+ else:
417
+ emotion = "😊 Barátságos"
418
+ bg_color = "#f3e5f5"
419
+ border_color = "#9c27b0"
420
+
421
+ # Model-specific styling
422
+ if "Llama-4-Scout" in model_used:
423
+ model_icon = "🦙"
424
+ model_color = "#ff6b35"
425
+ elif "OpenAI" in model_used:
426
+ model_icon = "🤖"
427
+ model_color = "#00a67e"
428
+ else:
429
+ model_icon = "⚙️"
430
+ model_color = "#666"
431
+
432
+ avatar_html = f"""
433
+ <div style="text-align: center; padding: 25px; border: 3px solid {border_color}; border-radius: 15px; background: {bg_color}; margin: 10px;">
434
+ <div style="display: flex; align-items: center; justify-content: center; margin-bottom: 15px;">
435
+ <div style="font-size: 48px; margin-right: 15px;">🎭</div>
436
+ <div>
437
+ <h3 style="margin: 0; color: #333;">{persona_name}</h3>
438
+ <p style="margin: 5px 0; color: #666; font-size: 14px;">Hangulat: {emotion}</p>
439
+ <p style="margin: 5px 0; color: {model_color}; font-size: 12px; font-weight: bold;">
440
+ {model_icon} {model_used}
441
+ </p>
442
+ </div>
443
+ </div>
444
+
445
+ <div style="background: white; padding: 20px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
446
+ <p style="font-size: 16px; color: #333; line-height: 1.6; margin: 0; font-style: italic;">
447
+ "{text_response}"
448
+ </p>
449
+ </div>
450
+
451
+ <div style="margin-top: 15px; padding: 10px; background: rgba(255,255,255,0.7); border-radius: 8px;">
452
+ <p style="color: #666; font-size: 12px; margin: 0;">
453
+ 🦙 <strong>Llama-4-Scout Integration:</strong> {'Aktív' if 'Llama-4-Scout' in model_used else 'Fallback módban'}
454
+ </p>
455
+ <p style="color: #666; font-size: 12px; margin: 5px 0 0 0;">
456
+ 🎬 Következő fázis: TTS + Lip-sync + Valódi avatar animáció
457
+ </p>
458
+ </div>
459
+ </div>
460
+ """
461
+ return avatar_html
462
+
463
+ def process_enhanced_document_upload(file):
464
+ """Enhanced document processing with better analysis"""
465
+ if file is None:
466
+ return "❌ Nincs feltöltött fájl."
467
+
468
+ try:
469
+ # Try different encodings
470
+ encodings = ['utf-8', 'latin-1', 'cp1252']
471
+ content = None
472
+ used_encoding = None
473
+
474
+ for encoding in encodings:
475
+ try:
476
+ with open(file.name, 'r', encoding=encoding) as f:
477
+ content = f.read()
478
+ used_encoding = encoding
479
+ break
480
+ except UnicodeDecodeError:
481
+ continue
482
+
483
+ if content is None:
484
+ return "❌ Nem sikerült dekódolni a fájlt. Próbálja UTF-8 kódolással."
485
+
486
+ # Extract filename as title
487
+ title = Path(file.name).stem
488
+
489
+ # Add to knowledge base
490
+ doc_id = kb.add_document(title, content, "uploaded_document")
491
+
492
+ # Generate summary statistics
493
+ word_count = len(content.split())
494
+ sentence_count = len([s for s in content.split('.') if s.strip()])
495
+ char_count = len(content)
496
+
497
+ return f"""✅ **Dokumentum sikeresen feldolgozva!**
498
+
499
+ 📄 **Fájl:** {title}
500
+ 🆔 **Azonosító:** {doc_id}
501
+ 📊 **Statisztikák:**
502
+ • Szavak száma: {word_count}
503
+ • Mondatok száma: {sentence_count}
504
+ • Karakterek száma: {char_count}
505
+ • Kódolás: {used_encoding}
506
+
507
+ 💡 **Tipp:** Most már kérdezhet a dokumentum tartalmáról a beszélgetés során!"""
508
+
509
+ except Exception as e:
510
+ return f"❌ **Hiba a dokumentum feldolgozása során:** {str(e)}"
511
+
512
+ def create_enhanced_persona(name, age, personality, background):
513
+ """Enhanced persona creation with validation"""
514
+ try:
515
+ # Validate inputs
516
+ if not name.strip():
517
+ return "❌ A név megadása kötelező!"
518
+
519
+ if age and not age.isdigit():
520
+ return "❌ A kor csak szám lehet!"
521
+
522
+ if not personality.strip():
523
+ return "❌ A személyiség leírása kötelező!"
524
+
525
+ kb.add_persona_info(name.strip(), age.strip(), personality.strip(), background.strip())
526
+
527
+ return f"""✅ **Persona sikeresen létrehozva!**
528
+
529
+ 👤 **Név:** {name}
530
+ 🎂 **Kor:** {age if age else 'Nem megadott'}
531
+ 🎭 **Személyiség:** {personality}
532
+ 📖 **Háttér:** {background if background else 'Nem megadott'}
533
+
534
+ 🎯 **Beszélgetési stílus:** {kb.persona_data.get('conversation_style', 'Alapértelmezett')}
535
+
536
+ 💬 **Most már beszélgethet az avatarral a beszélgetés tabon!**"""
537
+
538
+ except Exception as e:
539
+ return f"❌ **Hiba a persona létrehozása során:** {str(e)}"
540
+
541
+ def get_enhanced_knowledge_summary():
542
+ """Enhanced knowledge base summary with model status"""
543
+ doc_count = len(kb.knowledge_data)
544
+ persona_info = "✅ Beállítva" if kb.persona_data else "❌ Nincs beállítva"
545
+ conversation_count = len(kb.conversation_history)
546
+
547
+ summary = f"""📊 **Eternity Tudásbázis Állapota**
548
+
549
+ 👤 **Persona:** {persona_info}
550
+ 📚 **Dokumentumok száma:** {doc_count}
551
+ 💬 **Beszélgetések száma:** {conversation_count}
552
+
553
+ """
554
+
555
+ if kb.persona_data:
556
+ summary += f"""🎭 **Aktív Persona:**
557
+ • Név: {kb.persona_data['name']}
558
+ • Kor: {kb.persona_data.get('age', 'N/A')}
559
+ • Személyiség: {kb.persona_data['personality'][:50]}...
560
+
561
+ """
562
+
563
+ if kb.knowledge_data:
564
+ summary += "📄 **Feltöltött Dokumentumok:**\n"
565
+ for i, (doc_id, doc) in enumerate(list(kb.knowledge_data.items())[:5]):
566
+ summary += f" {i+1}. **{doc['title']}** ({doc['word_count']} szó, {doc['type']})\n"
567
+
568
+ if doc_count > 5:
569
+ summary += f" ... és még {doc_count - 5} dokumentum\n"
570
+
571
+ summary += "\n"
572
+
573
+ if kb.conversation_history:
574
+ summary += f"💭 **Legutóbbi beszélgetések:**\n"
575
+ for i, conv in enumerate(kb.conversation_history[-3:]):
576
+ model_info = conv.get('model', 'Unknown')
577
+ summary += f" {i+1}. \"{conv['user'][:40]}...\" ({model_info})\n"
578
+
579
+ summary += f"""
580
+ 🔧 **AI Modellek állapota:**
581
+ • Llama-4-Scout: {model_loading_status}
582
+ • OpenAI API: {'✅ Aktív' if os.getenv('OPENAI_API_KEY') else '❌ Nincs beállítva'}
583
+ • GPU Support: {'✅ CUDA elérhető' if torch.cuda.is_available() else '❌ Csak CPU'}
584
+ • Tudásbázis méret: {sum(doc['word_count'] for doc in kb.knowledge_data.values())} szó összesen
585
+ """
586
+
587
+ return summary
588
+
589
+ def initialize_models():
590
+ """Initialize AI models on startup"""
591
+ print("🚀 Initializing Eternity AI models...")
592
+
593
+ # Try to load Llama-4-Scout model
594
+ success = load_llama4_model()
595
+
596
+ if success:
597
+ print("✅ Llama-4-Scout model ready!")
598
+ else:
599
+ print("⚠️ Llama-4-Scout model failed to load, using fallback models")
600
+
601
+ return get_enhanced_knowledge_summary()
602
+
603
+ # Create the enhanced Gradio interface
604
+ def create_enhanced_eternity_interface():
605
+ """Create the enhanced Eternity POC interface with Llama-4-Scout"""
606
+
607
+ with gr.Blocks(title="Eternity POC - Magyar Avatar", theme=gr.themes.Soft()) as demo:
608
+ gr.Markdown("""
609
+ # 🎭 Eternity - Magyar Interaktív Avatar POC v3.0
610
+
611
+ **Llama-4-Scout integrációval fejlesztett Proof-of-Concept**
612
+
613
+ 🚀 **Új funkciók ebben a verzióban:**
614
+ - 🦙 **Llama-4-Scout-17B-16E-Instruct** - Meta legújabb multimodális modellje
615
+ - 🧠 **Fejlett tudásbázis keresés** - Jobb relevanciával és kontextussal
616
+ - 🎭 **Dinamikus avatar érzelmek** - Válasz alapú hangulat szimuláció
617
+ - 💬 **Beszélgetési memória** - Korábbi üzenetek figyelembevétele
618
+ - 📊 **Részletes statisztikák** - Dokumentum és beszélgetés elemzés
619
+ - 🎨 **Javított vizuális megjelenés** - Professzionális avatar display
620
+
621
+ **Használat:** Hozzon létre personát → Töltsön fel dokumentumokat → Beszélgessen!
622
+ """)
623
+
624
+ with gr.Tab("💬 Beszélgetés"):
625
+ with gr.Row():
626
+ with gr.Column(scale=2):
627
+ user_input = gr.Textbox(
628
+ label="💭 Az Ön üzenete",
629
+ placeholder="Írja ide az üzenetét magyarul... (pl. 'Szia! Mesélj magadról!')",
630
+ lines=3
631
+ )
632
+ with gr.Row():
633
+ chat_btn = gr.Button("📤 Küldés", variant="primary", size="lg")
634
+ clear_btn = gr.Button("🗑️ Törlés", variant="secondary")
635
+
636
+ with gr.Column(scale=3):
637
+ avatar_response = gr.HTML(
638
+ label="🎭 Avatar Válasz",
639
+ value="""<div style='text-align: center; padding: 50px; color: #666; border: 2px dashed #ccc; border-radius: 10px;'>
640
+ <h3>🎭 Avatar várakozik...</h3>
641
+ <p>Írjon egy üzenetet és kattintson a Küldés gombra!</p>
642
+ <p style='font-size: 12px; color: #999;'>🦙 Llama-4-Scout model betöltés alatt...</p>
643
+ </div>"""
644
+ )
645
+
646
+ with gr.Tab("👤 Persona Beállítás"):
647
+ with gr.Column():
648
+ gr.Markdown("### 🎭 Hozza létre az avatar személyiségét")
649
+ gr.Markdown("*Minél részletesebb információkat ad meg, annál személyesebb lesz a beszélgetés.*")
650
+
651
+ with gr.Row():
652
+ persona_name = gr.Textbox(
653
+ label="👤 Név",
654
+ placeholder="pl. Kovács Anna",
655
+ info="Az avatar neve (kötelező)"
656
+ )
657
+ persona_age = gr.Textbox(
658
+ label="🎂 Kor",
659
+ placeholder="pl. 30",
660
+ info="Életkor számban (opcionális)"
661
+ )
662
+
663
+ persona_personality = gr.Textbox(
664
+ label="🎭 Személyiség",
665
+ placeholder="pl. Barátságos, segítőkész, humoros, türelmes, energikus...",
666
+ lines=2,
667
+ info="Személyiségjegyek vesszővel elválasztva (kötelező)"
668
+ )
669
+
670
+ persona_background = gr.Textbox(
671
+ label="📖 Háttér/Történet",
672
+ placeholder="pl. Tanár vagyok, szeretem a könyveket és az utazást. Budapesten élek...",
673
+ lines=4,
674
+ info="Életrajz, hobbik, érdeklődési körök (opcionális, de ajánlott)"
675
+ )
676
+
677
+ create_persona_btn = gr.Button("✨ Persona Létrehozása", variant="primary", size="lg")
678
+ persona_status = gr.Textbox(label="📋 Állapot", interactive=False, lines=8)
679
+
680
+ with gr.Tab("📚 Dokumentum Feltöltés"):
681
+ with gr.Column():
682
+ gr.Markdown("### 📄 Töltsön fel személyes dokumentumokat")
683
+ gr.Markdown("""
684
+ **Támogatott fájltípusok:** `.txt`, `.md`, `.json`
685
+ **Kódolás:** UTF-8 ajánlott (automatikus detektálás)
686
+ **Tartalom:** Életrajz, naplók, blog bejegyzések, emlékek, stb.
687
+ """)
688
+
689
+ file_upload = gr.File(
690
+ label="📁 Dokumentum kiválasztása",
691
+ file_types=[".txt", ".md", ".json"],
692
+ file_count="single"
693
+ )
694
+
695
+ upload_btn = gr.Button("⬆️ Dokumentum Feldolgozása", variant="primary", size="lg")
696
+ upload_status = gr.Textbox(label="📊 Feltöltés Eredménye", interactive=False, lines=10)
697
+
698
+ with gr.Tab("📊 Tudásbázis & AI Modellek"):
699
+ with gr.Column():
700
+ gr.Markdown("### 📈 Tudásbázis áttekintése és AI model státusz")
701
+
702
+ refresh_kb_btn = gr.Button("🔄 Frissítés", variant="secondary")
703
+ kb_summary = gr.Textbox(
704
+ label="📋 Részletes Összefoglaló",
705
+ lines=20,
706
+ interactive=False
707
+ )
708
+
709
+ with gr.Tab("ℹ️ Információ"):
710
+ gr.Markdown("""
711
+ ## 🎭 Eternity POC v3.0 - Llama-4-Scout Integration
712
+
713
+ ### ✅ Implementált Funkciók:
714
+ - **🦙 Llama-4-Scout-17B-16E-Instruct** - Meta legújabb 17B paraméteres MoE modellje
715
+ - **Magyar nyelvű beszélgetés** - Natív magyar támogatás Llama-4-Scout-tal
716
+ - **Fejlett persona rendszer** - Részletes személyiség és beszélgetési stílus
717
+ - **Intelligens tudásbázis** - Dokumentum feldolgozás és kontextuális keresés
718
+ - **Beszélgetési memória** - Korábbi üzenetek figyelembevétele
719
+ - **Dinamikus avatar érzelmek** - Válasz alapú hangulat szimuláció
720
+ - **Model fallback rendszer** - OpenAI API és szabály alapú backup
721
+
722
+ ### 🦙 Llama-4-Scout Jellemzők:
723
+ - **Paraméterek:** 17B aktív, 109B teljes (16 expert MoE)
724
+ - **Multimodális:** Szöveg és kép megértés
725
+ - **Kontextus:** 10M token (ultra-hosszú memória)
726
+ - **Nyelvek:** 12 nyelv, beleértve a magyart
727
+ - **Architektúra:** Mixture-of-Experts (MoE) early fusion
728
+
729
+ ### 🛠️ Használt Technológiák:
730
+ - **AI Model:** Meta Llama-4-Scout-17B-16E-Instruct
731
+ - **Fallback:** OpenAI GPT-4o-mini API
732
+ - **Frontend:** Gradio 5.x (Python web UI framework)
733
+ - **Backend:** Python 3.11+ (PyTorch, Transformers)
734
+ - **Nyelv:** Magyar (natív támogatás)
735
+ - **Adattárolás:** Memória alapú (POC szinten)
736
+
737
+ ### 📈 Teljesítmény Jellemzők:
738
+ - **Válaszidő:** 2-5 másodperc (GPU függő)
739
+ - **Memóriahasználat:** 8-16GB GPU RAM (quantized)
740
+ - **Dokumentum méret:** Max 10MB / fájl
741
+ - **Tudásbázis kapacitás:** Korlátlan (memória függő)
742
+ - **Beszélgetési memória:** Utolsó 10 üzenet
743
+
744
+ ### 🚀 Következő Fejlesztési Lépések:
745
+ 1. **Multimodális képességek** - Kép input és megértés
746
+ 2. **Magyar TTS integráció** - Hang kimenet Llama-4-Scout válaszokhoz
747
+ 3. **Avatar videó generálás** - Valódi avatar animáció
748
+ 4. **Perzisztens adattárolás** - Adatbázis integráció
749
+ 5. **Teljesítmény optimalizálás** - GPU cluster és parallel processing
750
+
751
+ ### ⚠️ POC Korlátozások:
752
+ - **GPU követelmények** - 8GB+ VRAM ajánlott Llama-4-Scout-hoz
753
+ - **Nincs adatperzisztencia** - Újraindításkor elvesznek az adatok
754
+ - **Egyszerű keresés** - Nincs szemantikus embedding
755
+ - **Nincs felhasználói hitelesítés** - Nyilvános hozzáférés
756
+ - **Minimális hibakezelés** - Fejlesztési célokra optimalizált
757
+
758
+ ---
759
+
760
+ **Verzió:** POC 3.0 - Llama-4-Scout Integration
761
+ **Utolsó frissítés:** 2025. október
762
+ **Státusz:** Aktív fejlesztés
763
+ **Licenc:** Apache 2.0 + Llama 4 Community License
764
+ """)
765
+
766
+ # Enhanced event handlers
767
+ def handle_chat(user_msg):
768
+ if not user_msg.strip():
769
+ return """<div style='text-align: center; padding: 30px; color: #ff6b6b; border: 2px dashed #ff6b6b; border-radius: 10px;'>
770
+ <h3>⚠️ Üres üzenet</h3>
771
+ <p>Kérem, írjon be egy üzenetet a beszélgetéshez!</p>
772
+ </div>"""
773
+
774
+ response_text = generate_hungarian_response(user_msg, use_llama4=True)
775
+ persona_name = kb.persona_data.get('name', 'Avatar') if kb.persona_data else 'Avatar'
776
+ return create_enhanced_avatar_display(response_text, persona_name)
777
+
778
+ def clear_input():
779
+ return ""
780
+
781
+ # Event bindings
782
+ chat_btn.click(
783
+ fn=handle_chat,
784
+ inputs=[user_input],
785
+ outputs=[avatar_response]
786
+ )
787
+
788
+ clear_btn.click(
789
+ fn=clear_input,
790
+ outputs=[user_input]
791
+ )
792
+
793
+ create_persona_btn.click(
794
+ fn=create_enhanced_persona,
795
+ inputs=[persona_name, persona_age, persona_personality, persona_background],
796
+ outputs=[persona_status]
797
+ )
798
+
799
+ upload_btn.click(
800
+ fn=process_enhanced_document_upload,
801
+ inputs=[file_upload],
802
+ outputs=[upload_status]
803
+ )
804
+
805
+ refresh_kb_btn.click(
806
+ fn=get_enhanced_knowledge_summary,
807
+ outputs=[kb_summary]
808
+ )
809
+
810
+ # Initialize models and knowledge base summary on load
811
+ demo.load(
812
+ fn=initialize_models,
813
+ outputs=[kb_summary]
814
+ )
815
+
816
+ return demo
817
+
818
+ if __name__ == "__main__":
819
+ print("🎭 Eternity POC v3.0 - Llama-4-Scout Integration indítása...")
820
+ print("📚 Magyar interaktív avatar rendszer - Llama-4-Scout verzió")
821
+
822
+ # Check system requirements
823
+ print(f"🖥️ GPU Support: {'✅ CUDA elérhető' if torch.cuda.is_available() else '❌ Csak CPU'}")
824
+ if torch.cuda.is_available():
825
+ print(f"🎮 GPU: {torch.cuda.get_device_name(0)}")
826
+ print(f"💾 GPU Memory: {torch.cuda.get_device_properties(0).total_memory // 1024**3}GB")
827
+
828
+ # Check for OpenAI API key
829
+ if os.getenv('OPENAI_API_KEY'):
830
+ print("✅ OpenAI API kulcs észlelve - fallback támogatás engedélyezve")
831
+ else:
832
+ print("⚠️ OpenAI API kulcs nem található - csak Llama-4-Scout és szabály alapú válaszok")
833
+ print(" 💡 Tipp: Állítsa be az OPENAI_API_KEY környezeti változót a fallback támogatásért")
834
+
835
+ # Create and launch the enhanced interface
836
+ demo = create_enhanced_eternity_interface()
837
+
838
+ print("🚀 Eternity POC v3.0 - Llama-4-Scout Integration elindítva!")
839
+ print("🌐 Elérhető: http://localhost:7860")
840
+ print("📖 Használati útmutató: README.md")
841
+ print("🦙 Llama-4-Scout model betöltés a háttérben...")
842
+
843
+ demo.launch(
844
+ server_name="0.0.0.0",
845
+ server_port=7860,
846
+ share=False,
847
+ show_error=True
848
+ )
requirements.txt CHANGED
@@ -1,3 +1,4 @@
1
  gradio>=4.0.0
2
  openai>=1.0.0
3
  python-dotenv>=1.0.0
 
 
1
  gradio>=4.0.0
2
  openai>=1.0.0
3
  python-dotenv>=1.0.0
4
+ requests>=2.31.0
requirements_api.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ gradio>=4.0.0
2
+ openai>=1.0.0
3
+ python-dotenv>=1.0.0
4
+ requests>=2.31.0
requirements_llama4.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ gradio>=4.0.0
2
+ openai>=1.0.0
3
+ python-dotenv>=1.0.0
4
+ torch>=2.0.0
5
+ transformers>=4.51.0
6
+ accelerate>=0.20.0
7
+ bitsandbytes>=0.41.0
8
+ flash-attn>=2.0.0
9
+ safetensors>=0.3.0
10
+ sentencepiece>=0.1.99
11
+ protobuf>=3.20.0