Spaces:
Sleeping
Sleeping
Download engine.py from echerkaoui/interprete: direct link, hf CLI and curl.
- Browser
- Download file 22.6 kB
-
https://huggingface.co/spaces/echerkaoui/interprete/resolve/main/engine.py
- Command line
-
hf download hf://spaces/echerkaoui/interprete/engine.py
-
curl -L -o engine.py https://huggingface.co/spaces/echerkaoui/interprete/resolve/main/engine.py
22.6 kB
| import io | |
| import json | |
| import os | |
| import re | |
| import time | |
| import wave | |
| import requests | |
| from requests.adapters import HTTPAdapter | |
| HERE = os.path.dirname(os.path.abspath(__file__)) | |
| GROQ_KEY = os.environ.get("GROQ_API_KEY", "") | |
| GROQ_URL = "https://api.groq.com/openai/v1/audio/transcriptions" | |
| GROQ_CHAT = "https://api.groq.com/openai/v1/chat/completions" | |
| OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions" | |
| ASR_MODEL = os.environ.get("ASR_MODEL", "whisper-large-v3") | |
| LANG_NATIVE = {"fr": "French (français)", "ar": "Arabic (العربية, arabe standard)", "en": "English", | |
| "zh": "Simplified Chinese (简体中文)"} | |
| HTTP = requests.Session() | |
| HTTP.mount("https://", HTTPAdapter(pool_connections=4, pool_maxsize=16)) | |
| def log(msg): | |
| print(f"{time.strftime('%H:%M:%S')} {msg}", flush=True) | |
| def engines_from_env(): | |
| """Ordre mesuré : Qwen (le plus rapide, ne dégrade rien), GPT-OSS 20B, puis OpenRouter.""" | |
| out = [] | |
| if GROQ_KEY: | |
| out += [ | |
| {"name": "Qwen 3.8 27B (Groq)", "model": "qwen/qwen3.8-27b", "url": GROQ_CHAT, "api_key": GROQ_KEY, | |
| "extra": {"reasoning_effort": "none"}}, | |
| {"name": "GPT-OSS 20B (Groq)", "model": "openai/gpt-oss-20b", "url": GROQ_CHAT, "api_key": GROQ_KEY, | |
| "extra": {"reasoning_effort": "low"}}, | |
| ] | |
| for var, name, model in (("OPENROUTER_KEY_1", "Gemma 4 26B (OpenRouter)", "google/gemma-4-26b-a4b-it:free"), | |
| ("OPENROUTER_KEY_2", "Nemotron 3 Nano Omni (OpenRouter)", | |
| "nvidia/nemotron-3-nano-omni-30b-a3b-reasoning:free")): | |
| if os.environ.get(var): | |
| out.append({"name": name, "model": model, "api_key": os.environ[var]}) | |
| return out | |
| def load_glossary(): | |
| env = os.environ.get("GLOSSARY", "") | |
| if env.strip(): | |
| return [g.strip() for g in env.split(",") if g.strip()] | |
| try: | |
| with open(os.path.join(HERE, "glossary.json"), encoding="utf-8") as f: | |
| return [str(g) for g in json.load(f) if str(g).strip()] | |
| except (FileNotFoundError, ValueError): | |
| return [] | |
| _load_glossary = load_glossary # nom utilisé par le code repris de l'appli de bureau | |
| LANG_NAMES = { | |
| "zh": "Chinese", "en": "English", "fr": "French", "ar": "Arabic", "ja": "Japanese", | |
| "ko": "Korean", "es": "Spanish", "de": "German", "ru": "Russian", "it": "Italian", | |
| "pt": "Portuguese", "tr": "Turkish", | |
| } | |
| HALLUCINATIONS = ( | |
| "谢谢观看", "谢谢收看", "字幕由", "请不吝点赞", "订阅", "明镜", "感谢观看", | |
| "独播剧场", "优优独播", "yoyo television", "television series exclusive", "字幕组", | |
| "中文字幕", "点赞", "打赏", "amara.org", "本期视频", "欢迎收看", "下期再见", | |
| "thank you for watching", "thanks for watching", "subscribe", | |
| ) | |
| STOCK_PHRASES = { | |
| "谢谢大家", "谢谢", "谢谢观看", "谢谢收看", "感谢观看", "全新的", "好的", "嗯", "啊", | |
| "请订阅", "下期再见", "我们下期再见", "拜拜", "thankyou", "thanks", "bye", | |
| } | |
| def _is_stock_noise(text, audio_s, no_speech, avg_logprob): | |
| import re | |
| norm = re.sub(r"[\s\W_]+", "", text.lower()) | |
| return norm in STOCK_PHRASES and (audio_s < 3.5 or no_speech > 0.15 or avg_logprob < -0.5) | |
| def _keep_segment(text, no_speech, avg_logprob, compression): | |
| """Règle de Whisper (OpenAI) : on jette seulement si « sans parole » ET peu sûr, ou répétitif. | |
| L'ancien filtre (no_speech seul) jetait de la vraie parole sur un micro lointain | |
| (8 s d'audio réduites à « 对 » dans le journal du 2026-11-05). | |
| """ | |
| if not text: | |
| return False | |
| low = text.lower() | |
| if any(h in low for h in HALLUCINATIONS): | |
| return False | |
| if no_speech > 0.6 and avg_logprob < -1.0: | |
| return False | |
| if compression > 2.4: # boucle du type « 是软件,是软件,是软件 » | |
| return False | |
| return True | |
| _T2S = None | |
| def _simplified(text, lang): | |
| """Whisper mélange parfois traditionnel et simplifié (沒有/这里) : on uniformise en simplifié.""" | |
| global _T2S | |
| if lang != "zh" or not text: | |
| return text | |
| if _T2S is None: | |
| from opencc import OpenCC | |
| _T2S = OpenCC("t2s") | |
| return _T2S.convert(text) | |
| class OnlineChain: | |
| """Essaie les moteurs en ligne dans l'ordre ; bascule au suivant en cas de quota ou d'erreur.""" | |
| def __init__(self, engines): | |
| self.engines = engines | |
| self.cooldown = {} # nom -> instant où on peut réessayer | |
| self.dead = {} # nom -> raison (crédits épuisés, clé refusée) | |
| def _cjk_ratio(self, s): | |
| cjk = sum(1 for c in s if "一" <= c <= "鿿") | |
| return cjk / max(1, len(s.strip())) | |
| def _call(self, e, text, src, dst): | |
| src_name = LANG_NAMES.get(src, "the source language") | |
| dst_name = LANG_NAMES[dst] | |
| body = { | |
| "model": e["model"], "temperature": 0.1, "max_tokens": 400, | |
| "messages": [ | |
| {"role": "system", "content": | |
| f"You are a simultaneous interpreter. Translate the {src_name} text given by the user " | |
| f"into {LANG_NATIVE[dst]}. Your answer must be written entirely in {dst_name}. " | |
| f"Never repeat the original. Output only the translation, nothing else."}, | |
| {"role": "user", "content": f"{src_name}: {text}\n{dst_name}:"}, | |
| ], | |
| } | |
| return self._post(e, body) | |
| def _post(e, body, timeout=12): | |
| """Envoie au fournisseur du moteur (OpenRouter par défaut, ou `url` du config, ex. Groq).""" | |
| if "reasoning" in e["model"] and "url" not in e: | |
| body["reasoning"] = {"enabled": False} # OpenRouter : pas de réflexion, réponse immédiate | |
| body.update(e.get("extra", {})) # réglages propres au moteur (ex. reasoning_effort chez Groq) | |
| return HTTP.post(e.get("url", OPENROUTER_URL), json=body, timeout=timeout, | |
| headers={"Authorization": f"Bearer {e['api_key']}", "X-Title": "Interprete local"}) | |
| def _target_ok(self, out, dst): | |
| ratio = self._cjk_ratio(out) | |
| return bool(out) and (ratio > 0.3 if dst == "zh" else ratio <= 0.3) | |
| def translate(self, text, src, dst): | |
| """Retourne (traduction, nom du moteur) ou lève RuntimeError si tous ont échoué.""" | |
| def parse(out): | |
| return out if self._target_ok(out, dst) else None | |
| return self._run(lambda e: self._call(e, text, src, dst), parse) | |
| def translate_text(self, text, src, dst, glossary): | |
| """Traduction d'un texte saisi (mode Texte) : peut être long, garde la mise en forme.""" | |
| src_name = LANG_NAMES.get(src) if src else None | |
| dst_name = LANG_NAMES[dst] | |
| system = ( | |
| f"You are a professional translator. Translate the user's text " | |
| f"{'from ' + src_name + ' ' if src_name else '(detect its language) '}" | |
| f"into {LANG_NATIVE[dst]}, entirely in {dst_name}. Keep the meaning, tone, line breaks, lists " | |
| f"and numbers. The glossary lists colleagues' names: write them exactly as spelled there " | |
| f"(Latin letters), except when translating into Chinese. Output only the translation." | |
| f"\nGlossary: {', '.join(glossary) if glossary else '(none)'}" | |
| ) | |
| def call(e): | |
| body = {"model": e["model"], "temperature": 0.1, "max_tokens": 3000, | |
| "messages": [{"role": "system", "content": system}, | |
| {"role": "user", "content": text}]} | |
| return self._post(e, body, timeout=40) | |
| def parse(out): | |
| return out if self._target_ok(out, dst) else None | |
| return self._run(call, parse) | |
| def suggest(self, text, glossary, n=3): | |
| """Saisie prédictive : propose la suite la plus probable du texte (même langue, même écriture). | |
| Chaque proposition est la chaîne exacte à ajouter au curseur (fin du mot en cours compris). | |
| """ | |
| system = ( | |
| "You are the predictive keyboard of a writing app. The user is typing; the cursor is at the " | |
| f"end of the text. Propose {n} different continuations the writer is most likely to type next, " | |
| "1 to 4 words each, consistent with the context, in the same language and script as the text. " | |
| "Each item MUST begin with the last word of the text, written in full and completed if it is " | |
| "unfinished (text ending '...quality rep' -> 'report to me'; text ending '...rapport de' -> " | |
| "'de la réunion'). For Chinese, give only the characters that come next. " | |
| "Colleagues' names (suggest one only where the sentence clearly calls for a person): " | |
| f"{', '.join(glossary) if glossary else '(none)'}.\n" | |
| 'Reply with JSON only: {"s": ["...", "...", "..."]}' | |
| ) | |
| def call(e): | |
| body = {"model": e["model"], "temperature": 0.3, "max_tokens": 120, | |
| "messages": [{"role": "system", "content": system}, | |
| {"role": "user", "content": text[-600:]}]} | |
| return self._post(e, body, timeout=6) | |
| def parse(out): | |
| import re | |
| m = re.search(r"\{.*\}", out, re.S) | |
| if not m: | |
| return None | |
| try: | |
| items = json.loads(m.group(0)).get("s", []) | |
| except ValueError: | |
| return None | |
| seen, clean = set(), [] | |
| for it in items: | |
| it = str(it).replace("\n", " ").strip() | |
| if it.strip() and len(it) <= 40 and it.strip().lower() not in seen: | |
| seen.add(it.strip().lower()) | |
| clean.append(it) | |
| return clean[:n] or None | |
| return self._run(call, parse) | |
| def correct_and_translate(self, raw, src, dst, context, glossary, alt=""): | |
| """Corrige les erreurs de reconnaissance dues à l'accent (avec le contexte), puis traduit. | |
| Retourne ((texte_corrigé, traduction), moteur). Un seul appel : pas de délai en plus. | |
| """ | |
| src_name = LANG_NAMES.get(src, "the spoken language") | |
| dst_name = LANG_NAMES[dst] | |
| system = ( | |
| f"You post-process a live speech recognizer. The speakers have different accents, so the " | |
| f"recognizer sometimes writes wrong words that SOUND similar (homophones, near-homophones, " | |
| f"wrong tones, words split or merged wrongly, a name heard as a common word).\n" | |
| f"1) corrected: fix ONLY such recognition errors in the CURRENT utterance, using the " | |
| f"conversation context and the glossary. Keep the speaker's wording. Do not paraphrase, " | |
| f"summarize, complete, or add anything. If an error is not clear, leave the text unchanged. " | |
| f"Keep mixed languages as they are. Write normal punctuation.\n" | |
| f"When a SECOND recognizer's reading of the same audio is given, it is independent evidence: " | |
| f"where the two readings differ, keep the words that make sense in the context and that both " | |
| f"readings could sound like. The first reading is the more reliable one: when you cannot " | |
| f"tell, keep the first. Never merge the two into a longer sentence.\n" | |
| f"The glossary lists colleagues' names (Chinese names in pinyin, plus Arabic first names; " | |
| f"in Chinese speech an Arabic name appears as its usual transliteration, e.g. 萨拉 for Salah). " | |
| f"The recognizer is imperfect, so be strict: a word is a glossary name ONLY if every one of its " | |
| f"syllables matches that name. An unknown word, a common noun, a surname alone (老张, 小李), or a " | |
| f"word that only partly sounds like a name is NOT a glossary name: keep it as heard. Never " | |
| f"replace words with a glossary name to fix an unclear passage.\n" | |
| f"2) translation: translate the corrected utterance into {LANG_NATIVE[dst]}, entirely in " | |
| f"{dst_name}. Use a glossary spelling (Latin letters) only for names that are really in the " | |
| f"utterance under the rule above; transliterate any other name normally.\n" | |
| 'Reply with JSON only: {"corrected": "...", "translation": "..."}' | |
| ) | |
| ctx = "\n".join(f"- {c}" for c in context) or "(start of the conversation)" | |
| gl = ", ".join(glossary) if glossary else "(none)" | |
| user = (f"Context (previous utterances, already corrected):\n{ctx}\n" | |
| f"Glossary (names and terms that may be spoken): {gl}\n" | |
| f"CURRENT {src_name} utterance from the recognizer: {raw}") | |
| if alt: | |
| user += f"\nSECOND recognizer's reading of the same audio: {alt}" | |
| def call(e): | |
| body = {"model": e["model"], "temperature": 0.0, "max_tokens": 600, | |
| "messages": [{"role": "system", "content": system}, | |
| {"role": "user", "content": user}]} | |
| return self._post(e, body) | |
| def parse(out): | |
| import re | |
| m = re.search(r"\{.*\}", out, re.S) | |
| if not m: | |
| return None | |
| try: | |
| j = json.loads(m.group(0)) | |
| except ValueError: | |
| return None | |
| corrected = str(j.get("corrected") or "").strip() | |
| translation = str(j.get("translation") or "").strip() | |
| if not corrected or not self._target_ok(translation, dst): | |
| return None | |
| return corrected, translation | |
| return self._run(call, parse) | |
| def _run(self, call, parse): | |
| errors = [] | |
| for e in self.engines: | |
| name = e.get("name", e["model"]) | |
| if name in self.dead or time.time() < self.cooldown.get(name, 0): | |
| continue | |
| try: | |
| r = call(e) | |
| except requests.RequestException as ex: | |
| self.cooldown[name] = time.time() + 15 | |
| errors.append(f"{name}: réseau ({ex.__class__.__name__})") | |
| log(f"moteur {name} : erreur réseau {ex!r}") | |
| continue | |
| if r.status_code in (401, 402, 403): | |
| reason = "crédits épuisés" if r.status_code == 402 else "clé refusée" | |
| self.dead[name] = reason | |
| errors.append(f"{name}: {reason}") | |
| log(f"moteur {name} : HTTP {r.status_code}, écarté pour la session ({reason})") | |
| continue | |
| if r.status_code == 429: | |
| self.cooldown[name] = time.time() + 30 | |
| errors.append(f"{name}: saturé") | |
| log(f"moteur {name} : HTTP 429 (saturé), réessai dans 30 s") | |
| continue | |
| if not r.ok: | |
| self.cooldown[name] = time.time() + 15 | |
| errors.append(f"{name}: HTTP {r.status_code}") | |
| log(f"moteur {name} : HTTP {r.status_code} {r.text[:200]}") | |
| continue | |
| try: | |
| out = (r.json()["choices"][0]["message"]["content"] or "").strip() | |
| except (ValueError, KeyError, IndexError): | |
| out = "" | |
| result = parse(out) if out else None | |
| if result is None: | |
| errors.append(f"{name}: réponse inutilisable") | |
| log(f"moteur {name} : réponse rejetée {out[:120]!r}") | |
| continue | |
| return result, name | |
| raise RuntimeError("; ".join(errors) or "aucun moteur en ligne disponible") | |
| def _glossary_latin(entry): | |
| """« Li Lijun (Frank) » -> « Li Lijun » ; « Zhang Wei 张伟 » -> « Zhang Wei ».""" | |
| import re | |
| name = re.sub(r"\s*\(.*?\)", "", entry) | |
| return re.sub(r"[^A-Za-z' -]", "", name).strip() | |
| def _unheard_names(raw, translation, glossary): | |
| """Noms du glossaire présents dans la traduction mais absents de ce qui a été entendu. | |
| Vérifié dans le code, pas par le modèle : on passe l'audio reconnu en pinyin et on exige | |
| que les syllabes du nom y soient (萨拉 « sala » ≈ Salah ; 老张 « laozhang » ≠ Zhang Wei). | |
| """ | |
| import difflib | |
| import re | |
| try: | |
| from pypinyin import lazy_pinyin | |
| except ImportError: | |
| log("pypinyin absent : vérification des noms désactivée") | |
| return [] | |
| heard = _heard_key(raw, lazy_pinyin) | |
| bad = [] | |
| for entry in glossary: | |
| latin = _glossary_latin(entry) | |
| if not latin or not re.search(r"(?<![A-Za-z])" + re.escape(latin) + r"(?![A-Za-z])", translation, re.I): | |
| continue | |
| if _sound_match(latin, heard, difflib) < 0.75: | |
| bad.append(latin) | |
| return bad | |
| def _heard_key(raw, lazy_pinyin): | |
| import re | |
| return re.sub(r"[^a-z]", "", "".join(lazy_pinyin(raw)).lower()) | |
| def _sound_match(latin, heard, difflib): | |
| """Ressemblance (0..1) entre un nom et la meilleure portion de ce qui a été entendu, en pinyin.""" | |
| import re | |
| key = re.sub(r"[^a-z]", "", latin.lower()) | |
| if not key: | |
| return 0.0 | |
| if key in heard: | |
| return 1.0 | |
| n = len(key) | |
| windows = [heard[i:i + n] for i in range(0, max(1, len(heard) - n + 1))] | |
| return max((difflib.SequenceMatcher(None, key, w).ratio() for w in windows), default=0.0) | |
| def plausible_names(raw, glossary, threshold=0.75): | |
| """Seulement les noms qui ressemblent à ce qui a été entendu : prompt plus court (moins de quota | |
| consommé, réponse plus rapide) et moins de tentation de « placer » un collègue.""" | |
| import difflib | |
| try: | |
| from pypinyin import lazy_pinyin | |
| except ImportError: | |
| return glossary | |
| heard = _heard_key(raw, lazy_pinyin) | |
| return [g for g in glossary if _sound_match(_glossary_latin(g), heard, difflib) >= threshold] | |
| def _correction_is_safe(raw, corrected): | |
| """Garde-fou : une correction d'accent change quelques mots, jamais le sens entier.""" | |
| import difflib | |
| if corrected == raw: | |
| return True | |
| sim = difflib.SequenceMatcher(None, raw, corrected).ratio() | |
| return sim >= 0.6 and len(corrected) <= len(raw) * 1.5 + 10 | |
| def _sounds_alike(raw, corrected, alt=""): | |
| """Une correction d'accent remplace un mot par un mot qui se prononce presque pareil (商周 -> 上周). | |
| Vérifié en pinyin, dans le code : 商周 -> 刘秀丽 est refusé. Un mot repris de la seconde lecture est accepté. | |
| """ | |
| import difflib | |
| try: | |
| from pypinyin import lazy_pinyin | |
| except ImportError: | |
| return True | |
| a = "".join(ch for ch in raw if "\u4e00" <= ch <= "\u9fff") | |
| b = "".join(ch for ch in corrected if "\u4e00" <= ch <= "\u9fff") | |
| for op, a1, a2, b1, b2 in difflib.SequenceMatcher(None, a, b, autojunk=False).get_opcodes(): | |
| if op != "replace" or (alt and b[b1:b2] in alt): | |
| continue | |
| if a2 - a1 == 1 and b2 - b1 == 1: | |
| continue # une seule syllabe (哈 -> 下) : variante d'accent courante, et aucun nom ne tient en une syllabe | |
| heard, fixed = "".join(lazy_pinyin(a[a1:a2])), "".join(lazy_pinyin(b[b1:b2])) | |
| if difflib.SequenceMatcher(None, heard, fixed).ratio() < 0.6: | |
| return False | |
| return True | |
| def wav_seconds(data): | |
| try: | |
| with wave.open(io.BytesIO(data)) as w: | |
| return w.getnframes() / float(w.getframerate()) | |
| except (wave.Error, EOFError): | |
| return 0.0 | |
| def transcribe(wav_bytes, lang=None): | |
| """Envoie une phrase (WAV 16 kHz) à Groq. Retourne (texte, langue, infos de journal).""" | |
| data = {"model": ASR_MODEL, "response_format": "verbose_json", "temperature": "0"} | |
| if lang: | |
| data["language"] = lang | |
| t = time.time() | |
| r = HTTP.post(GROQ_URL, headers={"Authorization": f"Bearer {GROQ_KEY}"}, data=data, | |
| files={"file": ("phrase.wav", wav_bytes, "audio/wav")}, timeout=20) | |
| if r.status_code == 429: | |
| raise RuntimeError("quota Groq atteint, réessaie dans une minute") | |
| r.raise_for_status() | |
| j = r.json() | |
| audio_s = wav_seconds(wav_bytes) | |
| kept = [] | |
| for s in j.get("segments") or []: | |
| txt = (s.get("text") or "").strip() | |
| ns, lp = s.get("no_speech_prob", 0), s.get("avg_logprob", 0) | |
| if _keep_segment(txt, ns, lp, s.get("compression_ratio", 1)) and not _is_stock_noise(txt, audio_s, ns, lp): | |
| kept.append(txt) | |
| else: | |
| log(f"segment écarté {txt!r} (no_speech={ns:.2f}, logprob={lp:.2f}, {audio_s:.1f}s)") | |
| if not j.get("segments"): | |
| txt = (j.get("text") or "").strip() | |
| if _keep_segment(txt, 0, 0, 1): | |
| kept.append(txt) | |
| detected = str(j.get("language") or lang or "zh").lower() | |
| detected = WHISPER_LANG.get(detected, detected[:2]) | |
| text = _simplified(" ".join(kept).strip(), detected) | |
| return text, detected, round(time.time() - t, 2) | |
| WHISPER_LANG = {"chinese": "zh", "mandarin": "zh", "english": "en", "french": "fr", "arabic": "ar", | |
| "japanese": "ja", "korean": "ko", "spanish": "es", "german": "de", "russian": "ru"} | |
| def correct_and_translate(chain, text, src, dst, context, correct=True, alt=""): | |
| """Même chemin que l'appli de bureau : correction d'accent bornée, puis garde-fous en code.""" | |
| glossary = load_glossary() | |
| t = time.time() | |
| if src == dst: | |
| return {"corrected": text, "translation": text, "engine": "aucun (même langue)", "s": 0} | |
| if correct: | |
| heard = f"{text} {alt}".strip() # un nom compte comme entendu si l'un des deux moteurs l'a entendu | |
| (corrected, out), engine = chain.correct_and_translate(text, src, dst, context, | |
| plausible_names(heard, glossary), alt) | |
| unheard = _unheard_names(heard, out, glossary) if glossary else [] | |
| if unheard: | |
| log(f"nom non entendu {unheard} dans {out!r} (entendu : {text!r}) : retraduction") | |
| out, engine = chain.translate(text, src, dst) | |
| corrected = text | |
| safe = _correction_is_safe(text, corrected) or bool(alt and _correction_is_safe(alt, corrected)) | |
| if safe and src == "zh" and not _sounds_alike(text, corrected, alt): | |
| safe = False | |
| if not safe: | |
| log(f"correction rejetée : {text!r} -> {corrected!r}") | |
| out, engine = chain.translate(text, src, dst) | |
| corrected = text | |
| else: | |
| out, engine = chain.translate(text, src, dst) | |
| corrected = text | |
| return {"corrected": corrected, "translation": out, "engine": engine, "s": round(time.time() - t, 2)} | |