From 9943a409f16f676abebc5bb1342da07511c4f0fa Mon Sep 17 00:00:00 2001 From: guy Date: Mon, 16 Nov 2026 23:05:48 -0300 Subject: [PATCH] OrbiSubs: English subtitle track translated by the gpu02 LLM (separate process) orbisubs.py escribe la cola cues.jsonl y anuncia la pista en el master (--en); orbisubs_tr.py junta frases, traduce con Qwen (sin thinking, contexto de la frase anterior) y escribe en/.vtt + en.m3u8. Tarea 077. --- bench_http.py | 57 ++++++++++ deploy/canal.env.example | 4 + deploy/orbisubs-asr@.service | 2 +- deploy/orbisubs-tr@.service | 15 +++ orbisubs.py | 10 ++ orbisubs_tr.py | 198 +++++++++++++++++++++++++++++++++++ web/player.html | 5 +- 7 files changed, 289 insertions(+), 2 deletions(-) create mode 100644 bench_http.py create mode 100644 deploy/orbisubs-tr@.service create mode 100644 orbisubs_tr.py diff --git a/bench_http.py b/bench_http.py new file mode 100644 index 0000000..3756f94 --- /dev/null +++ b/bench_http.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Calidad del modo en vivo contra una pasada de referencia, con el mismo motor HTTP. + +- referencia: el clip en pedazos de 30 s (el contexto completo que whisper soporta), + sin apuro de tiempo real: es lo mejor que da el motor sobre ese audio. +- en vivo: el mismo Transcriptor del servicio, alimentado de a 6 s (un segmento HLS). +Los pedidos van de a uno (gpu02 es compartido). Uso: bench_http.py clip.wav salida.json [url] +""" +import json, sys, time, wave + +import numpy as np + +from orbisubs import SR, MotorHTTP, Transcriptor, armar_cues + + +def leer_wav(p): + with wave.open(p) as w: + assert w.getframerate() == SR and w.getnchannels() == 1 + return np.frombuffer(w.readframes(w.getnframes()), " 3 else "http://192.168.2.10:8004" + audio = leer_wav(clip) + dur = len(audio) / SR + motor = MotorHTTP(url, timeout=60) + + ref, t_ref = [], [] + for i in range(0, len(audio), 30 * SR): + a = time.time() + ref += [w[2] for w in motor(audio[i:i + 30 * SR], None)] + t_ref.append(time.time() - a) + + tr = Transcriptor(motor, hold=1.0, max_buf=20.0) + vivo, t_vivo, cues = [], [], [] + for i in range(0, len(audio), 6 * SR): + tr.agregar(i / SR, audio[i:i + 6 * SR]) + conf, dt = tr.paso() + t_vivo.append(dt) + vivo += [w[2] for w in conf] + cues += armar_cues(conf) + + r = {"audio_s": round(dur, 1), + "ref_pedidos": len(t_ref), "ref_s_por_pedido": round(sum(t_ref) / len(t_ref), 2), + "vivo_pedidos": len(t_vivo), "vivo_s_por_pedido": round(sum(t_vivo) / len(t_vivo), 2), + "vivo_max_s": round(max(t_vivo), 2), "vivo_rtf": round(sum(t_vivo) / dur, 3), + "referencia": "".join(ref).strip(), "vivo": "".join(vivo).strip(), + "cues": [[round(a, 2), round(b, 2), t] for a, b, t in cues]} + from bench import wer + r["wer_vivo_vs_ref"] = round(wer(r["referencia"], r["vivo"]), 3) + json.dump(r, open(out, "w"), ensure_ascii=False, indent=1) + print(json.dumps({k: v for k, v in r.items() if k not in ("referencia", "vivo", "cues")})) + + +if __name__ == "__main__": + main() diff --git a/deploy/canal.env.example b/deploy/canal.env.example index 5f57b87..dc99ffe 100644 --- a/deploy/canal.env.example +++ b/deploy/canal.env.example @@ -8,3 +8,7 @@ DEVICE=cuda COMPUTE=int8 THREADS=4 BEAM=1 +# Pista English (tarea 077): ASR_EXTRA=--en anuncia la pista y escribe la cola para el traductor. +ASR_EXTRA=--en +LLM_URL=http://192.168.2.10:8001 +LLM_MODEL=qwen2.5-7b-instruct diff --git a/deploy/orbisubs-asr@.service b/deploy/orbisubs-asr@.service index d21f7b4..ac13454 100644 --- a/deploy/orbisubs-asr@.service +++ b/deploy/orbisubs-asr@.service @@ -6,7 +6,7 @@ After=orbisubs-ingest@%i.service EnvironmentFile=/etc/orbisubs/%i.env ExecStart=/opt/orbisubs/venv/bin/python /opt/orbisubs/orbisubs.py --dir /var/www/hls/%i \ --engine ${ENGINE} --url ${URL} --model ${MODEL} --device ${DEVICE} --compute ${COMPUTE} --threads ${THREADS} --beam ${BEAM} \ - --metrics /var/log/orbisubs/%i.jsonl + --metrics /var/log/orbisubs/%i.jsonl $ASR_EXTRA Restart=always RestartSec=5 # Arranque limpio: el .vtt de segmentos viejos no sirve (otro buffer). diff --git a/deploy/orbisubs-tr@.service b/deploy/orbisubs-tr@.service new file mode 100644 index 0000000..a1cf07e --- /dev/null +++ b/deploy/orbisubs-tr@.service @@ -0,0 +1,15 @@ +[Unit] +Description=OrbiSubs traducción %i (español → inglés con el LLM de gpu02) +After=orbisubs-asr@%i.service + +[Service] +EnvironmentFile=/etc/orbisubs/%i.env +# Proceso aparte: si el LLM se cuelga, la pista de español sigue igual. +ExecStartPre=/bin/sh -c 'rm -rf /var/www/hls/%i/en /var/www/hls/%i/en.m3u8; mkdir -p /var/log/orbisubs' +ExecStart=/opt/orbisubs/venv/bin/python /opt/orbisubs/orbisubs_tr.py --dir /var/www/hls/%i \ + --url ${LLM_URL} --model ${LLM_MODEL} --metrics /var/log/orbisubs/%i-en.jsonl +Restart=always +RestartSec=5 + +[Install] +WantedBy=multi-user.target diff --git a/orbisubs.py b/orbisubs.py index d3711a3..8c6b24e 100755 --- a/orbisubs.py +++ b/orbisubs.py @@ -251,6 +251,7 @@ def main(): ap.add_argument("--bandwidth", type=int, default=2600000) ap.add_argument("--resolution", default="1280x720") ap.add_argument("--metrics", default=None) + ap.add_argument("--en", action="store_true", help="anunciar la pista English (la escribe orbisubs_tr.py)") a = ap.parse_args() t = time.time() @@ -266,6 +267,8 @@ def main(): os.makedirs(subs_dir, exist_ok=True) tr = Transcriptor(motor, a.hold, max_buf=20.0) met = open(a.metrics, "a") if a.metrics else None + # Cola para el traductor (otro proceso): si el Qwen se cuelga, este loop ni se entera. + cola = open(os.path.join(a.dir, "cues.jsonl"), "w") if a.en else None llegada = {} # seq -> reloj de pared en que apareció en la lista de ffmpeg info = {} # seq -> (uri, dur, pdt, pts_ini, pts_fin) @@ -276,6 +279,9 @@ def main(): "#EXTM3U\n#EXT-X-VERSION:3\n" '#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID="subs",NAME="Español (automático)",LANGUAGE="es",' 'DEFAULT=NO,AUTOSELECT=YES,FORCED=NO,URI="subs.m3u8"\n' + + ('#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID="subs",NAME="English (automatic)",LANGUAGE="en",' + 'DEFAULT=NO,AUTOSELECT=NO,FORCED=NO,URI="en.m3u8"\n' if a.en else "") + + f'#EXT-X-STREAM-INF:BANDWIDTH={a.bandwidth},RESOLUTION={a.resolution},SUBTITLES="subs"\n' "video.m3u8\n") @@ -336,6 +342,10 @@ def main(): cuerpo += [f"{ts_vtt(c0)} --> {ts_vtt(c1)}", partir_lineas(txt), ""] escribir_atomico(os.path.join(subs_dir, f"{s}.vtt"), "\n".join(cuerpo) + "\n") publicado = s + if cola: + cola.write(json.dumps({"seq": seq, "s0": p0, "s1": p0 + dur, "listo": listo_hasta, + "cues": nuevos_cues}, ensure_ascii=False) + "\n") + cola.flush() # Listas publicadas: video sostenido hasta el último segmento con subtítulo. ventana = [x for x in segs if x[0] <= publicado][-a.window:] if ventana: diff --git a/orbisubs_tr.py b/orbisubs_tr.py new file mode 100644 index 0000000..71ef0ef --- /dev/null +++ b/orbisubs_tr.py @@ -0,0 +1,198 @@ +#!/usr/bin/env python3 +"""OrbiSubs traductor — segunda pista WebVTT en inglés (tarea 077). + +Proceso aparte del de transcripción a propósito: lee la cola /cues.jsonl que +escribe orbisubs.py y, si el LLM tarda o se cae, la pista de español no se entera +(la de inglés queda vacía en ese tramo). + +- Junta los cues en español en frases enteras (punto, pausa o ~6 s): el LLM + traduce mucho mejor una frase que un pedazo de segmento. +- Traduce con el llama.cpp de gpu02 (API OpenAI), temperature 0, sin "thinking" + (Qwen3 piensa por defecto y eso suma segundos), con la frase anterior como contexto. +- Reparte el inglés en cues sobre el tiempo original de la frase y escribe + en/.vtt + en.m3u8 con la misma secuencia que subs.m3u8. +Whisper translate no se usa: large-v3-turbo no se entrenó para traducir y cambiar +el modelo de gpu02 (/load) afecta a todos. +""" +import argparse, json, os, statistics, time + +import requests + +from orbisubs import escribir_atomico, log, partir_lineas, ts_vtt + +SISTEMA = ("You translate live Chilean Spanish TV captions into natural, concise English. " + "Keep proper names, place names and Chilean acronyms (e.g. Carabineros, PDI, SII, AFP, Fonasa) as they are. " + "Translate ONLY the new sentence. Output only the translation, no quotes, no notes.") + + +class Traductor: + def __init__(self, url, modelo, timeout): + self.s = requests.Session() + self.url = url.rstrip("/") + "/v1/chat/completions" + self.modelo, self.timeout = modelo, timeout + self.prev_es, self.prev_en = "", "" + self.tiempos, self.fallas = [], 0 + + def __call__(self, es): + msgs = [{"role": "system", "content": SISTEMA}] + if self.prev_es: + # Contexto: la frase anterior y su traducción, para sostener nombres y tema. + msgs += [{"role": "user", "content": self.prev_es}, {"role": "assistant", "content": self.prev_en}] + msgs.append({"role": "user", "content": es}) + t = time.time() + try: + r = self.s.post(self.url, json={"model": self.modelo, "temperature": 0, "max_tokens": 160, + "chat_template_kwargs": {"enable_thinking": False}, + "messages": msgs}, timeout=self.timeout) + r.raise_for_status() + en = r.json()["choices"][0]["message"]["content"].strip().strip('"').strip() + except Exception as e: + self.fallas += 1 + log("translate_error", err=str(e)[:200]) + return None, time.time() - t + dt = time.time() - t + self.tiempos.append(dt) + if "" in en: # por si el server ignora enable_thinking + en = en.split("")[-1].strip() + self.prev_es, self.prev_en = es, en + return en, dt + + +def repartir(t0, t1, en, max_chars=84): + """Corta el inglés en cues y les da tiempo proporcional a su largo.""" + palabras, trozos, cur = en.split(), [], "" + for w in palabras: + if cur and len(cur) + 1 + len(w) > max_chars: + trozos.append(cur) + cur = w + else: + cur = f"{cur} {w}".strip() + if cur: + trozos.append(cur) + total = sum(len(x) for x in trozos) or 1 + out, t = [], t0 + for x in trozos: + d = (t1 - t0) * len(x) / total + out.append([t, t + d, x]) + t += d + return out + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--dir", required=True) + ap.add_argument("--url", default="http://192.168.2.10:8001") + ap.add_argument("--model", default="qwen2.5-7b-instruct") + ap.add_argument("--timeout", type=float, default=8.0) + ap.add_argument("--max-frase", type=float, default=6.0) + ap.add_argument("--pausa", type=float, default=0.8) + ap.add_argument("--metrics", default=None) + a = ap.parse_args() + + cola_path = os.path.join(a.dir, "cues.jsonl") + en_dir = os.path.join(a.dir, "en") + os.makedirs(en_dir, exist_ok=True) + tr = Traductor(a.url, a.model, a.timeout) + met = open(a.metrics, "a") if a.metrics else None + + segs = {} # seq -> (s0, s1, llegada a la cola) + pend = [] # cues en español sin traducir: [t0, t1, texto] + en_cues = [] # cues en inglés ya escritos + listo_es = None # PTS hasta donde el español está confirmado + hecho = -1 # último seq con en/.vtt + f, pos = None, 0 + while True: + # Seguir la cola como tail -f; si orbisubs.py reinicia la trunca y se reabre. + if f is None or os.path.getsize(cola_path) < pos: + try: + f = open(cola_path) + except FileNotFoundError: + time.sleep(1) + continue + pos, segs, pend, en_cues, hecho = 0, {}, [], [], -1 + f.seek(pos) + lineas = f.readlines() + pos = f.tell() + if not lineas: + time.sleep(0.2) + continue + for l in lineas: + if not l.endswith("\n"): + pos -= len(l.encode()) + break + d = json.loads(l) + segs[d["seq"]] = (d["s0"], d["s1"], time.time()) + pend += d["cues"] + listo_es = d["listo"] + + # Frases cerradas: termina en . ? !, o viene una pausa, o pasó el máximo. + while pend: + fin = None + for i, c in enumerate(pend): + largo = c[1] - pend[0][0] + sig = pend[i + 1] if i + 1 < len(pend) else None + if (c[2].rstrip().endswith((".", "?", "!")) or largo >= a.max_frase + or (sig and sig[0] - c[1] > a.pausa) + or (sig is None and listo_es - c[1] > a.pausa)): + fin = i + break + if fin is None: + break + frase, pend = pend[:fin + 1], pend[fin + 1:] + es = " ".join(c[2] for c in frase) + en, dt = tr(es) + if en: + nuevos = repartir(frase[0][0], frase[-1][1], en) + en_cues = (en_cues + nuevos)[-300:] + if met: + met.write(json.dumps({"t": round(time.time(), 2), "t0": round(frase[0][0], 2), "es": es, "en": en, + "qwen_s": round(dt, 3)}, ensure_ascii=False) + "\n") + met.flush() + + # El inglés está listo hasta el comienzo de lo que falta traducir. + listo_en = pend[0][0] if pend else listo_es + for s in sorted(k for k in segs if k > hecho): + s0, s1, lleg = segs[s] + if s1 > listo_en + 0.05: + break + cuerpo = ["WEBVTT", "X-TIMESTAMP-MAP=MPEGTS:0,LOCAL:00:00:00.000", ""] + for c0, c1, txt in en_cues: + if c1 > s0 and c0 < s1: + cuerpo += [f"{ts_vtt(c0)} --> {ts_vtt(c1)}", partir_lineas(txt), ""] + escribir_atomico(os.path.join(en_dir, f"{s}.vtt"), "\n".join(cuerpo) + "\n") + hecho = s + if met: + met.write(json.dumps({"seg": s, "en_lag_vs_es_s": round(time.time() - lleg, 2)}) + "\n") + met.flush() + # en.m3u8 = subs.m3u8 cortada en el último segmento con inglés. + try: + lineas_es = open(os.path.join(a.dir, "subs.m3u8")).read().splitlines(True) + except FileNotFoundError: + continue + out, bloque = [], [] + for l in lineas_es: + if l.startswith("subs/"): + n = int(l[5:].split(".")[0]) + if n > hecho: + break + out += bloque + [f"en/{n}.vtt\n"] + bloque = [] + elif l.startswith(("#EXTINF", "#EXT-X-PROGRAM-DATE-TIME")): + bloque.append(l) + else: + out.append(l) + if any(l.startswith("en/") for l in out): + escribir_atomico(os.path.join(a.dir, "en.m3u8"), "".join(out)) + for x in os.listdir(en_dir): + if x.endswith(".vtt") and int(x[:-4]) < hecho - 30: + os.unlink(os.path.join(en_dir, x)) + for k in [k for k in segs if k < hecho - 30]: + segs.pop(k) + if tr.tiempos and len(tr.tiempos) % 20 == 0: + ts = sorted(tr.tiempos) + log("qwen_stats", n=len(ts), median=round(statistics.median(ts), 3), + p95=round(ts[int(len(ts) * 0.95) - 1], 3), fallas=tr.fallas) + + +if __name__ == "__main__": + main() diff --git a/web/player.html b/web/player.html index 9e4a86e..420094e 100644 --- a/web/player.html +++ b/web/player.html @@ -24,7 +24,10 @@ function cargar(){ hls.loadSource(document.getElementById('u').value); hls.attachMedia(v); hls.on(Hls.Events.SUBTITLE_TRACKS_UPDATED,()=>{ s.innerHTML=''+hls.subtitleTracks.map((t,i)=>``).join(''); - s.value=0; hls.subtitleTrack=0; hls.subtitleDisplay=true; + // Arranca en la pista pedida por ?lang=en (o en español). + const q=new URLSearchParams(location.search).get('lang')||'es'; + const i=Math.max(0,hls.subtitleTracks.findIndex(t=>t.lang===q)); + s.value=i; hls.subtitleTrack=i; hls.subtitleDisplay=true; }); s.onchange=()=>{hls.subtitleTrack=+s.value; hls.subtitleDisplay=+s.value>=0;}; // Diagnóstico: cuántos cues cargó la pista y cuál está en pantalla (sirve para