OrbiSubs: audio chunks for ASR, SRT delay set by Spanish, shorter English sentences, player hold-back
Tarea 081. T13 trae un keyframe cada 6 s y el video no se recodifica, así que los segmentos no bajan de 6 s: lo que se acorta es el audio. La ingesta saca además trozos de audio de 3 s (mismo ffmpeg, mismo PTS) y el ASR los transcribe apenas llegan. - Español listo 2,7 s después de cerrar el .ts (antes 7,7); WER en vivo igual (0,22/0,21). - audio_ctx 768 por pedido (whisper.cpp lo acepta): 0,63 s de mediana. - Se sacan las palabras que repiten la cola de lo confirmado. - HOLD-BACK en video.m3u8 + maxLiveSyncPlaybackRate 1.1: player a ~11 s (antes ~22,5). - SRT: cues desde las colas, retraso fijado por el español y calculado (6 s, antes 24); el inglés tarde se descarta (~2 %). - Frase máxima del inglés configurable (4 s en T13). - Panel: trozo de audio, audio_ctx, colchón, frase, pausa y modo/cálculo del retraso SRT. - medir_retraso.py y wer_vivo.py para medir; bench_http.py con --paso/--audio-ctx/--hold.
This commit is contained in:
@@ -0,0 +1,136 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Mide el retraso de un canal durante N segundos (tarea 081): cuándo cierra cada .ts de
|
||||
la ingesta, cuándo aparece su .vtt en español y en inglés, y los tiempos de los motores y
|
||||
de la salida SRT en esa misma ventana. Solo lee archivos: no toca el canal.
|
||||
|
||||
medir_retraso.py <canal> <segundos> [--player-lat S] [--etiqueta X]
|
||||
|
||||
--player-lat: retraso del player contra el PROGRAM-DATE-TIME (lo mide el Chromium
|
||||
headless con hls.playingDate). Con él se calcula cuánto inglés llega tarde al player.
|
||||
"""
|
||||
import argparse, glob, json, os, re, statistics, time
|
||||
|
||||
LOG = "/var/log/orbisubs"
|
||||
|
||||
|
||||
def q(v, p):
|
||||
if not v:
|
||||
return None
|
||||
s = sorted(v)
|
||||
k = (len(s) - 1) * p
|
||||
lo, hi = int(k), min(int(k) + 1, len(s) - 1)
|
||||
return round(s[lo] + (s[hi] - s[lo]) * (k - lo), 2)
|
||||
|
||||
|
||||
def lista(path):
|
||||
out, pdt = {}, None
|
||||
try:
|
||||
lines = open(path).read().splitlines()
|
||||
except FileNotFoundError:
|
||||
return out
|
||||
seq, dur = None, None
|
||||
for l in lines:
|
||||
if l.startswith("#EXT-X-MEDIA-SEQUENCE:"):
|
||||
seq = int(l.split(":")[1])
|
||||
elif l.startswith("#EXT-X-PROGRAM-DATE-TIME:"):
|
||||
from datetime import datetime
|
||||
pdt = datetime.fromisoformat(l.split(":", 1)[1].replace("Z", "+00:00")).timestamp()
|
||||
elif l.startswith("#EXTINF:"):
|
||||
dur = float(l[8:].split(",")[0])
|
||||
elif l and not l.startswith("#"):
|
||||
m = re.search(r"(\d+)\.ts$", l)
|
||||
n = int(m.group(1)) if m else seq
|
||||
out[n] = (pdt, dur)
|
||||
pdt, seq = None, (seq + 1 if seq is not None else None)
|
||||
return out
|
||||
|
||||
|
||||
def jsonl(path, t0, t1, key="t"):
|
||||
out = []
|
||||
try:
|
||||
for l in open(path):
|
||||
try:
|
||||
r = json.loads(l)
|
||||
except ValueError:
|
||||
continue
|
||||
if key in r and t0 <= r[key] <= t1:
|
||||
out.append(r)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
return out
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("canal")
|
||||
ap.add_argument("segundos", type=float)
|
||||
ap.add_argument("--player-lat", type=float, default=None)
|
||||
ap.add_argument("--player-lat-file", default=None, help="archivo con el retraso del player (se lee al final)")
|
||||
ap.add_argument("--etiqueta", default="")
|
||||
a = ap.parse_args()
|
||||
d = f"/var/www/hls/{a.canal}"
|
||||
segs = {} # seq -> dict
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < a.segundos:
|
||||
src = lista(f"{d}/src/index.m3u8")
|
||||
for n, (pdt, dur) in src.items():
|
||||
s = segs.setdefault(n, {"pdt": pdt, "dur": dur})
|
||||
for k, path in (("ts", f"{d}/src/{n}.ts"), ("es", f"{d}/subs/{n}.vtt"), ("en", f"{d}/en/{n}.vtt")):
|
||||
if k not in s:
|
||||
try:
|
||||
s[k] = os.path.getmtime(path)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
t1 = time.time()
|
||||
# Solo segmentos que cerraron dentro de la ventana y con su español.
|
||||
ok = [s for s in segs.values() if s.get("ts") and t0 + 5 <= s["ts"] <= t1 - 30 and "es" in s]
|
||||
es = [s["es"] - s["ts"] for s in ok]
|
||||
en = [s["en"] - s["ts"] for s in ok if "en" in s]
|
||||
en_es = [s["en"] - s["es"] for s in ok if "en" in s]
|
||||
pdt_off = [s["ts"] - (s["pdt"] + s["dur"]) for s in ok if s.get("pdt")]
|
||||
r = {"etiqueta": a.etiqueta, "ventana_s": round(t1 - t0), "segmentos": len(ok),
|
||||
"dur_seg": q([s["dur"] for s in ok], 0.5),
|
||||
"es_med": q(es, .5), "es_p95": q(es, .95), "es_max": round(max(es), 2) if es else None,
|
||||
"en_med": q(en, .5), "en_p95": q(en, .95), "en_max": round(max(en), 2) if en else None,
|
||||
"en_tras_es_med": q(en_es, .5), "en_sin_vtt": len(ok) - len(en),
|
||||
# .ts cerrado contra el PDT + duración: cuánto llega "después" la ingesta.
|
||||
"cierre_vs_pdt_med": q(pdt_off, .5)}
|
||||
if a.player_lat is None and a.player_lat_file:
|
||||
try:
|
||||
a.player_lat = float(open(a.player_lat_file).read().strip())
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
if a.player_lat is not None:
|
||||
# El player muestra el segmento n a partir de pdt + player_lat: el inglés está
|
||||
# a tiempo si su .vtt ya existía (con ~1 s para que hls.js lo pida).
|
||||
tarde = [s["en"] + 1.0 - (s["pdt"] + a.player_lat) for s in ok if "en" in s and s.get("pdt")]
|
||||
r["player_lat"] = a.player_lat
|
||||
r["en_tarde_player"] = sum(1 for x in tarde if x > 0)
|
||||
r["en_tarde_player_max_s"] = round(max(tarde), 2) if tarde else None
|
||||
w = jsonl(f"{LOG}/{a.canal}.jsonl", t0, t1)
|
||||
wh = [x["http_s"] for x in w if "http_s" in x and not x.get("error")]
|
||||
r.update({"whisper_n": len(wh), "whisper_rpm": round(len(wh) / ((t1 - t0) / 60), 1),
|
||||
"whisper_med": q(wh, .5), "whisper_p95": q(wh, .95),
|
||||
"whisper_audio_med": q([x["audio_s"] for x in w if "audio_s" in x], .5),
|
||||
"whisper_fallas": sum(1 for x in w if x.get("error")),
|
||||
"canal_extra_med": q([x["channel_extra_s"] for x in w if "channel_extra_s" in x], .5)})
|
||||
t = [x for x in jsonl(f"{LOG}/{a.canal}-en.jsonl", t0, t1) if "es" in x]
|
||||
qw = [x["qwen_s"] for x in t if x.get("en")]
|
||||
r.update({"qwen_n": len(qw), "qwen_med": q(qw, .5), "qwen_p95": q(qw, .95),
|
||||
"qwen_fallas": sum(1 for x in t if not x.get("en"))})
|
||||
srt = jsonl(f"{LOG}/{a.canal}-srt.jsonl", t0, t1)
|
||||
if len(srt) >= 2:
|
||||
a_, b_ = srt[0], srt[-1]
|
||||
if b_.get("retraso_fijo_s") == a_.get("retraso_fijo_s"):
|
||||
r["srt_retraso"] = b_["retraso_fijo_s"]
|
||||
for k in ("es608", "en608", "es708", "en708"):
|
||||
if k in a_ and k in b_ and b_[k]["cues"] >= a_[k]["cues"]:
|
||||
r[f"srt_{k}"] = {x: b_[k][x] - a_[k][x] for x in ("cues", "tarde", "perdidos")}
|
||||
if a.etiqueta:
|
||||
json.dump(segs, open(f"/root/m081-{a.etiqueta}.json", "w"))
|
||||
print(json.dumps(r, ensure_ascii=False))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user