kcrobot102 commited on
Commit
373b981
·
verified ·
1 Parent(s): 7e35406

initial commit

Browse files
Files changed (1) hide show
  1. app.py +563 -351
app.py CHANGED
@@ -1,394 +1,326 @@
1
- # app.py - KC Robot AI V4.1 (Full - FPT female TTS)
2
- # Full-feature Flask server:
3
- # - /ask (text) -> HF LLM
4
- # - /tts (text) -> HF TTS (default: NguyenManhTuan/VietnameseTTS_FPT_AI_Female)
5
- # - /stt (audio) -> HF STT (default: openai/whisper-small)
6
- # - /presence (radar event) -> greeting + Telegram notify
7
- # - /display -> OLED lines
8
- # - Web UI for quick test
9
- # - Telegram poller (background thread) to accept /ask, /say, /status
10
- #
11
- # Configuration via environment variables / Secrets in HF Space:
12
- # HF_API_TOKEN (required for HF inference)
13
- # HF_MODEL (optional, default google/flan-t5-large)
14
- # HF_TTS_MODEL (optional, default NguyenManhTuan/VietnameseTTS_FPT_AI_Female)
15
- # HF_STT_MODEL (optional, default openai/whisper-small)
16
  # TELEGRAM_TOKEN (optional)
17
- # TELEGRAM_CHATID (optional)
18
- #
19
- # Keep requirements minimal to improve HF Space stability:
20
- # flask, requests
21
  #
22
- # Important: set tokens in HF Space Settings -> Secrets (do not hardcode)
 
23
 
24
  import os
25
  import io
 
26
  import time
27
  import json
28
  import uuid
29
  import logging
30
  import threading
31
- from typing import Optional, List, Tuple
32
  from pathlib import Path
33
-
34
  import requests
35
- from flask import Flask, request, jsonify, send_file, render_template_string, abort
36
-
37
- # ----------------- Config & Logging -----------------
38
- logging.basicConfig(level=logging.INFO)
39
- logger = logging.getLogger("kcrobot.v4")
40
-
41
- app = Flask(__name__)
42
-
43
- # Directory for temporary files (tts audio)
44
- TMP_DIR = Path("/tmp/kcrobot") if os.name != "nt" else Path.cwd() / "tmp_kcrobot"
45
- TMP_DIR.mkdir(parents=True, exist_ok=True)
46
-
47
- # Environment / Secrets (set these in HF Space)
48
- HF_API_TOKEN = os.getenv("HF_API_TOKEN", "").strip()
49
- HF_MODEL = os.getenv("HF_MODEL", "google/flan-t5-large").strip()
50
- # Default FPT female Vietnamese TTS
51
- HF_TTS_MODEL = os.getenv("HF_TTS_MODEL", "NguyenManhTuan/VietnameseTTS_FPT_AI_Female").strip()
 
52
  HF_STT_MODEL = os.getenv("HF_STT_MODEL", "openai/whisper-small").strip()
53
  TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN", "").strip()
54
- TELEGRAM_CHATID = os.getenv("TELEGRAM_CHATID", "").strip()
55
-
56
- # Port (HF sets PORT env in runtime)
57
- PORT = int(os.getenv("PORT", os.getenv("SERVER_PORT", 7860)))
58
 
59
- if not HF_API_TOKEN:
60
- logger.warning("HF_API_TOKEN is not set — HF inference will fail until you add it in Secrets.")
61
 
62
- HF_HEADERS = {"Authorization": f"Bearer {HF_API_TOKEN}"} if HF_API_TOKEN else {}
 
 
 
63
 
64
- # ----------------- In-memory buffers -----------------
65
- CONV: List[Tuple[str, str]] = [] # list of (user, bot)
66
- DISPLAY_LINES: List[str] = [] # lines for OLED display
 
67
 
68
- def push_display(line: str, limit: int = 6):
69
- """Keep last `limit` lines for display."""
70
- global DISPLAY_LINES
71
- DISPLAY_LINES.append(line)
72
- if len(DISPLAY_LINES) > limit:
73
- DISPLAY_LINES = DISPLAY_LINES[-limit:]
74
 
75
- # ----------------- Helper: Hugging Face inference -----------------
76
- def hf_post_json(model_id: str, payload: dict, timeout: int = 120):
77
- """POST JSON to HF inference; return parsed JSON or raise."""
78
- if not HF_API_TOKEN:
79
- raise RuntimeError("HF_API_TOKEN missing (set in Secrets).")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  url = f"https://api-inference.huggingface.co/models/{model_id}"
81
  headers = dict(HF_HEADERS)
82
  headers["Content-Type"] = "application/json"
83
- r = requests.post(url, headers=headers, json=payload, timeout=timeout)
84
- if not r.ok:
85
- logger.error("HF POST JSON error %s: %s", r.status_code, r.text[:400])
86
- r.raise_for_status()
87
- try:
88
- return r.json()
89
- except Exception:
90
- return r.text
91
 
92
- def hf_post_bytes(model_id: str, data: bytes, content_type: str = "application/octet-stream", timeout: int = 180):
93
- """POST binary data (audio) to HF inference; return response object or raise."""
94
- if not HF_API_TOKEN:
95
- raise RuntimeError("HF_API_TOKEN missing (set in Secrets).")
96
  url = f"https://api-inference.huggingface.co/models/{model_id}"
97
  headers = dict(HF_HEADERS)
98
  headers["Content-Type"] = content_type
