Spaces:
Sleeping
Sleeping
Fix chat startup latency, personalize greeting, stabilize auto/hands-free flow
Browse files- app.py +465 -21
- static/js/script.js +135 -66
app.py
CHANGED
|
@@ -3,6 +3,7 @@ import os
|
|
| 3 |
import time
|
| 4 |
import json
|
| 5 |
import random
|
|
|
|
| 6 |
import tempfile
|
| 7 |
import requests as _http
|
| 8 |
from collections import defaultdict
|
|
@@ -54,6 +55,38 @@ START_TIME = time.time()
|
|
| 54 |
# --- Rate Limiter (in-memory) ---
|
| 55 |
rate_limits = defaultdict(list)
|
| 56 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
# --- In-memory leaderboard ---
|
| 58 |
_leaderboard: dict = {} # keyed by email (from JWT) or IP
|
| 59 |
|
|
@@ -78,9 +111,10 @@ def is_rate_limited(ip):
|
|
| 78 |
limit = app.config.get("RATE_LIMIT", 30)
|
| 79 |
rate_limits[ip] = [t for t in rate_limits[ip] if now - t < window]
|
| 80 |
if len(rate_limits[ip]) >= limit:
|
| 81 |
-
return True
|
| 82 |
rate_limits[ip].append(now)
|
| 83 |
-
|
|
|
|
| 84 |
|
| 85 |
|
| 86 |
# --- OpenAI Client Factory (supports Groq key rotation) ---
|
|
@@ -175,8 +209,7 @@ def build_system_prompt(
|
|
| 175 |
f"LANGUAGE: Speak in {lang_name}.\n"
|
| 176 |
f"DIFFICULTY: {level_config['label']} — {level_config['description']}.\n"
|
| 177 |
f"DO NOT use emoji symbols. Speak naturally. Keep responses concise (2-4 sentences).\n"
|
| 178 |
-
f"You MAY use **bold** for emphasis.\n"
|
| 179 |
-
+ extra
|
| 180 |
)
|
| 181 |
|
| 182 |
topic_config = next(
|
|
@@ -254,17 +287,22 @@ def health():
|
|
| 254 |
whisper_sdk_available = GROQ_AVAILABLE
|
| 255 |
whisper_keys_configured = bool(Config.GROQ_API_KEYS)
|
| 256 |
whisper_available = whisper_sdk_available and whisper_keys_configured
|
|
|
|
| 257 |
return (
|
| 258 |
jsonify(
|
| 259 |
{
|
| 260 |
"status": "ok",
|
| 261 |
"uptime_seconds": uptime,
|
|
|
|
| 262 |
"provider": Config.AI_PROVIDER,
|
| 263 |
"model": Config.MODEL_NAME,
|
| 264 |
-
"ai_available":
|
| 265 |
"whisper_available": whisper_available,
|
| 266 |
"whisper_sdk_available": whisper_sdk_available,
|
| 267 |
"whisper_keys_configured": whisper_keys_configured,
|
|
|
|
|
|
|
|
|
|
| 268 |
}
|
| 269 |
),
|
| 270 |
200,
|
|
@@ -295,6 +333,14 @@ def transcribe():
|
|
| 295 |
if not groq_client:
|
| 296 |
return jsonify({"error": "Whisper service unavailable"}), 503
|
| 297 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 298 |
if "audio" not in request.files:
|
| 299 |
return jsonify({"error": "No audio file provided"}), 400
|
| 300 |
|
|
@@ -343,19 +389,43 @@ def chat():
|
|
| 343 |
if not client:
|
| 344 |
return jsonify({"error": "AI service is currently unavailable."}), 503
|
| 345 |
|
| 346 |
-
|
| 347 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 348 |
|
| 349 |
data = request.json or {}
|
| 350 |
history = data.get("history", [])
|
| 351 |
-
level = data.get("level", "intermediate")
|
| 352 |
-
topic = data.get("topic", "free")
|
| 353 |
-
language = data.get("language", "en")
|
| 354 |
scenario = data.get("scenario", None)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 355 |
|
| 356 |
if not history:
|
| 357 |
return (
|
| 358 |
-
jsonify(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 359 |
200,
|
| 360 |
)
|
| 361 |
|
|
@@ -363,6 +433,19 @@ def chat():
|
|
| 363 |
level, Config.DIFFICULTY_LEVELS["intermediate"]
|
| 364 |
)
|
| 365 |
system_prompt = build_system_prompt(level, topic, language, scenario)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 366 |
messages_payload = [{"role": "system", "content": system_prompt}] + history
|
| 367 |
|
| 368 |
try:
|
|
@@ -374,7 +457,12 @@ def chat():
|
|
| 374 |
max_tokens=level_config["max_tokens"],
|
| 375 |
stream=False,
|
| 376 |
)
|
| 377 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 378 |
except Exception as e:
|
| 379 |
logging.error(f"Error calling API: {e}", exc_info=True)
|
| 380 |
return (
|
|
@@ -390,8 +478,11 @@ def chat_stream():
|
|
| 390 |
if not client:
|
| 391 |
return jsonify({"error": "AI service is currently unavailable."}), 503
|
| 392 |
|
| 393 |
-
|
| 394 |
-
|
|
|
|
|
|
|
|
|
|
| 395 |
|
| 396 |
data = request.json or {}
|
| 397 |
history = data.get("history", [])
|
|
@@ -399,9 +490,15 @@ def chat_stream():
|
|
| 399 |
topic = data.get("topic", "free")
|
| 400 |
language = data.get("language", "en")
|
| 401 |
scenario = data.get("scenario", None)
|
|
|
|
| 402 |
|
| 403 |
if not history:
|
| 404 |
-
welcome = get_welcome_message(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 405 |
|
| 406 |
def welcome_gen():
|
| 407 |
yield f"data: {json.dumps({'token': welcome})}\n\n"
|
|
@@ -559,10 +656,21 @@ def submit_leaderboard():
|
|
| 559 |
|
| 560 |
@app.route("/story/generate", methods=["POST"])
|
| 561 |
def generate_story():
|
|
|
|
|
|
|
|
|
|
|
|
|
| 562 |
data = request.json or {}
|
| 563 |
language = data.get("language", "en")
|
| 564 |
level = data.get("level", "intermediate")
|
| 565 |
topic = data.get("topic", "daily life")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 566 |
lang_names = {
|
| 567 |
"en": "English",
|
| 568 |
"fr": "French",
|
|
@@ -590,7 +698,7 @@ def generate_story():
|
|
| 590 |
f"No markdown, no extra text — only the JSON object."
|
| 591 |
)
|
| 592 |
try:
|
| 593 |
-
completion =
|
| 594 |
model=Config.MODEL_NAME,
|
| 595 |
messages=[{"role": "user", "content": prompt}],
|
| 596 |
temperature=0.75,
|
|
@@ -603,7 +711,11 @@ def generate_story():
|
|
| 603 |
raw = raw[4:]
|
| 604 |
raw = raw.strip("`").strip()
|
| 605 |
story_data = json.loads(raw)
|
|
|
|
| 606 |
return jsonify(story_data)
|
|
|
|
|
|
|
|
|
|
| 607 |
except Exception as e:
|
| 608 |
logging.error(f"Story generation error: {e}")
|
| 609 |
return jsonify({"error": "Could not generate story"}), 500
|
|
@@ -634,7 +746,9 @@ def get_story_image():
|
|
| 634 |
if r.ok:
|
| 635 |
photos = r.json()
|
| 636 |
if isinstance(photos, list) and photos:
|
| 637 |
-
return jsonify(
|
|
|
|
|
|
|
| 638 |
except Exception as e:
|
| 639 |
logging.warning(f"Unsplash image fetch failed: {e}")
|
| 640 |
|
|
@@ -650,7 +764,9 @@ def get_story_image():
|
|
| 650 |
if r.ok:
|
| 651 |
d = r.json()
|
| 652 |
if d.get("photos"):
|
| 653 |
-
return jsonify(
|
|
|
|
|
|
|
| 654 |
except Exception as e:
|
| 655 |
logging.warning(f"Pexels image fetch failed: {e}")
|
| 656 |
|
|
@@ -658,25 +774,353 @@ def get_story_image():
|
|
| 658 |
return jsonify({"url": None, "source": "pollinations"})
|
| 659 |
|
| 660 |
|
| 661 |
-
def get_welcome_message(topic="free", language="en", scenario=None):
|
| 662 |
lang_config = Config.LANGUAGES.get(language, Config.LANGUAGES["en"])
|
|
|
|
|
|
|
| 663 |
|
| 664 |
if scenario:
|
| 665 |
scenario_config = next(
|
| 666 |
(s for s in Config.SCENARIOS if s["id"] == scenario), None
|
| 667 |
)
|
| 668 |
if scenario_config:
|
| 669 |
-
|
|
|
|
|
|
|
|
|
|
| 670 |
|
| 671 |
if topic == "free":
|
| 672 |
-
|
|
|
|
|
|
|
|
|
|
| 673 |
|
| 674 |
topic_config = next(
|
| 675 |
(t for t in Config.TOPICS if t["id"] == topic), Config.TOPICS[0]
|
| 676 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 677 |
return f"{lang_config['welcome']} {topic_config['prompt']} Ready to start?"
|
| 678 |
|
| 679 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 680 |
if __name__ == "__main__":
|
| 681 |
port = int(os.environ.get("PORT", 7860))
|
| 682 |
app.run(host="0.0.0.0", port=port, debug=Config.FLASK_DEBUG)
|
|
|
|
| 3 |
import time
|
| 4 |
import json
|
| 5 |
import random
|
| 6 |
+
import hashlib
|
| 7 |
import tempfile
|
| 8 |
import requests as _http
|
| 9 |
from collections import defaultdict
|
|
|
|
| 55 |
# --- Rate Limiter (in-memory) ---
|
| 56 |
rate_limits = defaultdict(list)
|
| 57 |
|
| 58 |
+
# --- In-memory response cache (TTL-based) ---
|
| 59 |
+
_response_cache: dict = {} # key -> {"response": ..., "expires_at": float}
|
| 60 |
+
CACHE_TTL_SECONDS = 300 # 5 minutes
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _cache_key(*parts: str) -> str:
|
| 64 |
+
"""Create a deterministic cache key from multiple parts."""
|
| 65 |
+
raw = "|".join(str(p) for p in parts)
|
| 66 |
+
return hashlib.md5(raw.encode()).hexdigest()
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _cache_get(key: str):
|
| 70 |
+
"""Return cached value or None if missing/expired."""
|
| 71 |
+
entry = _response_cache.get(key)
|
| 72 |
+
if entry and entry["expires_at"] > time.time():
|
| 73 |
+
return entry["value"]
|
| 74 |
+
if key in _response_cache:
|
| 75 |
+
del _response_cache[key]
|
| 76 |
+
return None
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _cache_set(key: str, value, ttl: int = CACHE_TTL_SECONDS):
|
| 80 |
+
"""Store value in cache with TTL."""
|
| 81 |
+
# Prune old entries if cache is getting large
|
| 82 |
+
if len(_response_cache) > 500:
|
| 83 |
+
now = time.time()
|
| 84 |
+
expired = [k for k, v in _response_cache.items() if v["expires_at"] <= now]
|
| 85 |
+
for k in expired:
|
| 86 |
+
del _response_cache[k]
|
| 87 |
+
_response_cache[key] = {"value": value, "expires_at": time.time() + ttl}
|
| 88 |
+
|
| 89 |
+
|
| 90 |
# --- In-memory leaderboard ---
|
| 91 |
_leaderboard: dict = {} # keyed by email (from JWT) or IP
|
| 92 |
|
|
|
|
| 111 |
limit = app.config.get("RATE_LIMIT", 30)
|
| 112 |
rate_limits[ip] = [t for t in rate_limits[ip] if now - t < window]
|
| 113 |
if len(rate_limits[ip]) >= limit:
|
| 114 |
+
return True, limit, 0
|
| 115 |
rate_limits[ip].append(now)
|
| 116 |
+
remaining = limit - len(rate_limits[ip])
|
| 117 |
+
return False, limit, remaining
|
| 118 |
|
| 119 |
|
| 120 |
# --- OpenAI Client Factory (supports Groq key rotation) ---
|
|
|
|
| 209 |
f"LANGUAGE: Speak in {lang_name}.\n"
|
| 210 |
f"DIFFICULTY: {level_config['label']} — {level_config['description']}.\n"
|
| 211 |
f"DO NOT use emoji symbols. Speak naturally. Keep responses concise (2-4 sentences).\n"
|
| 212 |
+
f"You MAY use **bold** for emphasis.\n" + extra
|
|
|
|
| 213 |
)
|
| 214 |
|
| 215 |
topic_config = next(
|
|
|
|
| 287 |
whisper_sdk_available = GROQ_AVAILABLE
|
| 288 |
whisper_keys_configured = bool(Config.GROQ_API_KEYS)
|
| 289 |
whisper_available = whisper_sdk_available and whisper_keys_configured
|
| 290 |
+
ai_client = get_client()
|
| 291 |
return (
|
| 292 |
jsonify(
|
| 293 |
{
|
| 294 |
"status": "ok",
|
| 295 |
"uptime_seconds": uptime,
|
| 296 |
+
"uptime_human": f"{uptime // 3600}h {(uptime % 3600) // 60}m",
|
| 297 |
"provider": Config.AI_PROVIDER,
|
| 298 |
"model": Config.MODEL_NAME,
|
| 299 |
+
"ai_available": ai_client is not None,
|
| 300 |
"whisper_available": whisper_available,
|
| 301 |
"whisper_sdk_available": whisper_sdk_available,
|
| 302 |
"whisper_keys_configured": whisper_keys_configured,
|
| 303 |
+
"cache_entries": len(_response_cache),
|
| 304 |
+
"leaderboard_entries": len(_leaderboard),
|
| 305 |
+
"version": "2.2.0",
|
| 306 |
}
|
| 307 |
),
|
| 308 |
200,
|
|
|
|
| 333 |
if not groq_client:
|
| 334 |
return jsonify({"error": "Whisper service unavailable"}), 503
|
| 335 |
|
| 336 |
+
limited, limit, remaining = is_rate_limited(get_client_ip())
|
| 337 |
+
if limited:
|
| 338 |
+
resp = jsonify({"error": "Too many requests. Please slow down."})
|
| 339 |
+
resp.headers["X-RateLimit-Limit"] = str(limit)
|
| 340 |
+
resp.headers["X-RateLimit-Remaining"] = "0"
|
| 341 |
+
resp.headers["Retry-After"] = "60"
|
| 342 |
+
return resp, 429
|
| 343 |
+
|
| 344 |
if "audio" not in request.files:
|
| 345 |
return jsonify({"error": "No audio file provided"}), 400
|
| 346 |
|
|
|
|
| 389 |
if not client:
|
| 390 |
return jsonify({"error": "AI service is currently unavailable."}), 503
|
| 391 |
|
| 392 |
+
limited, limit, remaining = is_rate_limited(get_client_ip())
|
| 393 |
+
if limited:
|
| 394 |
+
resp = jsonify({"error": "Too many requests. Please slow down."})
|
| 395 |
+
resp.headers["X-RateLimit-Limit"] = str(limit)
|
| 396 |
+
resp.headers["X-RateLimit-Remaining"] = "0"
|
| 397 |
+
resp.headers["Retry-After"] = "60"
|
| 398 |
+
return resp, 429
|
| 399 |
|
| 400 |
data = request.json or {}
|
| 401 |
history = data.get("history", [])
|
| 402 |
+
level = str(data.get("level", "intermediate"))[:20]
|
| 403 |
+
topic = str(data.get("topic", "free"))[:50]
|
| 404 |
+
language = str(data.get("language", "en"))[:5]
|
| 405 |
scenario = data.get("scenario", None)
|
| 406 |
+
user_name = str(data.get("user_name", "") or "").strip()[:60]
|
| 407 |
+
|
| 408 |
+
# Input validation & sanitization
|
| 409 |
+
if not isinstance(history, list):
|
| 410 |
+
return jsonify({"error": "Invalid history format"}), 400
|
| 411 |
+
if len(history) > 100:
|
| 412 |
+
history = history[-100:] # Prevent context flooding
|
| 413 |
+
for msg in history:
|
| 414 |
+
if isinstance(msg, dict) and len(str(msg.get("content", ""))) > 4000:
|
| 415 |
+
msg["content"] = str(msg["content"])[:4000]
|
| 416 |
|
| 417 |
if not history:
|
| 418 |
return (
|
| 419 |
+
jsonify(
|
| 420 |
+
{
|
| 421 |
+
"response": get_welcome_message(
|
| 422 |
+
topic,
|
| 423 |
+
language,
|
| 424 |
+
scenario,
|
| 425 |
+
user_name=user_name,
|
| 426 |
+
)
|
| 427 |
+
}
|
| 428 |
+
),
|
| 429 |
200,
|
| 430 |
)
|
| 431 |
|
|
|
|
| 433 |
level, Config.DIFFICULTY_LEVELS["intermediate"]
|
| 434 |
)
|
| 435 |
system_prompt = build_system_prompt(level, topic, language, scenario)
|
| 436 |
+
|
| 437 |
+
# Check cache for identical conversation state
|
| 438 |
+
last_user_msg = next(
|
| 439 |
+
(m["content"] for m in reversed(history) if m.get("role") == "user"), ""
|
| 440 |
+
)
|
| 441 |
+
cache_key = _cache_key(last_user_msg, level, topic, language, scenario or "")
|
| 442 |
+
cached = _cache_get(cache_key)
|
| 443 |
+
if cached:
|
| 444 |
+
resp = jsonify({"response": cached})
|
| 445 |
+
resp.headers["X-Cache"] = "HIT"
|
| 446 |
+
resp.headers["X-RateLimit-Remaining"] = str(remaining)
|
| 447 |
+
return resp
|
| 448 |
+
|
| 449 |
messages_payload = [{"role": "system", "content": system_prompt}] + history
|
| 450 |
|
| 451 |
try:
|
|
|
|
| 457 |
max_tokens=level_config["max_tokens"],
|
| 458 |
stream=False,
|
| 459 |
)
|
| 460 |
+
reply = completion.choices[0].message.content
|
| 461 |
+
_cache_set(cache_key, reply)
|
| 462 |
+
resp = jsonify({"response": reply})
|
| 463 |
+
resp.headers["X-Cache"] = "MISS"
|
| 464 |
+
resp.headers["X-RateLimit-Remaining"] = str(remaining)
|
| 465 |
+
return resp
|
| 466 |
except Exception as e:
|
| 467 |
logging.error(f"Error calling API: {e}", exc_info=True)
|
| 468 |
return (
|
|
|
|
| 478 |
if not client:
|
| 479 |
return jsonify({"error": "AI service is currently unavailable."}), 503
|
| 480 |
|
| 481 |
+
limited, limit, remaining = is_rate_limited(get_client_ip())
|
| 482 |
+
if limited:
|
| 483 |
+
resp = jsonify({"error": "Too many requests. Please slow down."})
|
| 484 |
+
resp.headers["Retry-After"] = "60"
|
| 485 |
+
return resp, 429
|
| 486 |
|
| 487 |
data = request.json or {}
|
| 488 |
history = data.get("history", [])
|
|
|
|
| 490 |
topic = data.get("topic", "free")
|
| 491 |
language = data.get("language", "en")
|
| 492 |
scenario = data.get("scenario", None)
|
| 493 |
+
user_name = str(data.get("user_name", "") or "").strip()[:60]
|
| 494 |
|
| 495 |
if not history:
|
| 496 |
+
welcome = get_welcome_message(
|
| 497 |
+
topic,
|
| 498 |
+
language,
|
| 499 |
+
scenario,
|
| 500 |
+
user_name=user_name,
|
| 501 |
+
)
|
| 502 |
|
| 503 |
def welcome_gen():
|
| 504 |
yield f"data: {json.dumps({'token': welcome})}\n\n"
|
|
|
|
| 656 |
|
| 657 |
@app.route("/story/generate", methods=["POST"])
|
| 658 |
def generate_story():
|
| 659 |
+
story_client = get_client()
|
| 660 |
+
if not story_client:
|
| 661 |
+
return jsonify({"error": "AI service unavailable"}), 503
|
| 662 |
+
|
| 663 |
data = request.json or {}
|
| 664 |
language = data.get("language", "en")
|
| 665 |
level = data.get("level", "intermediate")
|
| 666 |
topic = data.get("topic", "daily life")
|
| 667 |
+
|
| 668 |
+
# Check cache first
|
| 669 |
+
story_key = _cache_key("story", language, level, topic)
|
| 670 |
+
cached_story = _cache_get(story_key)
|
| 671 |
+
if cached_story:
|
| 672 |
+
return jsonify(cached_story)
|
| 673 |
+
|
| 674 |
lang_names = {
|
| 675 |
"en": "English",
|
| 676 |
"fr": "French",
|
|
|
|
| 698 |
f"No markdown, no extra text — only the JSON object."
|
| 699 |
)
|
| 700 |
try:
|
| 701 |
+
completion = story_client.chat.completions.create(
|
| 702 |
model=Config.MODEL_NAME,
|
| 703 |
messages=[{"role": "user", "content": prompt}],
|
| 704 |
temperature=0.75,
|
|
|
|
| 711 |
raw = raw[4:]
|
| 712 |
raw = raw.strip("`").strip()
|
| 713 |
story_data = json.loads(raw)
|
| 714 |
+
_cache_set(story_key, story_data, ttl=600) # cache stories for 10 min
|
| 715 |
return jsonify(story_data)
|
| 716 |
+
except json.JSONDecodeError as e:
|
| 717 |
+
logging.error(f"Story JSON parse error: {e} | raw: {raw[:200]}")
|
| 718 |
+
return jsonify({"error": "Story format error. Please try again."}), 500
|
| 719 |
except Exception as e:
|
| 720 |
logging.error(f"Story generation error: {e}")
|
| 721 |
return jsonify({"error": "Could not generate story"}), 500
|
|
|
|
| 746 |
if r.ok:
|
| 747 |
photos = r.json()
|
| 748 |
if isinstance(photos, list) and photos:
|
| 749 |
+
return jsonify(
|
| 750 |
+
{"url": photos[0]["urls"]["regular"], "source": "unsplash"}
|
| 751 |
+
)
|
| 752 |
except Exception as e:
|
| 753 |
logging.warning(f"Unsplash image fetch failed: {e}")
|
| 754 |
|
|
|
|
| 764 |
if r.ok:
|
| 765 |
d = r.json()
|
| 766 |
if d.get("photos"):
|
| 767 |
+
return jsonify(
|
| 768 |
+
{"url": d["photos"][0]["src"]["large"], "source": "pexels"}
|
| 769 |
+
)
|
| 770 |
except Exception as e:
|
| 771 |
logging.warning(f"Pexels image fetch failed: {e}")
|
| 772 |
|
|
|
|
| 774 |
return jsonify({"url": None, "source": "pollinations"})
|
| 775 |
|
| 776 |
|
| 777 |
+
def get_welcome_message(topic="free", language="en", scenario=None, user_name=""):
|
| 778 |
lang_config = Config.LANGUAGES.get(language, Config.LANGUAGES["en"])
|
| 779 |
+
safe_name = str(user_name or "").strip()[:40]
|
| 780 |
+
first_name = safe_name.split()[0] if safe_name else ""
|
| 781 |
|
| 782 |
if scenario:
|
| 783 |
scenario_config = next(
|
| 784 |
(s for s in Config.SCENARIOS if s["id"] == scenario), None
|
| 785 |
)
|
| 786 |
if scenario_config:
|
| 787 |
+
opening = scenario_config["opening"]
|
| 788 |
+
if first_name:
|
| 789 |
+
return f"{opening} {first_name}, let's begin."
|
| 790 |
+
return opening
|
| 791 |
|
| 792 |
if topic == "free":
|
| 793 |
+
welcome = lang_config["welcome"]
|
| 794 |
+
if first_name:
|
| 795 |
+
return f"{welcome} Nice to meet you, {first_name}."
|
| 796 |
+
return welcome
|
| 797 |
|
| 798 |
topic_config = next(
|
| 799 |
(t for t in Config.TOPICS if t["id"] == topic), Config.TOPICS[0]
|
| 800 |
)
|
| 801 |
+
if first_name:
|
| 802 |
+
return (
|
| 803 |
+
f"{lang_config['welcome']} {topic_config['prompt']} "
|
| 804 |
+
f"Ready to start, {first_name}?"
|
| 805 |
+
)
|
| 806 |
return f"{lang_config['welcome']} {topic_config['prompt']} Ready to start?"
|
| 807 |
|
| 808 |
|
| 809 |
+
@app.route("/api/status")
|
| 810 |
+
def api_status():
|
| 811 |
+
"""Detailed status endpoint for monitoring and debugging."""
|
| 812 |
+
now = time.time()
|
| 813 |
+
uptime = int(now - START_TIME)
|
| 814 |
+
active_ips = len(rate_limits)
|
| 815 |
+
cache_live = sum(1 for v in _response_cache.values() if v["expires_at"] > now)
|
| 816 |
+
return jsonify(
|
| 817 |
+
{
|
| 818 |
+
"status": "operational",
|
| 819 |
+
"version": "2.2.0",
|
| 820 |
+
"uptime_seconds": uptime,
|
| 821 |
+
"uptime_human": f"{uptime // 3600}h {(uptime % 3600) // 60}m {uptime % 60}s",
|
| 822 |
+
"ai_provider": Config.AI_PROVIDER,
|
| 823 |
+
"model": Config.MODEL_NAME,
|
| 824 |
+
"ai_available": get_client() is not None,
|
| 825 |
+
"whisper_available": GROQ_AVAILABLE and bool(Config.GROQ_API_KEYS),
|
| 826 |
+
"cache": {
|
| 827 |
+
"total_entries": len(_response_cache),
|
| 828 |
+
"live_entries": cache_live,
|
| 829 |
+
"ttl_seconds": CACHE_TTL_SECONDS,
|
| 830 |
+
},
|
| 831 |
+
"rate_limiter": {
|
| 832 |
+
"tracked_ips": active_ips,
|
| 833 |
+
"limit_per_minute": app.config.get("RATE_LIMIT", 30),
|
| 834 |
+
},
|
| 835 |
+
"leaderboard_entries": len(_leaderboard),
|
| 836 |
+
}
|
| 837 |
+
)
|
| 838 |
+
|
| 839 |
+
|
| 840 |
+
# ─── Vocabulary Suggestion Endpoint ───
|
| 841 |
+
@app.route("/vocab/suggest", methods=["POST"])
|
| 842 |
+
def vocab_suggest():
|
| 843 |
+
"""AI-powered vocabulary suggestions based on topic, level, and language."""
|
| 844 |
+
client = get_client()
|
| 845 |
+
if not client:
|
| 846 |
+
return jsonify({"error": "AI service unavailable"}), 503
|
| 847 |
+
|
| 848 |
+
limited, _, _ = is_rate_limited(get_client_ip())
|
| 849 |
+
if limited:
|
| 850 |
+
return jsonify({"error": "Too many requests. Please slow down."}), 429
|
| 851 |
+
|
| 852 |
+
data = request.json or {}
|
| 853 |
+
topic = str(data.get("topic", "daily life"))[:100]
|
| 854 |
+
level = str(data.get("level", "intermediate"))
|
| 855 |
+
language = str(data.get("language", "en"))[:5]
|
| 856 |
+
count = min(int(data.get("count", 8)), 15)
|
| 857 |
+
|
| 858 |
+
lang_names = {
|
| 859 |
+
"en": "English",
|
| 860 |
+
"fr": "French",
|
| 861 |
+
"es": "Spanish",
|
| 862 |
+
"de": "German",
|
| 863 |
+
"ar": "Arabic",
|
| 864 |
+
"it": "Italian",
|
| 865 |
+
}
|
| 866 |
+
lang_name = lang_names.get(language, "English")
|
| 867 |
+
|
| 868 |
+
cache_key = _cache_key("vocab_suggest", topic, level, language, str(count))
|
| 869 |
+
cached = _cache_get(cache_key)
|
| 870 |
+
if cached:
|
| 871 |
+
resp = jsonify(cached)
|
| 872 |
+
resp.headers["X-Cache"] = "HIT"
|
| 873 |
+
return resp
|
| 874 |
+
|
| 875 |
+
prompt = (
|
| 876 |
+
f"Generate {count} useful {lang_name} vocabulary words for a {level} learner studying '{topic}'.\n"
|
| 877 |
+
f"Return ONLY a valid JSON array. Each item must have:\n"
|
| 878 |
+
f' "word": the word in {lang_name}\n'
|
| 879 |
+
f' "translation": English translation\n'
|
| 880 |
+
f' "example": short natural sentence using the word in {lang_name}\n'
|
| 881 |
+
f' "tip": one memory tip or usage note (in English)\n'
|
| 882 |
+
f"No markdown, no extra text — only the JSON array."
|
| 883 |
+
)
|
| 884 |
+
|
| 885 |
+
try:
|
| 886 |
+
completion = client.chat.completions.create(
|
| 887 |
+
model=Config.MODEL_NAME,
|
| 888 |
+
messages=[{"role": "user", "content": prompt}],
|
| 889 |
+
temperature=0.5,
|
| 890 |
+
max_tokens=900,
|
| 891 |
+
)
|
| 892 |
+
raw = completion.choices[0].message.content.strip()
|
| 893 |
+
if raw.startswith("```"):
|
| 894 |
+
raw = raw.split("```")[1]
|
| 895 |
+
if raw.startswith("json"):
|
| 896 |
+
raw = raw[4:]
|
| 897 |
+
raw = raw.strip("`").strip()
|
| 898 |
+
words = json.loads(raw)
|
| 899 |
+
result = {"words": words, "topic": topic, "level": level, "language": language}
|
| 900 |
+
_cache_set(cache_key, result, ttl=600)
|
| 901 |
+
return jsonify(result)
|
| 902 |
+
except json.JSONDecodeError as e:
|
| 903 |
+
logging.error(f"Vocab suggest JSON parse error: {e}")
|
| 904 |
+
return jsonify({"error": "Could not parse vocabulary. Try again."}), 500
|
| 905 |
+
except Exception as e:
|
| 906 |
+
logging.error(f"Vocab suggest error: {e}")
|
| 907 |
+
return jsonify({"error": "Could not generate vocabulary."}), 500
|
| 908 |
+
|
| 909 |
+
|
| 910 |
+
# ─── Grammar Check Endpoint ───
|
| 911 |
+
@app.route("/grammar/check", methods=["POST"])
|
| 912 |
+
def grammar_check():
|
| 913 |
+
"""Check a sentence or paragraph for grammar errors and return corrections."""
|
| 914 |
+
client = get_client()
|
| 915 |
+
if not client:
|
| 916 |
+
return jsonify({"error": "AI service unavailable"}), 503
|
| 917 |
+
|
| 918 |
+
limited, _, _ = is_rate_limited(get_client_ip())
|
| 919 |
+
if limited:
|
| 920 |
+
return jsonify({"error": "Too many requests. Please slow down."}), 429
|
| 921 |
+
|
| 922 |
+
data = request.json or {}
|
| 923 |
+
text = str(data.get("text", "")).strip()
|
| 924 |
+
language = str(data.get("language", "en"))[:5]
|
| 925 |
+
|
| 926 |
+
if not text:
|
| 927 |
+
return jsonify({"error": "No text provided"}), 400
|
| 928 |
+
if len(text) > 1000:
|
| 929 |
+
return jsonify({"error": "Text too long (max 1000 characters)"}), 400
|
| 930 |
+
|
| 931 |
+
lang_names = {
|
| 932 |
+
"en": "English",
|
| 933 |
+
"fr": "French",
|
| 934 |
+
"es": "Spanish",
|
| 935 |
+
"de": "German",
|
| 936 |
+
"ar": "Arabic",
|
| 937 |
+
"it": "Italian",
|
| 938 |
+
}
|
| 939 |
+
lang_name = lang_names.get(language, "English")
|
| 940 |
+
|
| 941 |
+
cache_key = _cache_key("grammar", text[:200], language)
|
| 942 |
+
cached = _cache_get(cache_key)
|
| 943 |
+
if cached:
|
| 944 |
+
resp = jsonify(cached)
|
| 945 |
+
resp.headers["X-Cache"] = "HIT"
|
| 946 |
+
return resp
|
| 947 |
+
|
| 948 |
+
prompt = (
|
| 949 |
+
f"You are a {lang_name} grammar expert. Analyze this text and return a grammar check report.\n\n"
|
| 950 |
+
f'Text: "{text}"\n\n'
|
| 951 |
+
f"Return ONLY valid JSON with these fields:\n"
|
| 952 |
+
f' "is_correct": boolean\n'
|
| 953 |
+
f' "corrected": the fully corrected version (same as input if no errors)\n'
|
| 954 |
+
f' "errors": array of {{"original": str, "corrected": str, "explanation": str}}\n'
|
| 955 |
+
f' "score": integer 1-10 (grammar quality)\n'
|
| 956 |
+
f' "tip": one concise improvement tip\n'
|
| 957 |
+
f"No markdown, no extra text."
|
| 958 |
+
)
|
| 959 |
+
|
| 960 |
+
try:
|
| 961 |
+
completion = client.chat.completions.create(
|
| 962 |
+
model=Config.MODEL_NAME,
|
| 963 |
+
messages=[{"role": "user", "content": prompt}],
|
| 964 |
+
temperature=0.1,
|
| 965 |
+
max_tokens=600,
|
| 966 |
+
)
|
| 967 |
+
raw = completion.choices[0].message.content.strip()
|
| 968 |
+
if raw.startswith("```"):
|
| 969 |
+
raw = raw.split("```")[1]
|
| 970 |
+
if raw.startswith("json"):
|
| 971 |
+
raw = raw[4:]
|
| 972 |
+
raw = raw.strip("`").strip()
|
| 973 |
+
result = json.loads(raw)
|
| 974 |
+
_cache_set(cache_key, result, ttl=300)
|
| 975 |
+
return jsonify(result)
|
| 976 |
+
except json.JSONDecodeError as e:
|
| 977 |
+
logging.error(f"Grammar check JSON parse error: {e}")
|
| 978 |
+
return jsonify({"error": "Could not parse grammar check response."}), 500
|
| 979 |
+
except Exception as e:
|
| 980 |
+
logging.error(f"Grammar check error: {e}")
|
| 981 |
+
return jsonify({"error": "Grammar check failed. Try again."}), 500
|
| 982 |
+
|
| 983 |
+
|
| 984 |
+
# ─── Pronunciation Tip Endpoint ───
|
| 985 |
+
@app.route("/pronunciation/tip", methods=["POST"])
|
| 986 |
+
def pronunciation_tip():
|
| 987 |
+
"""Get pronunciation tips for a word or phrase."""
|
| 988 |
+
client = get_client()
|
| 989 |
+
if not client:
|
| 990 |
+
return jsonify({"error": "AI service unavailable"}), 503
|
| 991 |
+
|
| 992 |
+
limited, _, _ = is_rate_limited(get_client_ip())
|
| 993 |
+
if limited:
|
| 994 |
+
return jsonify({"error": "Too many requests."}), 429
|
| 995 |
+
|
| 996 |
+
data = request.json or {}
|
| 997 |
+
word = str(data.get("word", "")).strip()[:100]
|
| 998 |
+
language = str(data.get("language", "en"))[:5]
|
| 999 |
+
|
| 1000 |
+
if not word:
|
| 1001 |
+
return jsonify({"error": "No word provided"}), 400
|
| 1002 |
+
|
| 1003 |
+
cache_key = _cache_key("pron_tip", word.lower(), language)
|
| 1004 |
+
cached = _cache_get(cache_key)
|
| 1005 |
+
if cached:
|
| 1006 |
+
resp = jsonify(cached)
|
| 1007 |
+
resp.headers["X-Cache"] = "HIT"
|
| 1008 |
+
return resp
|
| 1009 |
+
|
| 1010 |
+
lang_names = {
|
| 1011 |
+
"en": "English",
|
| 1012 |
+
"fr": "French",
|
| 1013 |
+
"es": "Spanish",
|
| 1014 |
+
"de": "German",
|
| 1015 |
+
"ar": "Arabic",
|
| 1016 |
+
"it": "Italian",
|
| 1017 |
+
}
|
| 1018 |
+
lang_name = lang_names.get(language, "English")
|
| 1019 |
+
|
| 1020 |
+
prompt = (
|
| 1021 |
+
f'Give a pronunciation guide for the {lang_name} word or phrase: "{word}".\n'
|
| 1022 |
+
f"Return ONLY valid JSON:\n"
|
| 1023 |
+
f' "word": the word\n'
|
| 1024 |
+
f' "ipa": IPA phonetic transcription\n'
|
| 1025 |
+
f' "phonetic": simple phonetic spelling (e.g. SEE-ren-DIP-ih-tee)\n'
|
| 1026 |
+
f' "tips": array of 2-3 short tips for native English speakers to pronounce it correctly\n'
|
| 1027 |
+
f' "similar_sound": an English word that has a similar sound (if applicable)\n'
|
| 1028 |
+
f"No markdown, no extra text."
|
| 1029 |
+
)
|
| 1030 |
+
|
| 1031 |
+
try:
|
| 1032 |
+
completion = client.chat.completions.create(
|
| 1033 |
+
model=Config.MODEL_NAME,
|
| 1034 |
+
messages=[{"role": "user", "content": prompt}],
|
| 1035 |
+
temperature=0.2,
|
| 1036 |
+
max_tokens=400,
|
| 1037 |
+
)
|
| 1038 |
+
raw = completion.choices[0].message.content.strip()
|
| 1039 |
+
if raw.startswith("```"):
|
| 1040 |
+
raw = raw.split("```")[1]
|
| 1041 |
+
if raw.startswith("json"):
|
| 1042 |
+
raw = raw[4:]
|
| 1043 |
+
raw = raw.strip("`").strip()
|
| 1044 |
+
result = json.loads(raw)
|
| 1045 |
+
_cache_set(cache_key, result, ttl=3600) # cache 1 hour
|
| 1046 |
+
return jsonify(result)
|
| 1047 |
+
except Exception as e:
|
| 1048 |
+
logging.error(f"Pronunciation tip error: {e}")
|
| 1049 |
+
return jsonify({"error": "Could not generate pronunciation tip."}), 500
|
| 1050 |
+
|
| 1051 |
+
|
| 1052 |
+
# ─── Daily Challenge Endpoint ───
|
| 1053 |
+
@app.route("/challenge/daily", methods=["GET"])
|
| 1054 |
+
def daily_challenge():
|
| 1055 |
+
"""Return a daily language challenge based on level and language."""
|
| 1056 |
+
level = request.args.get("level", "intermediate")
|
| 1057 |
+
language = request.args.get("language", "en")
|
| 1058 |
+
|
| 1059 |
+
client = get_client()
|
| 1060 |
+
if not client:
|
| 1061 |
+
return jsonify({"error": "AI service unavailable"}), 503
|
| 1062 |
+
|
| 1063 |
+
# Use date as seed for consistent daily challenge
|
| 1064 |
+
today = time.strftime("%Y-%m-%d")
|
| 1065 |
+
cache_key = _cache_key("daily_challenge", today, level, language)
|
| 1066 |
+
cached = _cache_get(cache_key)
|
| 1067 |
+
if cached:
|
| 1068 |
+
resp = jsonify(cached)
|
| 1069 |
+
resp.headers["X-Cache"] = "HIT"
|
| 1070 |
+
return resp
|
| 1071 |
+
|
| 1072 |
+
lang_names = {
|
| 1073 |
+
"en": "English",
|
| 1074 |
+
"fr": "French",
|
| 1075 |
+
"es": "Spanish",
|
| 1076 |
+
"de": "German",
|
| 1077 |
+
"ar": "Arabic",
|
| 1078 |
+
"it": "Italian",
|
| 1079 |
+
}
|
| 1080 |
+
lang_name = lang_names.get(language, "English")
|
| 1081 |
+
|
| 1082 |
+
prompt = (
|
| 1083 |
+
f"Create a short daily language challenge for a {level} {lang_name} learner.\n"
|
| 1084 |
+
f"Return ONLY valid JSON:\n"
|
| 1085 |
+
f' "title": short catchy title (max 6 words)\n'
|
| 1086 |
+
f' "description": what the learner should do (1-2 sentences)\n'
|
| 1087 |
+
f' "prompt": the exact conversation starter or task prompt to send to the AI tutor\n'
|
| 1088 |
+
f' "xp_reward": integer 15-50 based on difficulty\n'
|
| 1089 |
+
f' "category": one of ["speaking", "vocabulary", "grammar", "roleplay", "pronunciation"]\n'
|
| 1090 |
+
f"No markdown, no extra text."
|
| 1091 |
+
)
|
| 1092 |
+
|
| 1093 |
+
try:
|
| 1094 |
+
completion = client.chat.completions.create(
|
| 1095 |
+
model=Config.MODEL_NAME,
|
| 1096 |
+
messages=[{"role": "user", "content": prompt}],
|
| 1097 |
+
temperature=0.8,
|
| 1098 |
+
max_tokens=300,
|
| 1099 |
+
)
|
| 1100 |
+
raw = completion.choices[0].message.content.strip()
|
| 1101 |
+
if raw.startswith("```"):
|
| 1102 |
+
raw = raw.split("```")[1]
|
| 1103 |
+
if raw.startswith("json"):
|
| 1104 |
+
raw = raw[4:]
|
| 1105 |
+
raw = raw.strip("`").strip()
|
| 1106 |
+
result = json.loads(raw)
|
| 1107 |
+
result["date"] = today
|
| 1108 |
+
_cache_set(cache_key, result, ttl=86400) # cache 24 hours
|
| 1109 |
+
return jsonify(result)
|
| 1110 |
+
except Exception as e:
|
| 1111 |
+
logging.error(f"Daily challenge error: {e}")
|
| 1112 |
+
return jsonify(
|
| 1113 |
+
{
|
| 1114 |
+
"title": "Free Talk Practice",
|
| 1115 |
+
"description": "Have a natural conversation with your AI tutor.",
|
| 1116 |
+
"prompt": "Let's have a natural conversation. Tell me about your day.",
|
| 1117 |
+
"xp_reward": 20,
|
| 1118 |
+
"category": "speaking",
|
| 1119 |
+
"date": today,
|
| 1120 |
+
}
|
| 1121 |
+
)
|
| 1122 |
+
|
| 1123 |
+
|
| 1124 |
if __name__ == "__main__":
|
| 1125 |
port = int(os.environ.get("PORT", 7860))
|
| 1126 |
app.run(host="0.0.0.0", port=port, debug=Config.FLASK_DEBUG)
|
static/js/script.js
CHANGED
|
@@ -51,71 +51,74 @@ document.addEventListener('DOMContentLoaded', () => {
|
|
| 51 |
let isMuted = false;
|
| 52 |
let ended = false;
|
| 53 |
let turn = 'user';
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
// ─── UI TRANSLATIONS ───
|
| 56 |
const uiTranslations = {
|
| 57 |
en: {
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
},
|
| 81 |
ar: {
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
}
|
| 105 |
};
|
| 106 |
|
| 107 |
let currentUILang = localStorage.getItem('echo_ui_lang') || 'en';
|
| 108 |
|
| 109 |
-
window.setUILanguage = function(lang) {
|
| 110 |
currentUILang = lang;
|
| 111 |
localStorage.setItem('echo_ui_lang', lang);
|
| 112 |
document.documentElement.dir = lang === 'ar' ? 'rtl' : 'ltr';
|
| 113 |
document.documentElement.lang = lang;
|
| 114 |
-
|
| 115 |
const t = uiTranslations[lang];
|
| 116 |
if (!t) return;
|
| 117 |
|
| 118 |
-
document.querySelectorAll('[data-i18n]').forEach(el => {
|
| 119 |
const key = el.getAttribute('data-i18n');
|
| 120 |
if (t[key]) {
|
| 121 |
if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') {
|
|
@@ -125,7 +128,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|
| 125 |
}
|
| 126 |
}
|
| 127 |
});
|
| 128 |
-
|
| 129 |
// Update toggle button text
|
| 130 |
const toggleBtn = $('ui-lang-toggle');
|
| 131 |
if (toggleBtn) {
|
|
@@ -159,7 +162,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|
| 159 |
localStorage.setItem('echo_last_visit', today);
|
| 160 |
localStorage.setItem('echo_streak', streak);
|
| 161 |
}
|
| 162 |
-
|
| 163 |
const streakEl = $('streak-count');
|
| 164 |
if (streakEl) {
|
| 165 |
streakEl.innerHTML = `🔥 ${streak}`;
|
|
@@ -875,7 +878,11 @@ document.addEventListener('DOMContentLoaded', () => {
|
|
| 875 |
// Sync new words to flashcard deck (echo_vocab_deck)
|
| 876 |
if (window.echoSaveVocabWord) {
|
| 877 |
vocabWords.forEach((v) => {
|
| 878 |
-
window.echoSaveVocabWord(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 879 |
});
|
| 880 |
}
|
| 881 |
} catch (e) {}
|
|
@@ -1204,7 +1211,26 @@ document.addEventListener('DOMContentLoaded', () => {
|
|
| 1204 |
turn = 'user';
|
| 1205 |
updateStats();
|
| 1206 |
sessionTimer = setInterval(updateStats, 1000);
|
| 1207 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1208 |
}
|
| 1209 |
|
| 1210 |
function updateStats() {
|
|
@@ -1223,9 +1249,11 @@ document.addEventListener('DOMContentLoaded', () => {
|
|
| 1223 |
const avatarOrb = document.getElementById('avatar-orb');
|
| 1224 |
|
| 1225 |
// Setup character buttons
|
| 1226 |
-
document.querySelectorAll('.char-btn').forEach(btn => {
|
| 1227 |
btn.addEventListener('click', () => {
|
| 1228 |
-
document
|
|
|
|
|
|
|
| 1229 |
btn.classList.add('active');
|
| 1230 |
currentChar = btn.dataset.char;
|
| 1231 |
localStorage.setItem('echo_char', currentChar);
|
|
@@ -1234,9 +1262,13 @@ document.addEventListener('DOMContentLoaded', () => {
|
|
| 1234 |
});
|
| 1235 |
|
| 1236 |
// Apply saved character on load
|
| 1237 |
-
const savedCharBtn = document.querySelector(
|
|
|
|
|
|
|
| 1238 |
if (savedCharBtn) {
|
| 1239 |
-
document
|
|
|
|
|
|
|
| 1240 |
savedCharBtn.classList.add('active');
|
| 1241 |
}
|
| 1242 |
if (avatarOrb) applyCharacter(currentChar);
|
|
@@ -1248,7 +1280,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|
| 1248 |
// Hide orb face elements for non-orb characters
|
| 1249 |
const orbFace = avatarOrb.querySelector('.orb-face');
|
| 1250 |
if (orbFace) {
|
| 1251 |
-
orbFace.style.opacity =
|
| 1252 |
}
|
| 1253 |
}
|
| 1254 |
|
|
@@ -1272,8 +1304,37 @@ document.addEventListener('DOMContentLoaded', () => {
|
|
| 1272 |
thinking: t.thinking || 'Thinking...',
|
| 1273 |
happy: '✨',
|
| 1274 |
};
|
| 1275 |
-
stateLabel.textContent = labels[state] ||
|
| 1276 |
-
headerStatus.textContent = labels[state] ||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1277 |
}
|
| 1278 |
|
| 1279 |
// Eye blink
|
|
@@ -1433,7 +1494,8 @@ document.addEventListener('DOMContentLoaded', () => {
|
|
| 1433 |
if (!blob) {
|
| 1434 |
setAvatarState('idle');
|
| 1435 |
if (autoListen && !ended && turn === 'user') {
|
| 1436 |
-
|
|
|
|
| 1437 |
}
|
| 1438 |
return;
|
| 1439 |
}
|
|
@@ -1446,22 +1508,23 @@ document.addEventListener('DOMContentLoaded', () => {
|
|
| 1446 |
setAvatarState('idle');
|
| 1447 |
showToast(result?.error || 'Whisper transcription failed', 'error');
|
| 1448 |
if (autoListen && !ended && turn === 'user') {
|
| 1449 |
-
|
|
|
|
| 1450 |
}
|
| 1451 |
return;
|
| 1452 |
}
|
| 1453 |
const transcript = result?.text?.trim();
|
| 1454 |
if (!transcript) {
|
| 1455 |
setAvatarState('idle');
|
| 1456 |
-
// showToast('No speech detected', ''); // Too spammy for users
|
| 1457 |
if (autoListen && !ended && turn === 'user') {
|
| 1458 |
-
|
| 1459 |
-
|
| 1460 |
-
// Actually, better to just let the user tap again if silence
|
| 1461 |
}
|
| 1462 |
return;
|
| 1463 |
}
|
| 1464 |
|
|
|
|
|
|
|
| 1465 |
if (enforceGuestTrialLimit()) {
|
| 1466 |
setAvatarState('idle');
|
| 1467 |
return;
|
|
@@ -1487,6 +1550,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|
| 1487 |
recognition.onresult = (event) => {
|
| 1488 |
if (turn === 'user') {
|
| 1489 |
if (enforceGuestTrialLimit()) return;
|
|
|
|
| 1490 |
const result = event.results[0][0];
|
| 1491 |
const transcript = result.transcript;
|
| 1492 |
const confidence = result.confidence; // 0-1
|
|
@@ -1516,13 +1580,15 @@ document.addEventListener('DOMContentLoaded', () => {
|
|
| 1516 |
recognition.onend = () => {
|
| 1517 |
recognizing = false;
|
| 1518 |
micBtn.classList.remove('active');
|
| 1519 |
-
if (autoListen && !ended && turn === 'user')
|
| 1520 |
else if (turn === 'user') setAvatarState('idle');
|
| 1521 |
};
|
| 1522 |
|
| 1523 |
recognition.onerror = (event) => {
|
| 1524 |
recognizing = false;
|
| 1525 |
micBtn.classList.remove('active');
|
|
|
|
|
|
|
| 1526 |
if (event.error !== 'no-speech' && event.error !== 'aborted') {
|
| 1527 |
showToast('Mic error: ' + event.error, 'error');
|
| 1528 |
}
|
|
@@ -1640,6 +1706,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|
| 1640 |
topic: selectedTopic,
|
| 1641 |
language: selectedLanguage,
|
| 1642 |
scenario: selectedScenario,
|
|
|
|
| 1643 |
}),
|
| 1644 |
signal,
|
| 1645 |
});
|
|
@@ -1720,6 +1787,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|
| 1720 |
topic: selectedTopic,
|
| 1721 |
language: selectedLanguage,
|
| 1722 |
scenario: selectedScenario,
|
|
|
|
| 1723 |
}),
|
| 1724 |
signal: streamController.signal,
|
| 1725 |
});
|
|
@@ -2114,6 +2182,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|
| 2114 |
if (enforceGuestTrialLimit()) return;
|
| 2115 |
const text = textInput.value.trim();
|
| 2116 |
if (!text || ended) return;
|
|
|
|
| 2117 |
// Always allow interrupt: cancel any ongoing TTS/STT and take control
|
| 2118 |
if (turn !== 'user') {
|
| 2119 |
try {
|
|
|
|
| 51 |
let isMuted = false;
|
| 52 |
let ended = false;
|
| 53 |
let turn = 'user';
|
| 54 |
+
let autoMicRetryCount = 0;
|
| 55 |
+
let autoMicBlockedUntil = 0;
|
| 56 |
+
let lastAutoMicAt = 0;
|
| 57 |
|
| 58 |
// ─── UI TRANSLATIONS ───
|
| 59 |
const uiTranslations = {
|
| 60 |
en: {
|
| 61 |
+
app_title: "ECHO <span class='accent'>TUTOR</span>",
|
| 62 |
+
app_subtitle: 'Your AI-Powered Language Tutor',
|
| 63 |
+
choose_lang: 'Choose Language',
|
| 64 |
+
choose_level: 'Choose Your Level',
|
| 65 |
+
choose_mode: 'Choose Mode',
|
| 66 |
+
pick_topic: 'Pick a Topic',
|
| 67 |
+
pick_scenario: 'Pick a Scenario',
|
| 68 |
+
start_btn: 'Start Conversation',
|
| 69 |
+
chat_tab: 'Chat',
|
| 70 |
+
stories_tab: 'Stories',
|
| 71 |
+
cards_tab: 'Cards',
|
| 72 |
+
progress_tab: 'Progress',
|
| 73 |
+
settings_title: 'Settings',
|
| 74 |
+
close_btn: 'Close',
|
| 75 |
+
type_msg: 'Type a message...',
|
| 76 |
+
ready: 'Ready',
|
| 77 |
+
listening: 'Listening...',
|
| 78 |
+
thinking: 'Thinking...',
|
| 79 |
+
speaking: 'Speaking...',
|
| 80 |
+
streak: '🔥 Streak',
|
| 81 |
+
xp: 'XP',
|
| 82 |
+
level: 'Lv.',
|
| 83 |
},
|
| 84 |
ar: {
|
| 85 |
+
app_title: "إيكو <span class='accent'>تيوتر</span>",
|
| 86 |
+
app_subtitle: 'معلم اللغات الذكي الخاص بك',
|
| 87 |
+
choose_lang: 'اختر لغة التعلم',
|
| 88 |
+
choose_level: 'اختر مستواك',
|
| 89 |
+
choose_mode: 'اختر النمط',
|
| 90 |
+
pick_topic: 'اختر موضوعاً',
|
| 91 |
+
pick_scenario: 'اختر سيناريو',
|
| 92 |
+
start_btn: 'ابدأ المحادثة',
|
| 93 |
+
chat_tab: 'الدردشة',
|
| 94 |
+
stories_tab: 'القصص',
|
| 95 |
+
cards_tab: 'البطاقات',
|
| 96 |
+
progress_tab: 'التقدم',
|
| 97 |
+
settings_title: 'الإعدادات',
|
| 98 |
+
close_btn: 'إغلاق',
|
| 99 |
+
type_msg: 'اكتب رسالة...',
|
| 100 |
+
ready: 'مستعد',
|
| 101 |
+
listening: 'يستمع...',
|
| 102 |
+
thinking: 'يفكر...',
|
| 103 |
+
speaking: 'يتحدث...',
|
| 104 |
+
streak: '🔥 أيام متتالية',
|
| 105 |
+
xp: 'نقطة',
|
| 106 |
+
level: 'مستوى ',
|
| 107 |
+
},
|
| 108 |
};
|
| 109 |
|
| 110 |
let currentUILang = localStorage.getItem('echo_ui_lang') || 'en';
|
| 111 |
|
| 112 |
+
window.setUILanguage = function (lang) {
|
| 113 |
currentUILang = lang;
|
| 114 |
localStorage.setItem('echo_ui_lang', lang);
|
| 115 |
document.documentElement.dir = lang === 'ar' ? 'rtl' : 'ltr';
|
| 116 |
document.documentElement.lang = lang;
|
| 117 |
+
|
| 118 |
const t = uiTranslations[lang];
|
| 119 |
if (!t) return;
|
| 120 |
|
| 121 |
+
document.querySelectorAll('[data-i18n]').forEach((el) => {
|
| 122 |
const key = el.getAttribute('data-i18n');
|
| 123 |
if (t[key]) {
|
| 124 |
if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') {
|
|
|
|
| 128 |
}
|
| 129 |
}
|
| 130 |
});
|
| 131 |
+
|
| 132 |
// Update toggle button text
|
| 133 |
const toggleBtn = $('ui-lang-toggle');
|
| 134 |
if (toggleBtn) {
|
|
|
|
| 162 |
localStorage.setItem('echo_last_visit', today);
|
| 163 |
localStorage.setItem('echo_streak', streak);
|
| 164 |
}
|
| 165 |
+
|
| 166 |
const streakEl = $('streak-count');
|
| 167 |
if (streakEl) {
|
| 168 |
streakEl.innerHTML = `🔥 ${streak}`;
|
|
|
|
| 878 |
// Sync new words to flashcard deck (echo_vocab_deck)
|
| 879 |
if (window.echoSaveVocabWord) {
|
| 880 |
vocabWords.forEach((v) => {
|
| 881 |
+
window.echoSaveVocabWord(
|
| 882 |
+
v.word,
|
| 883 |
+
v.translation || '',
|
| 884 |
+
v.context || '',
|
| 885 |
+
);
|
| 886 |
});
|
| 887 |
}
|
| 888 |
} catch (e) {}
|
|
|
|
| 1211 |
turn = 'user';
|
| 1212 |
updateStats();
|
| 1213 |
sessionTimer = setInterval(updateStats, 1000);
|
| 1214 |
+
const displayName =
|
| 1215 |
+
(currentUser?.full_name || currentUser?.email || '').trim().split('@')[0] ||
|
| 1216 |
+
'friend';
|
| 1217 |
+
const topicLabel =
|
| 1218 |
+
selectedMode === 'topic'
|
| 1219 |
+
? (
|
| 1220 |
+
topics.find((t) => t.id === selectedTopic)?.label ||
|
| 1221 |
+
selectedTopic ||
|
| 1222 |
+
'free talk'
|
| 1223 |
+
)
|
| 1224 |
+
: selectedScenario || 'practice';
|
| 1225 |
+
const instantGreeting =
|
| 1226 |
+
currentUILang === 'ar'
|
| 1227 |
+
? `مرحباً ${displayName}! جاهز نبدأ الآن؟ اخترت ${topicLabel}.`
|
| 1228 |
+
: `Welcome ${displayName}! Ready to start now? You chose ${topicLabel}.`;
|
| 1229 |
+
addMessage(instantGreeting, 'assistant');
|
| 1230 |
+
setAvatarState('idle');
|
| 1231 |
+
if (autoListen && !ended) {
|
| 1232 |
+
scheduleAutoMic(260);
|
| 1233 |
+
}
|
| 1234 |
}
|
| 1235 |
|
| 1236 |
function updateStats() {
|
|
|
|
| 1249 |
const avatarOrb = document.getElementById('avatar-orb');
|
| 1250 |
|
| 1251 |
// Setup character buttons
|
| 1252 |
+
document.querySelectorAll('.char-btn').forEach((btn) => {
|
| 1253 |
btn.addEventListener('click', () => {
|
| 1254 |
+
document
|
| 1255 |
+
.querySelectorAll('.char-btn')
|
| 1256 |
+
.forEach((b) => b.classList.remove('active'));
|
| 1257 |
btn.classList.add('active');
|
| 1258 |
currentChar = btn.dataset.char;
|
| 1259 |
localStorage.setItem('echo_char', currentChar);
|
|
|
|
| 1262 |
});
|
| 1263 |
|
| 1264 |
// Apply saved character on load
|
| 1265 |
+
const savedCharBtn = document.querySelector(
|
| 1266 |
+
`.char-btn[data-char="${currentChar}"]`,
|
| 1267 |
+
);
|
| 1268 |
if (savedCharBtn) {
|
| 1269 |
+
document
|
| 1270 |
+
.querySelectorAll('.char-btn')
|
| 1271 |
+
.forEach((b) => b.classList.remove('active'));
|
| 1272 |
savedCharBtn.classList.add('active');
|
| 1273 |
}
|
| 1274 |
if (avatarOrb) applyCharacter(currentChar);
|
|
|
|
| 1280 |
// Hide orb face elements for non-orb characters
|
| 1281 |
const orbFace = avatarOrb.querySelector('.orb-face');
|
| 1282 |
if (orbFace) {
|
| 1283 |
+
orbFace.style.opacity = char === 'orb' ? '1' : '0';
|
| 1284 |
}
|
| 1285 |
}
|
| 1286 |
|
|
|
|
| 1304 |
thinking: t.thinking || 'Thinking...',
|
| 1305 |
happy: '✨',
|
| 1306 |
};
|
| 1307 |
+
stateLabel.textContent = labels[state] || t.ready || 'Ready';
|
| 1308 |
+
headerStatus.textContent = labels[state] || t.ready || 'Ready';
|
| 1309 |
+
}
|
| 1310 |
+
|
| 1311 |
+
function resetAutoMicGuard() {
|
| 1312 |
+
autoMicRetryCount = 0;
|
| 1313 |
+
autoMicBlockedUntil = 0;
|
| 1314 |
+
}
|
| 1315 |
+
|
| 1316 |
+
function registerAutoMicRetry() {
|
| 1317 |
+
autoMicRetryCount += 1;
|
| 1318 |
+
if (autoMicRetryCount >= 3) {
|
| 1319 |
+
autoMicBlockedUntil = Date.now() + 2500;
|
| 1320 |
+
autoMicRetryCount = 0;
|
| 1321 |
+
}
|
| 1322 |
+
}
|
| 1323 |
+
|
| 1324 |
+
function scheduleAutoMic(delayMs = 320) {
|
| 1325 |
+
if (!autoListen || ended || turn !== 'user') return;
|
| 1326 |
+
if (Date.now() < autoMicBlockedUntil) return;
|
| 1327 |
+
|
| 1328 |
+
setTimeout(() => {
|
| 1329 |
+
if (!autoListen || ended || turn !== 'user') return;
|
| 1330 |
+
if (Date.now() < autoMicBlockedUntil) return;
|
| 1331 |
+
if (recognizing || whisperRecording) return;
|
| 1332 |
+
|
| 1333 |
+
const now = Date.now();
|
| 1334 |
+
if (now - lastAutoMicAt < 450) return;
|
| 1335 |
+
lastAutoMicAt = now;
|
| 1336 |
+
openMic();
|
| 1337 |
+
}, Math.max(220, delayMs));
|
| 1338 |
}
|
| 1339 |
|
| 1340 |
// Eye blink
|
|
|
|
| 1494 |
if (!blob) {
|
| 1495 |
setAvatarState('idle');
|
| 1496 |
if (autoListen && !ended && turn === 'user') {
|
| 1497 |
+
registerAutoMicRetry();
|
| 1498 |
+
scheduleAutoMic(520);
|
| 1499 |
}
|
| 1500 |
return;
|
| 1501 |
}
|
|
|
|
| 1508 |
setAvatarState('idle');
|
| 1509 |
showToast(result?.error || 'Whisper transcription failed', 'error');
|
| 1510 |
if (autoListen && !ended && turn === 'user') {
|
| 1511 |
+
registerAutoMicRetry();
|
| 1512 |
+
scheduleAutoMic(620);
|
| 1513 |
}
|
| 1514 |
return;
|
| 1515 |
}
|
| 1516 |
const transcript = result?.text?.trim();
|
| 1517 |
if (!transcript) {
|
| 1518 |
setAvatarState('idle');
|
|
|
|
| 1519 |
if (autoListen && !ended && turn === 'user') {
|
| 1520 |
+
registerAutoMicRetry();
|
| 1521 |
+
scheduleAutoMic(560);
|
|
|
|
| 1522 |
}
|
| 1523 |
return;
|
| 1524 |
}
|
| 1525 |
|
| 1526 |
+
resetAutoMicGuard();
|
| 1527 |
+
|
| 1528 |
if (enforceGuestTrialLimit()) {
|
| 1529 |
setAvatarState('idle');
|
| 1530 |
return;
|
|
|
|
| 1550 |
recognition.onresult = (event) => {
|
| 1551 |
if (turn === 'user') {
|
| 1552 |
if (enforceGuestTrialLimit()) return;
|
| 1553 |
+
resetAutoMicGuard();
|
| 1554 |
const result = event.results[0][0];
|
| 1555 |
const transcript = result.transcript;
|
| 1556 |
const confidence = result.confidence; // 0-1
|
|
|
|
| 1580 |
recognition.onend = () => {
|
| 1581 |
recognizing = false;
|
| 1582 |
micBtn.classList.remove('active');
|
| 1583 |
+
if (autoListen && !ended && turn === 'user') scheduleAutoMic(320);
|
| 1584 |
else if (turn === 'user') setAvatarState('idle');
|
| 1585 |
};
|
| 1586 |
|
| 1587 |
recognition.onerror = (event) => {
|
| 1588 |
recognizing = false;
|
| 1589 |
micBtn.classList.remove('active');
|
| 1590 |
+
if (event.error === 'no-speech') registerAutoMicRetry();
|
| 1591 |
+
else resetAutoMicGuard();
|
| 1592 |
if (event.error !== 'no-speech' && event.error !== 'aborted') {
|
| 1593 |
showToast('Mic error: ' + event.error, 'error');
|
| 1594 |
}
|
|
|
|
| 1706 |
topic: selectedTopic,
|
| 1707 |
language: selectedLanguage,
|
| 1708 |
scenario: selectedScenario,
|
| 1709 |
+
user_name: currentUser?.full_name || currentUser?.email || '',
|
| 1710 |
}),
|
| 1711 |
signal,
|
| 1712 |
});
|
|
|
|
| 1787 |
topic: selectedTopic,
|
| 1788 |
language: selectedLanguage,
|
| 1789 |
scenario: selectedScenario,
|
| 1790 |
+
user_name: currentUser?.full_name || currentUser?.email || '',
|
| 1791 |
}),
|
| 1792 |
signal: streamController.signal,
|
| 1793 |
});
|
|
|
|
| 2182 |
if (enforceGuestTrialLimit()) return;
|
| 2183 |
const text = textInput.value.trim();
|
| 2184 |
if (!text || ended) return;
|
| 2185 |
+
resetAutoMicGuard();
|
| 2186 |
// Always allow interrupt: cancel any ongoing TTS/STT and take control
|
| 2187 |
if (turn !== 'user') {
|
| 2188 |
try {
|