#!/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 [--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()