99
- r = requests.post(url, headers=headers, data=data, timeout=timeout)
100
- if not r.ok:
101
- logger.error("HF POST bytes error %s: %s", r.status_code, r.text[:400])
102
- r.raise_for_status()
103
- return r
104
-
105
- # ----------------- Text generation (LLM) -----------------
106
- def hf_text_generate(prompt: str, model: Optional[str] = None, max_new_tokens: int = 256, temperature: float = 0.7) -> str:
107
- model = model or HF_MODEL
108
- payload = {
109
- "inputs": prompt,
110
- "parameters": {"max_new_tokens": int(max_new_tokens), "temperature": float(temperature)},
111
- "options": {"wait_for_model": True}
112
- }
113
- out = hf_post_json(model, payload, timeout=120)
114
- # parse common shapes
115
- if isinstance(out, list) and len(out) > 0:
116
- first = out[0]
117
- if isinstance(first, dict) and "generated_text" in first:
118
- return first["generated_text"]
119
- return str(first)
120
- if isinstance(out, dict):
121
- for k in ("generated_text", "text", "summary_text"):
122
- if k in out:
123
- return out[k]
124
- return json.dumps(out)
125
- return str(out)
126
-
127
- # ----------------- TTS (Text -> audio bytes) -----------------
128
- def hf_tts_get_audio_bytes(text: str, model: Optional[str] = None) -> bytes:
129
- """Call HF TTS model and return audio bytes (commonly mp3 or wav)."""
130
- model = model or HF_TTS_MODEL
131
- payload = {"inputs": text}
132
- r = requests.post(f"https://api-inference.huggingface.co/models/{model}", headers={**HF_HEADERS, "Content-Type": "application/json"}, json=payload, timeout=120)
133
- if not r.ok:
134
- logger.error("HF TTS error %s: %s", r.status_code, r.text[:400])
135
- r.raise_for_status()
136
- return r.content
137
-
138
- def save_tts_temp(audio_bytes: bytes, ext_hint: str = "mp3") -> str:
139
- """Save bytes to a temp file under TMP_DIR and return filename."""
140
- fname = f"tts_{int(time.time())}_{uuid.uuid4().hex}.{ext_hint}"
141
- p = TMP_DIR / fname
142
- p.write_bytes(audio_bytes)
143
- return fname
144
-
145
- # ----------------- STT (audio bytes -> text) -----------------
146
- def hf_stt_from_bytes(audio_bytes: bytes, model: Optional[str] = None) -> str:
147
- model = model or HF_STT_MODEL
148
- r = hf_post_bytes(model, audio_bytes, content_type="application/octet-stream", timeout=180)
149
- # often returns {"text": "..."}
150
  try:
151
- j = r.json()
152
- if isinstance(j, dict) and "text" in j:
153
- return j["text"]
154
- if isinstance(j, list) and len(j) and isinstance(j[0], dict) and "text" in j[0]:
155
- return j[0]["text"]
156
- return str(j)
 
 
 
 
 
 
 
 
 
 
157
  except Exception:
158
- return r.text if hasattr(r, "text") else ""
 
159
 
160
- # ----------------- Endpoints for ESP32 / Web -----------------
161
- @app.route("/health", methods=["GET"])
162
- def health():
163
- return jsonify({
164
- "ok": True,
165
- "hf_api_token": bool(HF_API_TOKEN),
166
- "hf_model": HF_MODEL,
167
- "hf_tts_model": HF_TTS_MODEL,
168
- "hf_stt_model": HF_STT_MODEL,
169
- "telegram": bool(TELEGRAM_TOKEN and TELEGRAM_CHATID),
170
- "tmp_dir": str(TMP_DIR),
171
- })
172
 
173
- @app.route("/ask", methods=["POST"])
174
- def route_ask():
175
  """
176
- POST JSON: { "text": "...", "lang": "vi"|"en"|"auto" (optional) }
177
- Returns: { "answer": "..." }
178
  """
179
  try:
180
- data = request.get_json(force=True) or {}
181
- text = (data.get("text") or "").strip()
182
- lang = (data.get("lang") or "auto").lower()
183
- if not text:
184
- return jsonify({"error": "no text"}), 400
185
-
186
- # build bilingual instruction
187
- if lang == "vi":
188
- prompt = f"Bạn là trợ lý thông minh, trả lời bằng tiếng Việt, ngắn gọn và lịch sự:\n\n{text}"
189
- elif lang == "en":
190
- prompt = f"You are a helpful assistant. Answer in clear English, concise:\n\n{text}"
191
- else:
192
- prompt = f"Bạn trợ thông minh song ngữ (Vietnamese/English). Trả lời bằng ngôn ngữ phù hợp với câu hỏi:\n\n{text}"
193
-
194
- answer = hf_text_generate(prompt)
195
- # store conversation and display preview
196
- CONV.append((text, answer))
197
- push_display("YOU: " + (text[:40]))
198
- push_display("BOT: " + (answer[:40]))
199
- return jsonify({"answer": answer})
200
- except Exception as e:
201
- logger.exception("route_ask failed")
202
- return jsonify({"error": str(e)}), 500
203
 
204
- @app.route("/tts", methods=["POST"])
205
- def route_tts():
206
  """
207
- POST JSON: { "text":"..." }
208
- Returns: audio bytes (audio/mpeg) - HF TTS output (mp3/wav)
209
  """
210
- try:
211
- data = request.get_json(force=True) or {}
212
- text = (data.get("text") or "").strip()
213
- if not text:
214
- return jsonify({"error": "no text"}), 400
215
- audio_bytes = hf_tts_get_audio_bytes(text)
216
- # Try to detect extension: if content-type present? HF sometimes returns mp3 bytes.
217
- # We'll send as audio/mpeg (mp3) which is widely supported by ESP32 players.
218
- return send_file(io.BytesIO(audio_bytes), mimetype="audio/mpeg", as_attachment=False, download_name="tts.mp3")
219
- except Exception as e:
220
- logger.exception("route_tts failed")
221
- return jsonify({"error": str(e)}), 500
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
222
 
223
- @app.route("/stt", methods=["POST"])
224
- def route_stt():
225
- """
226
- Accepts multipart 'file' or raw audio bytes in body.
227
- Returns JSON: { "text": "recognized text" }
228
- """
229
- try:
230
- if "file" in request.files:
231
- f = request.files["file"]
232
- audio_bytes = f.read()
233
- else:
234
- audio_bytes = request.get_data() or b""
235
- if not audio_bytes:
236
- return jsonify({"error": "no audio"}), 400
237
- text = hf_stt_from_bytes(audio_bytes)
238
- push_display("UserAudio: " + (text[:40]))
239
- return jsonify({"text": text})
240
- except Exception as e:
241
- logger.exception("route_stt failed")
242
- return jsonify({"error": str(e)}), 500
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
243
 
244
- @app.route("/presence", methods=["POST"])
245
- def route_presence():
246
- """
247
- ESP32 radar posts: JSON {"note": "..." }
248
- Server responds with greeting, and optionally sends Telegram alert.
249
- """
250
  try:
