kcrobot102 commited on
Commit
71afd37
·
verified ·
1 Parent(s): 2b2178a

initial commit

Browse files
Files changed (1) hide show
  1. app.py +404 -439
app.py CHANGED
@@ -1,479 +1,444 @@
1
- """
2
- RobotAI v9.8 Gemini Brain + gTTS + Telegram (Hugging Face ready)
3
-
4
- Features:
5
- - Keep original Gemini AI logic (uses google-generativeai)
6
- - Web UI: auto language detect (vi/en), clean punctuation for TTS
7
- - Only play the newest audio on the web (stop previous audio)
8
- - Telegram integration (polling): replies with text and sends audio file if possible
9
- - Audio caching and cleanup
10
- """
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
  import os
 
 
13
  import json
14
  import uuid
15
- import re
16
- import time
17
  import logging
18
  import threading
19
- from flask import Flask, request, jsonify, render_template_string, send_file, redirect, url_for
20
-
21
- # Gemini SDK
22
- import google.generativeai as genai
23
 
24
- # gTTS for TTS (female-like voice)
25
- from gtts import gTTS
26
 
27
- # Telegram support (try modern v20, fallback v13)
28
- try:
29
- from telegram import Bot
30
- from telegram.ext import ApplicationBuilder, MessageHandler, CommandHandler, filters
31
- TELEGRAM_LIB = "v20"
32
- except Exception:
33
- try:
34
- from telegram import Bot
35
- from telegram.ext import Updater, MessageHandler, Filters, CommandHandler
36
- TELEGRAM_LIB = "v13"
37
- except Exception:
38
- TELEGRAM_LIB = None
39
-
40
- # ---------------- Config ----------------
41
- CONFIG_FILE = "config.json"
42
- AUDIO_DIR = "audio_cache"
43
- os.makedirs(AUDIO_DIR, exist_ok=True)
44
 
45
  app = Flask(__name__)
46
- logging.basicConfig(level=logging.INFO)
47
- logger = logging.getLogger("RobotAI")
48
-
49
- DEFAULT_MODEL = "gemini-2.5-flash"
50
- USE_GEMINI = False
51
-
52
- # ----------------- config helpers -----------------
53
- def load_config():
54
- cfg = {
55
- "GEMINI_API_KEY": os.environ.get("GEMINI_API_KEY", ""),
56
- "GEMINI_MODEL": os.environ.get("GEMINI_MODEL", DEFAULT_MODEL),
57
- "TELEGRAM_TOKEN": os.environ.get("TELEGRAM_TOKEN", ""),
58
- "TELEGRAM_CHAT_ID": os.environ.get("TELEGRAM_CHAT_ID", "")
59
- }
60
- if os.path.exists(CONFIG_FILE):
61
- try:
62
- with open(CONFIG_FILE, "r", encoding="utf-8") as f:
63
- data = json.load(f)
64
- cfg.update(data)
65
- except Exception as e:
66
- logger.exception("Load config error")
67
- return cfg
68
-
69
- def save_config(cfg):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  try:
71
- with open(CONFIG_FILE, "w", encoding="utf-8") as f:
72
- json.dump(cfg, f, ensure_ascii=False, indent=2)
73
- return True
74
  except Exception:
75
- logger.exception("Save config failed")
76
- return False
77
-
78
- # ----------------- Gemini init + wrapper -----------------
79
- def init_gemini():
80
- global USE_GEMINI
81
- cfg = load_config()
82
- key = cfg.get("GEMINI_API_KEY") or ""
83
- if not key:
84
- logger.warning("Gemini API key missing.")
85
- USE_GEMINI = False
86
- return
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  try:
88
- genai.configure(api_key=key)
89
- USE_GEMINI = True
90
- logger.info("✅ Gemini connected OK.")
 
 
 
91
  except Exception:
92
- USE_GEMINI = False
93
- logger.exception("Gemini init error")
94
-
95
- init_gemini()
96
-
97
- def gemini_answer(prompt: str) -> str:
 
 
 
 
 
 
 
 
 
 
 
98
  """
99
- Call Gemini. Keep simple: use GenerativeModel if present (matches your v9.2).
 
100
  """
101
- cfg = load_config()
102
- model = cfg.get("GEMINI_MODEL", DEFAULT_MODEL)
103
  try:
104
- if hasattr(genai, "GenerativeModel"):
105
- try:
106
- m = genai.GenerativeModel(model)
107
- resp = m.generate_content(prompt)
108
- if hasattr(resp, "text"):
109
- return resp.text
110
- return str(resp)
111
- except Exception:
112
- logger.debug("GenerativeModel failed, trying responses.generate", exc_info=True)
113
- # fallback: try responses.create (newer)
114
- if hasattr(genai, "responses") and hasattr(genai.responses, "create"):
115
- r = genai.responses.create(model=model, input=prompt)
116
- if hasattr(r, "output_text"):
117
- return r.output_text
118
- return str(r)
119
- except Exception:
120
- logger.exception("Gemini call error")
121
- return "⚠️ Gemini không phản hồi — kiểm tra API key / library."
122
-
123
- # ----------------- Language detection & TTS cleaning -----------------
124
- VIET_CHARS = "ăâđêôơưáàảãạắằẳẵặấầẩẫậéèẻẽẹíìỉĩịóòỏõọốồổỗộớờởỡợúùủũụưứừửữựýỳỷỹỵ"
125
-
126
- def detect_lang(text: str) -> str:
127
- return "vi" if any(ch in VIET_CHARS for ch in text.lower()) else "en"
128
-
129
- # Clean punctuation but keep letters & numbers and basic punctuation replacement -> single spaces.
130
- # We must not return empty string; fallback to short phrase.
131
- def clean_text_for_tts(text: str) -> str:
132
- if not text:
133
- return "Xin chào"
134
- # replace typical punctuation with space
135
- cleaned = re.sub(r"[.,!?;:()\"'“”‘’\[\]{}<>\/\\\|@#\$%\^&\*\+=~`–—\-]", " ", text)
136
- cleaned = re.sub(r"\s+", " ", cleaned).strip()
137
- if not cleaned:
138
- return "Xin chào"
139
- return cleaned
140
-
141
- def speak_text(text: str, lang: str = "vi") -> str:
142
  """
143
- Generate mp3 via gTTS, return local path or None.
 
144
  """
145
  try:
146
- tts_text = clean_text_for_tts(text)
147
- fname = f"tts_{uuid.uuid4().hex[:8]}.mp3"
148
- path = os.path.join(AUDIO_DIR, fname)
149
- tts = gTTS(text=tts_text, lang=lang, slow=False)
150
- tts.save(path)
151
- logger.info("gTTS saved %s", path)
152
- return path
153
- except Exception:
154
- logger.exception("TTS generation failed")
155
- return None
156
-
157
- # ----------------- Audio cleanup -----------------
158
- def cleanup_audio_older_than(seconds: int = 3600):
159
- now = time.time()
160
- for f in os.listdir(AUDIO_DIR):
161
- p = os.path.join(AUDIO_DIR, f)
162
- try:
163
- if os.path.isfile(p) and (now - os.path.getmtime(p) > seconds):
164
- os.remove(p)
165
- logger.info("Removed old audio: %s", p)
166
- except Exception:
167
- logger.exception("cleanup failed for %s", p)
168
-
169
- # ----------------- Web UI templates (client-side ensures only newest audio plays) -----------------
170
- INDEX_HTML = """<!doctype html><html><head>
171
- <meta charset="utf-8"><title>RobotAI v9.8</title>
172
- <style>
173
- body{font-family:Arial;background:#f5faff;padding:12px}
174
- #chat{background:#fff;border:1px solid #ddd;padding:12px;min-height:260px;border-radius:8px;overflow:auto}
175
- .you{color:#0b66c3;margin:6px 0}
176
- .bot{color:#0b8a5f;margin:6px 0}
177
- .button{background:#0b66c3;color:white;border:none;padding:8px 12px;border-radius:6px;cursor:pointer}
178
- .audio-controls{margin-top:6px}
179
- </style>
180
- </head><body>
181
- <h2>🤖 RobotAI v9.8 — Gemini Brain + Voice + Telegram</h2>
182
- <div>Gemini: <b>{{ gemini_status }}</b> | Model: <b>{{ model }}</b> | <a href="/config">Config</a></div>
183
- <hr>
184
- <textarea id="text" rows="4" style="width:100%;padding:8px;border-radius:6px;border:1px solid #ccc"></textarea><br><br>
185
- <button class="button" onclick="send()">Gửi</button> <button class="button" onclick="clearChat()">Xóa</button>
186
- <div id="chat" style="margin-top:12px"></div>
187
-
188
- <script>
189
- let currentAudio = null;
190
-
191
- function append(cls, txt){
192
- const c = document.getElementById('chat');
193
- c.innerHTML += '<div class="'+cls+'">'+txt+'</div>';
194
- c.scrollTop = c.scrollHeight;
195
- }
196
-
197
- function stopCurrentAudio(){
198
- if(currentAudio){
199
- try{ currentAudio.pause(); currentAudio.currentTime = 0; }catch(e){}
200
- currentAudio = null;
201
- }
202
- }
203
-
204
- function clearChat(){
205
- document.getElementById('chat').innerHTML = '';
206
- stopCurrentAudio();
207
- }
208
-
209
- async function send(){
210
- let txt = document.getElementById('text').value.trim();
211
- if(!txt) return;
212
- append('you', 'Bạn: ' + txt);
213
- document.getElementById('text').value = '';
214
-
215
- // stop previous audio (so we only play the newest)
216
- stopCurrentAudio();
217
-
218
- try{
219
- const res = await fetch('/api/chat', {
220
- method: 'POST',
221
- headers: {'Content-Type':'application/json'},
222
- body: JSON.stringify({text: txt})
223
- });
224
- const j = await res.json();
225
- append('bot', '🤖: ' + (j.reply || '(no reply)'));
226
- if(j.tts_url){
227
- currentAudio = new Audio(j.tts_url);
228
- currentAudio.autoplay = true;
229
- currentAudio.controls = false;
230
- // optional: show an audio control for manual replay
231
- const audioEl = document.createElement('audio');
232
- audioEl.src = j.tts_url;
233
- audioEl.controls = true;
234
- audioEl.className = 'audio-controls';
235
- document.getElementById('chat').appendChild(audioEl);
236
- // play newest
237
- try{ currentAudio.play(); }catch(e){}
238
- }
239
- }catch(e){
240
- append('bot', '[Lỗi mạng] ' + e);
241
- }
242
- }
243
- </script>
244
- </body></html>
245
- """
246
-
247
- CONFIG_HTML = """<!doctype html><html><head><meta charset="utf-8"><title>Config</title></head>
248
- <body style="font-family:Arial;padding:12px">
249
- <h3>⚙️ Config RobotAI</h3>
250
- <form method="post" action="/config">
251
- Gemini API Key:<br><textarea name="GEMINI_API_KEY" rows="2" cols="80">{{ GEMINI_API_KEY }}</textarea><br><br>
252
- Gemini Model:<br><input name="GEMINI_MODEL" value="{{ GEMINI_MODEL }}" size="50"><br><br>
253
- Telegram Token:<br><input name="TELEGRAM_TOKEN" value="{{ TELEGRAM_TOKEN }}" size="60"><br><br>
254
- Telegram Chat ID (optional):<br><input name="TELEGRAM_CHAT_ID" value="{{ TELEGRAM_CHAT_ID }}" size="30"><br><br>
255
- <button type="submit">Lưu</button>
256
- </form>
257
- <p><a href="/">⬅ Trở về</a></p>
258
- </body></html>
259
- """
260
-
261
- # ----------------- Flask routes -----------------
262
- @app.route("/")
263
- def home():
264
- cfg = load_config()
265
- return render_template_string(INDEX_HTML,
266
- gemini_status="✅ Kết nối" if USE_GEMINI else "❌ Chưa kết nối",
267
- model=cfg.get("GEMINI_MODEL"))
268
-
269
- @app.route("/config", methods=["GET","POST"])
270
- def config_page():
271
- if request.method == "POST":
272
- data = {
273
- "GEMINI_API_KEY": request.form.get("GEMINI_API_KEY","").strip(),
274
- "GEMINI_MODEL": request.form.get("GEMINI_MODEL", DEFAULT_MODEL).strip(),
275
- "TELEGRAM_TOKEN": request.form.get("TELEGRAM_TOKEN","").strip(),
276
- "TELEGRAM_CHAT_ID": request.form.get("TELEGRAM_CHAT_ID","").strip()
277
- }
278
- save_config(data)
279
- init_gemini()
280
- # restart telegram thread if token provided
281
- try:
282
- start_telegram_bot_thread()
283
- except Exception:
284
- logger.exception("start telegram thread failed")
285
- return redirect(url_for("config_page"))
286
- return render_template_string(CONFIG_HTML, **load_config())
287
-
288
- @app.route("/api/chat", methods=["POST"])
289
- def api_chat():
290
- payload = request.get_json(force=True)
291
- text = (payload.get("text") or "").strip()
292
- if not text:
293
- return jsonify({"error":"empty"}), 400
294
-
295
- lang = detect_lang(text)
296
  try:
297
- if USE_GEMINI:
298
- prefix = "Trả lời bằng tiếng Việt:" if lang == "vi" else "Answer in English:"
299
- reply = gemini_answer(prefix + "\n" + text)
300
  else:
301
- reply = "⚠️ Chưa kết nối Gemini. Kiểm tra API Key."
302
- except Exception:
303
- logger.exception("gemini call")
304
- reply = "⚠️ Lỗi khi gọi Gemini."
305
-
306
- tts_path = None
307
- try:
308
- if reply:
309
- tts_path = speak_text(reply, lang)
310
- except Exception:
311
- logger.exception("tts generation failed")
312
-
313
- tts_url = f"/api/tts/{os.path.basename(tts_path)}" if tts_path else None
314
-
315
- # send to telegram (background) if configured
316
- try:
317
- cfg = load_config()
318
- token = cfg.get("TELEGRAM_TOKEN","")
319
- chat_id = cfg.get("TELEGRAM_CHAT_ID","")
320
- if token and chat_id:
321
- threading.Thread(target=send_to_telegram_sync, args=(token, chat_id, reply, tts_path), daemon=True).start()
322
- except Exception:
323
- logger.exception("telegram dispatch failed")
324
-
325
- # cleanup audio in background
326
- try:
327
- threading.Thread(target=cleanup_audio_older_than, kwargs={"seconds":3600}, daemon=True).start()
328
- except Exception:
329
- pass
330
-
331
- return jsonify({"reply": reply, "tts_url": tts_url})
332
-
333
- @app.route("/api/tts/<fname>")
334
- def get_tts(fname):
335
- path = os.path.join(AUDIO_DIR, fname)
336
- if not os.path.exists(path):
337
- return jsonify({"error":"not found"}), 404
338
- return send_file(path, mimetype="audio/mpeg")
339
-
340
- # ----------------- Telegram integration -----------------
341
- TG_THREAD = None
342
-
343
- def send_to_telegram_sync(token: str, chat_id: str, text: str, tts_path: str = None):
344
  """
345
- Send text and (optionally) audio to Telegram chat.
 
346
  """
347
  try:
348
- bot = Bot(token=token)
349
- try:
350
- bot.send_message(chat_id=chat_id, text=text)
351
- except Exception:
352
- logger.exception("telegram send_message failed")
353
- if tts_path and os.path.exists(tts_path):
 
354
  try:
355
- with open(tts_path, "rb") as fh:
356
- bot.send_audio(chat_id=chat_id, audio=fh)
357
  except Exception:
358
- logger.exception("telegram send_audio failed")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
359
  except Exception:
360
- logger.exception("telegram overall send failed")
361
-
362
- def start_telegram_bot_thread():
363
- global TG_THREAD
364
- cfg = load_config()
365
- token = cfg.get("TELEGRAM_TOKEN","")
366
- if not token:
367
- logger.info("Telegram token not configured; skipping")
368
- return
369
 
370
- if TG_THREAD and TG_THREAD.is_alive():
371
- logger.info("Telegram thread already running.")
 
 
372
  return
373
-
374
- def _runner_v20(token):
 
 
375
  try:
376
- app_builder = ApplicationBuilder().token(token).build()
377
-
378
- async def start_cmd(update, context):
379
- await update.message.reply_text("RobotAI is running. Send me text and I'll reply with Gemini + TTS.")
380
-
381
- async def handle_msg(update, context):
382
- text = update.message.text or ""
383
- if not text.strip():
384
- await update.message.reply_text("Không nhận được nội dung.")
385
- return
386
- lang = detect_lang(text)
387
- if USE_GEMINI:
388
- prefix = "Trả lời bằng tiếng Việt:" if lang == "vi" else "Answer in English:"
389
- reply = gemini_answer(prefix + "\n" + text)
390
- else:
391
- reply = "⚠️ Chưa kết nối Gemini."
392
-
393
- # generate tts using same cleaning logic
394
- tts_path = None
395
- try:
396
- if reply:
397
- tts_path = speak_text(reply, lang)
398
- except Exception:
399
- logger.exception("tts for telegram failed")
400
-
401
- await update.message.reply_text(reply)
402
- if tts_path and os.path.exists(tts_path):
403
  try:
404
- with open(tts_path, "rb") as fh:
405
- await context.bot.send_audio(chat_id=update.effective_chat.id, audio=fh)
406
  except Exception:
407
- logger.exception("send audio to telegram (v20) failed")
408
-
409
- app_builder.add_handler(CommandHandler("start", start_cmd))
410
- app_builder.add_handler(MessageHandler(filters.TEXT & (~filters.COMMAND), handle_msg))
411
- logger.info("Starting Telegram polling (v20)...")
412
- app_builder.run_polling()
413
- except Exception:
414
- logger.exception("telegram v20 runner exception")
415
-
416
- def _runner_v13(token):
417
- try:
418
- updater = Updater(token=token, use_context=True)
419
- dp = updater.dispatcher
420
-
421
- def start_cmd(update, context):
422
- update.message.reply_text("RobotAI is running. Send me text and I'll reply with Gemini + TTS.")
423
-
424
- def handle_msg(update, context):
425
- text = update.message.text or ""
426
- if not text.strip():
427
- update.message.reply_text("Không nhận được nội dung.")
428
- return
429
- lang = detect_lang(text)
430
- if USE_GEMINI:
431
- prefix = "Trả lời bằng tiếng Việt:" if lang == "vi" else "Answer in English:"
432
- reply = gemini_answer(prefix + "\n" + text)
433
  else:
434
- reply = "⚠️ Chưa kết nối Gemini."
435
-
436
- tts_path = None
437
- try:
438
- if reply:
439
- tts_path = speak_text(reply, lang)
440
- except Exception:
441
- logger.exception("tts for telegram failed")
442
-
443
- update.message.reply_text(reply)
444
- if tts_path and os.path.exists(tts_path):
445
  try:
446
- context.bot.send_audio(chat_id=update.effective_chat.id, audio=open(tts_path, "rb"))
447
  except Exception:
448
- logger.exception("send audio to telegram (v13) failed")
449
-
450
- dp.add_handler(CommandHandler("start", start_cmd))
451
- dp.add_handler(MessageHandler(Filters.text & (~Filters.command), handle_msg))
452
- updater.start_polling()
453
- updater.idle()
454
  except Exception:
455
- logger.exception("telegram v13 runner exception")
456
-
457
- def runner():
458
- if TELEGRAM_LIB == "v20":
459
- _runner_v20(token)
460
- elif TELEGRAM_LIB == "v13":
461
- _runner_v13(token)
462
- else:
463
- logger.warning("python-telegram-bot not available; skipping telegram polling")
464
-
465
- TG_THREAD = threading.Thread(target=runner, daemon=True)
466
- TG_THREAD.start()
467
- logger.info("Telegram thread launched (if configured).")
468
-
469
- # start telegram thread at startup if token present
470
- try:
471
- start_telegram_bot_thread()
472
- except Exception:
473
- logger.exception("Starting telegram thread failed")
474
 
475
  # ----------------- Run -----------------
476
  if __name__ == "__main__":
477
- port = int(os.environ.get("PORT", 7860))
478
- logger.info("Starting RobotAI v9.8 on 0.0.0.0:%s", port)
479
- app.run(host="0.0.0.0", port=port)
 
 
 
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 là trợ lý 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", "Có 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()
395
+ try:
396
+ ans = hf_text_generate(q)
397
+ except Exception as e:
398
+ ans = f"[HF error] {e}"
 
 
399
  try:
400
+ requests.post(base + "/sendMessage", json={"chat_id": chat_id, "text": ans}, timeout=10)
 
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:
 
 
 
 
 
 
 
 
 
 
 
417
  try:
418
+ requests.post(base + "/sendMessage", json={"chat_id": chat_id, "text": "Commands: /ask <q> | /say <text> | /status"}, timeout=10)
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
+