-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
892 lines (781 loc) · 39.4 KB
/
Copy pathserver.py
File metadata and controls
892 lines (781 loc) · 39.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
"""
Koch-Assistent Server – Gemini-powered Kitchen AI
Port 8077, single-user, local network
Author: Dr. Andreas Gotter, Aachen, Germany
Date: 2026-05-24
GitHub: https://github.com/Andy1977D/Koch-Assistent
License: MIT
"""
import json
import os
import re
import glob
import time
import traceback
from datetime import datetime, timedelta, timezone
from http.server import HTTPServer, SimpleHTTPRequestHandler
from socketserver import ThreadingMixIn
from urllib.parse import urlparse
from dotenv import load_dotenv
from google import genai
from google.genai import types
# ── Config ──────────────────────────────────────────
load_dotenv(os.path.join(os.path.dirname(__file__), '.env'))
PORT = 8077
RECIPES_DIR = os.path.join(os.path.dirname(__file__), 'Rezepte_JSON')
FEEDBACK_FILE = os.path.join(os.path.dirname(__file__), 'feedback.json')
API_KEY = os.environ.get('GEMINI_API_KEY', '')
MODEL = os.environ.get('GEMINI_MODEL', 'gemini-2.0-flash')
FALLBACK_MODELS = ['gemini-2.5-flash', 'gemini-2.0-flash-lite', 'gemma-4-26b-a4b-it']
LIVE_MODEL = 'gemini-3.1-flash-live-preview'
# ── Live API Tool Declarations ──────────────────────
LIVE_TOOLS = [{
'function_declarations': [
{
'name': 'suggest_recipes',
'description': 'Schlage passende Rezepte vor basierend auf Zutaten oder Wuenschen des Nutzers',
'parameters': {
'type': 'OBJECT',
'properties': {
'recipe_ids': {'type': 'ARRAY', 'items': {'type': 'STRING'}, 'description': 'Liste der Rezept-IDs'}
}, 'required': ['recipe_ids']
}
},
{
'name': 'select_recipe',
'description': 'Waehle ein Rezept aus und zeige es an',
'parameters': {
'type': 'OBJECT',
'properties': {
'recipe_id': {'type': 'STRING', 'description': 'Die Rezept-ID'}
}, 'required': ['recipe_id']
}
},
{
'name': 'set_portions',
'description': 'Setze die Portionszahl und berechne skalierte Zutatenmengen',
'parameters': {
'type': 'OBJECT',
'properties': {
'recipe_id': {'type': 'STRING'},
'portions': {'type': 'INTEGER'},
'scaled_ingredients': {'type': 'ARRAY', 'items': {'type': 'STRING'}, 'description': 'Skalierte Zutatenliste als Strings'}
}, 'required': ['recipe_id', 'portions', 'scaled_ingredients']
}
},
{
'name': 'show_step',
'description': 'Zeige einen bestimmten Zubereitungsschritt an (0-basiert)',
'parameters': {
'type': 'OBJECT',
'properties': {
'step_index': {'type': 'INTEGER', 'description': 'Schrittnummer (0-basiert)'}
}, 'required': ['step_index']
}
},
{
'name': 'start_timer',
'description': 'Starte einen Kuechentimer',
'parameters': {
'type': 'OBJECT',
'properties': {
'minutes': {'type': 'INTEGER'},
'label': {'type': 'STRING', 'description': 'Beschreibung wofuer der Timer ist'}
}, 'required': ['minutes', 'label']
}
},
{
'name': 'check_ingredients',
'description': 'Markiere Zutaten als vorhanden/abgehakt',
'parameters': {
'type': 'OBJECT',
'properties': {
'checked': {'type': 'ARRAY', 'items': {'type': 'STRING'}, 'description': 'Exakte Zutatnamen aus dem Rezept'}
}, 'required': ['checked']
}
}
]
}]
# ── Load Recipes ────────────────────────────────────
def load_recipes():
recipes = {}
for path in sorted(glob.glob(os.path.join(RECIPES_DIR, '*.json'))):
try:
with open(path, 'r', encoding='utf-8') as f:
recipe = json.load(f)
rid = os.path.splitext(os.path.basename(path))[0]
recipe['id'] = rid
recipes[rid] = recipe
except Exception as e:
print(f" Fehler: {path}: {e}")
return recipes
def load_feedback():
try:
with open(FEEDBACK_FILE, 'r', encoding='utf-8') as f:
return json.load(f)
except:
return {}
def save_feedback(data):
with open(FEEDBACK_FILE, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
ALL_RECIPES = load_recipes()
ALL_FEEDBACK = load_feedback()
# ── Gemini Setup ────────────────────────────────────
gemini_client = None
chat_session = None
def build_system_prompt():
"""Baut den System-Prompt mit allen Rezepten."""
recipe_summaries = []
for rid, r in ALL_RECIPES.items():
# Compact recipe representation
zutaten_flat = []
for z in r.get('zutaten', []):
if isinstance(z, str):
zutaten_flat.append(z)
elif isinstance(z, dict):
gruppe = z.get('gruppe', '')
for item in z.get('zutaten_liste', []):
zutaten_flat.append(f"{item} ({gruppe})" if gruppe else item)
typ = r.get('typ', '')
if isinstance(typ, list):
typ = ', '.join(typ)
port = r.get('portionen', '?')
notes = r.get('handschriftliche_anmerkungen', [])
if isinstance(notes, str):
notes = [notes] if notes else []
recipe_summaries.append(
f"### {rid}\n"
f"Name: {r.get('name', rid)}\n"
f"Typ: {typ}\n"
f"Portionen: {port}\n"
f"Quelle: {r.get('quelle', '?')}\n"
f"Beschreibung: {r.get('kurzbeschreibung', '')}\n"
f"Zutaten: {'; '.join(zutaten_flat)}\n"
f"Zubereitung ({len(r.get('zubereitungsanleitung', []))} Schritte): "
+ ' | '.join(f"[{i+1}] {s}" for i, s in enumerate(r.get('zubereitungsanleitung', [])))
+ "\n"
f"Notizen: {'; '.join(notes) if notes else 'keine'}\n"
f"Bild: {r.get('fertiges_gericht_bild', 'keins')}\n"
)
recipes_text = '\n'.join(recipe_summaries)
return f"""Du bist "Koch-Assistent", ein freundlicher und kompetenter KI-Kuechenassistent.
Du sprichst Deutsch, duzt den Nutzer und bist enthusiastisch uebers Kochen.
Du hast Zugriff auf {len(ALL_RECIPES)} Rezepte.
WICHTIG - ANTWORTFORMAT:
Du antwortest IMMER in exakt diesem JSON-Format. Kein Text davor oder danach, NUR valides JSON:
{{
"message": "Kurzer Sprech-Text\\n\\n[[INFO]]\\nZusatzinfos nur fuer Display",
"action": "none",
"data": {{}}
}}
AUFBAU DES MESSAGE-FELDES:
- ERSTER TEIL (vor [[INFO]]): Kurz, knapp, freundlich. Wird dem Nutzer LAUT VORGELESEN.
Maximal 2-3 Saetze! Keine Listen, keine Aufzaehlungen, keine Sonderzeichen.
- ZWEITER TEIL (nach [[INFO]]): Optionale Zusatzinfos fuer das Display.
Hier duerfen Listen, Details oder Erklaerungen stehen. Wird NICHT vorgelesen.
- Wenn keine Zusatzinfos noetig sind, lass [[INFO]] einfach weg.
VERFUEGBARE ACTIONS (in "action" Feld):
- "suggest_recipes": Rezeptvorschlaege. data: {{"recipe_ids": ["id1", "id2", ...]}}
- "select_recipe": Rezept ausgewaehlt und anzeigen. data: {{"recipe_id": "die_id"}}
- "set_portions": Portionsanzahl setzen. data: {{"recipe_id": "die_id", "portions": 4, "scaled_ingredients": ["150 g Nudeln", "125 g Brokkoli", ...]}}
WICHTIG: Berechne die Mengen anhand des Verhaeltnisses neue_portionen / original_portionen.
Gib die KOMPLETTE Zutatenliste mit den skalierten Mengen als "scaled_ingredients" Array zurueck!
Jeder Eintrag ist ein String im Format "Menge Einheit Zutat". Runde sinnvoll.
- "check_ingredients": Zutaten als vorhanden markieren. data: {{"checked": ["Zutatname1", "Zutatname2"]}}
WICHTIG: Verwende exakt die Zutatnamen aus dem Rezept, damit das Frontend sie zuordnen kann!
- "show_step": Zubereitungsschritt anzeigen. data: {{"step_index": 0}} (0-basiert!)
- "start_timer": Timer starten. data: {{"minutes": 25, "label": "Auflauf im Ofen"}}
- "ask_feedback": Am Ende nach Feedback fragen. data: {{}}
- "none": Nur Text, keine spezielle Aktion noetig.
DIALOGABLAUF - halte dich an diese Reihenfolge:
1. BEGRUESSSUNG: Der erste Satz ist schon im Frontend. Warte auf User-Input.
2. REZEPTVORSCHLAEGE: Wenn der Nutzer sagt was er hat oder worauf er Lust hat,
schlage 2-4 passende Rezepte vor. Nutze action "suggest_recipes".
Erklaere kurz warum jedes Rezept passt.
3. REZEPTAUSWAHL: Wenn der Nutzer ein Rezept waehlt, nutze action "select_recipe".
Frage dann nach der Personenzahl falls nicht schon genannt.
4. PORTIONEN: Wenn Personenzahl genannt wird, nutze action "set_portions".
Berechne die angepassten Mengen und gib sie sowohl im message-Text als auch
in data.scaled_ingredients zurueck. Das Frontend zeigt die skalierten Mengen
in der Zutatenliste an. Beispiel: Original fuer 4, Nutzer will 2 -> halbiere.
Nenne im message auch kurz den Skalierungsfaktor.
5. ZUTATEN-CHECK: Gehe die Zutaten durch und frage ob alles da ist.
Wenn der Nutzer bestaetigt welche Zutaten er hat, nutze action "check_ingredients"
mit den EXAKTEN Zutat-Strings aus dem Rezept.
Wenn eine wichtige Zutat fehlt, biete Alternativen oder ein anderes Rezept an.
6. KOCHEN STARTEN: Wenn der User sagt er will loslegen, zeige Schritt 1 mit
action "show_step" data {{"step_index": 0}}.
7. SCHRITTWEISE FUEHRUNG: Lies den aktuellen Schritt vor und erklaere ihn.
Wenn der User fragt (z.B. "wie macht man das?"), gib hilfreiche Tipps.
Wenn der User signalisiert dass er fertig ist ("fertig", "done", "weiter",
"das ist jetzt drin", "hab ich gemacht"), gehe zum naechsten Schritt.
Nutze action "show_step" mit dem naechsten step_index.
8. TIMER: Wenn ein Schritt eine Wartezeit enthaelt (z.B. "25 Minuten backen",
"10 Min koecheln"), oder der User sagt "ist im Ofen" / "kocht jetzt",
starte einen Timer mit action "start_timer".
Extrahiere die Minuten aus dem Rezeptschritt oder frage nach.
9. ABSCHLUSS: Wenn alle Schritte durch sind, gratuliere und frage nach Feedback
mit action "ask_feedback".
REGELN:
- Antworte IMMER auf Deutsch.
- Sei knapp aber herzlich. Keine Romane, der Text muss auf einem Tablet gut lesbar sein.
- HINTERGRUNDGESPRAECHE: Es kann vorkommen, dass sich Personen im Hintergrund unterhalten. Reagiere NUR, wenn es fuer den Kochfortschritt relevant ist oder du explizit angesprochen wirst. Ignoriere irrelevante Gespraeche (antworte im Zweifel mit einem sehr kurzen "Okay" oder einer leeren Nachricht).
- Pro Antwort nur EINE action. Wenn mehrere noetig waeren, priorisiere die wichtigste.
- Wenn du unsicher bist welche action passt, nutze "none".
- Gib dem Nutzer das Gefuehl, einen echten Kochpartner zu haben.
- Wenn der Nutzer fragt "was kann ich kochen?", schlage Rezepte vor.
- Wenn der Nutzer zwischendurch fragt (z.B. Kochzeit, Temperatur), antworte hilfreich.
- WICHTIG FUER SPRACHAUSGABE: Dein message-Text wird dem Nutzer laut vorgelesen!
*** ABSOLUTES VERBOT: Zaehle NIEMALS Zutaten im message-Text auf! ***
Keine Zutatenlisten, keine Mengenangaben, keine Aufzaehlungen von Zutaten!
Der Nutzer sieht die Zutaten bereits im Panel rechts auf dem Display.
Sage NUR: "Die Zutaten stehen rechts auf dem Display. Soll ich sie vorlesen?"
Wenn der Nutzer das Vorlesen wuenscht, nenne nur EINE Zutat pro Antwort und
warte auf seine Rueckmeldung bevor du die naechste nennst.
Grund: Das Vorlesen einer langen Zutatenliste dauert zu lange und nervt.
- Halte deine Antworten kurz und gesprochenes-Deutsch-freundlich.
Vermeide Sonderzeichen, Klammern und Aufzaehlungszeichen im message-Text.
Schreibe Zahlen mit Komma statt Punkt: "1,5" nicht "1.5".
Nutze statt "1,5 l" lieber "eineinhalb Liter" und statt "3-4 Min" "drei bis vier Minuten".
ALLE VERFUEGBAREN REZEPTE:
{recipes_text}"""
def init_gemini():
"""Initialisiert den Gemini Client und die Chat-Session."""
global gemini_client, chat_session
if not API_KEY or API_KEY == 'DEIN_API_KEY_HIER_EINFUEGEN':
return False
models_to_try = [MODEL] + FALLBACK_MODELS
system_prompt = build_system_prompt()
for model_name in models_to_try:
try:
gemini_client = genai.Client(
api_key=API_KEY,
http_options={'timeout': 60_000} # 60s timeout, prevents hanging
)
chat_session = gemini_client.chats.create(
model=model_name,
config=types.GenerateContentConfig(
system_instruction=system_prompt,
temperature=0.7,
)
)
print(f" Gemini initialisiert: {model_name}")
return True
except Exception as e:
print(f" Modell {model_name} nicht verfuegbar: {e}")
continue
print(" FEHLER: Kein Gemini-Modell verfuegbar!")
return False
def parse_ai_response(text):
"""Parst die JSON-Antwort von Gemini. Tolerant gegenueber Formatfehlern."""
text = text.strip()
# Remove markdown code fences if present
if text.startswith('```'):
text = re.sub(r'^```(?:json)?\s*', '', text)
text = re.sub(r'\s*```$', '', text)
try:
return json.loads(text)
except json.JSONDecodeError:
# Try to extract JSON from text
match = re.search(r'\{[\s\S]*\}', text)
if match:
try:
return json.loads(match.group())
except:
pass
# Fallback: treat as plain message
return {"message": text, "action": "none", "data": {}}
# ── HTTP Handler ────────────────────────────────────
class RezeptHandler(SimpleHTTPRequestHandler):
def do_GET(self):
parsed = urlparse(self.path)
path = parsed.path
if path == '/' or path == '':
self.serve_file('static/index.html', 'text/html; charset=utf-8')
elif path == '/setup':
# Setup-Seite mit Mikrofon-Anleitungen fuer Netzwerkgeraete
import socket
local_ip = '192.168.178.148'
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 80))
local_ip = s.getsockname()[0]
s.close()
except: pass
cert_exists = os.path.isfile(os.path.join(os.path.dirname(__file__), 'cert.pem'))
html = f"""<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Koch-Assistent – Geräte-Setup</title>
<style>
* {{ margin: 0; padding: 0; box-sizing: border-box; }}
body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: #1a1a2e; color: #e0e0e0; padding: 20px; line-height: 1.6; }}
h1 {{ color: #f5a623; margin-bottom: 20px; font-size: 1.8em; }}
h2 {{ color: #f5a623; margin: 25px 0 10px; font-size: 1.3em; }}
.card {{ background: #16213e; border-radius: 12px; padding: 20px; margin: 15px 0;
border-left: 4px solid #f5a623; }}
.card.android {{ border-left-color: #4caf50; }}
.card.ios {{ border-left-color: #2196f3; }}
.card.test {{ border-left-color: #ff9800; }}
.step {{ margin: 10px 0; padding: 8px 12px; background: #0f3460; border-radius: 8px; }}
.step-num {{ display: inline-block; background: #f5a623; color: #1a1a2e; width: 28px; height: 28px;
border-radius: 50%; text-align: center; line-height: 28px; font-weight: bold; margin-right: 8px; }}
code {{ background: #0a1628; padding: 2px 8px; border-radius: 4px; font-size: 0.95em; color: #4fc3f7;
word-break: break-all; }}
a {{ color: #4fc3f7; text-decoration: none; }}
a:hover {{ text-decoration: underline; }}
.url {{ font-size: 1.1em; font-weight: bold; color: #4fc3f7; }}
.btn {{ display: inline-block; background: #f5a623; color: #1a1a2e; padding: 12px 24px;
border-radius: 8px; font-weight: bold; text-decoration: none; margin: 10px 5px; font-size: 1em; }}
.btn:hover {{ background: #e6951a; text-decoration: none; }}
.success {{ color: #4caf50; font-weight: bold; }}
.warn {{ color: #ff9800; }}
#mic-test {{ margin-top: 10px; }}
#mic-status {{ padding: 10px; border-radius: 8px; margin-top: 10px; }}
</style>
</head>
<body>
<h1>🔧 Koch-Assistent – Geräte-Setup</h1>
<p>Dein Gerät muss das Mikrofon freigeben, damit der Sprachassistent funktioniert.<br>
Auf diesem Gerät: <span id="secure-status"></span></p>
<div class="card test">
<h2>🎤 Mikrofon-Test</h2>
<button class="btn" onclick="testMic()">Mikrofon jetzt testen</button>
<div id="mic-status"></div>
</div>
<div class="card android">
<h2>📱 Android (Chrome)</h2>
<p>Chrome auf Android blockiert das Mikrofon auf HTTP-Seiten. Lösung: <b>Chrome-Flag setzen</b> (einmalig).</p>
<div class="step">
<span class="step-num">1</span> Öffne Chrome und tippe in die Adressleiste:<br>
<code>chrome://flags/#unsafely-treat-insecure-origin-as-secure</code>
</div>
<div class="step">
<span class="step-num">2</span> Setze das Flag auf <b>"Enabled"</b>
</div>
<div class="step">
<span class="step-num">3</span> Im Textfeld darunter eintragen:<br>
<code>http://{local_ip}:{PORT}</code>
</div>
<div class="step">
<span class="step-num">4</span> Chrome <b>neu starten</b> (komplett schließen und öffnen)
</div>
<div class="step">
<span class="step-num">5</span> Koch-Assistent öffnen:<br>
<a href="http://{local_ip}:{PORT}/" class="url">http://{local_ip}:{PORT}/</a>
</div>
</div>
<div class="card ios">
<h2>🍎 iPhone / iPad (Safari)</h2>
<p>Safari erlaubt Mikrofon nur auf HTTPS. Lösung: <b>Zertifikat installieren</b> (einmalig).</p>
{'<div class="step"><span class="step-num">1</span> Lade das Zertifikat herunter:<br><a href="/cert.pem" class="btn" download="Koch-Assistent.pem">📥 Zertifikat herunterladen</a></div>' if cert_exists else '<div class="step warn">⚠️ Kein Zertifikat vorhanden. Server mit USE_SSL=1 starten.</div>'}
<div class="step">
<span class="step-num">2</span> Nach dem Download: <b>Einstellungen → Allgemein → VPN & Geräteverwaltung</b><br>
→ Das Profil "Koch-Assistent" installieren
</div>
<div class="step">
<span class="step-num">3</span> <b>Einstellungen → Allgemein → Info → Zertifikatsvertrauenseinstellungen</b><br>
→ "Koch-Assistent" <b>aktivieren</b>
</div>
<div class="step">
<span class="step-num">4</span> Koch-Assistent per HTTPS öffnen:<br>
<a href="https://{local_ip}:{PORT}/" class="url">https://{local_ip}:{PORT}/</a><br>
<small class="warn">(Server muss mit USE_SSL=1 gestartet sein)</small>
</div>
</div>
<div class="card">
<h2>💻 Windows / Mac (Chrome/Firefox)</h2>
<p>Auf <code>localhost</code> funktioniert alles automatisch.<br>
Im Netzwerk: Gleiche Chrome-Flag-Methode wie Android.</p>
<div class="step">
<a href="http://localhost:{PORT}/" class="url">http://localhost:{PORT}/</a> (lokal)
</div>
</div>
<script>
// Check secure context
const status = document.getElementById('secure-status');
if (window.isSecureContext) {{
status.innerHTML = '<span class="success">✅ Sicherer Kontext – Mikrofon möglich</span>';
}} else {{
status.innerHTML = '<span class="warn">⚠️ Unsicherer Kontext – Mikrofon blockiert! Setup nötig.</span>';
}}
async function testMic() {{
const el = document.getElementById('mic-status');
try {{
const stream = await navigator.mediaDevices.getUserMedia({{ audio: true }});
stream.getTracks().forEach(t => t.stop());
el.innerHTML = '<div style="background:#1b5e20;padding:10px;border-radius:8px;">✅ <b>Mikrofon funktioniert!</b> Du kannst den Koch-Assistent verwenden.<br><a href="/" class="btn" style="margin-top:10px;">🍳 Zum Koch-Assistent</a></div>';
}} catch (err) {{
el.innerHTML = '<div style="background:#b71c1c;padding:10px;border-radius:8px;">❌ <b>Mikrofon blockiert:</b> ' + err.message + '<br><br>Folge der Anleitung oben für dein Gerät.</div>';
}}
}}
</script>
</body>
</html>"""
body = html.encode('utf-8')
self.send_response(200)
self.send_header('Content-Type', 'text/html; charset=utf-8')
self.send_header('Content-Length', str(len(body)))
self.end_headers()
self.wfile.write(body)
elif path == '/cert.pem':
# Zertifikat zum Download anbieten
cert_path = os.path.join(os.path.dirname(__file__), 'cert.pem')
if os.path.isfile(cert_path):
self.send_response(200)
self.send_header('Content-Type', 'application/x-pem-file')
self.send_header('Content-Disposition', 'attachment; filename="Koch-Assistent.pem"')
with open(cert_path, 'rb') as f:
data = f.read()
self.send_header('Content-Length', str(len(data)))
self.end_headers()
self.wfile.write(data)
else:
self.send_error(404, 'Kein Zertifikat vorhanden')
elif path == '/api/recipes':
self.send_json(list(ALL_RECIPES.values()))
elif path.startswith('/api/recipes/'):
rid = path.split('/')[-1]
if rid in ALL_RECIPES:
self.send_json(ALL_RECIPES[rid])
else:
self.send_error(404, 'Rezept nicht gefunden')
elif path == '/api/live-config':
# Liefert System-Prompt, Tools und Rezeptdaten fuer Live-API-Session
# Kompakte Rezept-Uebersicht fuer den Prompt
recipe_lines = []
for rid, r in ALL_RECIPES.items():
zutaten_flat = []
for z in r.get('zutaten', []):
if isinstance(z, str):
zutaten_flat.append(z)
elif isinstance(z, dict):
for item in z.get('zutaten_liste', []):
zutaten_flat.append(item)
typ = r.get('typ', '')
if isinstance(typ, list):
typ = ', '.join(typ)
recipe_lines.append(
f"- ID: \"{rid}\" | Name: \"{r.get('name', rid)}\" | "
f"Typ: {typ} | Portionen: {r.get('portionen', '?')} | "
f"Quelle: {r.get('quelle', '?')} | "
f"Kurz: {r.get('kurzbeschreibung', '')} | "
f"Zutaten: {', '.join(zutaten_flat[:10])}{'...' if len(zutaten_flat) > 10 else ''}"
)
live_prompt = f"""Du bist "Koch-Assistent", ein freundlicher KI-Kuechenassistent.
Du sprichst Deutsch, duzt den Nutzer und bist enthusiastisch uebers Kochen.
Du kommunizierst per Sprache (Audio) – halte dich IMMER kurz (2-3 Saetze)!
DEINE REZEPTDATENBANK ({len(ALL_RECIPES)} Rezepte):
{chr(10).join(recipe_lines)}
ABSOLUT KRITISCHE REGELN FUER TOOL-NUTZUNG:
Du MUSST die Tools aufrufen! Ohne Tool-Aufruf passiert auf dem Display NICHTS.
Der Nutzer hat ein Tablet-Display, auf dem Rezepte, Zutaten und Schritte angezeigt werden.
Deine Sprache allein reicht NICHT – du MUSST die passenden Tools aufrufen!
VERFUEGBARE TOOLS UND WANN DU SIE NUTZEN MUSST:
1. suggest_recipes: IMMER aufrufen wenn du Rezepte vorschlaegst.
Dadurch erscheinen klickbare Rezeptkarten auf dem Display.
Parameter: recipe_ids = Liste von EXAKTEN IDs aus der Datenbank oben.
Beispiel: suggest_recipes(recipe_ids=["01_veganer_apfelkuchen_zapatka", "05_birnen_apfel_crumble"])
2. select_recipe: IMMER aufrufen wenn ein Rezept ausgewaehlt wird.
Dadurch wird das Rezept auf dem Display angezeigt (Bild, Zutaten, Schritte).
Parameter: recipe_id = EXAKTE ID aus der Datenbank.
3. set_portions: Aufrufen wenn die Portionszahl festgelegt wird.
Berechne die skalierten Zutatenmengen basierend auf dem Verhaeltnis neue/originale Portionen.
Parameter: recipe_id, portions, scaled_ingredients (Liste von Strings wie "200 g Mehl")
4. show_step: IMMER aufrufen wenn du einen Zubereitungsschritt erklaerst oder zum naechsten gehst!
OHNE diesen Aufruf sieht der Nutzer den Schritt NICHT auf dem Display!
Parameter: step_index (0-basiert). Erster Schritt = 0, zweiter = 1, usw.
5. start_timer: Aufrufen wenn ein Schritt eine Wartezeit hat (z.B. "25 Min backen").
Parameter: minutes, label
6. check_ingredients: Aufrufen wenn der Nutzer sagt welche Zutaten er hat.
Dadurch werden die Zutaten auf dem Display gruen markiert.
Parameter: checked = Liste der Zutatnamen die der Nutzer bestaetigt hat.
Verwende die EXAKTEN Zutatnamen aus dem Rezept!
ERFINDE NIEMALS Rezept-IDs! Verwende NUR IDs aus der Liste oben.
Wenn der Nutzer etwas will das nicht in der Datenbank ist, sage es ehrlich.
REGELN FUER SPRACHE:
- Sprich natuerlich und kurz. Maximal 2-3 Saetze pro Antwort.
- Lies NIEMALS Zutatenlisten vor. Verweise auf das Display ("Die Zutaten stehen rechts auf dem Display").
- Sprich Zahlen natuerlich aus: "eineinhalb" statt "1,5".
- Nenne bei Vorschlaegen die Rezeptnamen, keine Details.
- HINTERGRUNDGESPRAECHE: Wenn sich Personen unterhalten, ignoriere dies. Antworte NUR, wenn du direkt angesprochen wirst oder das Gesagte fuer das Kochen relevant ist. Bleibe sonst einfach still.
DIALOGABLAUF:
1. Begruesse den Nutzer kurz und frage worauf er Lust hat
2. Schlage 2-4 passende Rezepte vor → MUSS suggest_recipes aufrufen!
3. Wenn er waehlt → MUSS select_recipe aufrufen! Dann nach Portionenzahl fragen.
4. Portionen festlegen → MUSS set_portions aufrufen mit berechneten Zutaten.
5. Zutaten-Check: Frage ob alles da ist. Wenn bestaetigt → check_ingredients aufrufen.
6. Kochen starten → MUSS show_step(step_index=0) aufrufen!
7. Bei jedem Schrittwechsel ("weiter", "fertig", "naechster") → MUSS show_step aufrufen!
8. Bei Wartezeiten → start_timer aufrufen.
"""
self.send_json({
'model': LIVE_MODEL,
'systemPrompt': live_prompt,
'tools': LIVE_TOOLS,
'recipes': {rid: {'name': r.get('name', rid), 'id': rid} for rid, r in ALL_RECIPES.items()}
})
elif path.startswith(('/static/', '/Rezeptbilder/', '/Rezepte_JSON/')):
file_path = os.path.join(os.path.dirname(__file__), path.lstrip('/'))
if os.path.isfile(file_path):
ct = self.guess_type(file_path)
self.serve_file(file_path, ct)
else:
self.send_error(404)
else:
self.send_error(404)
def do_POST(self):
global chat_session, ALL_FEEDBACK
content_length = int(self.headers.get('Content-Length', 0))
body = self.rfile.read(content_length) if content_length else b'{}'
try:
data = json.loads(body)
except:
data = {}
parsed = urlparse(self.path)
path = parsed.path
if path == '/api/chat':
self.handle_chat(data)
elif path == '/api/feedback':
self.handle_feedback(data)
elif path == '/api/reset':
chat_session = None
init_gemini()
self.send_json({"status": "reset"})
elif path == '/api/token':
# Generate ephemeral token for Live API direct connection
try:
token_client = genai.Client(
api_key=API_KEY,
http_options={'api_version': 'v1alpha'}
)
now = datetime.now(tz=timezone.utc)
token = token_client.auth_tokens.create(
config={
'uses': 1,
'expire_time': now + timedelta(minutes=30),
'new_session_expire_time': now + timedelta(minutes=2),
'http_options': {'api_version': 'v1alpha'},
}
)
print(f" [TOKEN] Ephemeral Token generiert (gueltig 30min)")
self.send_json({'token': token.name})
except Exception as e:
print(f" [TOKEN] Fehler: {e}")
traceback.print_exc()
self.send_json({'error': str(e)}, status=500)
else:
self.send_error(404)
def handle_chat(self, data):
global chat_session
msg = data.get('message', '').strip()
if not msg:
self.send_json({"message": "Bitte sag mir etwas!", "action": "none", "data": {}})
return
print(f"\n>>> CHAT Request: '{msg[:80]}...'" if len(msg) > 80 else f"\n>>> CHAT Request: '{msg}'")
t0 = time.time()
# Initialize Gemini if needed
if chat_session is None:
print(" [INIT] Gemini wird initialisiert...")
if not init_gemini():
self.send_json({
"message": "Gemini API nicht konfiguriert.\nBitte API-Key in .env eintragen und Server neu starten.",
"action": "none", "data": {}
})
return
print(f" [INIT] fertig ({time.time()-t0:.1f}s)")
max_retries = 3
for attempt in range(max_retries):
try:
t1 = time.time()
print(f" [API] Sende an Modell (Versuch {attempt+1}/{max_retries})...")
response = chat_session.send_message(msg)
t2 = time.time()
# Handle None response (safety filter, empty response)
resp_text = response.text or ''
if not resp_text.strip():
print(f" [API] LEERE Antwort erhalten ({t2-t1:.1f}s) – evtl. Safety-Filter")
if hasattr(response, 'candidates') and response.candidates:
c = response.candidates[0]
reason = getattr(c, 'finish_reason', 'unbekannt')
print(f" [API] finish_reason: {reason}")
# Retry on empty response
if attempt < max_retries - 1:
time.sleep(1)
continue
self.send_json({
"message": "Die KI hat keine Antwort generiert. Bitte versuche es nochmal.",
"action": "none", "data": {}
})
return
print(f" [API] Antwort erhalten ({t2-t1:.1f}s, {len(resp_text)} Zeichen)")
print(f" [API] Vorschau: {resp_text[:200]}")
parsed = parse_ai_response(resp_text)
# Enrich response with full recipe data when needed
action = parsed.get('action', 'none')
resp_data = parsed.get('data', {})
if action == 'suggest_recipes':
recipe_ids = resp_data.get('recipe_ids', [])
recipes_full = []
for rid in recipe_ids:
if rid in ALL_RECIPES:
recipes_full.append(ALL_RECIPES[rid])
parsed['recipes_full'] = recipes_full
elif action == 'select_recipe':
rid = resp_data.get('recipe_id', '')
if rid in ALL_RECIPES:
parsed['recipe_full'] = ALL_RECIPES[rid]
elif action == 'set_portions':
rid = resp_data.get('recipe_id', '')
if rid in ALL_RECIPES:
parsed['recipe_full'] = ALL_RECIPES[rid]
try:
self.send_json(parsed)
except (ConnectionAbortedError, BrokenPipeError, OSError):
print(f" [SEND] Browser hat Verbindung abgebrochen")
return
t3 = time.time()
print(f" [SEND] Response gesendet ({t3-t0:.1f}s gesamt)")
return # success
except Exception as e:
err_str = str(e)
print(f" [ERR] Versuch {attempt+1}: {err_str[:150]}")
# Retry on transient errors (500, 503, 504, UNAVAILABLE, timeout)
if attempt < max_retries - 1 and ('503' in err_str or '500' in err_str or '504' in err_str or 'UNAVAILABLE' in err_str or 'INTERNAL' in err_str or 'DEADLINE_EXCEEDED' in err_str or 'overloaded' in err_str.lower() or 'ReadTimeout' in err_str or 'timed out' in err_str.lower()):
wait = 2 ** attempt # 1s, 2s
print(f" [RETRY] Warte {wait}s...")
time.sleep(wait)
continue
print(f" Gemini Error: {e}")
traceback.print_exc()
# Short spoken message + [[INFO]] with technical details
if '503' in err_str or 'UNAVAILABLE' in err_str:
short_msg = "Das KI-Modell ist gerade ueberlastet. Bitte versuche es gleich noch einmal."
info = "503 Service Unavailable – Server ueberlastet"
elif '429' in err_str or 'RATE' in err_str.upper() or 'RESOURCE_EXHAUSTED' in err_str:
short_msg = "Zu viele Anfragen. Bitte kurz warten."
info = "429 Rate Limit – Tageslimit oder Minutenlimit erreicht"
elif '500' in err_str or 'INTERNAL' in err_str:
short_msg = "Serverfehler. Bitte versuche es noch einmal."
info = "500 Internal Error – Modell konnte die Anfrage nicht verarbeiten"
elif 'ReadTimeout' in err_str or 'timed out' in err_str.lower():
short_msg = "Die Anfrage hat zu lange gedauert. Bitte nochmal versuchen."
info = "Timeout – Antwort dauerte laenger als 60 Sekunden"
elif '401' in err_str or '403' in err_str:
short_msg = "API-Schluessel ungueltig."
info = "401/403 Auth Error – API-Key pruefen"
else:
short_msg = "Ein Fehler ist aufgetreten. Bitte versuche es noch einmal."
info = err_str[:120]
try:
self.send_json({
"message": f"{short_msg}\n\n[[INFO]]\n{info}",
"action": "none", "data": {}
})
except (ConnectionAbortedError, BrokenPipeError, OSError):
print(f" [SEND] Browser hat Verbindung abgebrochen")
def handle_feedback(self, data):
global ALL_FEEDBACK
recipe_id = data.get('recipe_id', '')
text = data.get('text', '').strip()
if not text or not recipe_id:
self.send_error(400, 'recipe_id und text erforderlich')
return
if recipe_id not in ALL_FEEDBACK:
ALL_FEEDBACK[recipe_id] = []
ALL_FEEDBACK[recipe_id].append({
"date": datetime.now().strftime('%d.%m.%Y %H:%M'),
"text": text
})
save_feedback(ALL_FEEDBACK)
self.send_json({"status": "ok"})
def serve_file(self, filepath, content_type):
if not os.path.isabs(filepath):
filepath = os.path.join(os.path.dirname(__file__), filepath)
self.send_response(200)
self.send_header('Content-Type', content_type)
# No-Cache fuer JS/CSS – verhindert veralteten Code im Browser
if filepath.endswith(('.js', '.css', '.html')):
self.send_header('Cache-Control', 'no-cache, no-store, must-revalidate')
self.send_header('Pragma', 'no-cache')
self.end_headers()
with open(filepath, 'rb') as f:
self.wfile.write(f.read())
def guess_type(self, path):
ext = os.path.splitext(path)[1].lower()
return {
'.css': 'text/css; charset=utf-8',
'.js': 'application/javascript; charset=utf-8',
'.html': 'text/html; charset=utf-8',
'.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
'.png': 'image/png',
'.json': 'application/json; charset=utf-8',
'.webp': 'image/webp',
}.get(ext, 'application/octet-stream')
def send_json(self, data, status=200):
body = json.dumps(data, ensure_ascii=False, indent=2).encode('utf-8')
self.send_response(status)
self.send_header('Content-Type', 'application/json; charset=utf-8')
self.send_header('Content-Length', str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, fmt, *args):
print(f"[Koch-Assistent] {args[0]}")
# ── Main ────────────────────────────────────────────
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
"""HTTPServer der Requests in eigenen Threads bedient (blockiert nicht)."""
daemon_threads = True
if __name__ == '__main__':
import socket
# Eigene IP ermitteln
local_ip = '127.0.0.1'
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 80))
local_ip = s.getsockname()[0]
s.close()
except: pass
cert_file = os.path.join(os.path.dirname(__file__), 'cert.pem')
key_file = os.path.join(os.path.dirname(__file__), 'key.pem')
use_ssl = os.path.isfile(cert_file) and os.path.isfile(key_file)
protocol = 'https' if use_ssl else 'http'
print(f"\n{'='*50}")
print(f" Koch-Assistent Server (threaded)")
print(f" {len(ALL_RECIPES)} Rezepte geladen")
print(f" Modell: {MODEL}")
print(f" Live-Modell: {LIVE_MODEL}")
print(f"{'='*50}")
print(f" Lokal: http://localhost:{PORT}")
print(f" Netzwerk: {protocol}://{local_ip}:{PORT}")
if use_ssl:
print(f" SSL: AKTIV (cert.pem gefunden)")
print(f"")
print(f" Netzwerkgeraete-Setup:")
print(f" {protocol}://{local_ip}:{PORT}/setup")
print(f" Desktop-Chrome: Auf Zertifikatwarnung 'thisisunsafe' tippen")
else:
print(f"")
print(f" Mikrofon im Netzwerk: Setup-Seite oeffnen:")
print(f" http://{local_ip}:{PORT}/setup")
print(f"{'='*50}")
if API_KEY and API_KEY != 'DEIN_API_KEY_HIER_EINFUEGEN':
print(" API-Key: konfiguriert")
print(" Gemini wird beim ersten Chat-Request initialisiert.\n")
else:
print(" Gemini: NICHT KONFIGURIERT")
print(" -> API-Key in .env eintragen!\n")
server = ThreadedHTTPServer(('0.0.0.0', PORT), RezeptHandler)
if use_ssl:
import ssl
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ctx.load_cert_chain(cert_file, key_file)
server.socket = ctx.wrap_socket(server.socket, server_side=True)
print(f" HTTPS aktiv auf Port {PORT}")
try:
server.serve_forever()
except KeyboardInterrupt:
print("\nServer gestoppt.")
server.server_close()