251
- data = request.get_json(force=True) or {}
252
- note = data.get("note", " người tới")
253
- greeting = f"Xin chào! {note}"
254
- CONV.append(("__presence__", greeting))
255
- push_display("RADAR: " + note[:40])
256
- # Telegram notify
257
- if TELEGRAM_TOKEN and TELEGRAM_CHATID:
258
- try:
259
- send_telegram_message(f"⚠️ Robot: Phát hiện: {note}")
260
- except Exception:
261
- logger.exception("Telegram notify failed")
262
- return jsonify({"greeting": greeting})
263
- except Exception as e:
264
- logger.exception("route_presence failed")
265
- return jsonify({"error": str(e)}), 500
266
-
267
- @app.route("/display", methods=["GET"])
268
- def route_display():
269
- return jsonify({"lines": DISPLAY_LINES[-6:], "conv_len": len(CONV)})
270
-
271
- # Serve tts files by filename if needed
272
- @app.route("/tts_file/<path:fname>", methods=["GET"])
273
- def serve_tts_file(fname):
274
- p = TMP_DIR / fname
275
- if not p.exists():
276
- return abort(404)
277
- # guess mime
278
- mime = "audio/mpeg" if str(fname).lower().endswith(".mp3") else "audio/wav"
279
- return send_file(str(p), mimetype=mime)
280
-
281
- # ----------------- Simple Web UI for testing -----------------
282
- INDEX_HTML = """
283
- <!doctype html>
284
- <html>
285
- <head>
286
- <meta charset="utf-8">
287
- <title>KC Robot AI V4.1</title>
288
- <meta name="viewport" content="width=device-width,initial-scale=1">
289
- <style>
290
- body{font-family:Arial,Helvetica, sans-serif; margin:12px; color:#111}
291
- textarea{width:100%; height:90px; padding:8px; font-size:16px}
292
- #chat{border:1px solid #ddd; padding:8px; height:260px; overflow:auto; background:#fbfbfb}
293
- button{padding:8px 12px; margin-top:8px; font-size:15px}
294
- </style>
295
- </head>
296
- <body>
297
- <h2>KC Robot AI V4.1 — Cloud Brain (FPT female)</h2>
298
- <div id="chat"></div>
299
- <textarea id="txt" placeholder="Nhập tiếng Việt hoặc English..."></textarea><br>
300
- <button onclick="ask()">Gửi (Ask)</button>
301
- <button onclick="playLast()">Phát TTS</button>
302
- <hr/>
303
- <input type="file" id="afile" accept="audio/*"><button onclick="uploadAudio()">Upload audio → STT</button>
304
- <hr/>
305
- <div id="log"></div>
306
- <script>
307
- window._lastAnswer = "";
308
- async function ask(){
309
- let t = document.getElementById('txt').value;
310
- if(!t) return;
311
- appendUser(t);
312
- let res = await fetch('/ask', {method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({text:t})});
313
- let j = await res.json();
314
- if(j.answer){ appendBot(j.answer); window._lastAnswer = j.answer; }
315
- else appendBot('[Error] ' + JSON.stringify(j));
316
- }
317
- function appendUser(t){ document.getElementById('chat').innerHTML += '<div style="color:#006"><b>You:</b> '+escapeHtml(t)+'</div>'; scroll();}
318
- function appendBot(t){ document.getElementById('chat').innerHTML += '<div style="color:#080"><b>Robot:</b> '+escapeHtml(t)+'</div>'; scroll();}
319
- function escapeHtml(s){ return (s+'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); }
320
- function scroll(){ let c = document.getElementById('chat'); c.scrollTop = c.scrollHeight; }
321
- async function playLast(){
322
- const txt = window._lastAnswer || document.getElementById('txt').value;
323
- if(!txt) return alert('Chưa có câu trả lời');
324
- let r = await fetch('/tts',{method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({text: txt})});
325
- if(!r.ok) return alert('TTS lỗi');
326
- const b = await r.blob();
327
- const url = URL.createObjectURL(b);
328
- const a = new Audio(url);
329
- a.play();
330
- }
331
- async function uploadAudio(){
332
- const f = document.getElementById('afile').files[0];
333
- if(!f) return alert('Chọn file audio');
334
- const fd = new FormData(); fd.append('file', f);
335
- const r = await fetch('/stt', {method:'POST', body: fd});
336
- const j = await r.json();
337
- if(j.text) appendUser('[voice] '+j.text);
338
- else appendUser('[stt error] '+JSON.stringify(j));
339
- }
340
- </script>
341
- </body>
342
- </html>
343
- """
344
- @app.route("/", methods=["GET"])
345
- def index():
346
- return render_template_string(INDEX_HTML)
347
 
348
- # ----------------- Telegram helpers & poller -----------------
349
- def send_telegram_message(text: str) -> bool:
350
- if not TELEGRAM_TOKEN or not TELEGRAM_CHATID:
351
- logger.debug("Telegram not configured")
352
  return False
353
  try:
354
- url = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage"
355
- r = requests.post(url, json={"chat_id": TELEGRAM_CHATID, "text": text}, timeout=10)
356
- if not r.ok:
357
- logger.warning("Telegram send failed: %s %s", r.status_code, r.text)
 
 
358
  return False
359
  return True
360
  except Exception:
361
- logger.exception("send_telegram_message exception")
362
  return False
363
 
364
- def telegram_poll_loop():
365
- """Long-polling loop to fetch updates and respond to simple commands."""
366
  if not TELEGRAM_TOKEN:
367
- logger.info("telegram_poll_loop: TELEGRAM_TOKEN not set, exiting poller.")
368
  return
 
369
  base = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}"
370
  offset = None
371
- logger.info("telegram_poll_loop: starting.")
372
  while True:
373
  try:
374
  params = {"timeout": 30}
375
- if offset:
376
- params["offset"] = offset
377
  r = requests.get(base + "/getUpdates", params=params, timeout=35)
378
- if not r.ok:
379
- logger.warning("telegram getUpdates failed: %s", r.status_code)
380
- time.sleep(2)
381
- continue
382
  j = r.json()
383
  for upd in j.get("result", []):
384
- offset = upd["update_id"] + 1
385
  msg = upd.get("message") or {}
386
  chat = msg.get("chat", {})
387
- chat_id = chat.get("id")
388
  text = (msg.get("text") or "").strip()
389
- if not text:
390
- continue
391
- logger.info("TG msg %s: %s", chat_id, text)
392
  lower = text.lower()
393
  if lower.startswith("/ask "):
394
  q = text[5:].strip()
@@ -401,16 +333,15 @@ def telegram_poll_loop():
401
  except Exception:
402
  logger.exception("tg reply failed")
403
  elif lower.startswith("/say "):
404
- tts_text = text[5:].strip()
405
  try:
406
- audio = hf_tts_get_audio_bytes(tts_text)
407
- files = {"audio": ("reply.mp3", audio, "audio/mpeg")}
408
- requests.post(base + "/sendAudio", files=files, data={"chat_id": chat_id}, timeout=30)
409
  except Exception:
410
  logger.exception("tg say failed")
411
  elif lower.startswith("/status"):
412
  try:
413
- requests.post(base + "/sendMessage", json={"chat_id": chat_id, "text": "KC Robot AI is running."}, timeout=10)
414
  except Exception:
415
  pass
416
  else:
@@ -419,24 +350,305 @@ def telegram_poll_loop():
419
  except Exception:
420
  pass
421
  except Exception:
422
- logger.exception("telegram_poll_loop exception, sleeping 3s")
423
  time.sleep(3)
424
 
425
- def start_background_tasks():
426
- # start telegram poller thread (if token provided)
427
- if TELEGRAM_TOKEN:
428
- t = threading.Thread(target=telegram_poll_loop, daemon=True)
429
  t.start()
430
- logger.info("Started Telegram poller thread.")
431
- else:
432
- logger.info("Telegram token not provided; poller disabled.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
433
 
434
- @app.before_first_request
435
- def _startup():
436
- start_background_tasks()
437
 
438
- # ----------------- Run -----------------
439
  if __name__ == "__main__":
440
- logger.info("Starting KC Robot AI V4.1 (FPT female TTS).")
441
- start_background_tasks()
442
- app.run(host="0.0.0.0", port=PORT)
 
1
+ # app.py KC Robot AI v7.5 FINAL (auto-model-select, bilingual, TTS fallback, Telegram, ESP32 endpoints)
2
+ # Secrets expected (HF Space -> Settings -> Secrets):
3
+ # HF_TOKEN (required)
4
+ # HF_MODEL (optional preferred model id like "mistralai/Mistral-7B-Instruct-v0.3")
 
 
 
 
 
 
 
 
 
 
 
5
  # TELEGRAM_TOKEN (optional)
6
+ # TELEGRAM_CHAT_ID (optional)
7
+ # Optional:
8
+ # HF_TTS_MODEL, HF_STT_MODEL
 
9
  #
10
+ # Minimal deps: flask, requests, gTTS, python-multipart
11
+ # Keep requirements.txt consistent with these packages.
12
 
13
  import os
14
  import io
15
+ import sys
16
  import time
17
  import json
18
  import uuid
19
  import logging
20
  import threading
21
+ from typing import Any, List, Tuple, Optional
22
  from pathlib import Path
 
23
  import requests
24
+ from flask import Flask, request, jsonify, Response, render_template_string
25
+
26
+ # gTTS fallback
27
+ try:
28
+ from gtts import gTTS
29
+ _HAS_GTTS = True
30
+ except Exception:
31
+ _HAS_GTTS = False
32
+
33
+ # ---------------- logging ----------------
34
+ logging.basicConfig(stream=sys.stdout, level=logging.INFO,
35
+ format="%(asctime)s %(levelname)s %(name)s: %(message)s")
36
+ logger = logging.getLogger("kcrobot.v7.5")
37
+
38
+ # ---------------- env / secrets ----------------
39
+ HF_TOKEN = os.getenv("HF_TOKEN", "").strip()
40
+ HF_MODEL = os.getenv("HF_MODEL", "google/flan-t5-base").strip() # preferred model (may be empty)
41
+ HF_TTS_MODEL = os.getenv("HF_TTS_MODEL", "").strip() # optional HF TTS model
42
  HF_STT_MODEL = os.getenv("HF_STT_MODEL", "openai/whisper-small").strip()
43
  TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN", "").strip()
44
+ TELEGRAM_CHAT_ID = os.getenv("TELEGRAM_CHAT_ID", "").strip()
45
+ PORT = int(os.getenv("PORT", 7860))
 
 
46
 
47
+ HF_HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"} if HF_TOKEN else {}
 
48
 
49
+ # ---------------- tmp dir ----------------
50
+ TMPDIR = Path("/tmp/kcrobot") if os.name != "nt" else Path.cwd() / "tmp_kcrobot"
51
+ TMPDIR.mkdir(parents=True, exist_ok=True)
52
+ CONV_LOG = TMPDIR / "conversation_log.jsonl"
53
 
54
+ # ---------------- in-memory ----------------
55
+ CONVERSATION: List[Tuple[str, str]] = []
56
+ DISPLAY_BUFFER: List[str] = []
57
+ DISPLAY_LIMIT = 6
58
 
59
+ def push_display(line: str):
60
+ global DISPLAY_BUFFER
61
+ DISPLAY_BUFFER.append(line)
62
+ if len(DISPLAY_BUFFER) > DISPLAY_LIMIT:
63
+ DISPLAY_BUFFER = DISPLAY_BUFFER[-DISPLAY_LIMIT:]
 
64
 
65
+ def save_conv(user: str, bot: str):
66
+ try:
67
+ with open(CONV_LOG, "a", encoding="utf-8") as f:
68
+ f.write(json.dumps({"time": time.time(), "user": user, "bot": bot}, ensure_ascii=False) + "\n")
69
+ except Exception:
70
+ logger.exception("save_conv failed")
71
+
72
+ # ---------------- small helpers ----------------
73
+ def clean_text(text: Any) -> str:
74
+ if text is None:
75
+ return ""
76
+ s = str(text)
77
+ import re
78
+ s = re.sub(r'[\x00-\x08\x0b-\x0c\x0e-\x1f]+', ' ', s)
79
+ s = re.sub(r'\s+', ' ', s).strip()
80
+ return s
81
+
82
+ VI_CHARS = set("ăâđêôơưáàảãạắằẳẵặấầẩẫậéèẻẽẹíìỉĩịóòỏõọúùủũụứừửữựýỳỷỹỵ")
83
+ def detect_language(text: str) -> str:
84
+ t = (text or "").lower()
85
+ for ch in t:
86
+ if ch in VI_CHARS:
87
+ return "vi"
88
+ return "en"
89
+
90
+ # ---------------- Hugging Face HTTP helpers ----------------
91
+ def hf_post_json(model_id: str, payload: dict, timeout: int = 90) -> requests.Response:
92
+ if not HF_TOKEN:
93
+ raise RuntimeError("HF_TOKEN not configured in Secrets")
94
  url = f"https://api-inference.huggingface.co/models/{model_id}"
95
  headers = dict(HF_HEADERS)
96
  headers["Content-Type"] = "application/json"
97
+ return requests.post(url, headers=headers, json=payload, timeout=timeout)
 
 
 
 
 
 
 
98
 
99
+ def hf_post_bytes(model_id: str, data: bytes, content_type: str = "application/octet-stream", timeout: int = 180) -> requests.Response:
100
+ if not HF_TOKEN:
101
+ raise RuntimeError("HF_TOKEN not configured in Secrets")
 
102
  url = f"https://api-inference.huggingface.co/models/{model_id}"
103
  headers = dict(HF_HEADERS)
104
  headers["Content-Type"] = content_type
105
+ return requests.post(url, headers=headers, data=data, timeout=timeout)
106
+
107
+ def parse_hf_text_output(obj: Any) -> str:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  try:
109
+ if isinstance(obj, dict):
110
+ for k in ("generated_text","text","answer"):
111
+ if k in obj:
112
+ return obj.get(k,"")
113
+ if "choices" in obj and isinstance(obj["choices"], list) and obj["choices"]:
114
+ c0 = obj["choices"][0]
115
+ return c0.get("text") or c0.get("message",{}).get("content","") or str(c0)
116
+ return json.dumps(obj, ensure_ascii=False)
117
+ if isinstance(obj, list) and obj:
118
+ first = obj[0]
119
+ if isinstance(first, dict):
120
+ for k in ("generated_text","text"):
121
+ if k in first:
122
+ return first.get(k,"")
123
+ return str(first)
124
+ return str(obj)
125
  except Exception:
126
+ logger.exception("parse_hf_text_output")
127
+ return str(obj)
128
 
129
+ # ---------------- Auto model finder ----------------
130
+ # Candidate fallback list — you can extend
131
+ DEFAULT_MODEL_CANDIDATES = [
132
+ "google/flan-t5-base"
133
+
134
+ ]
 
 
 
 
 
 
135
 
136
+ def test_model_working(model_id: str, sample_prompt: str = "Xin chào, bạn khỏe không?") -> Tuple[bool, dict]:
 
137
  """
138
+ Return (ok, response_short_info)
139
+ ok True if got status 200 and some textual output parseable
140
  """
141
  try:
142
+ payload = {"inputs": sample_prompt, "parameters": {"max_new_tokens": 20}, "options": {"wait_for_model": True}}
143
+ r = hf_post_json(model_id, payload, timeout=30)
144
+ info = {"status": r.status_code, "text": (r.text[:500] if r.text else "")}
145
+ if r.status_code == 200:
146
+ # try parse
147
+ try:
148
+ j = r.json()
149
+ out = parse_hf_text_output(j)
150
+ if out and len(out.strip())>0:
151
+ info["result"] = out
152
+ return True, info
153
+ except Exception:
154
+ # maybe non-json; if text length present, accept minimally
155
+ if r.text and len(r.text.strip())>0:
156
+ info["result"] = r.text
157
+ return True, info
158
+ return False, info
159
+ except requests.exceptions.RequestException as e:
160
+ logger.warning("test_model_working request exception for %s: %s", model_id, e)
161
+ return False, {"error": str(e)}
162
+ except Exception:
163
+ logger.exception("test_model_working unexpected")
164
+ return False, {"error": "unexpected"}
165
 
166
+ def auto_select_model(preferred: Optional[str] = None) -> Optional[str]:
 
167
  """
168
+ Try preferred model first. If fail, iterate DEFAULT_MODEL_CANDIDATES
169
+ Returns selected model id or None.
170
  """
171
+ tried = []
172
+ if preferred:
173
+ logger.info("Auto-check preferred model: %s", preferred)
174
+ ok, info = test_model_working(preferred)
175
+ tried.append((preferred, ok, info))
176
+ if ok:
177
+ logger.info("Preferred model OK: %s", preferred)
178
+ return preferred
179
+ logger.info("Preferred model not usable or not provided, scanning candidates...")
180
+ for m in DEFAULT_MODEL_CANDIDATES:
181
+ if m == preferred:
182
+ continue
183
+ logger.info("Testing candidate: %s", m)
184
+ ok, info = test_model_working(m)
185
+ tried.append((m, ok, info))
186
+ if ok:
187
+ logger.info("Selected fallback model: %s", m)
188
+ return m
189
+ # nothing found
190
+ logger.warning("Auto-select model found none usable. Tried: %s", [(t[0], t[1]) for t in tried])
191
+ return None
192
+
193
+ # initial selected model (will be mutated at runtime)
194
+ SELECTED_MODEL = HF_MODEL if HF_MODEL else None
195
+
196
+ # ---------------- HF text / stt / tts wrappers using SELECTED_MODEL ----------------
197
+ def hf_text_generate(prompt: str, model_override: Optional[str] = None, max_new_tokens: int = 256, temperature: float = 0.7) -> str:
198
+ model = model_override or SELECTED_MODEL
199
+ if not model:
200
+ raise RuntimeError("No HF model selected")
201
+ payload = {"inputs": prompt, "parameters": {"max_new_tokens": int(max_new_tokens), "temperature": float(temperature)}, "options": {"wait_for_model": True}}
202
+ r = hf_post_json(model, payload, timeout=120)
203
+ if r.status_code == 200:
204
+ try:
205
+ j = r.json()
206
+ return parse_hf_text_output(j)
207
+ except Exception:
208
+ return r.text
209
+ elif r.status_code == 403:
210
+ raise RuntimeError("HF returned 403 (forbidden) — token or access rights issue")
211
+ elif r.status_code == 404:
212
+ raise RuntimeError("HF returned 404 (model not found) — check HF_MODEL or model access")
213
+ else:
214
+ raise RuntimeError(f"HF text gen returned {r.status_code}: {r.text[:300]}")
215
 
216
+ def hf_stt_from_bytes(audio_bytes: bytes, model_override: Optional[str] = None) -> str:
217
+ model = model_override or HF_STT_MODEL
218
+ if not model:
219
+ raise RuntimeError("HF_STT_MODEL not configured")
220
+ r = hf_post_bytes(model, audio_bytes, content_type="application/octet-stream", timeout=180)
221
+ if r.status_code == 200:
222
+ try:
223
+ j = r.json()
224
+ if isinstance(j, dict) and "text" in j:
225
+ return j["text"]
226
+ return parse_hf_text_output(j)
227
+ except Exception:
228
+ return r.text
229
+ else:
230
+ raise RuntimeError(f"HF STT returned {r.status_code}: {r.text[:300]}")
231
+
232
+ def hf_tts_get_bytes(text: str, model_override: Optional[str] = None) -> bytes:
233
+ text = text.strip()
234
+ if not text:
235
+ raise RuntimeError("TTS text empty")
236
+ model = model_override or HF_TTS_MODEL
237
+ if model:
238
+ # Try HF TTS model first
239
+ try:
240
+ payload = {"inputs": text}
241
+ r = hf_post_json(model, payload, timeout=120)
242
+ if r.status_code == 200 and r.content:
243
+ return r.content
244
+ # fallback to content or parse
245
+ if r.status_code == 200:
246
+ try:
247
+ j = r.json()
248
+ return parse_hf_text_output(j).encode("utf-8")
249
+ except Exception:
250
+ return r.content
251
+ logger.warning("HF TTS returned %s: %s", r.status_code, r.text[:200])
252
+ except Exception:
253
+ logger.exception("HF TTS call failed")
254
+ # fallback to gTTS if present
255
+ if _HAS_GTTS:
256
+ try:
257
+ lang = "vi" if detect_language(text) == "vi" else "en"
258
+ tts = gTTS(text=text, lang=lang)
259
+ bio = io.BytesIO()
260
+ tts.write_to_fp(bio)
261
+ bio.seek(0)
262
+ return bio.read()
263
+ except Exception:
264
+ logger.exception("gTTS fallback failed")
265
+ raise RuntimeError("gTTS fallback failed")
266
+ raise RuntimeError("No TTS available (no HF_TTS_MODEL and gTTS not installed)")
267
 
268
+ # ---------------- Telegram helpers ----------------
269
+ def telegram_send_message(chat_id: str, text: str) -> bool:
270
+ if not TELEGRAM_TOKEN or not chat_id:
271
+ return False
 
 
272
  try:
273
+ url = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage"
274
+ r = requests.post(url, json={"chat_id": chat_id, "text": text}, timeout=8)
275
+ if r.status_code != 200:
276
+ logger.warning("Telegram sendMessage failed %s: %s", r.status_code, r.text[:300])
277
+ return False
278
+ return True
279
+ except Exception:
280
+ logger.exception("telegram_send_message")
281
+ return False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
282
 
283
+ def telegram_send_audio(chat_id: str, audio_bytes: bytes, filename: str = "reply.mp3") -> bool:
284
+ if not TELEGRAM_TOKEN or not chat_id:
 
 
285
  return False
286
  try:
287
+ url = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendAudio"
288
+ files = {"audio": (filename, io.BytesIO(audio_bytes), "audio/mpeg")}
289
+ data = {"chat_id": chat_id}
290
+ r = requests.post(url, files=files, data=data, timeout=30)
291
+ if r.status_code != 200:
292
+ logger.warning("Telegram sendAudio failed %s: %s", r.status_code, r.text[:300])
293
  return False
294
  return True
295
  except Exception:
296
+ logger.exception("telegram_send_audio")
297
  return False
298
 
299
+ # ---------------- Telegram poller (background) ----------------
300
+ def telegram_poller_loop():
301
  if not TELEGRAM_TOKEN:
302
+ logger.info("Telegram token not set; poller disabled")
303
  return
304
+ logger.info("Starting Telegram poller")
305
  base = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}"
