Spaces:
Sleeping
Sleeping
initial commit
Browse files
app.py
CHANGED
|
@@ -1,398 +1,660 @@
|
|
| 1 |
-
#
|
| 2 |
-
#
|
| 3 |
-
#
|
| 4 |
-
#
|
| 5 |
-
#
|
| 6 |
-
#
|
| 7 |
-
#
|
| 8 |
-
#
|
| 9 |
-
#
|
|
|
|
|
|
|
|
|
|
| 10 |
import os
|
| 11 |
-
import
|
|
|
|
|
|
|
|
|
|
| 12 |
import uuid
|
| 13 |
-
import
|
| 14 |
-
import
|
| 15 |
-
import
|
| 16 |
from pathlib import Path
|
| 17 |
-
from flask import Flask, request, jsonify, send_file, abort
|
| 18 |
-
from dotenv import load_dotenv
|
| 19 |
-
|
| 20 |
-
# TTS
|
| 21 |
-
from gtts import gTTS
|
| 22 |
-
# STT
|
| 23 |
-
import speech_recognition as sr
|
| 24 |
-
# AI client (optional)
|
| 25 |
-
try:
|
| 26 |
-
from google import genai
|
| 27 |
-
except Exception:
|
| 28 |
-
genai = None
|
| 29 |
|
| 30 |
-
# HTTP
|
| 31 |
import requests
|
|
|
|
| 32 |
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
#
|
| 48 |
-
|
| 49 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
try:
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
# In-memory commands queue per device_id (simple)
|
| 57 |
-
DEVICE_COMMANDS = {} # device_id -> [ {cmd}, ... ]
|
| 58 |
-
|
| 59 |
-
# Regex / utils for cleaning text (remove punctuation/emoji/digits)
|
| 60 |
-
_EMOJI_RE = re.compile(
|
| 61 |
-
"["
|
| 62 |
-
"\U0001F600-\U0001F64F"
|
| 63 |
-
"\U0001F300-\U0001F5FF"
|
| 64 |
-
"\U0001F680-\U0001F6FF"
|
| 65 |
-
"\U00002600-\U000026FF"
|
| 66 |
-
"\U00002700-\U000027BF"
|
| 67 |
-
"\U0001F1E6-\U0001F1FF"
|
| 68 |
-
"]+", flags=re.UNICODE
|
| 69 |
-
)
|
| 70 |
-
|
| 71 |
-
_PUNCT_WORDS = [
|
| 72 |
-
r"\bdấu\s*chấm\b", r"\bchấm\b",
|
| 73 |
-
r"\bdấu\s*phẩy\b", r"\bphẩy\b", r"\bphay\b",
|
| 74 |
-
r"\bdấu\s*sao\b", r"\bsao\b",
|
| 75 |
-
r"\bdấu\s*hỏi\b", r"\bhỏi\b",
|
| 76 |
-
r"\bdấu\s*hai\s*chấm\b", r"\bcomma\b", r"\bdot\b", r"\bperiod\b"
|
| 77 |
-
]
|
| 78 |
|
| 79 |
-
|
| 80 |
-
|
|
|
|
| 81 |
return ""
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
t = re.sub(r"[^A-Za-zÀ-ỹ\s]", " ", t)
|
| 88 |
-
t = re.sub(r"\s+", " ", t).strip()
|
| 89 |
-
return t
|
| 90 |
|
|
|
|
| 91 |
def detect_language(text: str) -> str:
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
if
|
| 95 |
return "vi"
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
except Exception:
|
| 103 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
-
def
|
| 106 |
"""
|
| 107 |
-
|
|
|
|
| 108 |
"""
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
try:
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
return
|
| 130 |
-
return
|
| 131 |
-
except Exception
|
| 132 |
-
|
| 133 |
-
return
|
| 134 |
-
|
| 135 |
-
def
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
raise ValueError("No text to synthesize after cleaning.")
|
| 139 |
-
# detect lang
|
| 140 |
-
lang = "en"
|
| 141 |
try:
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
|
|
|
|
|
|
|
|
|
| 147 |
except Exception:
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
try:
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
print("STT error:", e)
|
| 167 |
-
return ""
|
| 168 |
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
|
| 175 |
-
# endpoint: health
|
| 176 |
@app.route("/", methods=["GET"])
|
| 177 |
def index():
|
| 178 |
-
return
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
try:
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
|
|
|
|
|
|
|
|
|
| 193 |
try:
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
try:
|
| 199 |
-
|
| 200 |
except Exception:
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
print("STT pipeline error:", e)
|
| 207 |
-
transcript = ""
|
| 208 |
-
|
| 209 |
-
# choose msg for Gemini: if no transcript, fallback to asking generic
|
| 210 |
-
if not transcript:
|
| 211 |
-
return jsonify({"error":"could not transcribe audio"}), 200
|
| 212 |
-
|
| 213 |
-
# optional: gemini key may be passed in payload
|
| 214 |
-
gemini_key = request.form.get("gemini_api_key") or request.json.get("gemini_api_key") if request.is_json else None
|
| 215 |
-
|
| 216 |
-
reply = call_gemini(transcript, api_key_override=gemini_key)
|
| 217 |
-
# parse relay commands from reply (simple)
|
| 218 |
-
commands = parse_relay_commands(reply)
|
| 219 |
|
| 220 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
try:
|
| 222 |
-
|
| 223 |
-
file_id = tts_file.stem
|
| 224 |
-
base = request.url_root.rstrip("/")
|
| 225 |
-
audio_url = f"{base}/tts-file/{file_id}"
|
| 226 |
except Exception as e:
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
# cleanup uploaded wav
|
| 231 |
-
try:
|
| 232 |
-
wav_path.unlink()
|
| 233 |
-
except Exception:
|
| 234 |
-
pass
|
| 235 |
-
|
| 236 |
-
# if any device commands detected, push to DEVICE_COMMANDS queue
|
| 237 |
-
if commands:
|
| 238 |
-
device_id = request.form.get("device_id") or "esp32_default"
|
| 239 |
-
DEVICE_COMMANDS.setdefault(device_id, []).extend(commands)
|
| 240 |
-
|
| 241 |
-
return jsonify({"reply": reply, "clean_text": clean_text_keep_letters(reply), "audio_url": audio_url, "commands": commands}), 200
|
| 242 |
-
|
| 243 |
except Exception as e:
|
| 244 |
-
|
| 245 |
return jsonify({"error": str(e)}), 500
|
| 246 |
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
def api_chat():
|
| 250 |
try:
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
if commands:
|
| 259 |
-
device_id = data.get("device_id") or "esp32_default"
|
| 260 |
-
DEVICE_COMMANDS.setdefault(device_id, []).extend(commands)
|
| 261 |
-
# synthesize
|
| 262 |
try:
|
| 263 |
-
|
| 264 |
-
audio_url = request.url_root.rstrip("/") + f"/tts-file/{mp3path.stem}"
|
| 265 |
except Exception as e:
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
|
|
|
|
|
|
|
|
|
| 269 |
except Exception as e:
|
| 270 |
-
|
| 271 |
return jsonify({"error": str(e)}), 500
|
| 272 |
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
break
|
| 281 |
-
if not target:
|
| 282 |
-
return abort(404)
|
| 283 |
-
return send_file(str(target), mimetype="audio/mpeg")
|
| 284 |
-
|
| 285 |
-
# sensor forwarding -> telegram
|
| 286 |
-
@app.route("/api/sensor", methods=["POST"])
|
| 287 |
-
def api_sensor():
|
| 288 |
try:
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
|
|
|
|
|
|
| 294 |
try:
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
|
|
|
|
|
|
|
|
|
| 300 |
except Exception as e:
|
|
|
|
| 301 |
return jsonify({"error": str(e)}), 500
|
| 302 |
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 306 |
try:
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 316 |
except Exception as e:
|
|
|
|
| 317 |
return jsonify({"error": str(e)}), 500
|
| 318 |
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
def device_commands_get():
|
| 322 |
-
device_id = request.args.get("device_id", "esp32_default")
|
| 323 |
-
cmds = DEVICE_COMMANDS.get(device_id, [])
|
| 324 |
-
# return and clear queue
|
| 325 |
-
DEVICE_COMMANDS[device_id] = []
|
| 326 |
-
return jsonify({"commands": cmds})
|
| 327 |
-
|
| 328 |
-
# simple admin endpoint to add a command to device queue (for testing)
|
| 329 |
-
@app.route("/device/commands", methods=["POST"])
|
| 330 |
-
def device_commands_post():
|
| 331 |
-
data = request.get_json(force=True, silent=True) or {}
|
| 332 |
-
device_id = data.get("device_id", "esp32_default")
|
| 333 |
-
cmd = data.get("command")
|
| 334 |
-
if not cmd:
|
| 335 |
-
return jsonify({"error":"missing command"}), 400
|
| 336 |
-
DEVICE_COMMANDS.setdefault(device_id, []).append(cmd)
|
| 337 |
-
return jsonify({"status":"queued", "device_id": device_id, "command": cmd})
|
| 338 |
-
|
| 339 |
-
# utility: parse relay commands from text (basic heuristic)
|
| 340 |
-
def parse_relay_commands(text: str):
|
| 341 |
"""
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
- 'turn on relay 1', 'turn off relay2'
|
| 346 |
"""
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
ttl = int(data.get("ttl", 3600))
|
| 386 |
-
now = __import__('time').time()
|
| 387 |
-
removed = 0
|
| 388 |
-
for f in TMP_DIR.iterdir():
|
| 389 |
-
try:
|
| 390 |
-
if f.is_file() and (f.stat().st_mtime + ttl) < now:
|
| 391 |
-
f.unlink()
|
| 392 |
-
removed += 1
|
| 393 |
-
except Exception:
|
| 394 |
-
pass
|
| 395 |
-
return {"removed": removed}
|
| 396 |
|
|
|
|
| 397 |
if __name__ == "__main__":
|
|
|
|
|
|
|
| 398 |
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 |
|
|
|
|
| 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()
|
| 333 |
+
try:
|
| 334 |
+
ans = hf_text_generate(q)
|
| 335 |
+
except Exception as e:
|
| 336 |
+
ans = f"[HF error] {e}"
|
| 337 |
+
try:
|
| 338 |
+
requests.post(base + "/sendMessage", json={"chat_id": chat_id, "text": ans}, timeout=10)
|
| 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:
|
| 354 |
+
try:
|
| 355 |
+
requests.post(base + "/sendMessage", json={"chat_id": chat_id, "text": "Commands: /ask <q> | /say <text> | /status"}, timeout=10)
|
| 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,'&').replace(/</g,'<').replace(/>/g,'>'); }
|
| 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)
|