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/<seq>.vtt + en.m3u8. Tarea 077.
This commit is contained in:
+198
@@ -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 <dir>/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/<seq>.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 "<think>" in en: # por si el server ignora enable_thinking
|
||||
en = en.split("</think>")[-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/<seq>.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()
|
||||
Reference in New Issue
Block a user