306
  offset = None
 
307
  while True:
308
  try:
309
  params = {"timeout": 30}
310
+ if offset: params["offset"] = offset
 
311
  r = requests.get(base + "/getUpdates", params=params, timeout=35)
312
+ if r.status_code != 200:
313
+ logger.warning("Telegram getUpdates failed: %s", r.status_code)
314
+ time.sleep(2); continue
 
315
  j = r.json()
316
  for upd in j.get("result", []):
317
+ offset = upd.get("update_id", 0) + 1
318
  msg = upd.get("message") or {}
319
  chat = msg.get("chat", {})
320
+ chat_id = str(chat.get("id"))
321
  text = (msg.get("text") or "").strip()
322
+ if not text: continue
323
+ logger.info("TG msg %s: %s", chat_id, text[:200])
 
324
  lower = text.lower()
325
  if lower.startswith("/ask "):
326
  q = text[5:].strip()
 
333
  except Exception:
334
  logger.exception("tg reply failed")
335
  elif lower.startswith("/say "):
336
+ phrase = text[5:].strip()
337
  try:
338
+ audio = hf_tts_get_bytes(phrase)
339
+ telegram_send_audio(chat_id, audio, filename="say.mp3")
 
340
  except Exception:
341
  logger.exception("tg say failed")
