From 85309585af9cb9472faef3c860591c2f79fb23cd Mon Sep 17 00:00:00 2001 From: guy Date: Sun, 22 Nov 2026 14:12:04 -0300 Subject: [PATCH] OrbiSubs ASR: skip a segment whose PTS cannot be read; prune Master.vistos MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Revisión externa 1.4 y 3.2: después de 10 intentos, y con un segmento posterior en la lista, el seq sale con un .vtt vacío (sin inventar PTS) y se loguea pts_skip. test_revision.py cubre también 1.3, 1.5 y 1.6. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JAUCv2ADyD2NSg4ub9YPr1 --- orbisubs.py | 58 ++++++++++++++++++++++--- test_revision.py | 111 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 164 insertions(+), 5 deletions(-) create mode 100644 test_revision.py diff --git a/orbisubs.py b/orbisubs.py index 999c393..652f934 100755 --- a/orbisubs.py +++ b/orbisubs.py @@ -485,6 +485,9 @@ class Master: nuevo = True except OSError: pass + # Solo los seq que siguen en la lista: antes crecía para siempre, uno por segmento + # (~14.400 por día con 6 s; revisión externa, 3.2). + self.vistos &= {x[0] for x in segs} if not nuevo: return False cambio = False @@ -572,6 +575,39 @@ ADELANTO_SRT = 0.5 CARGA_608 = 1.5 +class PtsFallidos: + """Segmentos de video cuyo PTS no se puede leer (.ts dañado). Antes se reintentaba + para siempre y video.m3u8 se frenaba en ese segmento hasta que salía de la ventana + de la ingesta (~1 min con 10 de 6 s): el player se quedaba sin video y el canal sin + subtítulos (revisión externa, 1.4). Después de INTENTOS, y si ya hay uno después (el + .ts está cerrado), se saltea: sale en video.m3u8 con un .vtt vacío. El PTS no se + inventa: un cue con PTS supuesto podría aparecer en otro lado del video.""" + INTENTOS = 10 + + def __init__(self): + self.n, self.salteados = {}, set() + + def fallo(self, seq, ultimo, err=""): + """Un intento fallido. Devuelve True si quedó salteado.""" + n = self.n[seq] = self.n.get(seq, 0) + 1 + if n >= self.INTENTOS and seq < ultimo and seq not in self.salteados: + self.salteados.add(seq) + log("pts_skip", seq=seq, tries=n, err=str(err)[:200]) + return True + return False + + def podar(self, desde): + self.n = {k: v for k, v in self.n.items() if k >= desde} + self.salteados = {k for k in self.salteados if k >= desde} + + def limpiar(self): + self.n.clear() + self.salteados.clear() + + +VTT_VACIO = "WEBVTT\n\n" + + def pts_inicio(path): pr = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "a:0", "-show_entries", "stream=start_time", "-of", "csv=p=0", path], capture_output=True, text=True) @@ -610,6 +646,7 @@ def bucle_trozos(a, motor, tr, met, cola, src, subs_dir): # La 081 medía contra la llegada del propio segmento (y0 = y): con ráfagas daba de menos. ys = deque() # (reloj, y) ys_nuevos = [] + pts_mal = PtsFallidos() while True: segs, tgt = leer_lista(src) trozos, _ = leer_lista(aud) @@ -619,7 +656,7 @@ def bucle_trozos(a, motor, tr, met, cola, src, subs_dir): if trozos and trozos[-1][0] < aud_hecho: log("sequence_reset", last=aud_hecho, now=trozos[-1][0]) aud_hecho, publicado = -1, None - info.clear(); llegada.clear(); ys.clear() + info.clear(); llegada.clear(); ys.clear(); pts_mal.limpiar() nuevos = [x for x in trozos if x[0] > aud_hecho] if aud_hecho < 0 or (nuevos and nuevos[0][0] != aud_hecho + 1): nuevos = nuevos[-1:] # arranque o salto: desde el último trozo @@ -634,15 +671,15 @@ def bucle_trozos(a, motor, tr, met, cola, src, subs_dir): lleg_audio = ahora # PTS de los segmentos de video nuevos (solo ffprobe, sin decodificar). for seq, uri, dur, pdt in segs: - if seq not in info and (publicado is None or seq > publicado): + if seq not in info and seq not in pts_mal.salteados and (publicado is None or seq > publicado): try: p = al_audio(pts_inicio(os.path.join(a.dir, "src", uri)), tr) info[seq] = (dur, p, p + dur) if seq in llegada and publicado is not None: ys.append((time.time(), llegada[seq] - (p + dur))) ys_nuevos.append(ys[-1][1]) - except Exception: - pass + except Exception as e: + pts_mal.fallo(seq, segs[-1][0], e) if publicado is None and segs: publicado = segs[-1][0] - 1 # arranque: no transcribir historia elif publicado is not None and segs and not any(x[0] == publicado + 1 for x in segs) \ @@ -654,6 +691,7 @@ def bucle_trozos(a, motor, tr, met, cola, src, subs_dir): publicado = segs[-1][0] - 1 ys.clear() # PTS nuevos: los y viejos son de otra línea de tiempo info = {k: v for k, v in info.items() if k > publicado} + pts_mal.limpiar() conf, dt, err = [], 0.0, None if nuevos: if hasattr(motor, "ultimo"): @@ -675,8 +713,17 @@ def bucle_trozos(a, motor, tr, met, cola, src, subs_dir): cola.flush() # Publicar los segmentos de video que ya tienen todo su texto (o el tope). pub_antes = publicado - while publicado is not None and publicado + 1 in info: + while publicado is not None and (publicado + 1 in info or publicado + 1 in pts_mal.salteados): s = publicado + 1 + if s not in info: + # .ts sin PTS legible: sale sin subtítulo (y sin inglés: el traductor no lo + # va a ver en la cola, y en.m3u8 lo nombra igual). + escribir_atomico(os.path.join(subs_dir, f"{s}.vtt"), VTT_VACIO) + if a.en: + os.makedirs(os.path.join(a.dir, "en"), exist_ok=True) + escribir_atomico(os.path.join(a.dir, "en", f"{s}.vtt"), VTT_VACIO) + publicado = s + continue dur, s0, s1 = info[s] ultimo_video = segs[-1][0] if segs else s if not (s1 <= listo + 0.05 or audio_fin >= s1 + cap or s < ultimo_video - 1): @@ -696,6 +743,7 @@ def bucle_trozos(a, motor, tr, met, cola, src, subs_dir): if primero is not None: for k in [k for k in info if k < primero - 5]: info.pop(k, None); llegada.pop(k, None) + pts_mal.podar(primero - 5) if not nuevos and publicado == pub_antes: time.sleep(0.1) continue diff --git a/test_revision.py b/test_revision.py new file mode 100644 index 0000000..326b8b4 --- /dev/null +++ b/test_revision.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python3 +"""Tests de los arreglos de la revisión externa (097). Correr: python3 -m unittest test_revision""" +import os +import tempfile +import types +import unittest + +import orbisubs as O +import orbisubs_srt as S +import orbisubs_tr as T + + +class Vistos(unittest.TestCase): + # 1.5: la poda tiene que olvidar los más viejos, nunca los recién vistos. + def test_poda_fifo(self): + v = S.Vistos(maximo=20, deja=10) + for i in range(21): + v.add(i) + self.assertEqual(len(v), 10) + self.assertNotIn(0, v) + self.assertNotIn(10, v) + for i in range(11, 21): + self.assertIn(i, v) + + def test_cue_repetido_no_entra_tras_la_poda(self): + e = S.Enc608(1) + # 2500 cues distintos (pasa la poda) y el último vuelve a llegar (por la cola y el .vtt). + for i in range(2500): + e.agregar((1000.0 + i, 1000.5 + i, f"cue {i}"), 0) + n = len(e.cola) + e.agregar((1000.0 + 2499, 1000.5 + 2499, "cue 2499"), 0) + self.assertEqual(len(e.cola), n) + + +class Cola(unittest.TestCase): + # 1.6: al truncarse la cola se cierra el archivo viejo. + def test_cierra_al_reabrir(self): + with tempfile.TemporaryDirectory() as d: + p = os.path.join(d, "cues.jsonl") + open(p, "w").write('[1, 2, "a"]\n') + c = S.Cola(p) + c.primera = False + self.assertEqual(len(c.nuevos()), 1) + viejo = c.f + open(p, "w").write("") # truncada por un reinicio del ASR + c.nuevos() + self.assertTrue(viejo.closed) + os.unlink(p) # se borra: no se cae + self.assertEqual(c.nuevos(), []) + + +class Think(unittest.TestCase): + # 1.3: un cortado por max_tokens no sale como subtítulo. + def test_think(self): + self.assertEqual(T.sin_think("Hello."), "Hello.") + self.assertEqual(T.sin_think("hmm Hello."), "Hello.") + self.assertEqual(T.sin_think("The user wants me to translate"), "") + + +class PtsFallidos(unittest.TestCase): + # 1.4: un .ts dañado se saltea después de N intentos, sin inventar PTS. + def test_ts_danado(self): + with tempfile.TemporaryDirectory() as d: + p = os.path.join(d, "1.ts") + open(p, "wb").write(os.urandom(4000)) + with self.assertRaises(Exception): + O.pts_inicio(p) + + def test_saltea_despues_de_n(self): + f = O.PtsFallidos() + for _ in range(f.INTENTOS - 1): + self.assertFalse(f.fallo(5, 7)) + self.assertTrue(f.fallo(5, 7)) + self.assertIn(5, f.salteados) + self.assertFalse(f.fallo(5, 7)) # una sola vez + + def test_el_ultimo_no_se_saltea(self): + # El último de la lista puede estar escribiéndose: se espera a que haya otro. + f = O.PtsFallidos() + for _ in range(3 * f.INTENTOS): + f.fallo(7, 7) + self.assertNotIn(7, f.salteados) + self.assertTrue(f.fallo(7, 8)) + + def test_podar(self): + f = O.PtsFallidos() + for _ in range(f.INTENTOS): + f.fallo(5, 9) + f.podar(6) + self.assertEqual((f.n, f.salteados), ({}, set())) + + +class MasterVistos(unittest.TestCase): + # 3.2: Master.vistos solo guarda los seq que siguen en la lista. + def test_poda(self): + with tempfile.TemporaryDirectory() as d: + src = os.path.join(d, "index.m3u8") + m = O.Master(types.SimpleNamespace(resolution="1920x1080", bandwidth=8000000, dir=d)) + m.vistos = set() + for base in range(0, 100, 10): + lst = "#EXTM3U\n#EXT-X-TARGETDURATION:6\n#EXT-X-MEDIA-SEQUENCE:%d\n" % base + for i in range(10): + open(os.path.join(d, f"{base + i}.ts"), "wb").write(b"x" * 100) + lst += f"#EXTINF:6.0,\n{base + i}.ts\n" + open(src, "w").write(lst) + m.medir(src) + self.assertEqual(m.vistos, set(range(90, 99))) + + +if __name__ == "__main__": + unittest.main()