Spaces:
Sleeping
Sleeping
File size: 6,751 Bytes
75fc8b6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 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 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 | 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())
@app.middleware("http")
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
@app.get("/api/health")
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"]}
@app.post("/api/login")
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
@app.get("/api/config")
def config():
return {"spoken": SPOKEN, "targets": TARGETS, "glossary": engine.load_glossary(),
"engines": [e["name"] for e in chain.engines]}
@app.post("/api/transcribe")
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"]}
@app.post("/api/translate_live")
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}
@app.post("/api/translate_text")
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)}
@app.post("/api/suggest")
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")
|