342
  elif lower.startswith("/status"):
343
  try:
344
+ requests.post(base + "/sendMessage", json={"chat_id": chat_id, "text": "KC Robot v7.5 running"}, timeout=10)
345
  except Exception:
346
  pass
347
  else:
 
350
  except Exception:
351
  pass
352
  except Exception:
353
+ logger.exception("telegram poller crashed, sleeping 3s")
354
  time.sleep(3)
355
 
356
+ if TELEGRAM_TOKEN:
357
+ try:
358
+ t = threading.Thread(target=telegram_poller_loop, daemon=True)
 
359
  t.start()
360
+ except Exception:
361
+ logger.exception("start telegram thread failed")
362
+
363
+ # ---------------- Flask app & endpoints ----------------
364
+ app = Flask(__name__)
365
+
366
+ INDEX_HTML = """
367
+ <!doctype html>
368
+ <html>
369
+ <head>
370
+ <meta charset="utf-8">
371
+ <title>KC Robot AI v7.5</title>
372
+ <meta name="viewport" content="width=device-width,initial-scale=1">
373
+ <style>
374
+ body{font-family:Arial,Helvetica,sans-serif;margin:12px;color:#111}
375
+ .box{max-width:960px;margin:auto}
376
+ textarea{width:100%;height:90px;padding:10px;font-size:16px;border-radius:8px;border:1px solid #ddd}
377
+ button{padding:10px 14px;margin:6px 4px;border-radius:8px;background:#0b74de;color:white;border:none;cursor:pointer;font-weight:700}
378
+ #chat{border:1px solid #eee;padding:10px;height:360px;overflow:auto;background:#fafafa;border-radius:8px}
379
+ .you{color:#0b63d6;margin:6px 0}
380
+ .bot{color:#0b8a3f;margin:6px 0}
381
+ .small{font-size:13px;color:#666}
382
+ </style>
383
+ </head>
384
+ <body>
385
+ <div class="box">
386
+ <h2>🤖 KC Robot AI v7.5 — Final (Auto-model)</h2>
387
+ <div class="small">Model: <span id="modelName">loading...</span> | Telegram: <span id="tgstatus">checking...</span></div>
388
+ <textarea id="userText" placeholder="Nhập tiếng Việt hoặc English..."></textarea>
389
+ <div>
390
+ <select id="lang"><option value="auto">Auto</option><option value="vi">Vietnamese</option><option value="en">English</option></select>
391
+ <button onclick="send()">Gửi</button>
392
+ <button onclick="playLast()">Phát âm</button>
393
+ <button onclick="clearChat()">Xóa</button>
394
+ </div>
395
+ <div id="chat"></div>
396
+ <div style="margin-top:10px">
397
+ <input type="file" id="afile" accept="audio/*"><button onclick="uploadAudio()">Upload → STT</button>
398
+ </div>
399
+ <hr>
400
+ <div class="small">Diagnostics: <button onclick="modelCheck()">Kiểm tra model</button><span id="diag"></span></div>
401
+ </div>
402
+ <script>
403
+ let lastAnswer = "";
404
+ async function loadStatus(){ try{ let r=await fetch('/health'); let j=await r.json(); document.getElementById('modelName').innerText=j.hf_model||'(not set)'; document.getElementById('tgstatus').innerText=j.telegram ? 'enabled' : 'disabled'; }catch(e){ console.log(e); } }
405
+ function escapeHtml(s){ return (s+'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); }
406
+ function appendYou(t){ document.getElementById('chat').innerHTML += '<div class="you"><b>You:</b> '+escapeHtml(t)+'</div>'; scroll(); }
407
+ function appendBot(t){ document.getElementById('chat').innerHTML += '<div class="bot"><b>Robot:</b> '+escapeHtml(t)+'</div>'; scroll(); }
408
+ function scroll(){ let c=document.getElementById('chat'); c.scrollTop = c.scrollHeight; }
409
+ async function send(){
410
+ let t=document.getElementById('userText').value.trim(); if(!t) return; appendYou(t); document.getElementById('userText').value='';
411
+ let lang=document.getElementById('lang').value;
412
+ try{
413
+ let r=await fetch('/ask',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({text:t,lang:lang})});
414
+ let j=await r.json();
415
+ if(j.answer){ lastAnswer=j.answer; appendBot(j.answer); } else appendBot('[error] '+JSON.stringify(j));
416
+ }catch(e){ appendBot('[network error] '+e); }
417
+ }
418
+ async function playLast(){
419
+ if(!lastAnswer) return alert('Chưa có câu trả lời');
420
+ try{
421
+ let r=await fetch('/tts',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({text:lastAnswer})});
422
+ if(!r.ok){ alert('TTS lỗi'); return; }
423
+ const blob = await r.blob();
424
+ const url=URL.createObjectURL(blob);
425
+ const audio=new Audio(url); audio.play();
426
+ }catch(e){ alert('Play error: '+e); }
427
+ }
428
+ async function uploadAudio(){
429
+ const f=document.getElementById('afile').files[0]; if(!f) return alert('Chọn file audio');
430
+ const fd=new FormData(); fd.append('file', f);
431
+ const r=await fetch('/stt',{method:'POST', body: fd});
432
+ const j=await r.json();
433
+ if(j.text){ appendYou('[voice] '+j.text); } else appendYou('[stt error] '+JSON.stringify(j));
434
+ }
435
+ function clearChat(){ document.getElementById('chat').innerHTML=''; lastAnswer=''; }
436
+ async function modelCheck(){
437
+ document.getElementById('diag').innerText=' checking...';
438
+ try{
439
+ let r=await fetch('/model_check');
440
+ let j=await r.json();
441
+ document.getElementById('diag').innerText = ' ' + JSON.stringify(j).slice(0,200);
442
+ loadStatus();
443
+ }catch(e){ document.getElementById('diag').innerText=' error'; }
444
+ }
445
+ loadStatus();
446
+ </script>
447
+ </body>
448
+ </html>
449
+ """
450
+
451
+ @app.route("/", methods=["GET"])
452
+ def index():
453
+ return render_template_string(INDEX_HTML)
454
+
455
+ @app.route("/health", methods=["GET"])
456
+ def health():
457
+ return jsonify({
458
+ "ok": True,
459
+ "hf_token": bool(HF_TOKEN),
460
+ "hf_model": SELECTED_MODEL or HF_MODEL or "",
461
+ "hf_tts_model": HF_TTS_MODEL,
462
+ "hf_stt_model": HF_STT_MODEL,
463
+ "telegram": bool(TELEGRAM_TOKEN and TELEGRAM_CHAT_ID),
464
+ "conv_len": len(CONVERSATION),
465
+ "display_len": len(DISPLAY_BUFFER)
466
+ })
467
+
468
+ @app.route("/ask", methods=["POST"])
469
+ def route_ask():
470
+ try:
471
+ j = request.get_json(force=True) or {}
472
+ text = clean_text(j.get("text","") or "")
473
+ lang = (j.get("lang","auto") or "auto")
474
+ if not text:
475
+ return jsonify({"error":"no text"}), 400
476
+ if lang == "vi":
477
+ prompt = f"Bạn là trợ lý thông minh, trả lời bằng tiếng Việt, rõ ràng và ngắn gọn:\n\n{text}"
478
+ elif lang == "en":
479
+ prompt = f"You are a helpful assistant. Answer in clear English, concise:\n\n{text}"
480
+ else:
481
+ prompt = f"You are a bilingual assistant (Vietnamese/English). Answer in the same language as the user, clearly and concisely:\n\n{text}"
482
+ try:
483
+ ans = hf_text_generate(prompt)
484
+ except Exception as e:
485
+ logger.exception("hf_text_generate failed")
486
+ return jsonify({"error": str(e)}), 500
487
+ CONVERSATION.append((text, ans))
488
+ save_conv(text, ans)
489
+ push_display("YOU: " + (text[:60]))
490
+ push_display("BOT: " + (ans[:60] if isinstance(ans,str) else str(ans)[:60]))
491
+ # notify telegram
492
+ if TELEGRAM_TOKEN and TELEGRAM_CHAT_ID:
493
+ try:
494
+ telegram_send_message(TELEGRAM_CHAT_ID, f"You: {text}\nBot: {ans[:300]}")
495
+ except Exception:
496
+ logger.exception("telegram notify failed")
497
+ return jsonify({"answer": ans})
498
+ except Exception as e:
499
+ logger.exception("route_ask exception")
500
+ return jsonify({"error": str(e)}), 500
501
+
502
+ @app.route("/tts", methods=["POST"])
503
+ def route_tts():
504
+ try:
505
+ j = request.get_json(force=True) or {}
506
+ text = clean_text(j.get("text","") or "")
507
+ if not text:
508
+ return jsonify({"error":"no text"}), 400
509
+ try:
510
+ audio_bytes = hf_tts_get_bytes(text)
511
+ except Exception as e:
512
+ logger.exception("tts generation failed")
513
+ return jsonify({"error": str(e)}), 500
514
+ return Response(audio_bytes, mimetype="audio/mpeg")
515
+ except Exception as e:
516
+ logger.exception("route_tts exception")
517
+ return jsonify({"error": str(e)}), 500
518
+
519
+ @app.route("/stt", methods=["POST"])
520
+ def route_stt():
521
+ try:
522
+ if "file" in request.files:
523
+ f = request.files["file"]
524
+ audio_bytes = f.read()
525
+ else:
526
+ audio_bytes = request.get_data()
527
+ if not audio_bytes:
528
+ return jsonify({"error":"no audio provided"}), 400
529
+ try:
530
+ txt = hf_stt_from_bytes(audio_bytes)
531
+ except Exception as e:
532
+ logger.exception("STT failed")
533
+ return jsonify({"error": str(e)}), 500
534
+ CONVERSATION.append((f"[voice] {txt}", ""))
535
+ save_conv(f"[voice] {txt}", "")
536
+ push_display("VOICE: " + (txt[:60] if isinstance(txt,str) else str(txt)))
537
+ return jsonify({"text": txt})
538
+ except Exception as e:
539
+ logger.exception("route_stt exception")
540
+ return jsonify({"error": str(e)}), 500
541
+
542
+ @app.route("/presence", methods=["POST"])
543
+ def route_presence():
544
+ """
545
+ ESP32 radar should POST JSON {"note":"..."}.
546
+ Server returns greeting audio (if TTS available) or JSON greeting.
547
+ Also sends telegram notification if configured.
548
+ """
549
+ try:
550
+ j = request.get_json(force=True) or {}
551
+ note = clean_text(j.get("note","Có người phía trước") or "Có người phía trước")
552
+ greeting = f"Xin chào! {note}"
553
+ CONVERSATION.append(("__presence__", greeting))
554
+ save_conv("__presence__", greeting)
555
+ push_display("RADAR: " + note[:60])
556
+ if TELEGRAM_TOKEN and TELEGRAM_CHAT_ID:
557
+ try:
558
+ telegram_send_message(TELEGRAM_CHAT_ID, f"⚠️ Robot: Phát hiện người - {note}")
559
+ except Exception:
560
+ logger.exception("telegram notify failed")
561
+ try:
562
+ audio_bytes = hf_tts_get_bytes(greeting)
563
+ return Response(audio_bytes, mimetype="audio/mpeg")
564
+ except Exception:
565
+ return jsonify({"greeting": greeting})
566
+ except Exception as e:
567
+ logger.exception("route_presence exception")
568
+ return jsonify({"error": str(e)}), 500
569
+
570
+ @app.route("/display", methods=["GET"])
571
+ def route_display():
572
+ return jsonify({"lines": DISPLAY_BUFFER.copy(), "conv_len": len(CONVERSATION)})
573
+
574
+ @app.route("/model_check", methods=["GET"])
575
+ def model_check():
576
+ """
577
+ Attempt to verify HF_MODEL / select fallback, returns diagnostic JSON.
578
+ """
579
+ global SELECTED_MODEL
580
+ # first try current HF_MODEL
581
+ results = {}
582
+ try:
583
+ # if SELECTED_MODEL already set and seems good, return
584
+ if SELECTED_MODEL:
585
+ results["selected_model"] = SELECTED_MODEL
586
+ ok, info = test_model_working(SELECTED_MODEL)
587
+ results["selected_ok"] = ok
588
+ results["selected_info"] = info
589
+ return jsonify(results)
590
+ # else try auto-select with preference HF_MODEL
591
+ chosen = auto_select_model(HF_MODEL if HF_MODEL else None)
592
+ if chosen:
593
+ SELECTED_MODEL = chosen
594
+ results["selected_model"] = chosen
595
+ results["note"] = "Model selected"
596
+ return jsonify(results)
597
+ else:
598
+ results["error"] = "No usable model found in candidates"
599
+ return jsonify(results), 404
600
+ except Exception as e:
601
+ logger.exception("model_check failed")
602
+ return jsonify({"error": str(e)}), 500
603
+
604
+ @app.route("/config", methods=["GET","POST"])
605
+ def config():
606
+ """
607
+ GET returns current config.
608
+ POST JSON can change HF_MODEL / HF_TTS_MODEL / HF_STT_MODEL at runtime (temporary).
609
+ Example: {"hf_model":"...", "hf_tts_model":"..."}
610
+ """
611
+ global HF_MODEL, HF_TTS_MODEL, HF_STT_MODEL, SELECTED_MODEL
612
+ if request.method == "GET":
613
+ return jsonify({"hf_model": HF_MODEL, "hf_tts_model": HF_TTS_MODEL, "hf_stt_model": HF_STT_MODEL, "selected_model": SELECTED_MODEL})
614
+ try:
615
+ j = request.get_json(force=True) or {}
616
+ changed = {}
617
+ if "hf_model" in j:
618
+ HF_MODEL = j["hf_model"]
619
+ changed["hf_model"] = HF_MODEL
620
+ SELECTED_MODEL = None # force re-evaluation
621
+ if "hf_tts_model" in j:
622
+ HF_TTS_MODEL = j["hf_tts_model"]
623
+ changed["hf_tts_model"] = HF_TTS_MODEL
624
+ if "hf_stt_model" in j:
625
+ HF_STT_MODEL = j["hf_stt_model"]
626
+ changed["hf_stt_model"] = HF_STT_MODEL
627
+ return jsonify({"changed": changed})
628
+ except Exception as e:
629
+ logger.exception("config post failed")
630
+ return jsonify({"error": str(e)}), 500
631
+
632
+ # ---------------- startup auto model selection ----------------
633
+ def startup_model_check():
634
+ global SELECTED_MODEL
635
+ logger.info("Startup: checking/selecting model...")
636
+ try:
637
+ chosen = auto_select_model(HF_MODEL if HF_MODEL else None)
638
+ if chosen:
639
+ SELECTED_MODEL = chosen
640
+ logger.info("Startup: selected model = %s", SELECTED_MODEL)
641
+ else:
642
+ logger.warning("Startup: no usable HF model found yet. Use /model_check or set HF_MODEL secret.")
643
+ except Exception:
644
+ logger.exception("startup_model_check failed")
645
 
646
+ # run startup check in a thread so Flask starts quickly
647
+ t_start = threading.Thread(target=startup_model_check, daemon=True)
648
+ t_start.start()
649
 
650
+ # ---------------- run app ----------------
651
  if __name__ == "__main__":
652
+ logger.info("KC Robot AI v7.5 starting. PREF_HF_MODEL=%s HF_TTS=%s HF_STT=%s Telegram=%s",
653
+ HF_MODEL or "(none)", HF_TTS_MODEL or "(none)", HF_STT_MODEL or "(none)", bool(TELEGRAM_TOKEN and TELEGRAM_CHAT_ID))
654
+ app.run(host="0.0.0.0", port=PORT)