Spaces:
Sleeping
Sleeping
Download server.py from echerkaoui/interprete: direct link, hf CLI and curl.
- Browser
- Download file 6.75 kB
-
https://huggingface.co/spaces/echerkaoui/interprete/resolve/main/server.py
- Command line
-
hf download hf://spaces/echerkaoui/interprete/server.py
-
curl -L -o server.py https://huggingface.co/spaces/echerkaoui/interprete/resolve/main/server.py
6.75 kB
| import hashlib | |
| import hmac | |
| import os | |
| import secrets | |
| import time | |
| from fastapi import FastAPI, File, Form, Request, UploadFile | |
| from fastapi.responses import JSONResponse | |
| from fastapi.staticfiles import StaticFiles | |
| from pydantic import BaseModel | |
| import engine | |
| import listen | |
| TEAM_CODE = os.environ.get("TEAM_CODE", "") | |
| SECRET = os.environ.get("SESSION_SECRET") or secrets.token_hex(32) | |
| COOKIE = "interprete_session" | |
| MAX_AUDIO_BYTES = 3 * 1024 * 1024 # ~95 s de WAV 16 kHz mono : bien au-delà d'une phrase | |
| MAX_TEXT = 5000 | |
| SPOKEN = [["Chinois", "zh"], ["Détection auto", None], ["Anglais", "en"], ["Français", "fr"], | |
| ["Arabe", "ar"], ["Japonais", "ja"], ["Coréen", "ko"], ["Espagnol", "es"]] | |
| TARGETS = [["Français", "fr"], ["Arabe", "ar"], ["Anglais", "en"], ["Chinois", "zh"]] | |
| CODES = {c for _, c in SPOKEN if c} | {c for _, c in TARGETS} | |
| chain = engine.OnlineChain(engine.engines_from_env()) | |
| listen.start() | |
| app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) | |
| def _token(): | |
| return hmac.new(SECRET.encode(), TEAM_CODE.encode(), hashlib.sha256).hexdigest() | |
| def _authed(request: Request): | |
| return bool(TEAM_CODE) and hmac.compare_digest(request.cookies.get(COOKIE, ""), _token()) | |
| async def guard(request: Request, call_next): | |
| path = request.url.path | |
| if path.startswith("/api/") and path not in ("/api/login", "/api/health") and not _authed(request): | |
| return JSONResponse({"ok": False, "error": "auth"}, status_code=401) | |
| return await call_next(request) | |
| def _code(value): | |
| return value if value in CODES else None | |
| class Login(BaseModel): | |
| code: str | |
| class Live(BaseModel): | |
| text: str | |
| src: str | None = None | |
| dst: str = "fr" | |
| context: list[str] = [] | |
| correct: bool = True | |
| alt: str = "" | |
| class Text(BaseModel): | |
| text: str | |
| src: str | None = None | |
| dst: str = "fr" | |
| class Suggest(BaseModel): | |
| text: str | |
| def health(): | |
| return {"ok": True, "engines": [e["name"] for e in chain.engines], "configured": bool(TEAM_CODE), | |
| "voices": listen.state["ready"], "voices_error": listen.state["error"]} | |
| def login(body: Login, request: Request): | |
| if not TEAM_CODE: | |
| return JSONResponse({"ok": False, "error": "TEAM_CODE n'est pas configuré sur le serveur."}, status_code=503) | |
| if not hmac.compare_digest(body.code.strip(), TEAM_CODE): | |
| time.sleep(1.0) # freine les essais en série | |
| return JSONResponse({"ok": False, "error": "Code incorrect."}, status_code=403) | |
| resp = JSONResponse({"ok": True}) | |
| # Sur Render la page est toujours en HTTPS (cookie « secure ») ; en local, http://127.0.0.1 pour les tests. | |
| secure = request.url.scheme == "https" | |
| resp.set_cookie(COOKIE, _token(), max_age=30 * 24 * 3600, httponly=True, secure=secure, samesite="lax") | |
| return resp | |
| def config(): | |
| return {"spoken": SPOKEN, "targets": TARGETS, "glossary": engine.load_glossary(), | |
| "engines": [e["name"] for e in chain.engines]} | |
| def transcribe(audio: UploadFile = File(...), lang: str = Form(""), sid: str = Form("")): | |
| data = audio.file.read(MAX_AUDIO_BYTES + 1) | |
| if len(data) > MAX_AUDIO_BYTES: | |
| return JSONResponse({"ok": False, "error": "Phrase trop longue."}, status_code=413) | |
| try: | |
| turns, detected, info = listen.hear(data, _code(lang), sid[:40]) | |
| except Exception as e: # noqa: BLE001 | |
| engine.log(f"transcription impossible : {e!r}") | |
| return JSONResponse({"ok": False, "error": str(e)[:200]}, status_code=502) | |
| engine.log(f"entendu en {info['s']}s ({engine.wav_seconds(data):.1f}s d'audio) : " | |
| + " | ".join(f"voix {t['speaker']}{' +' if t['overlap'] else ''} {t['text']!r}" for t in turns)) | |
| return {"ok": True, "text": " ".join(t["text"] for t in turns), "lang": detected, "turns": turns, "s": info["s"]} | |
| def translate_live(body: Live): | |
| import difflib | |
| text = body.text.strip()[:MAX_TEXT] | |
| if not text: | |
| return {"ok": False, "error": "vide"} | |
| try: | |
| r = engine.correct_and_translate(chain, text, _code(body.src) or "zh", _code(body.dst) or "fr", | |
| [c[:300] for c in body.context[-5:]], body.correct, | |
| body.alt.strip()[:MAX_TEXT]) | |
| except RuntimeError as e: | |
| return JSONResponse({"ok": False, "error": f"Traduction indisponible : {e}"}, status_code=502) | |
| spans = [] # ce que la correction a changé, pour le souligner dans la page | |
| if r["corrected"] != text: | |
| sm = difflib.SequenceMatcher(None, text, r["corrected"]) | |
| import re | |
| punct = re.compile(r"^[\W_\s]*$") # « , » -> « , » : simple ponctuation, pas une correction d'accent | |
| for op, a1, a2, b1, b2 in sm.get_opcodes(): | |
| if op != "equal" and punct.match(text[a1:a2]) and punct.match(r["corrected"][b1:b2]): | |
| op = "equal" | |
| if op == "equal": | |
| spans.append({"t": r["corrected"][b1:b2]}) | |
| elif op in ("replace", "insert"): | |
| spans.append({"t": r["corrected"][b1:b2], "heard": text[a1:a2]}) | |
| elif op == "delete" and spans: | |
| spans[-1]["removed"] = spans[-1].get("removed", "") + text[a1:a2] | |
| engine.log(f"correction d'accent : {text!r} -> {r['corrected']!r}") | |
| return {"ok": True, **r, "spans": spans} | |
| def translate_text(body: Text): | |
| text = body.text.strip() | |
| if not text: | |
| return {"ok": False, "error": "Écris ou colle un texte à traduire."} | |
| if len(text) > MAX_TEXT: | |
| return {"ok": False, "error": f"Texte trop long ({len(text)} caractères, maximum {MAX_TEXT})."} | |
| src, dst = _code(body.src), _code(body.dst) or "fr" | |
| if src and src == dst: | |
| return {"ok": True, "text": text, "engine": "aucun (même langue)", "ms": 0} | |
| t = time.time() | |
| try: | |
| out, eng = chain.translate_text(text, src, dst, engine.load_glossary()) | |
| except RuntimeError as e: | |
| return JSONResponse({"ok": False, "error": f"Traduction indisponible : {e}"}, status_code=502) | |
| return {"ok": True, "text": out, "engine": eng, "ms": int((time.time() - t) * 1000)} | |
| def suggest(body: Suggest): | |
| if len(body.text.strip()) < 2: | |
| return {"ok": True, "items": []} | |
| try: | |
| items, eng = chain.suggest(body.text[-600:], engine.load_glossary()) | |
| return {"ok": True, "items": items} | |
| except RuntimeError: | |
| return {"ok": False, "items": []} | |
| app.mount("/", StaticFiles(directory=os.path.join(engine.HERE, "static"), html=True), name="static") | |