OrbiSubs: live WebVTT subtitles for an HLS channel (whisper.cpp HTTP or faster-whisper)
Video -c:v copy, audio AAC re-encode, VTT por segmento alineado por PTS, video sostenido hasta tener subtítulo. Prueba tarea 076 en pve7 CT 176.
This commit is contained in:
@@ -0,0 +1,71 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Compara modelos/precisiones de faster-whisper sobre un clip grabado del canal.
|
||||||
|
|
||||||
|
No es tiempo real: mide el factor de tiempo real (RTF = cómputo / duración del
|
||||||
|
audio) troceando el clip en pedazos del tamaño de un segmento HLS, como hace el
|
||||||
|
servicio, y guarda el texto para compararlo contra la referencia a mano.
|
||||||
|
Uso: bench.py clip.wav salida.json modelo:precision [modelo:precision ...]
|
||||||
|
"""
|
||||||
|
import json, re, sys, time, unicodedata
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
from faster_whisper import WhisperModel, decode_audio
|
||||||
|
|
||||||
|
SR = 16000
|
||||||
|
|
||||||
|
|
||||||
|
def normalizar(t):
|
||||||
|
t = unicodedata.normalize("NFKD", t.lower())
|
||||||
|
t = "".join(c for c in t if not unicodedata.combining(c))
|
||||||
|
return re.sub(r"[^a-z0-9ñ ]+", " ", t).split()
|
||||||
|
|
||||||
|
|
||||||
|
def wer(ref, hip):
|
||||||
|
"""Distancia de edición por palabras / palabras de la referencia."""
|
||||||
|
r, h = normalizar(ref), normalizar(hip)
|
||||||
|
d = list(range(len(h) + 1))
|
||||||
|
for i in range(1, len(r) + 1):
|
||||||
|
prev, d[0] = d[0], i
|
||||||
|
for j in range(1, len(h) + 1):
|
||||||
|
cur = min(d[j] + 1, d[j - 1] + 1, prev + (r[i - 1] != h[j - 1]))
|
||||||
|
prev, d[j] = d[j], cur
|
||||||
|
return d[len(h)] / max(1, len(r))
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
clip, out, combos = sys.argv[1], sys.argv[2], sys.argv[3:]
|
||||||
|
dev = "cpu"
|
||||||
|
if combos and combos[0].startswith("--device="):
|
||||||
|
dev = combos.pop(0).split("=", 1)[1]
|
||||||
|
audio = decode_audio(clip, sampling_rate=SR)
|
||||||
|
dur = len(audio) / SR
|
||||||
|
res = []
|
||||||
|
for c in combos:
|
||||||
|
modelo, prec = c.split(":")
|
||||||
|
t = time.time()
|
||||||
|
m = WhisperModel(modelo, device=dev, compute_type=prec, cpu_threads=8)
|
||||||
|
carga = time.time() - t
|
||||||
|
# Pedazos de 6 s + 1 s de solape: lo mismo que ve el servicio por segmento.
|
||||||
|
textos, comp = [], 0.0
|
||||||
|
for i in range(0, len(audio), 6 * SR):
|
||||||
|
trozo = audio[max(0, i - SR):i + 6 * SR]
|
||||||
|
a = time.time()
|
||||||
|
segs, _ = m.transcribe(trozo, language="es", beam_size=1, vad_filter=True,
|
||||||
|
condition_on_previous_text=False, word_timestamps=True)
|
||||||
|
ws = [w for s in segs for w in (s.words or []) if (i == 0 or w.start >= 1.0)]
|
||||||
|
comp += time.time() - a
|
||||||
|
textos.append("".join(w.word for w in ws))
|
||||||
|
# Pasada entera (contexto completo) para el texto de calidad.
|
||||||
|
segs, _ = m.transcribe(audio, language="es", beam_size=5, vad_filter=True)
|
||||||
|
completo = " ".join(s.text.strip() for s in segs)
|
||||||
|
r = {"modelo": modelo, "precision": prec, "carga_s": round(carga, 1), "audio_s": round(dur, 1),
|
||||||
|
"computo_trozos_s": round(comp, 1), "rtf": round(comp / dur, 3),
|
||||||
|
"texto_trozos": " ".join(textos).strip(), "texto_completo": completo}
|
||||||
|
res.append(r)
|
||||||
|
print(json.dumps({k: v for k, v in r.items() if not k.startswith("texto")}), flush=True)
|
||||||
|
del m
|
||||||
|
json.dump(res, open(out, "w"), ensure_ascii=False, indent=1)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
# /etc/orbisubs/<canal>.env
|
||||||
|
INPUT=srt://192.168.10.40:10013?mode=caller&latency=200000
|
||||||
|
# Motor: http = whisper.cpp server remoto (gpu02); local = faster-whisper en esta máquina.
|
||||||
|
ENGINE=http
|
||||||
|
URL=http://192.168.2.10:8004
|
||||||
|
MODEL=small
|
||||||
|
DEVICE=cuda
|
||||||
|
COMPUTE=int8
|
||||||
|
THREADS=4
|
||||||
|
BEAM=1
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
server {
|
||||||
|
listen 80 default_server;
|
||||||
|
root /var/www;
|
||||||
|
location /hls/ {
|
||||||
|
add_header Access-Control-Allow-Origin * always;
|
||||||
|
add_header Cache-Control "no-cache" always;
|
||||||
|
types { application/vnd.apple.mpegurl m3u8; video/mp2t ts; text/vtt vtt; }
|
||||||
|
}
|
||||||
|
# Las listas internas de ffmpeg no se publican: el player tiene que ir por
|
||||||
|
# video.m3u8, que va sostenido hasta tener subtítulo.
|
||||||
|
location ~ ^/hls/[^/]+/src/index\.m3u8$ { return 404; }
|
||||||
|
location = / { return 302 /player.html; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=OrbiSubs transcripción %i (faster-whisper → WebVTT)
|
||||||
|
After=orbisubs-ingest@%i.service
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
EnvironmentFile=/etc/orbisubs/%i.env
|
||||||
|
ExecStart=/opt/orbisubs/venv/bin/python /opt/orbisubs/orbisubs.py --dir /var/www/hls/%i \
|
||||||
|
--engine ${ENGINE} --url ${URL} --model ${MODEL} --device ${DEVICE} --compute ${COMPUTE} --threads ${THREADS} --beam ${BEAM} \
|
||||||
|
--metrics /var/log/orbisubs/%i.jsonl
|
||||||
|
Restart=always
|
||||||
|
RestartSec=5
|
||||||
|
# Arranque limpio: el .vtt de segmentos viejos no sirve (otro buffer).
|
||||||
|
ExecStartPre=/bin/sh -c 'rm -f /var/www/hls/%i/subs/*.vtt; mkdir -p /var/log/orbisubs'
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=OrbiSubs ingesta %i (ffmpeg -c copy a HLS)
|
||||||
|
After=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
EnvironmentFile=/etc/orbisubs/%i.env
|
||||||
|
ExecStart=/opt/orbisubs/ingest.sh %i ${INPUT}
|
||||||
|
Restart=always
|
||||||
|
RestartSec=3
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# Ingesta de un canal: recibe la fuente (SRT/UDP/HLS) y la empaqueta en HLS SIN
|
||||||
|
# recodificar el video (-c:v copy). El audio sí se recodifica (AAC, costo mínimo):
|
||||||
|
# el T13 de rudo trae paquetes AAC corruptos en las tandas ("AAC bitstream not in
|
||||||
|
# ADTS format") y con -c:a copy Chromium cortaba con PIPELINE_ERROR_DECODE a los
|
||||||
|
# ~20 s (2026-11-16). aresample async rellena los huecos para que el PTS siga. El audio a 16 kHz lo saca orbisubs.py de cada segmento:
|
||||||
|
# así el texto queda atado al PTS del mismo .ts que ve el player.
|
||||||
|
# Uso: ingest.sh <canal> <url-entrada> (config en /etc/orbisubs/<canal>.env)
|
||||||
|
set -eu
|
||||||
|
CANAL="$1"; IN="$2"
|
||||||
|
DIR="/var/www/hls/$CANAL/src"
|
||||||
|
mkdir -p "$DIR"
|
||||||
|
EXTRA=()
|
||||||
|
# HLS de un CDN público: algunos piden User-Agent de navegador.
|
||||||
|
case "$IN" in http*) EXTRA=(-user_agent "Mozilla/5.0" -reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5);; esac
|
||||||
|
exec ffmpeg -hide_banner -loglevel warning -nostdin "${EXTRA[@]}" -i "$IN" \
|
||||||
|
-map 0:v:0 -map 0:a:0 -c:v copy \
|
||||||
|
-c:a aac -b:a 128k -ar 48000 -ac 2 -af aresample=async=1000 \
|
||||||
|
-f hls -hls_time "${HLS_TIME:-6}" -hls_list_size 20 \
|
||||||
|
-hls_flags delete_segments+program_date_time+temp_file+independent_segments \
|
||||||
|
-hls_segment_filename "$DIR/%d.ts" "$DIR/index.m3u8"
|
||||||
Executable
+377
@@ -0,0 +1,377 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""OrbiSubs — subtítulos en vivo (transcripción, mismo idioma del audio) como pista
|
||||||
|
WebVTT aparte en HLS. El video NO se recodifica: lo empaqueta el ffmpeg de ingesta
|
||||||
|
con -c copy en <dir>/src/, y este proceso:
|
||||||
|
|
||||||
|
1. mira src/index.m3u8 y toma cada segmento recién cerrado,
|
||||||
|
2. le saca el audio a 16 kHz mono y lo transcribe con faster-whisper,
|
||||||
|
3. escribe un .vtt por segmento de video (misma secuencia y duración),
|
||||||
|
4. publica video.m3u8 + subs.m3u8 + master.m3u8 hasta el último segmento que
|
||||||
|
ya tiene subtítulo.
|
||||||
|
|
||||||
|
Por qué se demora el video en vez de publicar los subtítulos "cuando estén": si
|
||||||
|
la lista de subtítulos va atrás de la de video, el player muestra los primeros
|
||||||
|
segundos sin texto o lo saltea. Sosteniendo el video hasta que su .vtt existe,
|
||||||
|
el texto queda en sincronía y el costo es un retraso fijo del canal (se mide).
|
||||||
|
|
||||||
|
Alineación: cada .vtt lleva X-TIMESTAMP-MAP=MPEGTS:0,LOCAL:00:00:00.000 y los
|
||||||
|
tiempos de los cues son el PTS absoluto del audio en segundos. Así no depende de
|
||||||
|
PROGRAM-DATE-TIME (que ffmpeg pone por reloj de pared) sino del mismo PTS del .ts.
|
||||||
|
Ojo: el PTS da la vuelta a las 26,5 h (2^33 / 90 kHz); se maneja abajo (wrap).
|
||||||
|
"""
|
||||||
|
import argparse, json, os, re, subprocess, sys, time
|
||||||
|
from collections import deque
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
SR = 16000
|
||||||
|
WRAP = 2 ** 33 / 90000.0
|
||||||
|
|
||||||
|
|
||||||
|
def log(msg, **kw):
|
||||||
|
kw["msg"] = msg
|
||||||
|
kw["t"] = round(time.time(), 3)
|
||||||
|
print(json.dumps(kw, ensure_ascii=False), flush=True)
|
||||||
|
|
||||||
|
|
||||||
|
def leer_lista(path):
|
||||||
|
"""Devuelve [(seq, uri, dur, pdt)] de la lista que escribe ffmpeg."""
|
||||||
|
try:
|
||||||
|
txt = open(path).read()
|
||||||
|
except FileNotFoundError:
|
||||||
|
return [], None
|
||||||
|
seq0, segs, dur, pdt = 0, [], None, None
|
||||||
|
for l in txt.splitlines():
|
||||||
|
if l.startswith("#EXT-X-MEDIA-SEQUENCE:"):
|
||||||
|
seq0 = int(l.split(":")[1])
|
||||||
|
elif l.startswith("#EXTINF:"):
|
||||||
|
dur = float(l[8:].split(",")[0])
|
||||||
|
elif l.startswith("#EXT-X-PROGRAM-DATE-TIME:"):
|
||||||
|
pdt = l.split(":", 1)[1]
|
||||||
|
elif l and not l.startswith("#"):
|
||||||
|
segs.append((seq0 + len(segs), l, dur, pdt))
|
||||||
|
pdt = None
|
||||||
|
tgt = re.search(r"#EXT-X-TARGETDURATION:(\d+)", txt)
|
||||||
|
return segs, int(tgt.group(1)) if tgt else None
|
||||||
|
|
||||||
|
|
||||||
|
def audio_de_segmento(path):
|
||||||
|
"""PTS de inicio del audio (s) y muestras float32 16 kHz mono."""
|
||||||
|
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)
|
||||||
|
t0 = float(pr.stdout.strip().split("\n")[0])
|
||||||
|
# Las muestras arrancan en t0: el .vtt usa el mismo PTS que el video del .ts.
|
||||||
|
r = subprocess.run(["ffmpeg", "-v", "error", "-i", path, "-map", "0:a:0", "-ac", "1", "-ar", str(SR),
|
||||||
|
"-f", "f32le", "-"], capture_output=True)
|
||||||
|
return t0, np.frombuffer(r.stdout, dtype=np.float32)
|
||||||
|
|
||||||
|
|
||||||
|
def ts_vtt(s):
|
||||||
|
s = max(0.0, s)
|
||||||
|
h, rem = divmod(s, 3600)
|
||||||
|
m, sec = divmod(rem, 60)
|
||||||
|
return f"{int(h):02d}:{int(m):02d}:{sec:06.3f}"
|
||||||
|
|
||||||
|
|
||||||
|
def partir_lineas(txt, ancho=42):
|
||||||
|
"""Hasta 2 líneas de ~42 caracteres (estándar de subtitulado de TV)."""
|
||||||
|
if len(txt) <= ancho:
|
||||||
|
return txt
|
||||||
|
corte = txt.rfind(" ", 0, len(txt) // 2 + 8)
|
||||||
|
if corte <= 0:
|
||||||
|
corte = txt.find(" ", len(txt) // 2)
|
||||||
|
return txt if corte <= 0 else txt[:corte] + "\n" + txt[corte + 1:]
|
||||||
|
|
||||||
|
|
||||||
|
class MotorLocal:
|
||||||
|
"""faster-whisper en la misma máquina (P4 o CPU)."""
|
||||||
|
|
||||||
|
def __init__(self, modelo, device, compute, threads, beam):
|
||||||
|
from faster_whisper import WhisperModel
|
||||||
|
self.m = WhisperModel(modelo, device=device, compute_type=compute, cpu_threads=threads)
|
||||||
|
self.beam = beam
|
||||||
|
|
||||||
|
def __call__(self, audio, prompt):
|
||||||
|
segs, _ = self.m.transcribe(audio, language="es", beam_size=self.beam, word_timestamps=True,
|
||||||
|
vad_filter=True, vad_parameters={"min_silence_duration_ms": 500},
|
||||||
|
condition_on_previous_text=False, initial_prompt=prompt)
|
||||||
|
return [(w.start, w.end, w.word) for s in segs for w in (s.words or [])]
|
||||||
|
|
||||||
|
|
||||||
|
class MotorHTTP:
|
||||||
|
"""whisper.cpp server remoto (gpu02, tarea 076-agregado): solo POST /inference,
|
||||||
|
un pedido a la vez (este proceso es secuencial). Nunca /load: cambia el modelo
|
||||||
|
para todos los que comparten el servicio."""
|
||||||
|
|
||||||
|
def __init__(self, url, timeout=20.0):
|
||||||
|
import requests
|
||||||
|
self.s = requests.Session()
|
||||||
|
self.url = url.rstrip("/") + "/inference"
|
||||||
|
self.timeout = timeout
|
||||||
|
self.ultimo = {}
|
||||||
|
|
||||||
|
def __call__(self, audio, prompt):
|
||||||
|
import io, wave
|
||||||
|
pcm = (np.clip(audio, -1, 1) * 32767).astype("<i2").tobytes()
|
||||||
|
b = io.BytesIO()
|
||||||
|
with wave.open(b, "wb") as w:
|
||||||
|
w.setnchannels(1); w.setsampwidth(2); w.setframerate(SR); w.writeframes(pcm)
|
||||||
|
data = {"temperature": "0.0", "response_format": "verbose_json", "language": "es"}
|
||||||
|
if prompt:
|
||||||
|
data["prompt"] = prompt
|
||||||
|
t = time.time()
|
||||||
|
r = self.s.post(self.url, files={"file": ("a.wav", b.getvalue(), "audio/wav")}, data=data,
|
||||||
|
timeout=self.timeout)
|
||||||
|
r.raise_for_status()
|
||||||
|
d = r.json()
|
||||||
|
self.ultimo = {"http_s": round(time.time() - t, 3)}
|
||||||
|
out = []
|
||||||
|
for seg in d.get("segments") or []:
|
||||||
|
# whisper.cpp sin VAD alucina con música/silencio ("¡Gracias!", "Subtítulos por…"):
|
||||||
|
# se descartan los segmentos que el propio modelo marca como dudosos.
|
||||||
|
if seg.get("no_speech_prob", 0) > 0.6 or seg.get("avg_logprob", 0) < -1.0:
|
||||||
|
continue
|
||||||
|
for w in seg.get("words") or []:
|
||||||
|
txt = w.get("word", "")
|
||||||
|
if not txt.strip():
|
||||||
|
continue
|
||||||
|
# whisper.cpp da tokens, no palabras ("direct" + "a"): un token sin
|
||||||
|
# espacio adelante se pega al anterior, si no el corte de confirmación
|
||||||
|
# puede partir una palabra entre dos cues (visto en T13, 2026-11-16).
|
||||||
|
if out and not txt.startswith(" "):
|
||||||
|
a0, _, t = out[-1]
|
||||||
|
out[-1] = (a0, float(w["end"]), t + txt)
|
||||||
|
else:
|
||||||
|
out.append((float(w["start"]), float(w["end"]), txt))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
class Transcriptor:
|
||||||
|
"""Buffer de audio con confirmación por retención: se transcribe todo lo que
|
||||||
|
está sin confirmar y solo se confirman las palabras que terminan antes de
|
||||||
|
(fin del buffer − HOLD). Las del borde se vuelven a transcribir con el
|
||||||
|
segmento siguiente, cuando ya tienen contexto a los dos lados (whisper corta
|
||||||
|
mal las palabras pegadas al final del audio)."""
|
||||||
|
|
||||||
|
def __init__(self, motor, hold, max_buf):
|
||||||
|
self.model, self.hold, self.max_buf = motor, hold, max_buf
|
||||||
|
self.buf = np.zeros(0, dtype=np.float32)
|
||||||
|
self.t0 = None # PTS (s) de la primera muestra del buffer
|
||||||
|
self.contexto = ""
|
||||||
|
|
||||||
|
def fin(self):
|
||||||
|
return None if self.t0 is None else self.t0 + len(self.buf) / SR
|
||||||
|
|
||||||
|
def agregar(self, t0, muestras):
|
||||||
|
if self.t0 is None:
|
||||||
|
self.t0, self.buf = t0, muestras
|
||||||
|
return
|
||||||
|
hueco = t0 - self.fin()
|
||||||
|
if hueco < -WRAP / 2: # dio la vuelta el PTS
|
||||||
|
hueco += WRAP
|
||||||
|
if abs(hueco) > 1.0:
|
||||||
|
# Corte de la fuente (reconexión, salto de PTS): se descarta lo pendiente.
|
||||||
|
log("audio_discontinuity", gap=round(hueco, 3))
|
||||||
|
self.t0, self.buf, self.contexto = t0, muestras, ""
|
||||||
|
return
|
||||||
|
if hueco > 0:
|
||||||
|
self.buf = np.concatenate([self.buf, np.zeros(int(hueco * SR), np.float32)])
|
||||||
|
elif hueco < 0:
|
||||||
|
muestras = muestras[int(-hueco * SR):]
|
||||||
|
self.buf = np.concatenate([self.buf, muestras])
|
||||||
|
|
||||||
|
def paso(self):
|
||||||
|
"""Transcribe lo pendiente; devuelve (palabras confirmadas, segundos de cómputo)."""
|
||||||
|
if self.t0 is None or len(self.buf) < SR:
|
||||||
|
return [], 0.0
|
||||||
|
fin = self.fin()
|
||||||
|
forzar = len(self.buf) / SR > self.max_buf
|
||||||
|
limite = fin if forzar else fin - self.hold
|
||||||
|
a = time.time()
|
||||||
|
palabras = [(self.t0 + w0, self.t0 + w1, txt)
|
||||||
|
for w0, w1, txt in self.model(self.buf, self.contexto[-200:] or None)]
|
||||||
|
dt = time.time() - a
|
||||||
|
conf = [w for w in palabras if w[1] <= limite]
|
||||||
|
pend = [w for w in palabras if w[1] > limite]
|
||||||
|
if pend:
|
||||||
|
# Se corta donde termina lo confirmado (o donde empieza lo pendiente, si no hay nada).
|
||||||
|
corte = conf[-1][1] if conf else min(limite, pend[0][0])
|
||||||
|
else:
|
||||||
|
corte = limite
|
||||||
|
corte = max(corte, self.t0)
|
||||||
|
self.buf = self.buf[int((corte - self.t0) * SR):]
|
||||||
|
self.t0 = corte
|
||||||
|
if conf:
|
||||||
|
self.contexto = (self.contexto + "".join(w[2] for w in conf))[-400:]
|
||||||
|
return conf, dt
|
||||||
|
|
||||||
|
|
||||||
|
def armar_cues(palabras, pausa=0.8, max_chars=84, max_dur=5.0):
|
||||||
|
cues, cur = [], []
|
||||||
|
for w in palabras:
|
||||||
|
if cur:
|
||||||
|
txt = "".join(x[2] for x in cur).strip()
|
||||||
|
if (w[0] - cur[-1][1] > pausa or len(txt) + len(w[2]) > max_chars or w[1] - cur[0][0] > max_dur
|
||||||
|
or txt.endswith((".", "?", "!"))):
|
||||||
|
cues.append(cur)
|
||||||
|
cur = []
|
||||||
|
cur.append(w)
|
||||||
|
if cur:
|
||||||
|
cues.append(cur)
|
||||||
|
out = []
|
||||||
|
for c in cues:
|
||||||
|
txt = "".join(x[2] for x in c).strip()
|
||||||
|
if txt:
|
||||||
|
# Mínimo 1 s en pantalla: con menos no se alcanza a leer.
|
||||||
|
out.append([c[0][0], max(c[-1][1] + 0.3, c[0][0] + 1.0), txt])
|
||||||
|
for i in range(len(out) - 1):
|
||||||
|
out[i][1] = min(out[i][1], out[i + 1][0])
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def escribir_atomico(path, txt):
|
||||||
|
tmp = path + ".tmp"
|
||||||
|
with open(tmp, "w") as f:
|
||||||
|
f.write(txt)
|
||||||
|
os.replace(tmp, path)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
ap = argparse.ArgumentParser()
|
||||||
|
ap.add_argument("--dir", required=True, help="carpeta del canal; ffmpeg escribe en <dir>/src/index.m3u8")
|
||||||
|
ap.add_argument("--engine", default="http", choices=["http", "local"])
|
||||||
|
ap.add_argument("--url", default="http://192.168.2.10:8004", help="whisper.cpp server (engine=http)")
|
||||||
|
ap.add_argument("--model", default="small")
|
||||||
|
ap.add_argument("--device", default="cuda")
|
||||||
|
ap.add_argument("--compute", default="int8")
|
||||||
|
ap.add_argument("--threads", type=int, default=4)
|
||||||
|
ap.add_argument("--beam", type=int, default=1)
|
||||||
|
ap.add_argument("--hold", type=float, default=1.0, help="segundos del borde que no se confirman todavía")
|
||||||
|
ap.add_argument("--window", type=int, default=10, help="segmentos en las listas publicadas")
|
||||||
|
ap.add_argument("--bandwidth", type=int, default=2600000)
|
||||||
|
ap.add_argument("--resolution", default="1280x720")
|
||||||
|
ap.add_argument("--metrics", default=None)
|
||||||
|
a = ap.parse_args()
|
||||||
|
|
||||||
|
t = time.time()
|
||||||
|
if a.engine == "http":
|
||||||
|
motor = MotorHTTP(a.url)
|
||||||
|
log("engine_http", url=a.url)
|
||||||
|
else:
|
||||||
|
motor = MotorLocal(a.model, a.device, a.compute, a.threads, a.beam)
|
||||||
|
log("model_loaded", model=a.model, device=a.device, compute=a.compute, secs=round(time.time() - t, 1))
|
||||||
|
|
||||||
|
src = os.path.join(a.dir, "src", "index.m3u8")
|
||||||
|
subs_dir = os.path.join(a.dir, "subs")
|
||||||
|
os.makedirs(subs_dir, exist_ok=True)
|
||||||
|
tr = Transcriptor(motor, a.hold, max_buf=20.0)
|
||||||
|
met = open(a.metrics, "a") if a.metrics else None
|
||||||
|
|
||||||
|
llegada = {} # seq -> reloj de pared en que apareció en la lista de ffmpeg
|
||||||
|
info = {} # seq -> (uri, dur, pdt, pts_ini, pts_fin)
|
||||||
|
procesado = -1 # último seq cuyo audio ya entró al transcriptor
|
||||||
|
publicado = -1 # último seq con .vtt escrito
|
||||||
|
cues = deque(maxlen=400)
|
||||||
|
escribir_atomico(os.path.join(a.dir, "master.m3u8"),
|
||||||
|
"#EXTM3U\n#EXT-X-VERSION:3\n"
|
||||||
|
'#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID="subs",NAME="Español (automático)",LANGUAGE="es",'
|
||||||
|
'DEFAULT=NO,AUTOSELECT=YES,FORCED=NO,URI="subs.m3u8"\n'
|
||||||
|
f'#EXT-X-STREAM-INF:BANDWIDTH={a.bandwidth},RESOLUTION={a.resolution},SUBTITLES="subs"\n'
|
||||||
|
"video.m3u8\n")
|
||||||
|
|
||||||
|
while True:
|
||||||
|
segs, tgt = leer_lista(src)
|
||||||
|
ahora = time.time()
|
||||||
|
for seq, uri, dur, pdt in segs:
|
||||||
|
llegada.setdefault(seq, ahora)
|
||||||
|
nuevos = [s for s in segs if s[0] > procesado]
|
||||||
|
if not nuevos:
|
||||||
|
time.sleep(0.2)
|
||||||
|
continue
|
||||||
|
if procesado < 0 or nuevos[0][0] != procesado + 1:
|
||||||
|
# Arranque o salto: empezar por el último (no transcribir historia vieja).
|
||||||
|
nuevos = nuevos[-1:]
|
||||||
|
publicado = nuevos[0][0] - 1
|
||||||
|
for seq, uri, dur, pdt in nuevos:
|
||||||
|
path = os.path.join(a.dir, "src", uri)
|
||||||
|
try:
|
||||||
|
p0, muestras = audio_de_segmento(path)
|
||||||
|
except Exception as e:
|
||||||
|
log("segment_read_error", seq=seq, err=str(e))
|
||||||
|
procesado = seq
|
||||||
|
continue
|
||||||
|
info[seq] = (uri, dur, pdt, p0, p0 + dur)
|
||||||
|
tr.agregar(p0, muestras)
|
||||||
|
try:
|
||||||
|
conf, dt = tr.paso()
|
||||||
|
except Exception as e:
|
||||||
|
# Motor caído o lento: el canal sigue sin texto (el tope de 2 segmentos
|
||||||
|
# publica igual) y el audio pendiente se descarta para no acumular.
|
||||||
|
log("asr_error", seq=seq, err=str(e)[:200])
|
||||||
|
conf, dt = [], 0.0
|
||||||
|
tr.t0, tr.buf = tr.fin(), np.zeros(0, np.float32)
|
||||||
|
nuevos_cues = armar_cues(conf)
|
||||||
|
if cues and nuevos_cues:
|
||||||
|
# Que el último cue anterior no se pise con el primero nuevo (vienen de pasos distintos).
|
||||||
|
cues[-1][1] = min(cues[-1][1], nuevos_cues[0][0])
|
||||||
|
cues.extend(nuevos_cues)
|
||||||
|
listo_hasta = tr.t0 # todo lo anterior a este PTS ya está confirmado
|
||||||
|
fin_wall = time.time()
|
||||||
|
procesado = seq
|
||||||
|
# Retraso de cada palabra: cuándo se confirmó contra cuándo llegó su audio.
|
||||||
|
# El audio del final del segmento "llega" cuando el segmento cierra.
|
||||||
|
lags = [round(fin_wall - (llegada[seq] - (p0 + dur - w[1])), 2) for w in conf]
|
||||||
|
# Escribir .vtt de todos los segmentos ya cubiertos por lo confirmado.
|
||||||
|
for s in range(publicado + 1, seq + 1):
|
||||||
|
if s not in info:
|
||||||
|
continue
|
||||||
|
_, sd, _, s0, s1 = info[s]
|
||||||
|
# Tope: con 2 segmentos de atraso se publica igual (lo que falte entra en el
|
||||||
|
# .vtt siguiente), para que una frase larga sin pausa no trabe el canal.
|
||||||
|
if s1 > listo_hasta + 0.05 and s > seq - 2:
|
||||||
|
break
|
||||||
|
cuerpo = ["WEBVTT", "X-TIMESTAMP-MAP=MPEGTS:0,LOCAL:00:00:00.000", ""]
|
||||||
|
for c0, c1, txt in cues:
|
||||||
|
if c1 > s0 and c0 < s1:
|
||||||
|
cuerpo += [f"{ts_vtt(c0)} --> {ts_vtt(c1)}", partir_lineas(txt), ""]
|
||||||
|
escribir_atomico(os.path.join(subs_dir, f"{s}.vtt"), "\n".join(cuerpo) + "\n")
|
||||||
|
publicado = s
|
||||||
|
# Listas publicadas: video sostenido hasta el último segmento con subtítulo.
|
||||||
|
ventana = [x for x in segs if x[0] <= publicado][-a.window:]
|
||||||
|
if ventana:
|
||||||
|
td = max(tgt or 0, int(max(x[2] for x in ventana) + 0.999))
|
||||||
|
cab = f"#EXTM3U\n#EXT-X-VERSION:3\n#EXT-X-TARGETDURATION:{td}\n#EXT-X-MEDIA-SEQUENCE:{ventana[0][0]}\n"
|
||||||
|
v, sub = [cab], [cab]
|
||||||
|
for s, u, d, pdt in ventana:
|
||||||
|
if pdt:
|
||||||
|
v.append(f"#EXT-X-PROGRAM-DATE-TIME:{pdt}\n")
|
||||||
|
sub.append(f"#EXT-X-PROGRAM-DATE-TIME:{pdt}\n")
|
||||||
|
v.append(f"#EXTINF:{d:.6f},\nsrc/{u}\n")
|
||||||
|
sub.append(f"#EXTINF:{d:.6f},\nsubs/{s}.vtt\n")
|
||||||
|
escribir_atomico(os.path.join(a.dir, "video.m3u8"), "".join(v))
|
||||||
|
escribir_atomico(os.path.join(a.dir, "subs.m3u8"), "".join(sub))
|
||||||
|
# Limpieza de .vtt viejos (los .ts los borra ffmpeg).
|
||||||
|
for f in os.listdir(subs_dir):
|
||||||
|
if f.endswith(".vtt") and int(f[:-4]) < ventana[0][0] - 5:
|
||||||
|
os.unlink(os.path.join(subs_dir, f))
|
||||||
|
for k in [k for k in info if k < ventana[0][0] - 5]:
|
||||||
|
info.pop(k, None)
|
||||||
|
llegada.pop(k, None)
|
||||||
|
m = {"seq": seq, "dur": dur, "asr_s": round(dt, 2), **getattr(motor, "ultimo", {}), "rtf": round(dt / dur, 3) if dur else None,
|
||||||
|
"words": len(conf), "cues": len(nuevos_cues),
|
||||||
|
"word_lag_avg": round(sum(lags) / len(lags), 2) if lags else None,
|
||||||
|
"word_lag_max": max(lags) if lags else None,
|
||||||
|
"pending_s": round(tr.fin() - tr.t0, 2),
|
||||||
|
# Retraso extra del canal: cuánto atrás del ffmpeg va la lista publicada.
|
||||||
|
"held_segments": seq - publicado,
|
||||||
|
"channel_extra_s": round(sum(info[k][1] for k in range(publicado + 1, seq + 1) if k in info)
|
||||||
|
+ (fin_wall - llegada[seq]), 2),
|
||||||
|
"text": " | ".join(c[2] for c in nuevos_cues)}
|
||||||
|
log("segment", **m)
|
||||||
|
if met:
|
||||||
|
met.write(json.dumps(m, ensure_ascii=False) + "\n")
|
||||||
|
met.flush()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="es"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||||
|
<title>OrbiSubs prueba</title>
|
||||||
|
<style>body{background:#111;color:#ddd;font-family:sans-serif;margin:16px}video{width:100%;max-width:960px}
|
||||||
|
#info{font-size:13px;color:#999;margin-top:8px}select,input{font-size:14px}</style></head>
|
||||||
|
<body>
|
||||||
|
<h3>OrbiSubs — subtítulos en vivo (prueba)</h3>
|
||||||
|
<input id="u" size="50" value="/hls/t13/master.m3u8"> <button onclick="cargar()">Cargar</button>
|
||||||
|
<label> Subtítulos <select id="s"><option value="-1">Apagados</option></select></label>
|
||||||
|
<div><video id="v" controls muted autoplay playsinline></video></div>
|
||||||
|
<div id="info"></div>
|
||||||
|
<div id="diag" style="font-size:12px;color:#777"></div>
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/hls.js@1.5.20/dist/hls.min.js"></script>
|
||||||
|
<script>
|
||||||
|
let hls;
|
||||||
|
function cargar(){
|
||||||
|
const v=document.getElementById('v'), s=document.getElementById('s');
|
||||||
|
if(hls) hls.destroy();
|
||||||
|
hls=new Hls({liveSyncDurationCount:3});
|
||||||
|
// Recuperación estándar de hls.js: el CDN de origen mete cortes de PTS en las tandas
|
||||||
|
// y el decoder del navegador a veces se cae ahí (visto con Chromium, 2026-11-16).
|
||||||
|
hls.on(Hls.Events.ERROR,(e,d)=>{ if(!d.fatal) return;
|
||||||
|
if(d.type===Hls.ErrorTypes.MEDIA_ERROR) hls.recoverMediaError(); else hls.startLoad(); });
|
||||||
|
hls.loadSource(document.getElementById('u').value); hls.attachMedia(v);
|
||||||
|
hls.on(Hls.Events.SUBTITLE_TRACKS_UPDATED,()=>{
|
||||||
|
s.innerHTML='<option value="-1">Apagados</option>'+hls.subtitleTracks.map((t,i)=>`<option value="${i}">${t.name}</option>`).join('');
|
||||||
|
s.value=0; hls.subtitleTrack=0; hls.subtitleDisplay=true;
|
||||||
|
});
|
||||||
|
s.onchange=()=>{hls.subtitleTrack=+s.value; hls.subtitleDisplay=+s.value>=0;};
|
||||||
|
// Diagnóstico: cuántos cues cargó la pista y cuál está en pantalla (sirve para
|
||||||
|
// probar con un navegador headless que el texto llega y en qué tiempo del video).
|
||||||
|
setInterval(()=>{const t=[...v.textTracks].find(x=>x.mode==='showing');
|
||||||
|
const act=t&&t.activeCues&&t.activeCues.length?[...t.activeCues].map(c=>c.text.replace(/\n/g,' ')).join(' / '):'';
|
||||||
|
document.getElementById('diag').textContent=`t=${v.currentTime.toFixed(1)} pistas=${v.textTracks.length} cues=${t&&t.cues?t.cues.length:0} activo=[${act}]`;},500);
|
||||||
|
setInterval(()=>{const l=hls.latency; document.getElementById('info').textContent=
|
||||||
|
'Retraso al borde de la lista publicada: '+(l?l.toFixed(1):'?')+' s';},1000);
|
||||||
|
}
|
||||||
|
cargar();
|
||||||
|
</script></body></html>
|
||||||
Reference in New Issue
Block a user