kcrobot102 commited on
Commit
5e60392
·
verified ·
1 Parent(s): 71afd37

initial commit

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