Compare commits
7 Commits
b41593bf22
...
d6a410801c
| Author | SHA1 | Date | |
|---|---|---|---|
| d6a410801c | |||
| 85309585af | |||
| 2d7fe8a43b | |||
| ab1c542264 | |||
| d600150088 | |||
| e8261ab458 | |||
| e30fc3dd87 |
@@ -52,6 +52,7 @@ En HULK lo trabaja la sesión de Claude que corre ahí, por tareas de `../orbicl
|
||||
| 608, 708 o los dos | La sesión recomienda los dos |
|
||||
| Glosario de nombres y siglas chilenas | El panel tiene "Prompt fijo". Falta que Jorge diga si se usa por canal |
|
||||
| Otros idiomas | Por ahora es y en |
|
||||
| Fuente que ya trae captions propios (SEI) | Pendiente para producto (revisión externa, 097). Hoy el remux de `orbisubs_srt.py` mete nuestros 608/708 y deja los de la fuente: los dos quedan mezclados en el video. Hay que elegir entre sacar los de la fuente, dejarlos o no escribir los nuestros en ese canal |
|
||||
| GOP y segmento para OrbiStream | **Decidido** (Jorge, 2026-11-19: "dejemoslo con tus recomendaciones"): GOP 2 s, segmentos de 2 s y trozos de audio de 3 s, con margen de confirmación de 1 s. Medido en la 083: HLS ~8–10 s y SRT ~8 s, parejos, WER ~0,23 |
|
||||
| Colchón del player | **Decidido** (misma fecha): T13 queda en 13 s fijo por las ráfagas de su CDN; los demás canales, automático |
|
||||
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
# /etc/logrotate.d/orbisubs — métricas por segmento de los procesos de OrbiSubs (097).
|
||||
# ~100 MB por semana con ecuadortv solo (2026-11-22). copytruncate: orbisubs.py,
|
||||
# orbisubs_tr.py y orbisubs_srt.py tienen el archivo abierto en modo append y no lo
|
||||
# reabren; el panel lee la cola del archivo, así que después de truncar sigue leyendo bien
|
||||
# (las alarmas y el retraso automático esperan unos minutos de filas nuevas).
|
||||
/var/log/orbisubs/*.jsonl {
|
||||
daily
|
||||
rotate 7
|
||||
compress
|
||||
delaycompress
|
||||
missingok
|
||||
notifempty
|
||||
copytruncate
|
||||
}
|
||||
+53
-5
@@ -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
|
||||
|
||||
+33
-5
@@ -32,6 +32,29 @@ FPS_TICKS = 3000 # 90 kHz / 30 fps
|
||||
ADELANTO_S = 0.5
|
||||
|
||||
|
||||
class Vistos:
|
||||
"""Cues ya encolados, con poda FIFO. Antes era un set podado con
|
||||
set(list(vistos)[-1000:]): el orden de un set es el del hash, así que se olvidaban
|
||||
cues al azar (también los recién vistos) y uno repetido por la cola y el .vtt podía
|
||||
volver a entrar (revisión externa, 1.5)."""
|
||||
|
||||
def __init__(self, maximo=2000, deja=1000):
|
||||
self.d, self.maximo, self.deja = {}, maximo, deja
|
||||
|
||||
def __contains__(self, k):
|
||||
return k in self.d
|
||||
|
||||
def __len__(self):
|
||||
return len(self.d)
|
||||
|
||||
def add(self, k):
|
||||
self.d[k] = None
|
||||
if len(self.d) > self.maximo:
|
||||
# dict guarda el orden de inserción: se quedan los últimos `deja`.
|
||||
for viejo in list(self.d)[:len(self.d) - self.deja]:
|
||||
del self.d[viejo]
|
||||
|
||||
|
||||
class Cola:
|
||||
"""Sigue un .jsonl como tail -f (cues.jsonl del ASR o en_cues.jsonl del traductor):
|
||||
el texto está acá apenas se confirma, antes de que se escriba el .vtt del segmento."""
|
||||
@@ -43,6 +66,11 @@ class Cola:
|
||||
def nuevos(self):
|
||||
try:
|
||||
if self.f is None or os.path.getsize(self.path) < self.pos:
|
||||
# Truncada (el ASR reinició): se cierra el descriptor viejo, si no se
|
||||
# acumulaba uno abierto por cada reinicio del ASR (revisión externa, 1.6).
|
||||
if self.f is not None:
|
||||
self.f.close()
|
||||
self.f = None
|
||||
self.f, self.pos = open(self.path, encoding="utf-8"), 0
|
||||
if self.primera:
|
||||
# Lo que ya estaba al arrancar puede ser de una corrida anterior de la
|
||||
@@ -52,6 +80,8 @@ class Cola:
|
||||
self.pos = os.path.getsize(self.path)
|
||||
self.primera = False
|
||||
except OSError:
|
||||
if self.f is not None:
|
||||
self.f.close()
|
||||
self.f = None
|
||||
return []
|
||||
self.f.seek(self.pos)
|
||||
@@ -188,7 +218,7 @@ class Enc608:
|
||||
|
||||
def __init__(self, campo):
|
||||
self.misc = 0x14 if campo == 1 else 0x15 # CC1 en campo 1, CC3 en campo 2
|
||||
self.cola, self.vistos = [], set()
|
||||
self.cola, self.vistos = [], Vistos()
|
||||
self.cargando, self.cargado, self.mostrando = None, None, None
|
||||
self.out = deque()
|
||||
self.st = {"cues": 0, "tarde": 0, "perdidos": 0, "tarde_max_s": 0.0, "juntados": 0}
|
||||
@@ -208,8 +238,6 @@ class Enc608:
|
||||
if k in self.vistos:
|
||||
return
|
||||
self.vistos.add(k)
|
||||
if len(self.vistos) > 2000:
|
||||
self.vistos = set(list(self.vistos)[-1000:])
|
||||
if cue[1] <= t_actual + 0.5 or (self.descartar_tarde and cue[0] < t_actual):
|
||||
# Llegó cuando ya había pasado. Con el retraso fijado por el español, el
|
||||
# inglés que llega después de su PTS se descarta entero: no se atrasa el
|
||||
@@ -332,7 +360,7 @@ class Enc708:
|
||||
|
||||
def __init__(self, servicio, presupuesto=14):
|
||||
self.svc, self.pres = servicio, presupuesto
|
||||
self.cola, self.vistos = [], set()
|
||||
self.cola, self.vistos = [], Vistos()
|
||||
self.carga = bytearray() # definición + texto del cue planificado (oculto)
|
||||
self.eventos = [] # [t, bytes, es_mostrar] ordenados por t
|
||||
self.planificado = None # cue cargándose o cargado, todavía no mostrado
|
||||
@@ -808,7 +836,7 @@ def main():
|
||||
if ultimo_pcr is not None:
|
||||
# La ingesta reinició (PTS nuevos): lo encolado es de la línea de tiempo vieja.
|
||||
for e in (es608, en608, es708, en708):
|
||||
e.cola, e.vistos = [], set()
|
||||
e.cola, e.vistos = [], Vistos()
|
||||
atraso_envio = time.time() - (base_wall + (p0 - base_pcr) / 27e6)
|
||||
# Si la base se fijó con un segmento que llegó temprano (al reconectar la fuente,
|
||||
# ffmpeg suelta lo que tenía en el buffer de golpe), después todos llegan tarde
|
||||
|
||||
+36
-8
@@ -55,12 +55,25 @@ class Traductor:
|
||||
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()
|
||||
en = sin_think(en)
|
||||
if not en:
|
||||
return None, time.time() - t
|
||||
self.prev_es, self.prev_en = es, en
|
||||
return en, dt
|
||||
|
||||
|
||||
def sin_think(en):
|
||||
"""Saca el razonamiento si el server ignora enable_thinking. Un <think> sin </think>
|
||||
es una respuesta cortada por max_tokens: es razonamiento, no traducción, y antes salía
|
||||
entero como subtítulo en inglés (revisión externa, 1.3). Se descarta."""
|
||||
if "<think>" not in en:
|
||||
return en
|
||||
if "</think>" not in en:
|
||||
log("translate_cut", chars=len(en))
|
||||
return ""
|
||||
return en.split("</think>")[-1].strip()
|
||||
|
||||
|
||||
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(), [], ""
|
||||
@@ -121,13 +134,28 @@ def main():
|
||||
inicial = False # True recién abierta la cola, hasta saltear la historia
|
||||
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
|
||||
# getsize va dentro del try: si se borra la cola (canal borrado o reinstalado) se
|
||||
# espera a que vuelva en vez de caerse; y el archivo viejo se cierra al reabrir
|
||||
# (revisión externa, 1.6).
|
||||
try:
|
||||
reabrir = f is None or os.path.getsize(cola_path) < pos
|
||||
if reabrir:
|
||||
nuevo = open(cola_path)
|
||||
except FileNotFoundError:
|
||||
if f is not None:
|
||||
f.close()
|
||||
f = None
|
||||
time.sleep(1)
|
||||
continue
|
||||
if reabrir:
|
||||
if f is not None:
|
||||
f.close()
|
||||
f = nuevo
|
||||
pos, segs, pend, en_cues, hecho, hecho_s1 = 0, {}, [], [], -1, None
|
||||
# Cola truncada = el ASR reinició con PTS nuevos: los inicios de cue ya escritos
|
||||
# son de la línea de tiempo vieja y podían dejar afuera un cue nuevo con el
|
||||
# mismo inicio (revisión externa, 1.2).
|
||||
escritos.clear()
|
||||
inicial = True
|
||||
f.seek(pos)
|
||||
lineas = f.readlines()
|
||||
|
||||
+27
-10
@@ -9,6 +9,8 @@
|
||||
// oye habla (palabras en su log): un silencio real no la dispara, ni el canal parado.
|
||||
// El HLS solo guarda los .vtt de su ventana (~90 s), así que la hora del último con
|
||||
// texto la recuerda el panel entre vueltas.
|
||||
// Si el ASR se congela (proceso colgado con la unidad "active": no escribe más su log),
|
||||
// no hay palabras con qué juzgar, pero tampoco subtítulos: también la enciende.
|
||||
// - cc608: la salida SRT pierde más del CC_PCT % de los cues del 608 en CC_S, o no
|
||||
// muestra ninguno (o no escribe métricas) mientras el ASR sí transcribe.
|
||||
const fs = require('fs');
|
||||
@@ -24,6 +26,7 @@ const CFG = {
|
||||
CC_PCT: num('ALARMA_608_PCT', 5),
|
||||
CC_MIN: num('ALARMA_608_MIN', 20), // cues + perdidos mínimos para sacar un %
|
||||
SRT_STALE_S: 120,
|
||||
ASR_STALE_S: 120, // el ASR escribe una fila cada trozo (3 s), con o sin habla
|
||||
};
|
||||
const TICK_S = 30;
|
||||
|
||||
@@ -41,15 +44,23 @@ function delta608(rows, desde) {
|
||||
// Decisión pura (testeable). Devuelve { sin_subs: motivo|null, cc608: motivo|null }.
|
||||
// asr: filas del log del ASR (t, words); texto: epoch s del último .vtt con texto
|
||||
// visto (o desde cuándo se mira); srt: filas del log de la salida SRT o null si no tiene;
|
||||
// srtMtime: epoch s de la última métrica de la salida SRT.
|
||||
function evaluar({ now, asr, texto, srt, srtMtime, c = CFG }) {
|
||||
// srtMtime: epoch s de la última métrica de la salida SRT; desde: epoch s desde que la
|
||||
// ingesta y el ASR están activos (asr trae solo filas de esta corrida); asrUlt: epoch s
|
||||
// de la última fila del ASR de esta corrida (la ventana de asr puede quedar vacía).
|
||||
function evaluar({ now, asr, texto, srt, srtMtime, desde = null, asrUlt, c = CFG }) {
|
||||
const out = { sin_subs: null, cc608: null };
|
||||
// ASR congelado: activo hace rato y sin filas nuevas. Antes la alarma se apagaba a los
|
||||
// 5 min (ya no había palabras en la ventana) o al pasar el estado a 'error' (1.1).
|
||||
const ultAsr = asrUlt ?? (asr.length ? asr[asr.length - 1].t : desde);
|
||||
if (desde != null && now - desde >= c.SUBS_S && ultAsr != null && now - ultAsr > c.ASR_STALE_S && now - texto > c.SUBS_S) {
|
||||
out.sin_subs = `el ASR no escribe hace ${Math.round((now - ultAsr) / 60)} min (¿colgado?); ningún .vtt con texto hace ${Math.round((now - texto) / 60)} min`;
|
||||
}
|
||||
const palabras = d => asr.filter(r => r.t >= now - d).reduce((s, r) => s + (r.words || 0), 0);
|
||||
// El log tiene que cubrir la ventana entera: recién arrancado no hay con qué juzgar.
|
||||
const cubre = d => asr.length && asr[0].t <= now - d;
|
||||
// Las palabras se miran en al menos 5 min (con SUBS_S bajo, para probar, igual hay habla).
|
||||
const ventana = Math.max(c.SUBS_S, 300);
|
||||
if (cubre(ventana) && palabras(ventana) >= c.MIN_WORDS && now - texto > c.SUBS_S) {
|
||||
if (!out.sin_subs && cubre(ventana) && palabras(ventana) >= c.MIN_WORDS && now - texto > c.SUBS_S) {
|
||||
out.sin_subs = `ningún .vtt con texto hace ${Math.round((now - texto) / 60)} min, con ${palabras(ventana)} palabras del ASR en ${Math.round(ventana / 60)} min`;
|
||||
}
|
||||
if (srt && cubre(c.CC_S)) {
|
||||
@@ -126,18 +137,24 @@ async function tick(getChannels = canales) {
|
||||
const now = Date.now() / 1000;
|
||||
chans.forEach(ch => {
|
||||
const s = st[ch.id];
|
||||
// Parado o arrancando: nada que juzgar, y lo que estaba encendido se cierra.
|
||||
const corre = s && s.state === 'running';
|
||||
// Parado: nada que juzgar, y lo que estaba encendido se cierra. "Corre" es lo que
|
||||
// dice systemd de la ingesta y el ASR, no `state`: ese pasa a 'error' cuando el ASR
|
||||
// se congela, y cerraba la alarma justo cuando hacía falta (revisión externa, 1.1).
|
||||
const corre = !!(s && s.up);
|
||||
if (!corre) vistoTexto.delete(ch.slug);
|
||||
const res = corre ? evaluarCanal(ch, now) : { sin_subs: null, cc608: null };
|
||||
const res = corre ? evaluarCanal(ch, now, s.up_since) : { sin_subs: null, cc608: null };
|
||||
for (const [q, kind] of aplicar(ch.slug, res, now)) console.log(`[alarmas] ${ch.slug}: ${kind} ${q}`);
|
||||
});
|
||||
} finally { corriendo = false; }
|
||||
}
|
||||
|
||||
function evaluarCanal(ch, now) {
|
||||
const asr = status.tailJsonl(path.join(status.LOG_DIR, `${ch.slug}.jsonl`), 1 << 20).rows
|
||||
.filter(r => r.seq != null && typeof r.t === 'number' && r.t >= now - Math.max(CFG.SUBS_S, CFG.CC_S) - 60);
|
||||
function evaluarCanal(ch, now, desde = null) {
|
||||
// Solo filas de esta corrida: al arrancar, el .jsonl trae las de la anterior (y daba
|
||||
// por cubierta la ventana con datos viejos).
|
||||
const filas = status.tailJsonl(path.join(status.LOG_DIR, `${ch.slug}.jsonl`), 1 << 20).rows
|
||||
.filter(r => r.seq != null && typeof r.t === 'number' && (desde == null || r.t >= desde));
|
||||
const asrUlt = filas.length ? filas[filas.length - 1].t : desde;
|
||||
const asr = filas.filter(r => r.t >= now - Math.max(CFG.SUBS_S, CFG.CC_S) - 60);
|
||||
let srt = null, srtMtime = null;
|
||||
if (ch.cfg.srt && ch.cfg.srt.enabled) {
|
||||
const s = status.tailJsonl(path.join(status.LOG_DIR, `${ch.slug}-srt.jsonl`), 512 * 1024);
|
||||
@@ -146,7 +163,7 @@ function evaluarCanal(ch, now) {
|
||||
}
|
||||
const u = ultimoVttConTexto(ch.slug);
|
||||
vistoTexto.set(ch.slug, Math.max(vistoTexto.get(ch.slug) ?? now, u ?? 0));
|
||||
return evaluar({ now, asr, texto: vistoTexto.get(ch.slug), srt, srtMtime });
|
||||
return evaluar({ now, asr, texto: vistoTexto.get(ch.slug), srt, srtMtime, desde, asrUlt });
|
||||
}
|
||||
|
||||
function start(getChannels = canales) {
|
||||
|
||||
@@ -29,7 +29,14 @@ function inputUrl(i) {
|
||||
return `srt://${i.mode === 'listener' ? '0.0.0.0' : i.host}:${i.port}?${q.join('&')}`;
|
||||
}
|
||||
|
||||
const q = v => `"${String(v).replace(/[\\"]/g, '\\$&')}"`;
|
||||
// Valor entre comillas para el .env. Un \r, \n o \0 partiría la línea y metería variables
|
||||
// en el EnvironmentFile (revisión externa, 2.3): validate.js ya los rechaza; si igual
|
||||
// llega uno (canal viejo en la base, otro camino), no se escribe el .env.
|
||||
const q = v => {
|
||||
const s = String(v);
|
||||
if (/[\r\n\0]/.test(s)) throw new Error('Valor con salto de línea: no se escribe el .env');
|
||||
return `"${s.replace(/[\\"]/g, '\\$&')}"`;
|
||||
};
|
||||
|
||||
// Retraso automático de la salida SRT (tarea 081): p95 de lo que necesitó cada cue para
|
||||
// llegar a su PTS (srt_need_s, lo mide orbisubs.py) más 2 s (1,5 s de carga del 608 pop-on
|
||||
@@ -278,4 +285,4 @@ function removeEnv(slug) {
|
||||
try { fs.unlinkSync(posFile(slug)); } catch { /* no estaba */ }
|
||||
}
|
||||
|
||||
module.exports = { start, stop, envText, inputUrl, wanted, allUnits, removeEnv, srtDelay, holdBack, enPlazo, writePos, posFile };
|
||||
module.exports = { start, stop, envText, inputUrl, q, wanted, allUnits, removeEnv, srtDelay, holdBack, enPlazo, writePos, posFile };
|
||||
|
||||
@@ -28,7 +28,8 @@ function unitsOf(ch) {
|
||||
// Un solo `systemctl show` para todas las unidades de todos los canales.
|
||||
async function systemdState(units) {
|
||||
if (!units.length) return {};
|
||||
const out = await sh('systemctl', ['show', '--no-pager', '-p', 'Id,LoadState,ActiveState,SubState,NRestarts,Result,UnitFileState', ...units]);
|
||||
// --timestamp=unix: ActiveEnterTimestamp como @epoch (systemd ≥ 248; el CT 176 tiene 252).
|
||||
const out = await sh('systemctl', ['show', '--no-pager', '--timestamp=unix', '-p', 'Id,LoadState,ActiveState,SubState,NRestarts,Result,UnitFileState,ActiveEnterTimestamp', ...units]);
|
||||
const res = {};
|
||||
for (const block of out.split(/\n\s*\n/)) {
|
||||
const o = {};
|
||||
@@ -36,7 +37,9 @@ async function systemdState(units) {
|
||||
const i = line.indexOf('=');
|
||||
if (i > 0) o[line.slice(0, i)] = line.slice(i + 1);
|
||||
}
|
||||
if (o.Id) res[o.Id] = { load: o.LoadState, active: o.ActiveState, sub: o.SubState, restarts: Number(o.NRestarts || 0), result: o.Result, file: o.UnitFileState };
|
||||
// since: desde cuándo está activa (epoch s), para no juzgar el .jsonl de una corrida anterior.
|
||||
const since = /^@\d+/.test(o.ActiveEnterTimestamp || '') ? Number(o.ActiveEnterTimestamp.slice(1)) : null;
|
||||
if (o.Id) res[o.Id] = { load: o.LoadState, active: o.ActiveState, sub: o.SubState, restarts: Number(o.NRestarts || 0), result: o.Result, file: o.UnitFileState, since };
|
||||
}
|
||||
return res;
|
||||
}
|
||||
@@ -137,7 +140,18 @@ function summarize(ch, sd) {
|
||||
else if (act.some(a => a === 'activating' || a === 'reloading')) state = 'connecting';
|
||||
else state = 'error'; // a medias: algunas andan y otras no
|
||||
const notes = units.filter(u => u.active !== 'active' && state !== 'stopped').map(u => `${u.key}: ${u.active}${u.result && u.result !== 'success' ? ` (${u.result})` : ''}`);
|
||||
return { state, units, notes, managed: units.some(u => u.load === 'loaded') };
|
||||
return { state, units, notes, managed: units.some(u => u.load === 'loaded'), ...produce(units) };
|
||||
}
|
||||
|
||||
// ¿El canal está para producir subtítulos, según systemd? La ingesta y el ASR activos.
|
||||
// Las alarmas (096) miran esto y no `state`, que pasa a 'error' justo cuando el ASR se
|
||||
// congela y cerraba la alarma "sin subtítulos" (revisión externa, 1.1). up_since: desde
|
||||
// cuándo, la más reciente de las dos (epoch s).
|
||||
function produce(units) {
|
||||
const base = units.filter(u => u.key === 'ingest' || u.key === 'asr');
|
||||
const up = base.length === 2 && base.every(u => u.active === 'active');
|
||||
const since = up && base.every(u => u.since) ? Math.max(...base.map(u => u.since)) : null;
|
||||
return { up, up_since: since };
|
||||
}
|
||||
|
||||
async function all(channels) {
|
||||
@@ -146,8 +160,10 @@ async function all(channels) {
|
||||
for (const ch of channels) {
|
||||
const s = summarize(ch, sd);
|
||||
const m = metrics(ch);
|
||||
// Corriendo según systemd pero sin producir subtítulos: se muestra como error.
|
||||
if (s.state === 'running' && !m.fresh && m.age_s !== null && m.age_s > STALE_S * 2) {
|
||||
// Corriendo según systemd pero sin producir subtítulos: se muestra como error. Recién
|
||||
// arrancado, el .jsonl todavía es el de la corrida anterior: no es un error.
|
||||
const arrancando = s.up_since && Date.now() / 1000 - s.up_since < STALE_S * 2;
|
||||
if (s.state === 'running' && !arrancando && !m.fresh && m.age_s !== null && m.age_s > STALE_S * 2) {
|
||||
s.state = 'error'; s.notes.push(`sin subtítulos nuevos hace ${m.age_s} s`);
|
||||
}
|
||||
res[ch.id] = { ...s, metrics: m };
|
||||
@@ -155,4 +171,4 @@ async function all(channels) {
|
||||
return res;
|
||||
}
|
||||
|
||||
module.exports = { all, metrics, failures, unitsOf, systemdState, summarize, tailJsonl, LOG_DIR, HLS_DIR };
|
||||
module.exports = { all, metrics, failures, unitsOf, systemdState, summarize, produce, tailJsonl, STALE_S, LOG_DIR, HLS_DIR };
|
||||
|
||||
@@ -8,7 +8,9 @@
|
||||
|
||||
const SLUG_RE = /^[a-z0-9][a-z0-9-]{0,30}$/;
|
||||
// Puertos del CT que no puede tomar ningún canal (ssh, smtp local, nginx, este panel).
|
||||
const RESERVED = new Set([22, 25, 80, 443, Number(process.env.PORT) || 4700]);
|
||||
// 4700 siempre (es el del servicio instalado) y además PORT si el panel corre en otro
|
||||
// (revisión externa, 1.7: con PORT distinto, 4700 quedaba libre y el test fallaba).
|
||||
const RESERVED = new Set([22, 25, 80, 443, 4700, Number(process.env.PORT) || 4700]);
|
||||
// El codificador de la 078 escribe CC1 (campo 1) y CC3 (campo 2); CC2/CC4 no.
|
||||
const CC608 = ['CC1', 'CC3'];
|
||||
const LANGS = ['es', 'en', 'pt'];
|
||||
@@ -19,6 +21,14 @@ class ValidationError extends Error {
|
||||
const bad = (msg, field) => { throw new ValidationError(msg, field); };
|
||||
|
||||
const str = v => (v == null ? '' : String(v).trim());
|
||||
// Lo que va a /etc/orbisubs/<id>.env (EnvironmentFile de systemd) es una línea por
|
||||
// variable: un salto de línea en el prompt, el modelo o una URL metía variables nuevas
|
||||
// (revisión externa, 2.3). Se rechaza acá y apply.js q() tampoco lo deja pasar.
|
||||
const CTRL = /[\r\n\0]/;
|
||||
function sinCtrl(v, field, label) {
|
||||
if (CTRL.test(v == null ? '' : String(v))) bad(`${label}: no puede tener saltos de línea`, field);
|
||||
return v;
|
||||
}
|
||||
function int(v, field, min, max, label, { optional = false } = {}) {
|
||||
if (v === '' || v == null) {
|
||||
if (optional) return null;
|
||||
@@ -34,7 +44,8 @@ function num(v, field, min, max, label) {
|
||||
return n;
|
||||
}
|
||||
function httpUrl(v, field, label) {
|
||||
const s = str(v);
|
||||
// new URL() saca los \n y \t sin quejarse, pero lo que se guarda es el texto original.
|
||||
const s = str(sinCtrl(v, field, label));
|
||||
let u;
|
||||
try { u = new URL(s); } catch { bad(`${label}: URL mal armada`, field); }
|
||||
if (!/^https?:$/.test(u.protocol)) bad(`${label}: tiene que empezar con http:// o https://`, field);
|
||||
@@ -45,6 +56,12 @@ function host(v, field, label) {
|
||||
if (!/^[A-Za-z0-9.-]{1,253}$/.test(s) && !/^\[[0-9a-fA-F:]+\]$/.test(s)) bad(`${label}: host mal armado`, field);
|
||||
return s;
|
||||
}
|
||||
// Nombre del modelo del LLM: va al .env y a la API de gpu02. Letras, números y . _ : / -
|
||||
function model(v) {
|
||||
const s = str(sinCtrl(v, 'tr_model', 'Modelo')) || 'qwen2.5-7b-instruct';
|
||||
if (!/^[A-Za-z0-9._:\/-]{1,128}$/.test(s)) bad('Modelo: solo letras, números y . _ : / - (hasta 128)', 'tr_model');
|
||||
return s;
|
||||
}
|
||||
function passphrase(v, field) {
|
||||
const s = str(v);
|
||||
if (s && (s.length < 10 || s.length > 79)) bad('La passphrase SRT tiene que tener entre 10 y 79 caracteres', field);
|
||||
@@ -65,12 +82,12 @@ function input(i = {}) {
|
||||
streamid: str(i.streamid),
|
||||
passphrase: passphrase(i.passphrase, 'in_passphrase'),
|
||||
};
|
||||
if (out.streamid.length > 512 || /[\s&]/.test(out.streamid)) bad('streamid: sin espacios ni &, hasta 512 caracteres', 'in_streamid');
|
||||
if (out.streamid.length > 512 || /[\s&\0]/.test(out.streamid)) bad('streamid: sin espacios ni &, hasta 512 caracteres', 'in_streamid');
|
||||
if (mode === 'listener' && (RESERVED.has(out.port) || out.port < 1024)) bad(`El puerto ${out.port} lo usa el sistema`, 'in_port');
|
||||
return Object.assign(out, avPick(i));
|
||||
}
|
||||
if (kind === 'udp') {
|
||||
const s = str(i.url);
|
||||
const s = str(sinCtrl(i.url, 'in_url', 'Entrada UDP'));
|
||||
const m = /^udp:\/\/(@?)([0-9.]+|[A-Za-z0-9.-]+)?:(\d{1,5})(\?.*)?$/.exec(s);
|
||||
if (!m || Number(m[3]) < 1 || Number(m[3]) > 65535) bad('Entrada UDP: tiene que ser udp://ip:puerto (o udp://@239.x.x.x:puerto)', 'in_url');
|
||||
return Object.assign({ kind, url: s }, avPick(i));
|
||||
@@ -116,7 +133,7 @@ function channel(body = {}) {
|
||||
asr: {
|
||||
lang: LANGS.includes(str(asr.lang)) ? str(asr.lang) : 'es',
|
||||
url: httpUrl(asr.url || 'http://192.168.2.10:8004', 'asr_url', 'URL del motor de reconocimiento'),
|
||||
prompt: str(asr.prompt).slice(0, 500),
|
||||
prompt: str(sinCtrl(asr.prompt, 'asr_prompt', 'Prompt')).slice(0, 500),
|
||||
// audio_ctx de whisper.cpp por pedido (0 = el del server, 1500 = 30 s). Tarea 081.
|
||||
audio_ctx: int(asr.audio_ctx ?? 0, 'asr_audio_ctx', 0, 1500, 'audio_ctx', {}),
|
||||
// Margen de confirmación (--hold): las palabras de los últimos N s del audio se
|
||||
@@ -126,7 +143,7 @@ function channel(body = {}) {
|
||||
tr: {
|
||||
langs: [...new Set((Array.isArray(tr.langs) ? tr.langs : []).map(str))].filter(l => l === 'en'),
|
||||
url: httpUrl(tr.url || 'http://192.168.2.10:8001', 'tr_url', 'URL del LLM'),
|
||||
model: str(tr.model) || 'qwen2.5-7b-instruct',
|
||||
model: model(tr.model),
|
||||
// Frases más cortas = inglés antes, con menos contexto para traducir (081).
|
||||
max_frase_s: num(tr.max_frase_s ?? 6, 'tr_max_frase', 2, 10, 'Largo máximo de frase (s)'),
|
||||
pausa_s: num(tr.pausa_s ?? 0.8, 'tr_pausa', 0.3, 2, 'Pausa que corta frase (s)'),
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
'use strict';
|
||||
// http.js — rutas async y manejador de errores del panel.
|
||||
//
|
||||
// Express 4 no captura el rechazo de un handler async: con Node 22 una promesa rechazada
|
||||
// sin catch tira abajo el proceso, o sea el panel entero, por ejemplo si falla
|
||||
// systemctl o la base en medio de un pedido (revisión externa, 2.1). asyncHandler pasa el
|
||||
// error a next() y errorHandler responde 500 y lo loguea.
|
||||
const asyncHandler = fn => (req, res, next) => Promise.resolve().then(() => fn(req, res, next)).catch(next);
|
||||
|
||||
function errorHandler(err, req, res, next) { // eslint-disable-line no-unused-vars
|
||||
console.error('[orbisubs-panel]', req.method, req.originalUrl, err);
|
||||
if (res.headersSent) return;
|
||||
res.status(err.status || 500).json({ error: err.status ? err.message : 'Error interno' });
|
||||
}
|
||||
|
||||
module.exports = { asyncHandler, errorHandler };
|
||||
@@ -299,7 +299,7 @@
|
||||
<label class="srt-on srt-caller"><span data-i18n>Destino (host)</span> <input name="srt_host" placeholder="10.100.101.211"></label>
|
||||
</div>
|
||||
<div class="grid-3 srt-on">
|
||||
<label><span data-i18n>Puerto</span> <input name="srt_port" type="number" min="1024" max="65534" placeholder="9002">
|
||||
<label><span data-i18n>Puerto</span> <input name="srt_port" type="number" min="1024" max="55000" placeholder="9002">
|
||||
<span class="field-hint" data-i18n>Hasta 55000. En listener toma también el siguiente (prueba interna).</span>
|
||||
</label>
|
||||
<label>Latency (ms) <input name="srt_latency" type="number" min="20" max="8000" step="10" value="200"></label>
|
||||
|
||||
@@ -9,6 +9,7 @@ const alarmas = require('../engine/alarmas');
|
||||
|
||||
const apply = require('../engine/apply');
|
||||
const P = require('../engine/posicion');
|
||||
const { asyncHandler: ah } = require('../http');
|
||||
|
||||
// Como máximo 2 canales andando a la vez: el reconocimiento y la traducción van a
|
||||
// gpu02, que es compartido (076-agregado: ~1 s de whisper por segmento de 6 s).
|
||||
@@ -24,11 +25,11 @@ function fail(res, e) {
|
||||
throw e;
|
||||
}
|
||||
|
||||
router.get('/', async (req, res) => {
|
||||
router.get('/', ah(async (req, res) => {
|
||||
const chs = allChannels();
|
||||
const st = await status.all(chs);
|
||||
res.json({ control: true, max_running: MAX_RUNNING, channels: chs.map(c => ({ ...c, status: st[c.id], busy: busy.has(c.id), alarms: alarmas.activas(c.slug) })) });
|
||||
});
|
||||
}));
|
||||
|
||||
// Una operación a la vez por canal, y como mucho 5 arranques en 10 min (el mismo
|
||||
// throttle que las unidades systemd; caso TVR-hls de v1: 15k restarts por un loop).
|
||||
@@ -86,14 +87,14 @@ router.get('/:id/frame', (req, res) => {
|
||||
});
|
||||
|
||||
// Lo que muestra "Ver canal": últimos subtítulos por idioma y números.
|
||||
router.get('/:id/view', async (req, res) => {
|
||||
router.get('/:id/view', ah(async (req, res) => {
|
||||
const ch = getChannel(req.params.id);
|
||||
if (!ch) return res.status(404).json({ error: 'Canal inexistente' });
|
||||
const st = (await status.all([ch]))[ch.id];
|
||||
st.metrics = status.metrics(ch, { last: 8 });
|
||||
res.json({ channel: ch, status: st, failures: await status.failures(ch),
|
||||
alarms: alarmas.activas(ch.slug), alarm_history: alarmas.historial(ch.slug) });
|
||||
});
|
||||
}));
|
||||
|
||||
router.post('/', (req, res) => {
|
||||
let ch;
|
||||
@@ -106,7 +107,7 @@ router.post('/', (req, res) => {
|
||||
res.status(201).json(getChannel(r.lastInsertRowid));
|
||||
});
|
||||
|
||||
router.put('/:id', async (req, res) => {
|
||||
router.put('/:id', ah(async (req, res) => {
|
||||
const old = getChannel(req.params.id);
|
||||
if (!old) return res.status(404).json({ error: 'Canal inexistente' });
|
||||
let ch;
|
||||
@@ -114,37 +115,39 @@ router.put('/:id', async (req, res) => {
|
||||
ch = V.channel(req.body);
|
||||
V.conflicts(ch, allChannels().filter(o => o.id !== old.id));
|
||||
} catch (e) { return fail(res, e); }
|
||||
// Renombrar el id corto con el canal andando dejaría instancias huérfanas con el nombre viejo.
|
||||
if (ch.slug !== old.slug) {
|
||||
const st = (await status.all([old]))[old.id];
|
||||
if (st.units.some(u => u.active === 'active' || u.active === 'activating')) {
|
||||
return res.status(409).json({ error: 'Detén el canal antes de cambiarle el id corto', field: 'slug' });
|
||||
}
|
||||
}
|
||||
// Ocupado se toma antes del primer await: si no, un start/stop/delete que entra mientras
|
||||
// se mira systemd encontraba el canal libre (revisión externa, 2.2).
|
||||
if (busy.has(old.id)) return res.status(409).json({ error: 'El canal está ocupado con otra operación' });
|
||||
const save = c => db.prepare("UPDATE channels SET slug = ?, name = ?, enabled = ?, cfg = ?, updated_at = datetime('now') WHERE id = ?")
|
||||
.run(c.slug, c.name, c.enabled ? 1 : 0, JSON.stringify(c.cfg), old.id);
|
||||
save(ch);
|
||||
// Solo cambió la posición del subtítulo (082): se reescribe el .pos.json, que los procesos
|
||||
// releen en cada segmento. No se reinicia nada ni se corta el video.
|
||||
// Solo nombre, id corto y configuración: la fila de la base trae además id y fechas.
|
||||
const sinPos = c => JSON.stringify({ name: c.name, slug: c.slug, cfg: { ...c.cfg, pos: undefined } });
|
||||
// Un .env de antes de la 082 no les pasa --pos-file a los procesos: esa vez se reinicia.
|
||||
let conPos = false;
|
||||
try { conPos = fs.readFileSync(`${process.env.ORBISUBS_ETC || '/etc/orbisubs'}/${old.slug}.env`, 'utf8').includes('--pos-file'); } catch { /* sin .env */ }
|
||||
if (conPos && sinPos(ch) === sinPos(old) && JSON.stringify(ch.cfg.pos) !== JSON.stringify(old.cfg.pos) && await isUp(old)) {
|
||||
apply.writePos(ch);
|
||||
const seg = ch.cfg.hls.seg_s || 6;
|
||||
const en_s = Math.round(seg + (apply.holdBack(ch).hb || seg * 3) + 3);
|
||||
event('info', `Posición del subtítulo de ${ch.name}: ${P.NOMBRE[ch.cfg.pos.modo]} (${ch.cfg.pos.pct} %)`, { channel: ch.slug, username: req.user.username });
|
||||
return res.json({ ...getChannel(old.id), applied: 'pos', applied_in_s: en_s });
|
||||
}
|
||||
// Andando: se aplica ya. Si no arranca con lo nuevo, vuelve todo (servicios y base)
|
||||
// a lo anterior, para no dejar el canal a medias.
|
||||
if (await isUp(old)) {
|
||||
if (throttled(old.id)) { save(old); return res.status(429).json({ error: 'Demasiados reinicios de este canal: espera unos minutos' }); }
|
||||
busy.add(old.id);
|
||||
try {
|
||||
busy.add(old.id);
|
||||
try {
|
||||
// Renombrar el id corto con el canal andando dejaría instancias huérfanas con el nombre viejo.
|
||||
if (ch.slug !== old.slug) {
|
||||
const st = (await status.all([old]))[old.id];
|
||||
if (st.units.some(u => u.active === 'active' || u.active === 'activating')) {
|
||||
return res.status(409).json({ error: 'Detén el canal antes de cambiarle el id corto', field: 'slug' });
|
||||
}
|
||||
}
|
||||
const save = c => db.prepare("UPDATE channels SET slug = ?, name = ?, enabled = ?, cfg = ?, updated_at = datetime('now') WHERE id = ?")
|
||||
.run(c.slug, c.name, c.enabled ? 1 : 0, JSON.stringify(c.cfg), old.id);
|
||||
save(ch);
|
||||
// Solo cambió la posición del subtítulo (082): se reescribe el .pos.json, que los procesos
|
||||
// releen en cada segmento. No se reinicia nada ni se corta el video.
|
||||
// Solo nombre, id corto y configuración: la fila de la base trae además id y fechas.
|
||||
const sinPos = c => JSON.stringify({ name: c.name, slug: c.slug, cfg: { ...c.cfg, pos: undefined } });
|
||||
// Un .env de antes de la 082 no les pasa --pos-file a los procesos: esa vez se reinicia.
|
||||
let conPos = false;
|
||||
try { conPos = fs.readFileSync(`${process.env.ORBISUBS_ETC || '/etc/orbisubs'}/${old.slug}.env`, 'utf8').includes('--pos-file'); } catch { /* sin .env */ }
|
||||
if (conPos && sinPos(ch) === sinPos(old) && JSON.stringify(ch.cfg.pos) !== JSON.stringify(old.cfg.pos) && await isUp(old)) {
|
||||
apply.writePos(ch);
|
||||
const seg = ch.cfg.hls.seg_s || 6;
|
||||
const en_s = Math.round(seg + (apply.holdBack(ch).hb || seg * 3) + 3);
|
||||
event('info', `Posición del subtítulo de ${ch.name}: ${P.NOMBRE[ch.cfg.pos.modo]} (${ch.cfg.pos.pct} %)`, { channel: ch.slug, username: req.user.username });
|
||||
return res.json({ ...getChannel(old.id), applied: 'pos', applied_in_s: en_s });
|
||||
}
|
||||
// Andando: se aplica ya. Si no arranca con lo nuevo, vuelve todo (servicios y base)
|
||||
// a lo anterior, para no dejar el canal a medias.
|
||||
if (await isUp(old)) {
|
||||
if (throttled(old.id)) { save(old); return res.status(429).json({ error: 'Demasiados reinicios de este canal: espera unos minutos' }); }
|
||||
const r = await apply.start({ ...ch, id: old.id }, { prevCh: old });
|
||||
if (!r.ok) {
|
||||
save(old);
|
||||
@@ -152,38 +155,44 @@ router.put('/:id', async (req, res) => {
|
||||
return res.status(409).json({ error: `No arrancó con la configuración nueva: ${r.errors.join(' · ')}` });
|
||||
}
|
||||
for (const w of r.warnings || []) event('warn', `${ch.name}: ${w}`, { channel: ch.slug, username: req.user.username });
|
||||
} finally { busy.delete(old.id); }
|
||||
event('info', `Canal editado y reiniciado: ${ch.name}`, { channel: ch.slug, username: req.user.username });
|
||||
} else {
|
||||
event('info', `Canal editado: ${ch.name}`, { channel: ch.slug, username: req.user.username });
|
||||
}
|
||||
res.json(getChannel(old.id));
|
||||
});
|
||||
event('info', `Canal editado y reiniciado: ${ch.name}`, { channel: ch.slug, username: req.user.username });
|
||||
} else {
|
||||
event('info', `Canal editado: ${ch.name}`, { channel: ch.slug, username: req.user.username });
|
||||
}
|
||||
res.json(getChannel(old.id));
|
||||
} finally { busy.delete(old.id); }
|
||||
}));
|
||||
|
||||
router.delete('/:id', async (req, res) => {
|
||||
router.delete('/:id', ah(async (req, res) => {
|
||||
const ch = getChannel(req.params.id);
|
||||
if (!ch) return res.status(404).json({ error: 'Canal inexistente' });
|
||||
const st = (await status.all([ch]))[ch.id];
|
||||
if (st.units.some(u => u.active === 'active' || u.active === 'activating')) {
|
||||
return res.status(409).json({ error: 'El canal está andando: detenlo antes de borrarlo' });
|
||||
}
|
||||
db.prepare('DELETE FROM channels WHERE id = ?').run(ch.id);
|
||||
apply.removeEnv(ch.slug);
|
||||
event('warn', `Canal borrado: ${ch.name}`, { channel: ch.slug, username: req.user.username });
|
||||
res.json({ ok: true });
|
||||
});
|
||||
// Borrar mientras arranca (start en curso) dejaba las unidades andando sin canal (2.2).
|
||||
if (busy.has(ch.id)) return res.status(409).json({ error: 'El canal está ocupado con otra operación' });
|
||||
busy.add(ch.id);
|
||||
try {
|
||||
const st = (await status.all([ch]))[ch.id];
|
||||
if (st.units.some(u => u.active === 'active' || u.active === 'activating')) {
|
||||
return res.status(409).json({ error: 'El canal está andando: detenlo antes de borrarlo' });
|
||||
}
|
||||
db.prepare('DELETE FROM channels WHERE id = ?').run(ch.id);
|
||||
apply.removeEnv(ch.slug);
|
||||
event('warn', `Canal borrado: ${ch.name}`, { channel: ch.slug, username: req.user.username });
|
||||
res.json({ ok: true });
|
||||
} finally { busy.delete(ch.id); }
|
||||
}));
|
||||
|
||||
router.post('/:id/start', async (req, res) => {
|
||||
router.post('/:id/start', ah(async (req, res) => {
|
||||
const ch = getChannel(req.params.id);
|
||||
if (!ch) return res.status(404).json({ error: 'Canal inexistente' });
|
||||
if (busy.has(ch.id)) return res.status(409).json({ error: 'El canal está ocupado con otra operación' });
|
||||
const others = await runningOthers(ch);
|
||||
if (others.length >= MAX_RUNNING) {
|
||||
return res.status(409).json({ error: `Ya hay ${others.length} canales andando (${others.join(', ')}): el máximo es ${MAX_RUNNING} por gpu02` });
|
||||
}
|
||||
if (throttled(ch.id)) return res.status(429).json({ error: 'Demasiados reinicios de este canal: espera unos minutos' });
|
||||
// Ocupado antes del primer await (2.2), como en PUT y DELETE.
|
||||
busy.add(ch.id);
|
||||
try {
|
||||
const others = await runningOthers(ch);
|
||||
if (others.length >= MAX_RUNNING) {
|
||||
return res.status(409).json({ error: `Ya hay ${others.length} canales andando (${others.join(', ')}): el máximo es ${MAX_RUNNING} por gpu02` });
|
||||
}
|
||||
if (throttled(ch.id)) return res.status(429).json({ error: 'Demasiados reinicios de este canal: espera unos minutos' });
|
||||
const r = await apply.start(ch);
|
||||
if (!r.ok) {
|
||||
event('error', `No arrancó ${ch.name}: ${r.errors.join(' · ')}`, { channel: ch.slug, username: req.user.username });
|
||||
@@ -193,9 +202,9 @@ router.post('/:id/start', async (req, res) => {
|
||||
event('info', `Canal iniciado: ${ch.name}`, { channel: ch.slug, username: req.user.username });
|
||||
res.json({ ok: true });
|
||||
} finally { busy.delete(ch.id); }
|
||||
});
|
||||
}));
|
||||
|
||||
router.post('/:id/stop', async (req, res) => {
|
||||
router.post('/:id/stop', ah(async (req, res) => {
|
||||
const ch = getChannel(req.params.id);
|
||||
if (!ch) return res.status(404).json({ error: 'Canal inexistente' });
|
||||
if (busy.has(ch.id)) return res.status(409).json({ error: 'El canal está ocupado con otra operación' });
|
||||
@@ -203,7 +212,7 @@ router.post('/:id/stop', async (req, res) => {
|
||||
try { await apply.stop(ch); } finally { busy.delete(ch.id); }
|
||||
event('info', `Canal parado: ${ch.name}`, { channel: ch.slug, username: req.user.username });
|
||||
res.json({ ok: true });
|
||||
});
|
||||
}));
|
||||
|
||||
// Base nueva: T13 (el canal de la 076-078, configurado a mano) entra como un canal
|
||||
// más, con lo que dice su /etc/orbisubs/t13.env. Solo se lee.
|
||||
|
||||
+1
-4
@@ -55,10 +55,7 @@ app.get('/api/events', (req, res) => {
|
||||
app.use(express.static(path.join(__dirname, 'public')));
|
||||
app.get('*', (req, res, next) => (req.path.startsWith('/api') ? next() : res.sendFile(path.join(__dirname, 'public', 'index.html'))));
|
||||
|
||||
app.use((err, req, res, next) => { // eslint-disable-line no-unused-vars
|
||||
console.error('[orbisubs-panel]', err);
|
||||
res.status(err.status || 500).json({ error: err.status ? err.message : 'Error interno' });
|
||||
});
|
||||
app.use(require('./http').errorHandler);
|
||||
|
||||
app.listen(PORT, () => console.log(`[orbisubs-panel] escuchando en :${PORT}`));
|
||||
|
||||
|
||||
@@ -7,7 +7,10 @@ const os = require('os');
|
||||
const path = require('path');
|
||||
|
||||
process.env.DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'orbisubs-alarmas-'));
|
||||
process.env.LOG_DIR = path.join(process.env.DATA_DIR, 'log');
|
||||
process.env.HLS_DIR = path.join(process.env.DATA_DIR, 'hls');
|
||||
const A = require('../src/engine/alarmas');
|
||||
const status = require('../src/engine/status');
|
||||
const { db } = require('../src/db');
|
||||
|
||||
const now = 1_795_266_154 + 3600; // una hora después de la vuelta del PTS de ecuadortv
|
||||
@@ -63,3 +66,68 @@ test('aplicar: se enciende, sigue, se apaga sola y queda registrada', () => {
|
||||
assert.match(ev[0], /^Alarma: Sin subtítulos/);
|
||||
assert.match(ev[1], /duró 10 min/);
|
||||
});
|
||||
|
||||
// Revisión externa, 1.1: con el ASR congelado (proceso colgado, unidad "active") la alarma
|
||||
// se apagaba sola: a los 5 min ya no había palabras en la ventana, y además status.all()
|
||||
// pasa el canal a 'error' y tick lo tomaba como parado.
|
||||
test('sin_subs: ASR congelado 10 min, encendida todo el rato (evaluar)', () => {
|
||||
const F = now - 600; // se congeló hace 10 min
|
||||
const log = asrLog(30).map(r => ({ ...r, t: r.t - 600 })).filter(r => r.t <= F);
|
||||
const desde = now - 7200;
|
||||
for (let T = F + A.CFG.SUBS_S + 30; T <= now; T += 30) {
|
||||
const asr = log.filter(r => r.t >= T - 660);
|
||||
const r = A.evaluar({ now: T, asr, texto: F, srt: null, desde, asrUlt: F });
|
||||
assert.ok(r.sin_subs, `apagada a los ${T - F} s`);
|
||||
}
|
||||
assert.match(A.evaluar({ now, asr: [], texto: F, srt: null, desde, asrUlt: F }).sin_subs, /no escribe hace 10 min/);
|
||||
// Recién arrancado con el .jsonl de la corrida anterior: sin filas nuevas todavía, nada.
|
||||
assert.strictEqual(A.evaluar({ now, asr: [], texto: now - 60, srt: null, desde: now - 60, asrUlt: now - 60 }).sin_subs, null);
|
||||
// Parado de verdad no llega acá (tick no evalúa), y en silencio con el ASR al día, nada.
|
||||
assert.strictEqual(A.evaluar({ now, asr: asrLog(15, 0), texto: now - 3600, srt: null, desde, asrUlt: now - 3 }).sin_subs, null);
|
||||
});
|
||||
|
||||
test('produce: corre según systemd (ingesta y ASR activos), con su hora', () => {
|
||||
const u = (key, active, since) => ({ key, active, since });
|
||||
assert.deepStrictEqual(status.produce([u('ingest', 'active', 100), u('asr', 'active', 200), u('srt', 'failed', 50)]), { up: true, up_since: 200 });
|
||||
assert.strictEqual(status.produce([u('ingest', 'active', 100), u('asr', 'activating', null)]).up, false);
|
||||
});
|
||||
|
||||
test('tick: ASR congelado 10 min con el estado en error, la alarma no se cierra', async () => {
|
||||
const slug = 'congelado';
|
||||
const realNow = Date.now;
|
||||
const F = Math.floor(realNow() / 1000);
|
||||
let reloj = F;
|
||||
Date.now = () => reloj * 1000;
|
||||
try {
|
||||
fs.mkdirSync(process.env.LOG_DIR, { recursive: true });
|
||||
const subs = path.join(process.env.HLS_DIR, slug, 'subs');
|
||||
fs.mkdirSync(subs, { recursive: true });
|
||||
// 15 min de ASR transcribiendo hasta F, y el último .vtt con texto en F.
|
||||
fs.writeFileSync(path.join(process.env.LOG_DIR, `${slug}.jsonl`),
|
||||
Array.from({ length: 300 }, (_, i) => JSON.stringify({ seq: i, dur: 3, t: F - 900 + i * 3, words: 5 })).join('\n') + '\n');
|
||||
const vtt = path.join(subs, '1.vtt');
|
||||
fs.writeFileSync(vtt, 'WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nhola\n');
|
||||
fs.utimesSync(vtt, F, F);
|
||||
const orig = status.all;
|
||||
// Lo que devuelve status.all con el ASR congelado: unidades activas, estado 'error'.
|
||||
status.all = async chs => Object.fromEntries(chs.map(c => [c.id, { state: 'error', up: true, up_since: F - 3600, units: [], notes: [] }]));
|
||||
const chans = () => [{ id: 1, slug, cfg: { srt: { enabled: false } } }];
|
||||
try {
|
||||
await A.tick(chans); // F: anda bien
|
||||
assert.strictEqual(A.activas(slug).length, 0);
|
||||
const encendida = [];
|
||||
for (reloj = F + 30; reloj <= F + 600; reloj += 30) {
|
||||
await A.tick(chans);
|
||||
encendida.push(A.activas(slug).length);
|
||||
}
|
||||
// Se enciende pasados los 5 min y queda encendida hasta el final.
|
||||
const i = encendida.indexOf(1);
|
||||
assert.ok(i >= 0 && i <= 10, String(encendida));
|
||||
assert.ok(encendida.slice(i).every(n => n === 1), String(encendida));
|
||||
// Parado de verdad (systemd): se cierra.
|
||||
status.all = async chs => Object.fromEntries(chs.map(c => [c.id, { state: 'stopped', up: false, up_since: null, units: [], notes: [] }]));
|
||||
await A.tick(chans);
|
||||
assert.strictEqual(A.activas(slug).length, 0);
|
||||
} finally { status.all = orig; }
|
||||
} finally { Date.now = realNow; }
|
||||
});
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
'use strict';
|
||||
// Rutas de canales (revisión externa, 2.1 y 2.2).
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const http = require('http');
|
||||
|
||||
process.env.DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'orbisubs-rutas-'));
|
||||
process.env.ORBISUBS_ETC = path.join(process.env.DATA_DIR, 'etc');
|
||||
process.env.LOG_DIR = path.join(process.env.DATA_DIR, 'log');
|
||||
const express = require('express');
|
||||
const status = require('../src/engine/status');
|
||||
const { db } = require('../src/db');
|
||||
const { errorHandler } = require('../src/http');
|
||||
const router = require('../src/routes/channels');
|
||||
|
||||
function servidor() {
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, res, next) => { req.user = { username: 'test' }; next(); });
|
||||
app.use('/api/channels', router);
|
||||
app.use(errorHandler);
|
||||
return new Promise(r => { const s = app.listen(0, '127.0.0.1', () => r(s)); });
|
||||
}
|
||||
function pedir(s, method, url) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = http.request({ host: '127.0.0.1', port: s.address().port, method, path: url }, res => {
|
||||
let b = '';
|
||||
res.on('data', d => { b += d; });
|
||||
res.on('end', () => resolve({ status: res.statusCode, body: b ? JSON.parse(b) : null }));
|
||||
});
|
||||
req.on('error', reject);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
const cfg = {
|
||||
input: { kind: 'udp', url: 'udp://@239.1.1.1:1234' }, asr: { lang: 'es', url: 'http://127.0.0.1:1' },
|
||||
tr: { langs: [] }, hls: { enabled: true, seg_s: 6, list_size: 10 }, srt: { enabled: false },
|
||||
};
|
||||
|
||||
test('2.1: un rechazo en una ruta async responde 500 y el panel sigue andando', async t => {
|
||||
const s = await servidor();
|
||||
const orig = status.all;
|
||||
t.after(() => { status.all = orig; s.close(); });
|
||||
const errores = [];
|
||||
const ce = console.error;
|
||||
console.error = (...a) => errores.push(a.join(' '));
|
||||
try {
|
||||
status.all = async () => { throw new Error('systemctl colgado'); };
|
||||
const r = await pedir(s, 'GET', '/api/channels');
|
||||
assert.strictEqual(r.status, 500);
|
||||
assert.strictEqual(r.body.error, 'Error interno');
|
||||
assert.ok(errores.some(e => e.includes('systemctl colgado')), 'se loguea');
|
||||
status.all = orig;
|
||||
// Sigue vivo: el pedido siguiente anda.
|
||||
status.all = async chs => Object.fromEntries(chs.map(c => [c.id, { state: 'stopped', units: [], notes: [] }]));
|
||||
assert.strictEqual((await pedir(s, 'GET', '/api/channels')).status, 200);
|
||||
} finally { console.error = ce; }
|
||||
});
|
||||
|
||||
test('2.2: dos DELETE a la vez: el segundo encuentra el canal ocupado', async t => {
|
||||
const s = await servidor();
|
||||
const orig = status.all;
|
||||
t.after(() => { status.all = orig; s.close(); });
|
||||
const id = db.prepare('INSERT INTO channels (slug, name, enabled, cfg) VALUES (?, ?, 1, ?)').run('borrame', 'Borrame', JSON.stringify(cfg)).lastInsertRowid;
|
||||
let soltar;
|
||||
const espera = new Promise(r => { soltar = r; });
|
||||
status.all = async chs => { await espera; return Object.fromEntries(chs.map(c => [c.id, { state: 'stopped', units: [], notes: [] }])); };
|
||||
const primero = pedir(s, 'DELETE', `/api/channels/${id}`);
|
||||
await new Promise(r => setTimeout(r, 50));
|
||||
const segundo = await pedir(s, 'DELETE', `/api/channels/${id}`);
|
||||
assert.strictEqual(segundo.status, 409);
|
||||
assert.match(segundo.body.error, /ocupado/);
|
||||
soltar();
|
||||
assert.strictEqual((await primero).status, 200);
|
||||
assert.strictEqual(db.prepare('SELECT 1 FROM channels WHERE id = ?').get(id), undefined);
|
||||
});
|
||||
@@ -125,3 +125,48 @@ test('083: el inglés nunca fija el retraso y el colchón sale del idioma del au
|
||||
assert.match(env, /--modo-retraso es /);
|
||||
fs.rmSync(dir, { recursive: true });
|
||||
});
|
||||
|
||||
// Revisión externa, 2.3: un salto de línea metía variables en /etc/orbisubs/<id>.env.
|
||||
test('2.3: saltos de línea en prompt, modelo y URLs se rechazan, y q() tampoco los deja pasar', () => {
|
||||
const malo = [
|
||||
[{ asr: { lang: 'es', prompt: 'Noticias\nURL=http://otro' } }, 'asr_prompt'],
|
||||
[{ asr: { lang: 'es', prompt: 'Noticias\r' } }, 'asr_prompt'],
|
||||
[{ asr: { lang: 'es', url: 'http://192.168.2.10:8004/\nX=1' } }, 'asr_url'],
|
||||
[{ tr: { langs: ['en'], model: 'qwen\nLLM_URL=http://otro' } }, 'tr_model'],
|
||||
[{ tr: { langs: ['en'], model: 'qwen 7b' } }, 'tr_model'],
|
||||
[{ tr: { langs: ['en'], url: 'http://192.168.2.10:8001\0' } }, 'tr_url'],
|
||||
[{ input: { kind: 'udp', url: 'udp://@239.1.1.1:1234\nX=1' } }, 'in_url'],
|
||||
[{ input: { kind: 'udp', url: 'udp://@239.1.1.1:1234?x=\0' } }, 'in_url'],
|
||||
];
|
||||
for (const [over, field] of malo) {
|
||||
assert.throws(() => V.channel(base(over)), e => e.field === field, JSON.stringify(over));
|
||||
}
|
||||
// Lo normal sigue pasando.
|
||||
assert.strictEqual(V.channel(base({ tr: { langs: ['en'], model: 'Qwen/Qwen2.5-7B-Instruct' } })).cfg.tr.model, 'Qwen/Qwen2.5-7B-Instruct');
|
||||
assert.strictEqual(V.channel(base({ asr: { lang: 'es', prompt: 'Noticias de Chile: Coyhaique, Boric.' } })).cfg.asr.prompt, 'Noticias de Chile: Coyhaique, Boric.');
|
||||
const A = require('../src/engine/apply');
|
||||
assert.strictEqual(A.q('a "b" \\c'), '"a \\"b\\" \\\\c"');
|
||||
for (const v of ['a\nb', 'a\rb', 'a\0b']) assert.throws(() => A.q(v), /salto de línea/);
|
||||
// Y un canal con salto de línea que ya estuviera en la base no llega al .env.
|
||||
const ch = V.channel(base());
|
||||
ch.cfg.asr.prompt = 'x\nURL=http://otro';
|
||||
assert.throws(() => A.envText(ch), /salto de línea/);
|
||||
});
|
||||
|
||||
// Revisión externa, 1.7: 4700 reservado aunque el panel corra en otro PORT.
|
||||
test('1.7: 4700 siempre reservado, y PORT también', () => {
|
||||
const ruta = require.resolve('../src/engine/validate');
|
||||
const antes = process.env.PORT;
|
||||
delete require.cache[ruta];
|
||||
process.env.PORT = '4800';
|
||||
try {
|
||||
const V2 = require('../src/engine/validate');
|
||||
const conPuerto = p => base({ input: { kind: 'srt', mode: 'listener', port: p }, srt: { enabled: false } });
|
||||
assert.throws(() => V2.channel(conPuerto(4700)), /lo usa el sistema/);
|
||||
assert.throws(() => V2.channel(conPuerto(4800)), /lo usa el sistema/);
|
||||
assert.ok(V2.channel(conPuerto(4900)));
|
||||
} finally {
|
||||
if (antes === undefined) delete process.env.PORT; else process.env.PORT = antes;
|
||||
delete require.cache[ruta];
|
||||
}
|
||||
});
|
||||
|
||||
@@ -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 <think> 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("<think>hmm</think> Hello."), "Hello.")
|
||||
self.assertEqual(T.sin_think("<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()
|
||||
Reference in New Issue
Block a user