#!/usr/bin/env python3 """ clip_workflow.py — Automated YouTube Livestream Clipper for Peñarol Fan Show Usage — canal (último stream): python clip_workflow.py --channel "https://www.youtube.com/@TuCanal" Usage — video directo: python clip_workflow.py --video "https://www.youtube.com/watch?v=VIDEO_ID" python clip_workflow.py --video "https://www.youtube.com/watch?v=VIDEO_ID" --clips 5 Requirements: see requirements.txt + setup.sh """ import argparse import contextlib import json import os import re import shutil import subprocess import sys import tempfile from pathlib import Path import anthropic # --------------------------------------------------------------------------- # Constants # --------------------------------------------------------------------------- # Use ffmpeg-full (includes libass/freetype for subtitle burning) FFMPEG_BIN = "/opt/homebrew/opt/ffmpeg-full/bin/ffmpeg" YTDLP_BIN = Path(sys.executable).with_name("yt-dlp") # Quality settings for encodes # CRF: lower = better quality / larger file. 18 = visually lossless. VIDEO_CRF = "18" VIDEO_PRESET = "slow" # slow = better compression at same quality AUDIO_BITRATE = "320k" # Subtle finishing filters. They are intentionally conservative: enough to make # livestream clips feel less flat without changing skin tones or making the # logo/subtitles look processed. Filters run before branding and subtitles. VIDEO_POLISH_FILTER = ( "eq=contrast=1.035:saturation=1.03:brightness=0.003," "unsharp=5:5:0.28:3:3:0.08" ) AUDIO_POLISH_FILTER = ( "aformat=sample_fmts=fltp:channel_layouts=stereo," "loudnorm=I=-16:LRA=11:TP=-1.5," "acompressor=threshold=-18dB:ratio=2.2:attack=8:release=160," "alimiter=limit=0.95," "aresample=async=1:first_pts=0" ) TARGET_MAX_CLIP_DURATION = 60.0 ABSOLUTE_MAX_CLIP_DURATION = 65.0 END_PAD_SECONDS = 0.25 # Split-panel livestream frames include a thin black/program border at the very # top. Panel crops should start a little lower so social clips show only the # active panel. Single-camera close-ups use a separate y anchor because their # bottom broadcast border is more visible than the top edge. VERTICAL_TOP_GUARD_RATIO = 0.04 PANEL_CROP_HEIGHT_RATIO = 0.88 TALKNET_DIR = Path(__file__).resolve().parent / "experiments" / "TalkNet-ASD" TALKNET_MODEL_PATH = TALKNET_DIR / "pretrain_TalkSet.model" _TALKNET_MODEL = None ASSETS_DIR = Path(__file__).resolve().parent / "assets" PYD_LOGO_PATH = ASSETS_DIR / "pyd-logo.png" PYD_LOGO_VERTICAL_WIDTH = 210 PYD_LOGO_HORIZONTAL_WIDTH = 230 PYD_LOGO_VERTICAL_MARGIN_X = 38 PYD_LOGO_VERTICAL_MARGIN_Y = 42 PYD_LOGO_HORIZONTAL_MARGIN_X = 42 PYD_LOGO_HORIZONTAL_MARGIN_Y = 34 SOURCE_LOGO_RIGHT_X = 320 SOURCE_LOGO_CLEAR_Y = 130 SOURCE_LOGO_BOTTOM_GUARD_RATIO = 0.035 # YouTube increasingly hides high-quality formats behind PO-token/SABR flows. # When the local bgutil provider is available, use it automatically so recently # finished lives expose 720p/1080p formats instead of only the low 360p stream. NODE22_BIN = Path("/opt/homebrew/opt/node@22/bin/node") BGUTIL_SERVER_HOME = Path("/Users/emiliarodrig/bgutil-ytdlp-pot-provider/server") YOUTUBE_HQ_FORMAT = ( "bv*[height<=1080][vcodec^=avc1]+ba[ext=m4a]/" "bv*[height<=1080]+ba/" "bv*+ba/" "best[ext=mp4]/best" ) WHISPER_INITIAL_PROMPT = ( "Programa uruguayo de fútbol de Padre y Decano sobre Peñarol. " "Vocabulario frecuente: Peñarol, Peñaroleando, Carbonero, aurinegro, " "Copa Libertadores, Campeón del Siglo, Ruglio, Aguirre, Nacho, Freddy, " "Ignacio Ruglio, abono, abonos, socios, butacas, palcos, entradas, " "Manyas, clásico, Nacional, Uruguay, CONMEBOL." ) # --------------------------------------------------------------------------- # Subtitle text normalization # --------------------------------------------------------------------------- # Known corrections applied automatically at subtitle-generation time. # Keys are regex patterns (case-insensitive), values are the correct replacement. # Extend this dict when recurring Whisper errors are found for this show. SUBTITLE_CORRECTIONS: dict[str, str] = { r"\bpe[nñ]arol\b": "Peñarol", r"\bpadre\s+y\s+decano\b": "Padre y Decano", r"\bpydtv\b": "PyDTV", r"\bpyd\b": "PyD", r"\bdanubio\b": "Danubio", r"\buruguay\b": "Uruguay", r"\buruguayo\b": "Uruguayo", r"\buruguaya\b": "Uruguaya", r"\buruguayos\b": "Uruguayos", r"\buruguayas\b": "Uruguayas", r"\baguirre\b": "Aguirre", r"\bfern[aá]ndez\b": "Fernández", r"\bmonumental\b": "Monumental", r"\bcentenario\b": "Centenario", r"\bparque central\b": "Parque Central", r"\bmercosur\b": "Mercosur", r"\bsud[aá]merica\b": "Sudamérica", r"\bruglio\b": "Ruglio", r"\bsarro\b": "Cerro", } RUGLIO_CONTEXT_RE = re.compile( r"\b(" r"ignacio|nacho|presidente|dirigente|directiva|directivo|consejo|" r"comisi[oó]n|club|pe[nñ]arol|carbonero|aurinegro|ruglio" r")\b", flags=re.IGNORECASE, ) ABONO_CONTEXT_RE = re.compile( r"\b(" r"abono|abonos|abonado|abonados|socio|socios|butaca|butacas|palco|palcos|" r"entrada|entradas|precio|precios|tribuna|estadio|cancha|campe[oó]n|siglo|" r"temporada|cuota|cuotas|pagar|pago|sacar|sac[oó]|sacado|saque|" r"llenar|llena|local|partido" r")\b", flags=re.IGNORECASE, ) SUBTITLE_FILLER_WORDS = { "ah", "eh", "ehh", "em", "mmm", "um", "este", "ta", } def _plain_subtitle_word(text: str) -> str: return re.sub(r"[^0-9A-Za-zÁÉÍÓÚÜÑáéíóúüñ]+", "", text).lower() def _case_like(source: str, replacement: str) -> str: if source.isupper(): return replacement.upper() if source[:1].isupper(): return replacement[:1].upper() + replacement[1:] return replacement def _replace_bono_as_abono(match: re.Match) -> str: word = match.group(0) replacement = "abonos" if _plain_subtitle_word(word).endswith("s") else "abono" return _case_like(word, replacement) def _replace_bono_phrase(match: re.Match) -> str: phrase = match.group(0) plural = _plain_subtitle_word(match.group("noun")).endswith("s") replacement = "los abonos" if plural else "el abono" if phrase.isupper(): return replacement.upper() if phrase[:1].isupper(): return replacement[:1].upper() + replacement[1:] return replacement def apply_contextual_subtitle_corrections(text: str, context: str = "") -> str: """Fix recurrent Whisper confusions only when the surrounding text supports it.""" context_text = f"{context} {text}".strip() if re.search(r"\b(?:rubio|rublio|rublo)\b", text, flags=re.IGNORECASE) and RUGLIO_CONTEXT_RE.search(context_text): text = re.sub( r"\b(?:rubio|rublio|rublo)\b", lambda m: _case_like(m.group(0), "Ruglio"), text, flags=re.IGNORECASE, ) text = re.sub( r"\b(?:iba\s+irre|eva\s+aguirre)\b", lambda m: _case_like(m.group(0), "Diego Aguirre"), text, flags=re.IGNORECASE, ) if re.search(r"\bbonos?\b", text, flags=re.IGNORECASE) and ABONO_CONTEXT_RE.search(context_text): text = re.sub( r"\b(?:la|las)\s+(?Pbonos?)\b", _replace_bono_phrase, text, flags=re.IGNORECASE, ) text = re.sub(r"\bbonos?\b", _replace_bono_as_abono, text, flags=re.IGNORECASE) return text def normalize_subtitle_word_sequence(word_items: list[dict]) -> None: """Polish grammar after per-word contextual corrections.""" for idx, item in enumerate(word_items): plain = _plain_subtitle_word(str(item.get("word", ""))) if idx > 0 and plain in {"irre", "aguirre"}: prev = word_items[idx - 1] prev_plain = _plain_subtitle_word(str(prev.get("word", ""))) if prev_plain in {"iba", "eva"}: prev["word"] = _case_like(str(prev.get("word", "")), "Diego") item["word"] = _case_like(str(item.get("word", "")), "Aguirre") continue if plain not in {"abono", "abonos"} or idx == 0: continue prev = word_items[idx - 1] prev_plain = _plain_subtitle_word(str(prev.get("word", ""))) if plain == "abono" and prev_plain in {"la", "las"}: prev["word"] = _case_like(str(prev.get("word", "")), "el") elif plain == "abonos" and prev_plain in {"la", "las", "el"}: prev["word"] = _case_like(str(prev.get("word", "")), "los") def normalize_subtitle_text(text: str, context: str = "") -> str: """ Normalize a subtitle line: - Applies known proper-noun corrections (Peñarol, Uruguay, player names…) - Removes transcription/control artifacts that look ugly when burned in - Drops standalone filler words only when they are not meaningful content """ text = str(text) text = re.sub(r"(?i)(?:\\n|/n)", " ", text) text = text.replace("\n", " ").replace("\r", " ") text = re.sub(r"\s+", " ", text).strip() if not text: return text for pattern, replacement in SUBTITLE_CORRECTIONS.items(): text = re.sub(pattern, replacement, text, flags=re.IGNORECASE) text = apply_contextual_subtitle_corrections(text, context) text = re.sub(r"\s+([,.;:!?])", r"\1", text) text = re.sub(r"([¿¡])\s+", r"\1", text) text = re.sub(r"\s{2,}", " ", text).strip() words = text.split() if words and all(_plain_subtitle_word(word) in SUBTITLE_FILLER_WORDS for word in words): return "" while len(words) > 1 and _plain_subtitle_word(words[0]) in SUBTITLE_FILLER_WORDS: words.pop(0) text = " ".join(words).strip() return text def subtitle_display_text(text: str, context: str = "") -> str: """Return final text as it should appear in burned social subtitles.""" return normalize_subtitle_text(text, context=context).upper() # --------------------------------------------------------------------------- # Helpers # --------------------------------------------------------------------------- def run(cmd: list[str], check: bool = True) -> subprocess.CompletedProcess: """Run a shell command, print it, and return the result.""" print(f" $ {' '.join(str(c) for c in cmd)}") result = subprocess.run(cmd, capture_output=True, text=True, check=False) if check and result.returncode != 0: print(f"[ERROR] Command failed:\n{result.stderr}", file=sys.stderr) sys.exit(1) return result def write_text_if_changed(path: Path, text: str) -> bool: """Write text only when content changed; returns whether the file changed.""" if path.exists() and path.read_text(encoding="utf-8") == text: return False path.write_text(text, encoding="utf-8") return True def ytdlp_hq_cmd() -> list[str]: """Return yt-dlp command prefix with local PO-token support when available.""" cmd = [str(YTDLP_BIN) if YTDLP_BIN.exists() else "yt-dlp"] bgutil_script = BGUTIL_SERVER_HOME / "build" / "generate_once.js" if NODE22_BIN.exists() and bgutil_script.exists(): cmd.extend([ "--js-runtimes", f"node:{NODE22_BIN}", # Disable Deno for the bgutil script provider: on this machine it # may spend minutes downloading deps and timeout before Node runs. "--js-runtimes", "deno:/nonexistent-deno", "--remote-components", "ejs:github", "--extractor-args", "youtube:player_client=mweb,web_safari,web,web_embedded,ios;formats=missing_pot", "--extractor-args", f"youtubepot-bgutilscript:server_home={BGUTIL_SERVER_HOME}", ]) return cmd def srt_time(seconds: float) -> str: """Float seconds → SRT timestamp format HH:MM:SS,mmm""" h = int(seconds // 3600) m = int((seconds % 3600) // 60) s = int(seconds % 60) ms = int((seconds % 1) * 1000) return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}" def safe_name(text: str, max_len: int = 50) -> str: """Convert arbitrary text to a safe filesystem name.""" cleaned = re.sub(r"[^\w\s-]", "", text, flags=re.UNICODE) return cleaned.strip().replace(" ", "_")[:max_len] def pyd_logo_path() -> Path | None: """Return the PyDTV logo asset when available.""" configured = os.environ.get("PYD_LOGO_PATH") path = Path(configured).expanduser() if configured else PYD_LOGO_PATH return path if path.exists() else None def add_pyd_logo_filter( parts: list[str], base_label: str, logo_input_index: int, output_label: str, *, vertical: bool = True, ) -> str: """Append ffmpeg filters that overlay the PyDTV logo on a finished frame.""" width = PYD_LOGO_VERTICAL_WIDTH if vertical else PYD_LOGO_HORIZONTAL_WIDTH margin_x = PYD_LOGO_VERTICAL_MARGIN_X if vertical else PYD_LOGO_HORIZONTAL_MARGIN_X margin_y = PYD_LOGO_VERTICAL_MARGIN_Y if vertical else PYD_LOGO_HORIZONTAL_MARGIN_Y logo_label = f"{output_label}_logo" parts.append(f"[{logo_input_index}:v]scale={width}:-1:flags=lanczos[{logo_label}]") parts.append( f"[{base_label}][{logo_label}]overlay={margin_x}:{margin_y}:format=auto[{output_label}]" ) return output_label def avoid_source_logo_crop(crop: dict, src_w: int, src_h: int) -> dict: """Move/trim crops so the broadcast PyDTV logo is outside the frame.""" out = dict(crop) x = int(out.get("x", 0)) y = int(out.get("y", 0)) w = int(out.get("w", src_w)) h = int(out.get("h", src_h)) if x > SOURCE_LOGO_RIGHT_X or y >= SOURCE_LOGO_CLEAR_Y: return out target_y = min(SOURCE_LOGO_CLEAR_Y, max(0, src_h - 1)) bottom_guard = max(0, int(src_h * SOURCE_LOGO_BOTTOM_GUARD_RATIO)) max_h = max(1, src_h - target_y - bottom_guard) if h > max_h: center_x = x + w / 2 h = max_h w = min(src_w, max(1, int(h * 9 / 16))) x = max(0, min(int(center_x - w / 2), src_w - w)) y = max(0, min(target_y, src_h - h - bottom_guard)) out.update({"x": x, "y": y, "w": w, "h": h}) return out def probe_video_dimensions(path: Path) -> tuple[int, int] | None: probe = subprocess.run([FFMPEG_BIN, "-i", str(path)], capture_output=True, text=True) dim_m = re.search(r"(\d{3,4})x(\d{3,4})", probe.stderr) if not dim_m: return None return int(dim_m.group(1)), int(dim_m.group(2)) def ffprobe_bin() -> str: candidate = Path(FFMPEG_BIN).with_name("ffprobe") return str(candidate) if candidate.exists() else "ffprobe" def feature_enabled(disable_env_name: str) -> bool: value = os.environ.get(disable_env_name, "").strip().lower() return value not in {"1", "true", "yes", "on"} def add_video_polish_filter(parts: list[str], base_label: str, output_label: str) -> str: if not feature_enabled("CLIP_DISABLE_VIDEO_POLISH"): return base_label parts.append(f"[{base_label}]{VIDEO_POLISH_FILTER}[{output_label}]") return output_label def has_audio_stream(path: Path) -> bool: result = subprocess.run( [ ffprobe_bin(), "-v", "error", "-select_streams", "a:0", "-show_entries", "stream=codec_type", "-of", "csv=p=0", str(path), ], capture_output=True, text=True, ) return result.returncode == 0 and "audio" in result.stdout def add_audio_polish_filter(parts: list[str], raw_clip: Path, output_label: str = "aout") -> str | None: if not feature_enabled("CLIP_DISABLE_AUDIO_POLISH") or not has_audio_stream(raw_clip): return None parts.append(f"[0:a]{AUDIO_POLISH_FILTER}[{output_label}]") return output_label def media_map_args(audio_label: str | None) -> list[str]: args = ["-map", "[vout]"] if audio_label: args.extend(["-map", f"[{audio_label}]"]) else: args.extend(["-map", "0:a?"]) return args # --------------------------------------------------------------------------- # Step 1 — Download latest video # --------------------------------------------------------------------------- def download_latest_video(channel_url: str, output_dir: Path) -> Path: """ Download the most recent completed livestream from a YouTube channel. Works with /streams URLs (e.g. https://www.youtube.com/@padreydecanocom/streams) as well as regular channel URLs. Skips any ongoing live broadcast. """ print("\n[1/6] Downloading latest completed livestream…") # Normalise: ensure we point at the /streams tab so yt-dlp lists past live # videos first. If the user already passed a /streams URL keep it as-is. if "/streams" not in channel_url: streams_url = channel_url.rstrip("/") + "/streams" else: streams_url = channel_url # Retrieve the ID of the most recent *completed* stream (was_live == True, # and not currently live). result = run([ *ytdlp_hq_cmd(), "--playlist-end", "3", # check first 3 in case one is live "--match-filter", "was_live & !is_live", "--print", "%(id)s\t%(title)s", streams_url, ]) lines = [l for l in result.stdout.strip().split("\n") if "\t" in l] if not lines: print("[ERROR] No completed livestreams found in the channel.", file=sys.stderr) print(" Tip: make sure the channel has past streams and is not currently live.", file=sys.stderr) sys.exit(1) video_id, title = lines[0].split("\t", 1) print(f" → Latest stream: [{video_id}] {title}") video_path = output_dir / f"{video_id}.mp4" if video_path.exists(): print(f" → Already downloaded, skipping.") return video_path run([ *ytdlp_hq_cmd(), "-f", YOUTUBE_HQ_FORMAT, "--merge-output-format", "mp4", "--concurrent-fragments", "8", "--retries", "infinite", "--fragment-retries", "infinite", "--retry-sleep", "fragment:exp=1:30", "--write-info-json", "-o", str(video_path), f"https://www.youtube.com/watch?v={video_id}", ]) return video_path # --------------------------------------------------------------------------- # Step 2 — Extract audio # --------------------------------------------------------------------------- def extract_audio(video_path: Path, output_dir: Path) -> Path: print("\n[2/6] Extracting audio…") audio_path = output_dir / f"{video_path.stem}.wav" if audio_path.exists(): print(f" → Already extracted, skipping.") return audio_path run([ FFMPEG_BIN, "-y", "-i", str(video_path), "-vn", "-acodec", "pcm_s16le", "-ar", "16000", "-ac", "1", str(audio_path), ]) return audio_path # --------------------------------------------------------------------------- # Step 3 — Transcribe with Whisper # --------------------------------------------------------------------------- def transcript_has_word_timestamps(transcript: dict) -> bool: """True when the cached transcript has usable per-word timing data.""" for seg in transcript.get("segments", []): for word in seg.get("words") or []: if "start" in word and "end" in word and str(word.get("word", "")).strip(): return True return False def transcribe_audio(audio_path: Path, output_dir: Path, model_size: str = "medium") -> dict: print(f"\n[3/6] Transcribing with Whisper ({model_size})…") transcript_path = output_dir / f"{audio_path.stem}_transcript.json" if transcript_path.exists(): with open(transcript_path, encoding="utf-8") as f: cached = json.load(f) if transcript_has_word_timestamps(cached): print(f" → Transcript found, loading from cache.") return cached backup_path = transcript_path.with_suffix(".no_word_timestamps.bak.json") print(" → Cached transcript has no word timestamps; regenerating for accurate subtitles.") if not backup_path.exists(): shutil.copy(transcript_path, backup_path) try: import whisper # type: ignore model = whisper.load_model(model_size) result = model.transcribe( str(audio_path), language="es", verbose=False, word_timestamps=True, initial_prompt=WHISPER_INITIAL_PROMPT, ) except ImportError: print(" openai-whisper not found as library, trying CLI…") run([ "whisper", str(audio_path), "--language", "es", "--model", model_size, "--word_timestamps", "True", "--initial_prompt", WHISPER_INITIAL_PROMPT, "--output_format", "json", "--output_dir", str(output_dir), ]) cli_out = output_dir / f"{audio_path.stem}.json" with open(cli_out, encoding="utf-8") as f: result = json.load(f) write_text_if_changed(transcript_path, json.dumps(result, ensure_ascii=False, indent=2)) total = len(result.get("segments", [])) print(f" → {total} segments transcribed, saved to {transcript_path.name}") return result # --------------------------------------------------------------------------- # Step 4 — Select best moments # --------------------------------------------------------------------------- def select_moments(transcript: dict, num_clips: int = 10, output_dir: Path = None) -> list[dict]: print(f"\n[4/6] Selecting {num_clips} best moments…") moments_path = output_dir / "moments.json" if output_dir else None if moments_path and moments_path.exists(): print(f" → Moments found, loading from cache.") with open(moments_path, encoding="utf-8") as f: return json.load(f) # Codex normally creates moments.json after reading the saved transcript. # Claude is still supported as an optional shortcut, but it is not required # for the user's workflow. if not os.environ.get("ANTHROPIC_API_KEY"): transcript_name = "VIDEO_ID_transcript.json" if output_dir: transcripts = sorted(output_dir.glob("*_transcript.json"), key=lambda p: p.stat().st_mtime, reverse=True) if transcripts: transcript_name = transcripts[0].name print(" → Todavía no existe moments.json.") print(f" → La transcripción quedó guardada en {transcript_name}.") print(" → Elegí los momentos, guardá moments.json y relanzá el mismo comando para continuar sin repetir descarga ni Whisper.") sys.exit(2) # Build a condensed transcript string (max ~6000 tokens for the prompt) segments = transcript.get("segments", []) lines = [f"[{s['start']:.1f}s–{s['end']:.1f}s] {s['text'].strip()}" for s in segments] transcript_text = "\n".join(lines) # If transcript is very long, sample evenly to avoid token overflow if len(transcript_text) > 40_000: step = len(lines) // 600 sampled = lines[::step] transcript_text = "\n".join(sampled) print(f" → Transcript too long, sampled {len(sampled)} lines for analysis.") client = anthropic.Anthropic() prompt = f"""Sos un experto en contenido viral para redes sociales, especializado en programas de fútbol uruguayo. Analizá esta transcripción de un livestream de fans de Peñarol (club de fútbol uruguayo) y seleccioná los {num_clips} momentos MÁS POTENTES para recortar como clips cortos. Buscá específicamente: - Debates acalorados entre panelistas con una postura clara - Reacciones fuertes (goles, noticias, jugadas polémicas, hinchas enojados) - Momentos graciosos, chicanas, memes o situaciones inesperadas - Análisis tácticos o técnicos con una conclusión potente - Frases memorables que puedan funcionar solas en Instagram/TikTok/X - Momentos de tensión, emoción pura o euforia - Predicciones u opiniones controversiales sobre jugadores/DT Score editorial para elegir: - Hook inmediato: la primera frase debe enganchar sin necesitar 2 minutos de contexto. - Desarrollo: tiene que pasar algo durante el clip, no solo una idea repetida. - Remate: debe cerrar en frase completa, risa, silencio o conclusión. - Publicabilidad: evitar tramos confusos, internos o demasiado largos sin payoff. - Variedad: no elegir 10 clips del mismo tema si hay otros momentos fuertes. TRANSCRIPCIÓN: {transcript_text} Respondé ÚNICAMENTE con JSON válido con esta estructura exacta (sin texto adicional): {{ "clips": [ {{ "rank": 1, "start": 123.4, "end": 200.0, "title": "Título corto y viral (máx 60 chars)", "reason": "Por qué este momento es potente para redes", "hook": "Primera frase/gancho para el clip" }} ] }} Reglas OBLIGATORIAS: - Cada clip debe durar idealmente entre 40 y 60 segundos (end - start) - Comenzá el clip 2-3 segundos ANTES del momento clave para dar contexto - Terminá en un momento de cierre natural (risa, silencio, afirmación) - Los clips NO pueden superponerse entre sí - Priorizá inicio con gancho fuerte (la primera frase debe enganchar) - Evitá comienzos con muletillas, saludos, contexto flojo o frases ya empezadas - Rankeá del 1 (más viral) al {num_clips} (décimo más viral) - Usá timestamps exactos de la transcripción """ message = client.messages.create( model="claude-opus-4-6", max_tokens=4096, messages=[{"role": "user", "content": prompt}], ) raw = message.content[0].text.strip() # Extract JSON robustly json_match = re.search(r"\{[\s\S]*\}", raw) if not json_match: print("[ERROR] Claude returned unexpected format:", raw[:200], file=sys.stderr) sys.exit(1) data = json.loads(json_match.group()) moments = data["clips"] if moments_path: with open(moments_path, "w", encoding="utf-8") as f: json.dump(moments, f, ensure_ascii=False, indent=2) print(f" → {len(moments)} moments saved to {moments_path.name}") return moments # --------------------------------------------------------------------------- # Step 5 — Cut raw clips # --------------------------------------------------------------------------- def cut_clip(video_path: Path, start: float, end: float, output_path: Path) -> None: """Cut a segment from the source video (re-encode to ensure clean keyframes).""" dur = end - start run([ FFMPEG_BIN, "-y", "-ss", str(start), "-i", str(video_path), "-t", str(dur), "-c:v", "libx264", "-preset", VIDEO_PRESET, "-crf", VIDEO_CRF, "-c:a", "aac", "-b:a", AUDIO_BITRATE, "-movflags", "+faststart", str(output_path), ]) def clip_meta_path(raw_path: Path) -> Path: return raw_path.with_suffix(".clip.json") def clip_cache_matches(raw_path: Path, source_path: Path, start: float, end: float) -> bool: if not raw_path.exists(): return False meta_path = clip_meta_path(raw_path) if not meta_path.exists(): return False try: meta = json.loads(meta_path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError): return False return ( meta.get("source") == source_path.name and abs(float(meta.get("start", -1)) - start) < 0.02 and abs(float(meta.get("end", -1)) - end) < 0.02 ) def write_clip_cache_meta(raw_path: Path, source_path: Path, start: float, end: float) -> None: meta = { "source": source_path.name, "start": round(start, 3), "end": round(end, 3), "duration": round(end - start, 3), } write_text_if_changed(clip_meta_path(raw_path), json.dumps(meta, ensure_ascii=False, indent=2)) # --------------------------------------------------------------------------- # Step 6 — Generate SRT and encode final clips # --------------------------------------------------------------------------- def generate_srt(segments: list[dict], clip_start: float, clip_end: float, srt_path: Path) -> None: """Write an SRT file with timestamps relative to the clip's start.""" entries = [] counter = 1 for seg in segments: s_start, s_end = seg["start"], seg["end"] if s_end <= clip_start or s_start >= clip_end: continue adj_start = max(0.0, s_start - clip_start) adj_end = min(clip_end - clip_start, s_end - clip_start) text = normalize_subtitle_text(seg["text"]) if not text: continue entries.append(f"{counter}\n{srt_time(adj_start)} --> {srt_time(adj_end)}\n{text}\n") counter += 1 with open(srt_path, "w", encoding="utf-8") as f: f.write("\n".join(entries)) def _ass_time(seconds: float) -> str: """Convert float seconds to ASS timestamp format H:MM:SS.cs""" h = int(seconds // 3600) m = int((seconds % 3600) // 60) s = seconds % 60 return f"{h}:{m:02d}:{s:05.2f}" def _ass_escape_text(text: str) -> str: """Escape user/transcript text so it cannot be parsed as ASS override tags.""" return text.replace("\\", "/").replace("{", "(").replace("}", ")") def _wrap_subtitle_chunk(words: list[str], max_line_chars: int = 22) -> str: """Return one or two balanced ASS lines for a short word chunk.""" if not words: return "" if len(" ".join(words)) <= max_line_chars or len(words) == 1: return " ".join(words) best_i = 1 best_score = float("inf") for i in range(1, len(words)): left = " ".join(words[:i]) right = " ".join(words[i:]) overflow = max(0, len(left) - max_line_chars) + max(0, len(right) - max_line_chars) balance = abs(len(left) - len(right)) score = overflow * 100 + balance if score < best_score: best_i = i best_score = score return " ".join(words[:best_i]) + r"\N" + " ".join(words[best_i:]) def _subtitle_chunks(text: str, max_words: int = 5, max_chars: int = 34) -> list[list[str]]: """Split a Whisper segment into short social-clip subtitle beats.""" words = text.split() chunks: list[list[str]] = [] current: list[str] = [] for word in words: candidate = [*current, word] if current and (len(candidate) > max_words or len(" ".join(candidate)) > max_chars): chunks.append(current) current = [word] else: current = candidate if current: chunks.append(current) return chunks def _subtitle_word_chunks(words: list[dict], max_words: int = 5, max_chars: int = 34) -> list[list[dict]]: """Split Whisper word-timestamp items into short social-clip subtitle beats.""" chunks: list[list[dict]] = [] current: list[dict] = [] for word in words: candidate = [*current, word] candidate_text = " ".join(str(item["word"]) for item in candidate) if current and (len(candidate) > max_words or len(candidate_text) > max_chars): chunks.append(current) current = [word] else: current = candidate if current: chunks.append(current) return chunks def generate_ass( segments: list[dict], clip_start: float, clip_end: float, ass_path: Path, play_res_x: int = 1080, play_res_y: int = 1920, font_size: int = 72, margin_v: int = 120, ) -> bool: """Write a styled ASS subtitle file with timestamps relative to clip start. Using ASS instead of SRT+force_style avoids ffmpeg 8.x filter-complex escaping issues with colons and special characters in the style string. """ header = ( "[Script Info]\n" "ScriptType: v4.00+\n" "Collisions: Normal\n" f"PlayResX: {play_res_x}\n" f"PlayResY: {play_res_y}\n" "Timer: 100.0000\n\n" "[V4+ Styles]\n" "Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, " "OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, " "ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, " "Alignment, MarginL, MarginR, MarginV, Encoding\n" f"Style: Default,Arial Black,{font_size}," "&H00FFFFFF,&H000000FF,&H00000000,&HA0000000," f"-1,0,0,0,100,100,0,0,1,8,3,2,70,70,{margin_v},1\n\n" "[Events]\n" "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n" ) lines = [header] for seg in segments: s_start, s_end = seg["start"], seg["end"] if s_end <= clip_start or s_start >= clip_end: continue adj_start = max(0.0, s_start - clip_start) adj_end = min(clip_end - clip_start, s_end - clip_start) segment_text = str(seg.get("text", "")) word_items = [] for item in seg.get("words") or []: word = subtitle_display_text(str(item.get("word", "")).strip(), context=segment_text) if not word: continue w_start = float(item.get("start", s_start)) w_end = float(item.get("end", s_end)) if w_end <= clip_start or w_start >= clip_end: continue word_items.append({ "word": word, "start": max(0.0, w_start - clip_start), "end": min(clip_end - clip_start, w_end - clip_start), }) if word_items: normalize_subtitle_word_sequence(word_items) for chunk in _subtitle_word_chunks(word_items): chunk_start = max(0.0, min(item["start"] for item in chunk)) chunk_end = max(item["end"] for item in chunk) if chunk_end <= chunk_start: continue escaped_chunk = [_ass_escape_text(item["word"]) for item in chunk] chunk_text = _wrap_subtitle_chunk(escaped_chunk) lines.append( f"Dialogue: 0,{_ass_time(chunk_start)},{_ass_time(chunk_end)}," f"Default,,0,0,0,,{{\\fad(60,60)\\blur0.4}}{chunk_text}" ) continue text = subtitle_display_text(segment_text) if not text: continue chunks = _subtitle_chunks(text) total_words = sum(len(chunk) for chunk in chunks) if not chunks or total_words == 0: continue elapsed_words = 0 duration = max(0.01, adj_end - adj_start) for chunk in chunks: chunk_start = adj_start + duration * elapsed_words / total_words elapsed_words += len(chunk) chunk_end = adj_start + duration * elapsed_words / total_words escaped_chunk = [_ass_escape_text(word) for word in chunk] chunk_text = _wrap_subtitle_chunk(escaped_chunk) lines.append( f"Dialogue: 0,{_ass_time(chunk_start)},{_ass_time(chunk_end)}," f"Default,,0,0,0,,{{\\fad(60,60)\\blur0.4}}{chunk_text}" ) return write_text_if_changed(ass_path, "\n".join(lines)) def _looks_like_sentence_end(text: str) -> bool: text = normalize_subtitle_text(text) if not text: return False return bool(re.search(r"[.!?…][\"')\]]*$", text)) def snap_end_to_sentence(start: float, end: float, segments: list[dict], tolerance: float = 6.0) -> float: """ Snap clip end to a natural Whisper boundary near the selected end. Prefer punctuation or a real pause, and allow a tiny tail so the clip does not feel chopped off. Keep the total duration inside the social clip max. """ if not segments: return end upper = min(end + tolerance, start + ABSOLUTE_MAX_CLIP_DURATION) min_end = start + 24.0 candidates: list[tuple[float, float, float | None]] = [] boundaries: list[float] = [] for idx, seg in enumerate(segments): s_start = float(seg.get("start", 0.0)) s_end = float(seg.get("end", 0.0)) if s_start < start - 0.25 or s_end < min_end or s_end > upper: continue next_start = None if idx + 1 < len(segments): next_start = float(segments[idx + 1].get("start", s_end)) gap_after = max(0.0, next_start - s_end) if next_start is not None else 0.0 punctuation = _looks_like_sentence_end(str(seg.get("text", ""))) natural_pause = gap_after >= 0.42 boundaries.append(s_end) if not punctuation and not natural_pause: continue # Prefer a natural boundary close to the selected end. If two are close, # favor extending over cutting early, and punctuation over mere silence. score = abs(s_end - end) if s_end < end: score += 0.45 if not punctuation: score += 0.25 candidates.append((score, s_end, next_start)) if candidates: _, snapped, next_start = min(candidates, key=lambda item: item[0]) if next_start is None: pad = END_PAD_SECONDS else: pad = min(END_PAD_SECONDS, max(0.0, next_start - snapped)) return min(snapped + pad, start + ABSOLUTE_MAX_CLIP_DURATION) if boundaries: return max(boundaries) return min(end, start + ABSOLUTE_MAX_CLIP_DURATION) def snap_start_to_segment(start: float, segments: list[dict], tolerance: float = 3.0) -> float: """ If the selected moment starts inside a Whisper segment, move the clip start back to that segment boundary. Without word-level timestamps, burning the full segment text over only the tail of the audio makes subtitles look early. """ for seg in segments: s_start = float(seg["start"]) s_end = float(seg["end"]) if s_start < start < s_end and start - s_start <= tolerance: return s_start return start def detect_speaker_zoom(raw_clip: Path, n_samples: int = 6) -> dict | None: """ Detect the PRIMARY speaker face and return crop params for smart 9:16 zoom. Strategy: 1. Sample n_samples frames evenly across the clip. 2. Detect faces with Haar cascade; discard any face whose centre is below 55 % of the frame height — those are false positives (jersey logos, microphone stands, sponsor boards, etc.). 3. Among valid faces, pick the LARGEST one (highest pixel area). The largest face is the person sitting closest to camera, which is virtually always the active speaker in a podcast/talk-show setting. 4. Accumulate the position of the chosen face across frames and use the median centre so that small per-frame jitter doesn't shift the crop. 5. If no valid face is found in any frame, fall back to a centre crop of the upper portion of the frame (always better than a blurred pillarbox). Returns dict {x, y, w, h, faces, src_w, src_h} in source video coords, or None only when cv2 is not importable. """ try: import cv2 except ImportError: return None # --- Get clip duration and dimensions --- probe = subprocess.run([FFMPEG_BIN, "-i", str(raw_clip)], capture_output=True, text=True) dim_m = re.search(r"(\d{3,4})x(\d{3,4})", probe.stderr) dur_m = re.search(r"Duration:\s*(\d+):(\d+):([\d.]+)", probe.stderr) if not dim_m or not dur_m: return None src_w, src_h = int(dim_m.group(1)), int(dim_m.group(2)) duration = int(dur_m.group(1)) * 3600 + int(dur_m.group(2)) * 60 + float(dur_m.group(3)) cascade_path = cv2.data.haarcascades + "haarcascade_frontalface_default.xml" face_cascade = cv2.CascadeClassifier(cascade_path) eye_cascades = [ cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_eye_tree_eyeglasses.xml"), cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_eye.xml"), ] # Sample frames at evenly spaced timestamps (skip first/last 5 % to avoid fades) margin = max(2.0, duration * 0.05) sample_times = [ margin + (duration - 2 * margin) * i / (n_samples - 1) for i in range(n_samples) ] # Valid-face y-threshold: faces whose centre is below this are false positives # (logos, jersey numbers, desk objects) and must be ignored. valid_y_max = src_h * 0.55 # Per-frame: record the (cx, cy, area) of the largest valid face found best_cx_list: list[int] = [] best_cy_list: list[int] = [] best_area: int = 0 panel_hits = 0 for t in sample_times: with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as f: frame_path = f.name try: subprocess.run( [FFMPEG_BIN, "-ss", str(t), "-i", str(raw_clip), "-frames:v", "1", "-q:v", "2", "-y", frame_path], capture_output=True, check=True, ) img = cv2.imread(frame_path) except Exception: continue finally: with contextlib.suppress(FileNotFoundError): os.unlink(frame_path) if img is None: continue if _is_split_panel_frame(img, src_w): panel_hits += 1 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=4, minSize=(40, 40)) if not len(faces): continue # Keep only real-looking faces whose centre is in the upper 55 % of the # frame. Eye validation is important: studio signs, score tables and # sponsor graphics routinely trigger Haar "faces" and caused ultra-tight # crops of posters instead of journalists. valid = [] weak = [] for (fx, fy, fw, fh) in faces: if (fy + fh / 2) >= valid_y_max: continue if fw * fh < 8000: continue upper = gray[fy:fy + int(fh * 0.62), fx:fx + fw] eye_count = 0 if upper.size: for eye_cascade in eye_cascades: if eye_cascade.empty(): continue eyes = eye_cascade.detectMultiScale( upper, scaleFactor=1.05, minNeighbors=3, minSize=(max(14, fw // 10), max(10, fh // 14)), ) eye_count = max(eye_count, len(eyes)) if eye_count >= 2: valid.append((fx, fy, fw, fh)) elif eye_count >= 1: weak.append((fx, fy, fw, fh)) if not valid: valid = weak if not valid: continue # Pick the largest valid face in this frame (= closest / most prominent) fx, fy, fw, fh = max(valid, key=lambda f: f[2] * f[3]) best_cx_list.append(fx + fw // 2) best_cy_list.append(fy + fh // 2) best_area = max(best_area, fw * fh) if not best_cx_list: if panel_hits >= max(2, n_samples // 2): crop = _panel_crop_for_zone(src_w, src_h, 1) return {**crop, "faces": 0, "src_w": src_w, "src_h": src_h} # No valid face found in any frame — use a centre crop of the upper body. # A tight centre crop is always better than a blurred pillarbox. crop_h = _clean_closeup_height(src_h) crop_w = int(crop_h * 9 / 16) if crop_w > src_w: crop_w = src_w crop_h = int(crop_w * 16 / 9) crop_x = (src_w - crop_w) // 2 crop_y = _vertical_closeup_y(src_h, crop_h) crop = avoid_source_logo_crop( {"x": crop_x, "y": crop_y, "w": crop_w, "h": crop_h}, src_w, src_h, ) return {**crop, "faces": 0, "src_w": src_w, "src_h": src_h} # Median centre across frames (robust against jitter/occasional missed detections) best_cx_list.sort() best_cy_list.sort() face_center_x = best_cx_list[len(best_cx_list) // 2] face_center_y = best_cy_list[len(best_cy_list) // 2] face_side = int(best_area ** 0.5) # approximate face size (square root of area) if panel_hits >= max(2, n_samples // 2): crop = _panel_crop_for_zone(src_w, src_h, _panel_zone_for_x(src_w, face_center_x)) return {**crop, "faces": len(best_cx_list), "src_w": src_w, "src_h": src_h} # 9:16 crop: face + generous head/upper-body padding crop_h = min(int(face_side * 4.5), _clean_closeup_height(src_h)) crop_w = int(crop_h * 9 / 16) if crop_w > src_w: crop_w = src_w crop_h = int(crop_w * 16 / 9) # Anchor crop so face is in the upper-third of the vertical frame crop_x = max(0, min(face_center_x - crop_w // 2, src_w - crop_w)) crop_y = max(0, min(face_center_y - crop_h // 4, src_h - crop_h)) crop_y = min(crop_y, _vertical_closeup_y(src_h, crop_h)) crop = avoid_source_logo_crop( {"x": crop_x, "y": crop_y, "w": crop_w, "h": crop_h}, src_w, src_h, ) return {**crop, "faces": len(best_cx_list), "src_w": src_w, "src_h": src_h} def encode_vertical(raw_clip: Path, ass_path: Path, output_path: Path) -> None: """ Produce 1080×1920 (9:16) clip with blurred background. Layout: blurred full-bleed background + centred original video + burned subtitles. Uses a pre-generated ASS file (style embedded) to avoid ffmpeg filter escaping issues. """ with tempfile.TemporaryDirectory() as tmp: tmp_ass = Path(tmp) / "sub.ass" shutil.copy(ass_path, tmp_ass) # Escape only backslashes and colons for ffmpeg filter path esc = str(tmp_ass).replace("\\", "/").replace(":", r"\:") logo_path = pyd_logo_path() logo_input = ["-i", str(logo_path)] if logo_path else [] parts = [ "[0:v]scale=1080:1920:force_original_aspect_ratio=increase:flags=lanczos," "crop=1080:1920,boxblur=25:5[bg]", "[0:v]scale=1080:-2:flags=lanczos[fg]", "[bg][fg]overlay=(W-w)/2:(H-h)/2[base]", ] video_label = "base" video_label = add_video_polish_filter(parts, video_label, "polished") if logo_path: video_label = add_pyd_logo_filter(parts, video_label, 1, "branded", vertical=True) parts.append(f"[{video_label}]subtitles={esc}[vout]") audio_label = add_audio_polish_filter(parts, raw_clip) filter_complex = ";".join(parts) map_args = media_map_args(audio_label) run([ FFMPEG_BIN, "-y", "-i", str(raw_clip), *logo_input, "-filter_complex", filter_complex, *map_args, "-c:v", "libx264", "-preset", VIDEO_PRESET, "-crf", VIDEO_CRF, "-c:a", "aac", "-b:a", AUDIO_BITRATE, "-movflags", "+faststart", str(output_path), ]) def encode_vertical_interview_layout(raw_clip: Path, ass_path: Path, output_path: Path) -> None: """ Produce a vertical interview composition that keeps the guest large while preserving the three small journalist panels from the source layout. """ dims = probe_video_dimensions(raw_clip) if not dims: print(" → No pude medir el layout de entrevista; uso encuadre estándar") encode_vertical(raw_clip, ass_path, output_path) return src_w, src_h = dims remote_guest = is_remote_guest_interview_clip(raw_clip) if remote_guest: guest_x = max(0, int(src_w * 0.15)) guest_y = max(0, int(src_h * 0.088)) guest_w = min(src_w - guest_x, int(src_w * 0.70)) guest_h = min(src_h - guest_y, int(src_h * 0.60)) strip_x = max(0, int(src_w * 0.2375)) strip_y = max(0, int(src_h * 0.676)) strip_w = min(src_w - strip_x, int(src_w * 0.55)) strip_h = min(src_h - strip_y, int(src_h * 0.296)) print( " → Layout entrevista remota: invitado limpio + paneles completos " f"(guest {guest_w}×{guest_h}@{guest_x},{guest_y}; " f"strip {strip_w}×{strip_h}@{strip_x},{strip_y})" ) with tempfile.TemporaryDirectory() as tmp: tmp_ass = Path(tmp) / "sub.ass" shutil.copy(ass_path, tmp_ass) esc = str(tmp_ass).replace("\\", "/").replace(":", r"\:") logo_path = pyd_logo_path() logo_input = ["-i", str(logo_path)] if logo_path else [] parts = [ "[0:v]scale=1080:1920:force_original_aspect_ratio=increase:flags=lanczos," "crop=1080:1920,boxblur=30:5,eq=brightness=-0.08:saturation=0.90[bg]", f"[0:v]crop={guest_w}:{guest_h}:{guest_x}:{guest_y}," "scale=1080:960:force_original_aspect_ratio=increase:flags=lanczos," "crop=1080:960[guest]", f"[0:v]crop={strip_w}:{strip_h}:{strip_x}:{strip_y}," "scale=1018:-2:flags=lanczos," "pad=iw+12:ih+12:6:6:color=0xE5C01D[strip]", "[bg][guest]overlay=0:54[stage_guest]", "[stage_guest][strip]overlay=(W-w)/2:1168[base]", ] video_label = "base" video_label = add_video_polish_filter(parts, video_label, "polished") if logo_path: video_label = add_pyd_logo_filter(parts, video_label, 1, "branded", vertical=True) parts.append(f"[{video_label}]subtitles={esc}[vout]") audio_label = add_audio_polish_filter(parts, raw_clip) filter_complex = ";".join(parts) map_args = media_map_args(audio_label) run([ FFMPEG_BIN, "-y", "-i", str(raw_clip), *logo_input, "-filter_complex", filter_complex, *map_args, "-c:v", "libx264", "-preset", VIDEO_PRESET, "-crf", VIDEO_CRF, "-c:a", "aac", "-b:a", AUDIO_BITRATE, "-movflags", "+faststart", str(output_path), ]) return guest_x = max(0, int(src_w * 0.05)) guest_y = max(0, int(src_h * 0.05)) guest_w = min(src_w - guest_x, int(src_w * 0.78)) guest_h = min(src_h - guest_y, int(src_h * 0.51)) strip_x = max(0, int(src_w * 0.10)) strip_y = max(0, int(src_h * 0.56)) strip_w = min(src_w - strip_x, int(src_w * 0.76)) strip_h = min(src_h - strip_y, int(src_h * 0.36)) print( " → Layout entrevista: invitado grande + tira completa de periodistas " f"(guest {guest_w}×{guest_h}@{guest_x},{guest_y}; strip {strip_w}×{strip_h}@{strip_x},{strip_y})" ) with tempfile.TemporaryDirectory() as tmp: tmp_ass = Path(tmp) / "sub.ass" shutil.copy(ass_path, tmp_ass) esc = str(tmp_ass).replace("\\", "/").replace(":", r"\:") logo_path = pyd_logo_path() logo_input = ["-i", str(logo_path)] if logo_path else [] parts = [ "[0:v]scale=1080:1920:force_original_aspect_ratio=increase:flags=lanczos," "crop=1080:1920,boxblur=30:5,eq=brightness=-0.08:saturation=0.90[bg]", f"[0:v]crop={guest_w}:{guest_h}:{guest_x}:{guest_y}," "scale=1080:930:force_original_aspect_ratio=increase:flags=lanczos," "crop=1080:930[guest]", f"[0:v]crop={strip_w}:{strip_h}:{strip_x}:{strip_y}," "scale=1018:-2:flags=lanczos," "pad=iw+12:ih+12:6:6:color=0xE5C01D[strip]", "[bg][guest]overlay=0:126[stage_guest]", "[stage_guest][strip]overlay=(W-w)/2:1088[base]", ] video_label = "base" video_label = add_video_polish_filter(parts, video_label, "polished") if logo_path: video_label = add_pyd_logo_filter(parts, video_label, 1, "branded", vertical=True) parts.append(f"[{video_label}]subtitles={esc}[vout]") audio_label = add_audio_polish_filter(parts, raw_clip) filter_complex = ";".join(parts) map_args = media_map_args(audio_label) run([ FFMPEG_BIN, "-y", "-i", str(raw_clip), *logo_input, "-filter_complex", filter_complex, *map_args, "-c:v", "libx264", "-preset", VIDEO_PRESET, "-crf", VIDEO_CRF, "-c:a", "aac", "-b:a", AUDIO_BITRATE, "-movflags", "+faststart", str(output_path), ]) def encode_vertical_zoom(raw_clip: Path, ass_path: Path, output_path: Path) -> None: """ Produce 1080×1920 (9:16) clip with smart zoom to speaker face area. Detects faces with OpenCV Haar cascade and crops/zooms to them. Falls back to standard blurred-background encoding if no faces found. """ crop = detect_speaker_zoom(raw_clip) if crop is None: # detect_speaker_zoom now always returns a crop; this branch is kept as a # safety net in case cv2 import fails entirely. print(" → cv2 no disponible, usando encuadre estándar (blur)") encode_vertical(raw_clip, ass_path, output_path) return if crop["faces"] == 0: print(f" → Sin caras detectadas — center crop {crop['w']}×{crop['h']} " f"→ 1080×1920") else: print(f" → {crop['faces']} cara(s) detectada(s) — zoom {crop['src_w']}×{crop['src_h']} " f"→ crop {crop['w']}×{crop['h']} → 1080×1920") with tempfile.TemporaryDirectory() as tmp: tmp_ass = Path(tmp) / "sub.ass" shutil.copy(ass_path, tmp_ass) esc = str(tmp_ass).replace("\\", "/").replace(":", r"\:") logo_path = pyd_logo_path() logo_input = ["-i", str(logo_path)] if logo_path else [] parts = [ f"[0:v]crop={crop['w']}:{crop['h']}:{crop['x']}:{crop['y']}," "scale=1080:1920:force_original_aspect_ratio=increase:flags=lanczos," "crop=1080:1920[base]" ] video_label = "base" video_label = add_video_polish_filter(parts, video_label, "polished") if logo_path: video_label = add_pyd_logo_filter(parts, video_label, 1, "branded", vertical=True) parts.append(f"[{video_label}]subtitles={esc}[vout]") audio_label = add_audio_polish_filter(parts, raw_clip) filter_complex = ";".join(parts) map_args = media_map_args(audio_label) run([ FFMPEG_BIN, "-y", "-i", str(raw_clip), *logo_input, "-filter_complex", filter_complex, *map_args, "-c:v", "libx264", "-preset", VIDEO_PRESET, "-crf", VIDEO_CRF, "-c:a", "aac", "-b:a", AUDIO_BITRATE, "-movflags", "+faststart", str(output_path), ]) def _vertical_top_guard_y(src_h: int, crop_h: int) -> int: """Small y-offset to remove the source's top broadcast border from crops.""" return min(int(src_h * VERTICAL_TOP_GUARD_RATIO), max(0, src_h - crop_h)) def _clean_closeup_height(src_h: int) -> int: """Crop height that leaves the source's top and bottom layout borders out.""" guard = int(src_h * VERTICAL_TOP_GUARD_RATIO) return max(1, src_h - (guard * 2)) def _vertical_closeup_y(src_h: int, crop_h: int) -> int: """Y anchor for single-camera crops; keep layout borders out.""" return _vertical_top_guard_y(src_h, crop_h) def _panel_zone_centers(src_w: int, panel_count: int) -> list[int]: zone_w = src_w / max(1, panel_count) return [int(zone_w * (idx + 0.5)) for idx in range(panel_count)] def _panel_zone_for_x_count(src_w: int, x: int, panel_count: int) -> int: """Map a source x coordinate to a fixed horizontal panel index.""" zone_w = src_w / max(1, panel_count) return max(0, min(panel_count - 1, int(x // max(1.0, zone_w)))) def _panel_crop_for_zone_count(src_w: int, src_h: int, zone_idx: int, panel_count: int) -> dict: """Return the clean fixed 9:16 crop for one journalist in an N-panel layout.""" if panel_count == 4: return _four_panel_crop_for_zone(src_w, src_h, zone_idx) crop_h = int(src_h * PANEL_CROP_HEIGHT_RATIO) crop_w = int(crop_h * 9 / 16) if crop_w > src_w: crop_w = src_w crop_h = int(crop_w * 16 / 9) panel_count = max(1, panel_count) zone_idx = max(0, min(zone_idx, panel_count - 1)) zone_w = src_w / panel_count cx = int(zone_w * (zone_idx + 0.5)) # Preserve the older right-panel bias for the 3-panel layout: that journalist # often leans toward the centre mic, and anchoring at the panel edge keeps the # face inside the vertical crop. if panel_count == 3 and zone_idx == 2: x = int(2 * zone_w) else: x = max(0, min(cx - crop_w // 2, src_w - crop_w)) return avoid_source_logo_crop( {"x": x, "y": _vertical_top_guard_y(src_h, crop_h), "w": crop_w, "h": crop_h}, src_w, src_h, ) def _four_panel_crop_for_zone( src_w: int, src_h: int, zone_idx: int, face_box: tuple[int, int, int, int] | None = None, ) -> dict: """Return a tight 9:16 crop that stays inside one panel of the 4-up layout.""" panel_count = 4 zone_w = src_w / panel_count zone_idx = max(0, min(zone_idx, panel_count - 1)) # Four-up panels are narrower than the usual three-person layout. A crop # based on the old panel height is wider than one panel and shows separators. inner_left, inner_right = _four_panel_inner_bounds(src_w, zone_idx) inner_w = max(1, inner_right - inner_left) crop_w = min(inner_w, max(1, int(zone_w * 0.88))) crop_h = int(round(crop_w * 16 / 9)) if crop_h > src_h: crop_h = src_h crop_w = min(inner_w, max(1, int(crop_h * 9 / 16))) if face_box: face_cx, face_y, _face_w, face_h = face_box desired_x = int(round(face_cx - crop_w * 0.50)) desired_y = int(round(face_y - crop_h * 0.18)) else: desired_x = int(round(zone_w * (zone_idx + 0.5) - crop_w / 2)) desired_y = int(src_h * 0.11) max_x = inner_right - crop_w x = max(inner_left, min(desired_x, max_x)) bottom_guard = max(0, int(src_h * SOURCE_LOGO_BOTTOM_GUARD_RATIO)) min_y = max(_vertical_top_guard_y(src_h, crop_h), int(src_h * 0.10)) max_y = max(0, src_h - crop_h - bottom_guard) y = max(0, min(max(desired_y, min_y), max_y)) return avoid_source_logo_crop({"x": x, "y": y, "w": crop_w, "h": crop_h}, src_w, src_h) def _four_panel_inner_bounds(src_w: int, zone_idx: int) -> tuple[int, int]: """Return the safe horizontal bounds inside one 4-up panel separator.""" panel_count = 4 zone_w = src_w / panel_count zone_idx = max(0, min(zone_idx, panel_count - 1)) separator_margin = max(18, int(zone_w * 0.04)) inner_left = int(round(zone_idx * zone_w + (separator_margin if zone_idx > 0 else 0))) inner_right = int(round((zone_idx + 1) * zone_w - (separator_margin if zone_idx < panel_count - 1 else 0))) inner_left = max(0, min(src_w - 1, inner_left)) inner_right = max(inner_left + 1, min(src_w, inner_right)) return inner_left, inner_right def _panel_crop_for_zone(src_w: int, src_h: int, zone_idx: int) -> dict: """Return the clean fixed 9:16 crop for one journalist in the 3-panel layout.""" return _panel_crop_for_zone_count(src_w, src_h, zone_idx, 3) def sanitize_dynamic_crop(seg: dict, src_w: int, src_h: int) -> dict: """Repair saved crop plans that are no longer clean for the current layout.""" out = dict(seg) if out.get("layout") == "panel4": zone = _panel_zone_for_x_count(src_w, int(out["x"]) + int(out["w"]) // 2, 4) inner_left, inner_right = _four_panel_inner_bounds(src_w, zone) x = int(out.get("x", 0)) w = int(out.get("w", 0)) if w > 0 and x >= inner_left - 2 and x + w <= inner_right + 2: out.update(avoid_source_logo_crop(out, src_w, src_h)) else: clean = _panel_crop_for_zone_count(src_w, src_h, zone, 4) out.update(clean) return out out.update(avoid_source_logo_crop(out, src_w, src_h)) return out def _two_panel_crop_for_zone(src_w: int, src_h: int, zone_idx: int) -> dict: """Return a clean 9:16 crop for one journalist in a 2-panel layout.""" crop_h = _clean_closeup_height(src_h) crop_w = int(crop_h * 9 / 16) if crop_w > src_w: crop_w = src_w crop_h = int(crop_w * 16 / 9) half_w = src_w // 2 zone_idx = max(0, min(zone_idx, 1)) cx = half_w // 2 + half_w * zone_idx if zone_idx == 1: # The right-panel speaker often leans toward the centre seam, but their # face can also sit far right; bias slightly right to avoid half-face crops. cx += int(half_w * 0.08) x = max(0, min(cx - crop_w // 2, src_w - crop_w)) return avoid_source_logo_crop( {"x": x, "y": _vertical_closeup_y(src_h, crop_h), "w": crop_w, "h": crop_h}, src_w, src_h, ) def _panel_zone_for_x(src_w: int, x: int) -> int: """Map a source x coordinate to left/centre/right panel index.""" return _panel_zone_for_x_count(src_w, x, 3) def _two_panel_zone_for_x(src_w: int, x: int) -> int: """Map a source x coordinate to left/right panel index.""" return 0 if x < src_w / 2 else 1 def _is_split_panel_frame(img, src_w: int) -> bool: """ Detect the three-panel broadcast layout by its internal yellow separators. Active-speaker tracking is reliable only in this layout. Close-up camera shots reuse similar backgrounds and can fool Haar face detection with hands, logos, or wall patterns; the yellow dividers are a much stronger signal that fixed left/centre/right crops are safe. """ return _is_fixed_panel_frame(img, src_w, 3) def _yellow_separator_ratio(img, src_w: int, x: int, half_width: int = 12) -> float: import cv2 stripe = img[:, max(0, x - half_width): min(src_w, x + half_width + 1)] if stripe.size == 0: return 0.0 b, g, r = cv2.split(stripe) yellow = ( (r > 130) & (g > 110) & (b < 90) & ((r.astype("int16") - b.astype("int16")) > 60) & ((g.astype("int16") - b.astype("int16")) > 40) ) return float(yellow.mean()) def _is_fixed_panel_frame(img, src_w: int, panel_count: int) -> bool: """Detect a fixed split-panel frame by its internal yellow separators.""" if panel_count <= 1: return False separators = [round(src_w * i / panel_count) for i in range(1, panel_count)] ratios = [_yellow_separator_ratio(img, src_w, x, half_width=14) for x in separators] threshold = 0.08 if panel_count == 2 else 0.12 required = len(separators) return sum(ratio > threshold for ratio in ratios) >= required def _is_four_panel_frame(img, src_w: int) -> bool: """Detect the four-person interview layout before the central 2-panel check.""" return _is_fixed_panel_frame(img, src_w, 4) def _is_legacy_split_panel_frame(img, src_w: int) -> bool: import cv2 stripes_ok = 0 for x in (src_w // 3, 2 * src_w // 3): stripe = img[:, max(0, x - 10): min(src_w, x + 11)] if stripe.size == 0: continue b, g, r = cv2.split(stripe) yellow = ( (r > 130) & (g > 110) & (b < 85) & ((r.astype("int16") - b.astype("int16")) > 65) & ((g.astype("int16") - b.astype("int16")) > 45) ) if float(yellow.mean()) > 0.15: stripes_ok += 1 return stripes_ok >= 2 def _is_two_panel_frame(img, src_w: int) -> bool: """Detect the two-speaker broadcast layout by its central yellow divider.""" return _is_fixed_panel_frame(img, src_w, 2) def _is_bottom_strip_layout_frame(img, src_w: int, src_h: int) -> bool: """Detect layouts with a large main area and three small panels at the bottom.""" try: import cv2 except ImportError: return False lower = img[int(src_h * 0.55): int(src_h * 0.94), :] if lower.size == 0: return False b, g, r = cv2.split(lower) yellow = ( (r > 130) & (g > 105) & (b < 100) & ((r.astype("int16") - b.astype("int16")) > 45) & ((g.astype("int16") - b.astype("int16")) > 30) ) lower_yellow_ratio = float(yellow.mean()) upper = img[int(src_h * 0.04): int(src_h * 0.48), :] if upper.size == 0: return False ub, ug, ur = cv2.split(upper) upper_yellow = ( (ur > 130) & (ug > 105) & (ub < 100) & ((ur.astype("int16") - ub.astype("int16")) > 45) & ((ug.astype("int16") - ub.astype("int16")) > 30) ) upper_yellow_ratio = float(upper_yellow.mean()) # The lower strip is visually dominated by yellow panel frames. Equal split # studio layouts have yellow dividers through the upper area too; those # should stay in the active-speaker path instead of this composition. return lower_yellow_ratio > 0.075 and upper_yellow_ratio < 0.075 def _is_guest_interview_frame(img, src_w: int, src_h: int) -> bool: """Backward-compatible alias for the broader bottom-strip layout detector.""" return _is_bottom_strip_layout_frame(img, src_w, src_h) def _is_remote_guest_interview_frame(img, src_w: int, src_h: int) -> bool: """Detect the subset with a bright remote guest window above the panel strip.""" try: import cv2 except ImportError: return False if not _is_bottom_strip_layout_frame(img, src_w, src_h): return False top = img[int(src_h * 0.03): int(src_h * 0.55), int(src_w * 0.04): int(src_w * 0.86)] if top.size == 0: return False top_brightness = float((cv2.cvtColor(top, cv2.COLOR_BGR2GRAY) > 125).mean()) return top_brightness > 0.55 def is_guest_interview_clip(raw_clip: Path) -> bool: """Return true when the clip should preserve the full interview panel strip.""" try: import cv2 except ImportError: return False cap = cv2.VideoCapture(str(raw_clip)) if not cap.isOpened(): return False fps = cap.get(cv2.CAP_PROP_FPS) or 60 frame_count = cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0 if fps <= 0 or frame_count <= 0: cap.release() return False duration = frame_count / fps sample_times = [duration * p for p in (0.08, 0.25, 0.50, 0.75, 0.92)] hits = 0 total = 0 for sample_t in sample_times: cap.set(cv2.CAP_PROP_POS_MSEC, max(0.0, sample_t) * 1000) ok, frame = cap.read() if not ok: continue src_h, src_w = frame.shape[:2] total += 1 if _is_guest_interview_frame(frame, src_w, src_h): hits += 1 cap.release() return total >= 3 and hits >= max(3, int(total * 0.6)) def is_remote_guest_interview_clip(raw_clip: Path) -> bool: """Return true for remote guest layouts that should stay as one full block.""" try: import cv2 except ImportError: return False cap = cv2.VideoCapture(str(raw_clip)) if not cap.isOpened(): return False fps = cap.get(cv2.CAP_PROP_FPS) or 60 frame_count = cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0 if fps <= 0 or frame_count <= 0: cap.release() return False duration = frame_count / fps sample_times = [duration * p for p in (0.08, 0.25, 0.50, 0.75, 0.92)] hits = 0 total = 0 for sample_t in sample_times: cap.set(cv2.CAP_PROP_POS_MSEC, max(0.0, sample_t) * 1000) ok, frame = cap.read() if not ok: continue src_h, src_w = frame.shape[:2] total += 1 if _is_remote_guest_interview_frame(frame, src_w, src_h): hits += 1 cap.release() return total >= 3 and hits >= max(3, int(total * 0.6)) def _safe_closeup_crop( frame_files: list[Path], frame_indices: list[int], face_cascade, src_w: int, src_h: int, crop_w: int, crop_h: int, ) -> dict: """ Crop a non-split-screen camera shot. Prefer a detected face centre, but fall back to centre-crop because a close-up presenter is usually centred even when profile/microphone occlusion makes Haar miss the face. """ try: import cv2 import numpy as np except ImportError: cx_values = [] else: cx_values = [] for idx in frame_indices: if idx < 0 or idx >= len(frame_files): continue img = cv2.imread(str(frame_files[idx])) if img is None: continue gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale( gray, scaleFactor=1.1, minNeighbors=5, minSize=(max(80, src_w // 18), max(80, src_h // 14)), ) valid = [ (fx, fy, fw, fh) for (fx, fy, fw, fh) in faces if (fy + fh / 2) < src_h * 0.68 and fw * fh > 8000 ] if valid: fx, fy, fw, fh = max(valid, key=lambda f: f[2] * f[3]) cx_values.append(int(fx + fw / 2)) if cx_values: cx_values.sort() cx = cx_values[len(cx_values) // 2] else: cx = src_w // 2 x = max(0, min(cx - crop_w // 2, src_w - crop_w)) y = _vertical_closeup_y(src_h, crop_h) return {"x": x, "y": y, "w": crop_w, "h": crop_h} def _get_talknet_model(): """Load the local TalkNet model once. CPU is slower but stable on this Mac.""" global _TALKNET_MODEL if _TALKNET_MODEL is not None: return _TALKNET_MODEL if not TALKNET_MODEL_PATH.exists(): return None try: import torch # noqa: F401 import python_speech_features # noqa: F401 from scipy.io import wavfile # noqa: F401 except Exception: return None if str(TALKNET_DIR) not in sys.path: sys.path.insert(0, str(TALKNET_DIR)) previous_device = os.environ.get("TALKNET_DEVICE") os.environ["TALKNET_DEVICE"] = "cpu" try: from talkNet import talkNet model = talkNet() model.loadParameters(str(TALKNET_MODEL_PATH)) model.eval() except Exception: if previous_device is None: os.environ.pop("TALKNET_DEVICE", None) else: os.environ["TALKNET_DEVICE"] = previous_device return None _TALKNET_MODEL = model return _TALKNET_MODEL def _talknet_crop_rect( src_w: int, src_h: int, face: tuple[int, int, int, int], ) -> tuple[int, int, int, int]: """Return a fixed square face crop suitable for TalkNet's visual frontend.""" cx, fy, fw, fh = face cy = fy + fh // 2 side = max(96, int(max(fw, fh) * 1.65)) side = min(side, src_w, src_h) x = int(cx - side / 2) y = int(cy - side * 0.42) return x, y, side, side def _smooth_median(values, window: int): import numpy as np out = np.zeros_like(values) half = window // 2 for i in range(len(values)): out[i] = np.median(values[max(0, i - half): min(len(values), i + half + 1)]) return out def _fixed_face_motion_matrix( raw_clip: Path, face_boxes: dict[int, tuple[int, int, int, int]], output_len: int, duration: float, ) -> object | None: """Return per-face lower-face motion aligned to TalkNet's score timeline.""" try: import cv2 import numpy as np except Exception: return None if output_len <= 0 or duration <= 0: return None zones = sorted(face_boxes) cap = cv2.VideoCapture(str(raw_clip)) video_fps = cap.get(cv2.CAP_PROP_FPS) or 60 if not cap.isOpened() or video_fps <= 0: return None target_fps = output_len / duration matrix = np.zeros((output_len, len(zones)), dtype=float) previous_rois: dict[int, object] = {} output_index = 0 input_index = 0 while output_index < output_len: ok, img = cap.read() if not ok: break current_t = input_index / video_fps wanted_t = output_index / target_fps input_index += 1 if current_t + (0.5 / video_fps) < wanted_t: continue gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) for col, zone in enumerate(zones): cx, fy, fw, fh = face_boxes[zone] x0 = max(0, int(cx - fw * 0.36)) x1 = min(gray.shape[1], int(cx + fw * 0.36)) y0 = max(0, int(fy + fh * 0.46)) y1 = min(gray.shape[0], int(fy + fh * 0.86)) if x1 <= x0 or y1 <= y0: continue roi = cv2.resize(gray[y0:y1, x0:x1], (80, 48)) if zone in previous_rois: diff = cv2.absdiff(roi, previous_rois[zone]) matrix[output_index, col] = float((diff > 10).sum()) previous_rois[zone] = roi output_index += 1 cap.release() if output_index < max(4, output_len // 4): return None if output_index < output_len and output_index > 0: matrix[output_index:] = matrix[output_index - 1] return matrix def _fixed_face_visibility_matrix( raw_clip: Path, face_boxes: dict[int, tuple[int, int, int, int]], output_len: int, duration: float, ) -> object | None: """Return a per-face mouth visibility score aligned to TalkNet frames.""" try: import cv2 import numpy as np except Exception: return None if output_len <= 0 or duration <= 0: return None zones = sorted(face_boxes) cap = cv2.VideoCapture(str(raw_clip)) video_fps = cap.get(cv2.CAP_PROP_FPS) or 60 if not cap.isOpened() or video_fps <= 0: return None target_fps = output_len / duration matrix = np.ones((output_len, len(zones)), dtype=float) output_index = 0 input_index = 0 while output_index < output_len: ok, img = cap.read() if not ok: break current_t = input_index / video_fps wanted_t = output_index / target_fps input_index += 1 if current_t + (0.5 / video_fps) < wanted_t: continue gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) for col, zone in enumerate(zones): cx, fy, fw, fh = face_boxes[zone] x0 = max(0, int(cx - fw * 0.34)) x1 = min(gray.shape[1], int(cx + fw * 0.34)) y0 = max(0, int(fy + fh * 0.66)) y1 = min(gray.shape[0], int(fy + fh * 0.98)) if x1 <= x0 or y1 <= y0: continue roi = gray[y0:y1, x0:x1] dark_ratio = float((roi < 58).sum()) / float(roi.size) matrix[output_index, col] = 1.0 - min(1.0, max(0.0, (dark_ratio - 0.22) / 0.38)) output_index += 1 cap.release() if output_index < max(4, output_len // 4): return None if output_index < output_len and output_index > 0: matrix[output_index:] = matrix[output_index - 1] return matrix def _fixed_face_mouth_detail_matrix( raw_clip: Path, face_boxes: dict[int, tuple[int, int, int, int]], output_len: int, duration: float, *, max_seconds: float = 6.0, ) -> object | None: """Return early lower-face edge detail for fixing weak three-panel starts.""" try: import cv2 import numpy as np except Exception: return None if output_len <= 0 or duration <= 0: return None zones = sorted(face_boxes) cap = cv2.VideoCapture(str(raw_clip)) video_fps = cap.get(cv2.CAP_PROP_FPS) or 60 if not cap.isOpened() or video_fps <= 0: return None target_fps = output_len / duration max_output = max(1, min(output_len, int(target_fps * max_seconds))) matrix = np.zeros((output_len, len(zones)), dtype=float) output_index = 0 input_index = 0 while output_index < max_output: ok, img = cap.read() if not ok: break current_t = input_index / video_fps wanted_t = output_index / target_fps input_index += 1 if current_t + (0.5 / video_fps) < wanted_t: continue gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) for col, zone in enumerate(zones): cx, fy, fw, fh = face_boxes[zone] x0 = max(0, int(cx - fw * 0.36)) x1 = min(gray.shape[1], int(cx + fw * 0.36)) y0 = max(0, int(fy + fh * 0.56)) y1 = min(gray.shape[0], int(fy + fh * 0.92)) if x1 <= x0 or y1 <= y0: continue roi = gray[y0:y1, x0:x1] dark_ratio = float((roi < 58).sum()) / float(roi.size) visibility = 1.0 - min(1.0, max(0.0, (dark_ratio - 0.22) / 0.38)) edge_ratio = float((cv2.Canny(roi, 50, 150) > 0).sum()) / float(roi.size) matrix[output_index, col] = edge_ratio * visibility output_index += 1 cap.release() if output_index < max(4, max_output // 3): return None if output_index < max_output and output_index > 0: matrix[output_index:max_output] = matrix[output_index - 1] return matrix def _build_segments_from_talknet_scores( scores, duration: float, motion_scores=None, mouth_visibility=None, mouth_detail=None, face_boxes: dict[int, tuple[int, int, int, int]] | None = None, src_h: int | None = None, ) -> list[tuple[float, float, int]]: import numpy as np if scores.size == 0 or len(scores.shape) != 2 or scores.shape[1] < 2: return [] n_zones = int(scores.shape[1]) fps = 25 med = np.median(scores, axis=0) mad = np.median(np.abs(scores - med), axis=0) + 1e-6 zscores = (scores - med) / mad smoothed = np.vstack([ _smooth_median(zscores[:, z], fps) for z in range(n_zones) ]).T raw_smoothed = np.zeros_like(scores) raw_half_window = 13 // 2 for i in range(len(scores)): raw_smoothed[i] = np.median( scores[max(0, i - raw_half_window): min(len(scores), i + raw_half_window + 1)], axis=0, ) frame_raw = ( raw_smoothed - raw_smoothed.mean(axis=1, keepdims=True) ) / (raw_smoothed.std(axis=1, keepdims=True) + 1e-6) face_reliability = np.ones(n_zones, dtype=float) if n_zones >= 4 and face_boxes: ordered_faces = [face_boxes[z] for z in sorted(face_boxes) if z in face_boxes] if len(ordered_faces) == n_zones: median_h = float(np.median([f[3] for f in ordered_faces])) + 1e-6 for idx, (_cx, fy, _fw, fh) in enumerate(ordered_faces): size_ratio = float(fh) / median_h size_factor = min(1.0, max(0.45, (size_ratio - 0.45) / 0.35)) low_factor = 1.0 if src_h: cy_ratio = (float(fy) + float(fh) / 2) / max(1.0, float(src_h)) low_factor -= min(0.30, max(0.0, (cy_ratio - 0.49) / 0.22)) face_reliability[idx] = max(0.42, min(1.0, size_factor * low_factor)) if ( n_zones == 2 and motion_scores is not None and mouth_visibility is not None and getattr(motion_scores, "shape", None) == scores.shape and getattr(mouth_visibility, "shape", None) == scores.shape and float(np.max(motion_scores)) > 0 ): # In two-up layouts a large microphone can hide one speaker's mouth and # create false visual activity. Keep the TalkNet signal, but blend in # frame-relative mouth motion only where the mouth is actually visible. motion_smoothed = np.zeros_like(motion_scores, dtype=float) visibility_smoothed = np.zeros_like(mouth_visibility, dtype=float) motion_half_window = fps // 2 for i in range(len(motion_scores)): frame_slice = slice(max(0, i - motion_half_window), min(len(motion_scores), i + motion_half_window + 1)) motion_smoothed[i] = np.median(motion_scores[frame_slice], axis=0) visibility_smoothed[i] = np.median(mouth_visibility[frame_slice], axis=0) motion_log = np.log1p(motion_smoothed * visibility_smoothed) frame_motion = ( motion_log - motion_log.mean(axis=1, keepdims=True) ) / (motion_log.std(axis=1, keepdims=True) + 1e-6) visibility_rel = ( visibility_smoothed - visibility_smoothed.mean(axis=1, keepdims=True) ) / (visibility_smoothed.std(axis=1, keepdims=True) + 1e-6) smoothed = ( (smoothed * 0.10) + (frame_raw * 0.45) + (frame_motion * 0.35) + (visibility_rel * 0.10) ) if n_zones >= 4: # In four-up interview layouts, one panel can have consistently stronger # or weaker TalkNet scores because of lighting, microphone position or # face angle. Pure per-panel normalization over-corrects that baseline # and can ignore the guest while they speak. Blend in a frame-relative # raw score and lower-face motion so sustained speaker evidence wins. if ( motion_scores is not None and getattr(motion_scores, "shape", None) == scores.shape and float(np.max(motion_scores)) > 0 ): motion_smoothed = np.zeros_like(motion_scores, dtype=float) motion_half_window = fps // 2 for i in range(len(motion_scores)): motion_smoothed[i] = np.median( motion_scores[ max(0, i - motion_half_window): min(len(motion_scores), i + motion_half_window + 1) ], axis=0, ) motion_log = np.log1p(motion_smoothed) frame_motion = ( motion_log - motion_log.mean(axis=1, keepdims=True) ) / (motion_log.std(axis=1, keepdims=True) + 1e-6) smoothed = (smoothed * 0.10) + (frame_raw * 0.25) + (frame_motion * 0.65) else: smoothed = (smoothed * 0.25) + (frame_raw * 0.75) smoothed = smoothed - ((1.0 - face_reliability) * 0.45) start_win = min(len(smoothed), fps) current = int(np.argmax(np.mean(smoothed[:start_win], axis=0))) transitions: list[tuple[int, int]] = [(0, current)] candidate = None candidate_start = 0 last_switch = 0 # Talk-show interruptions are common: if we require too much certainty or a # long hold, the crop stays on the first speaker while someone else talks # over them. These thresholds still ignore one-off reactions, but let # sustained interruptions take the frame quickly. margin_threshold = 0.35 if n_zones >= 4 else 0.45 onset_frames = int(fps * (0.60 if n_zones >= 4 else 0.75)) min_hold_frames = int(fps * (2.0 if n_zones >= 4 else 2.5)) for i, row in enumerate(smoothed): order = np.argsort(row) top = int(order[-1]) margin = float(row[order[-1]] - row[order[-2]]) if top == current or margin < margin_threshold: candidate = None continue if candidate != top: candidate = top candidate_start = i if i - candidate_start >= onset_frames and i - last_switch >= min_hold_frames: transitions.append((candidate_start, top)) current = top last_switch = i candidate = None frame_count = len(smoothed) segments: list[list[int]] = [] for idx, (start, zone) in enumerate(transitions): end = transitions[idx + 1][0] if idx + 1 < len(transitions) else frame_count segments.append([start, end, zone]) # Merge short islands. A one-second model wobble is worse than a slightly # delayed cut, especially for clips intended for social publishing. changed = True min_segment_frames = int(fps * 1.6) while changed and len(segments) > 1: changed = False merged: list[list[int]] = [] i = 0 while i < len(segments): start, end, zone = segments[i] if end - start < min_segment_frames: if merged and i + 1 < len(segments): prev = merged[-1] nxt = segments[i + 1] if prev[2] == nxt[2]: prev[1] = nxt[1] i += 2 changed = True continue prev_len = prev[1] - prev[0] next_len = nxt[1] - nxt[0] if prev_len >= next_len: prev[1] = end i += 1 else: nxt[0] = start i += 1 changed = True continue if merged: merged[-1][1] = end i += 1 changed = True continue if i + 1 < len(segments): segments[i + 1][0] = start i += 1 changed = True continue merged.append([start, end, zone]) i += 1 segments = merged # Crosstalk correction: when the first speaker gets interrupted, the model # can briefly bounce back to the original speaker because both voices are # audible. If the same interrupter surrounds that return early in the clip, # keep the frame on the interrupter until the next clear turn change. if n_zones <= 3 and len(segments) >= 4: initial_zone = segments[0][2] for i in range(1, len(segments) - 1): prev_seg = segments[i - 1] cur_seg = segments[i] next_seg = segments[i + 1] surrounded_by_interrupter = ( prev_seg[2] == next_seg[2] and prev_seg[2] != initial_zone and cur_seg[2] == initial_zone ) early_return = cur_seg[0] < fps * 25 plausible_overlap = (cur_seg[1] - cur_seg[0]) <= fps * 16 if surrounded_by_interrupter and early_return and plausible_overlap: cur_seg[2] = prev_seg[2] merged = [] for start, end, zone in segments: if merged and merged[-1][2] == zone: merged[-1][1] = end else: merged.append([start, end, zone]) segments = merged if n_zones >= 4 and len(segments) >= 3: frame_count = max(1, len(smoothed)) zone_totals = np.zeros(n_zones, dtype=float) for start, end, zone in segments: zone_totals[zone] += max(0, end - start) dominant_zone = int(np.argmax(zone_totals)) dominant_share = float(zone_totals[dominant_zone]) / frame_count if dominant_share >= 0.58: for i in range(1, len(segments) - 1): prev_seg = segments[i - 1] cur_seg = segments[i] next_seg = segments[i + 1] start, end, zone = cur_seg if zone == dominant_zone: continue if prev_seg[2] != dominant_zone or next_seg[2] != dominant_zone: continue seg_len = end - start window = smoothed[start:end] evidence_gap = 0.0 if len(window): evidence_gap = float( np.mean(window[:, zone]) - np.mean(window[:, dominant_zone]) ) weak_face = bool(face_reliability[zone] < 0.72) # Four-up interviews often contain long guest monologues while # the other panels nod, gesture, drink mate or look down. Those # reactions can create short false active-speaker islands. Keep # real turn changes, but bridge brief listener islands when a # dominant speaker surrounds them. if ( seg_len <= int(fps * 2.45) or (weak_face and seg_len <= int(fps * 4.50)) or (seg_len <= int(fps * 4.00) and evidence_gap < 0.95) ): cur_seg[2] = dominant_zone merged = [] for start, end, zone in segments: if merged and merged[-1][2] == zone: merged[-1][1] = end else: merged.append([start, end, zone]) segments = merged if n_zones == 3: # Preserve short centre-speaker interventions. The centre journalist's # mouth is often hidden by the mic, so the normalised score can under-call # him during quick replies even when the raw audio-visual score is clearly # close to the active panel. These short turns matter in vertical clips. center_events: list[list[int]] = [] event_start = None center_median = med[1] center_mad = mad[1] for i, row in enumerate(raw_smoothed): side_top = max(row[0], row[2]) center_z = (row[1] - center_median) / center_mad is_center_turn = row[1] >= side_top - 0.35 and center_z > 0.45 if is_center_turn and event_start is None: event_start = i if (not is_center_turn or i == len(raw_smoothed) - 1) and event_start is not None: event_end = i if not is_center_turn else i + 1 if event_end - event_start >= int(fps * 0.45): center_events.append([ max(0, event_start - int(fps * 0.10)), min(len(raw_smoothed), event_end + int(fps * 0.15)), 1, ]) event_start = None merged_events: list[list[int]] = [] for start, end, zone in center_events: if merged_events and start - merged_events[-1][1] <= int(fps * 0.70): merged_events[-1][1] = end else: merged_events.append([start, end, zone]) for event_start, event_end, event_zone in merged_events: updated: list[list[int]] = [] for start, end, zone in segments: if end <= event_start or start >= event_end: updated.append([start, end, zone]) continue if start < event_start: updated.append([start, event_start, zone]) updated.append([max(start, event_start), min(end, event_end), event_zone]) if end > event_end: updated.append([event_end, end, zone]) segments = updated if ( n_zones == 3 and segments and mouth_detail is not None and getattr(mouth_detail, "shape", None) == scores.shape ): # TalkNet can occasionally give the first seconds to the wrong side # panel with a weak margin. Use early visible-mouth detail as a tiebreak, # but only for short lateral false starts so centre mic occlusion is not # punished in normal turns. current_zone = int(segments[0][2]) detail_window = min(len(mouth_detail), int(fps * 3.2)) if detail_window >= int(fps * 0.8) and current_zone in (0, 2): detail_mean = np.mean(mouth_detail[:detail_window], axis=0) best_zone = int(np.argmax(detail_mean)) raw_mean = np.mean(raw_smoothed[:detail_window], axis=0) raw_order = np.argsort(raw_mean) raw_margin = float(raw_mean[raw_order[-1]] - raw_mean[raw_order[-2]]) first_len = int(segments[0][1] - segments[0][0]) visual_beats_current = ( best_zone in (0, 2) and best_zone != current_zone and float(detail_mean[best_zone]) >= 0.055 and float(detail_mean[best_zone]) >= float(detail_mean[current_zone]) * 1.28 ) visual_confirms_current = ( best_zone == current_zone and float(detail_mean[best_zone]) >= 0.055 ) if ( (visual_beats_current or visual_confirms_current) and raw_margin < 0.65 and first_len <= int(fps * 4.2) ): if visual_beats_current: segments[0][2] = best_zone for idx in range(1, min(len(segments) - 1, 4)): next_clear_is_best = any( future[2] == best_zone for future in segments[idx + 1:min(len(segments), idx + 4)] ) if ( segments[idx][2] != best_zone and next_clear_is_best and segments[idx][1] - segments[idx][0] <= int(fps * 1.85) ): segments[idx][2] = best_zone merged = [] for start, end, zone in segments: if end <= start: continue if merged and merged[-1][2] == zone: merged[-1][1] = end else: merged.append([start, end, zone]) segments = merged return [ (round(start / fps, 1), round(min(end / fps, duration), 1), zone) for start, end, zone in segments if end > start ] def _detect_talknet_fixed_timeline( raw_clip: Path, face_boxes: dict[int, tuple[int, int, int, int]], src_w: int, src_h: int, duration: float, *, layout: str = "panel3", ) -> list[dict] | None: """ Use the local TalkNet active-speaker model on fixed per-panel face crops. The full TalkNet demo performs neural face detection on every frame, which is too slow for the daily workflow. In this show the three panel positions are fixed, so we reuse the already detected face boxes and only run the audio-visual active-speaker model. """ zones = sorted(face_boxes) if len(zones) < 2: return None model = _get_talknet_model() if model is None: return None try: import cv2 import numpy as np import torch import python_speech_features from scipy.io import wavfile except Exception: return None target_fps = 25 try: cache_dir = raw_clip.parent / ".talknet_cache" cache_dir.mkdir(exist_ok=True) face_cache_key = json.dumps( {str(k): [int(vv) for vv in v] for k, v in sorted(face_boxes.items())}, sort_keys=True, ) cache_path = cache_dir / f"{raw_clip.stem}_scores_v1.npz" score_matrix = None if cache_path.exists(): try: cached = np.load(cache_path, allow_pickle=False) if ( int(cached["raw_mtime"]) == int(raw_clip.stat().st_mtime) and int(cached["raw_size"]) == int(raw_clip.stat().st_size) and str(cached["face_key"]) == face_cache_key ): score_matrix = cached["scores"] print(" → TalkNet fijo: usando scores cacheados") except Exception: score_matrix = None if score_matrix is not None: motion_matrix = ( _fixed_face_motion_matrix(raw_clip, face_boxes, len(score_matrix), duration) if layout in {"panel2", "panel3", "panel4"} else None ) visibility_matrix = ( _fixed_face_visibility_matrix(raw_clip, face_boxes, len(score_matrix), duration) if layout in {"panel2", "panel3"} else None ) mouth_detail_matrix = ( _fixed_face_mouth_detail_matrix(raw_clip, face_boxes, len(score_matrix), duration) if layout == "panel3" else None ) speaker_segments = _build_segments_from_talknet_scores( score_matrix, duration, motion_scores=motion_matrix, mouth_visibility=visibility_matrix, mouth_detail=mouth_detail_matrix, face_boxes=face_boxes, src_h=src_h, ) if not speaker_segments: return None timeline = [] if layout == "panel2": crop_for_zone = _two_panel_crop_for_zone elif layout == "panel4": crop_for_zone = lambda w, h, zone: _four_panel_crop_for_zone( w, h, zone, face_boxes.get(zone) ) else: crop_for_zone = _panel_crop_for_zone for start, end, score_zone in speaker_segments: zone = zones[score_zone] timeline.append({ "t_start": start, "t_end": end, "layout": layout, **crop_for_zone(src_w, src_h, zone), }) timeline[0]["t_start"] = 0.0 timeline[-1]["t_end"] = duration return timeline with tempfile.TemporaryDirectory() as tmp: tmp_path = Path(tmp) crop_dir = tmp_path / "pycrop" crop_dir.mkdir() audio_path = crop_dir / "audio.wav" subprocess.run( [ FFMPEG_BIN, "-y", "-v", "error", "-i", str(raw_clip), "-ac", "1", "-vn", "-acodec", "pcm_s16le", "-ar", "16000", str(audio_path), ], check=True, ) cap = cv2.VideoCapture(str(raw_clip)) video_fps = cap.get(cv2.CAP_PROP_FPS) or 60 if not cap.isOpened() or video_fps <= 0: return None fourcc = cv2.VideoWriter_fourcc(*"XVID") writers = {} crop_rects = { z: _talknet_crop_rect(src_w, src_h, face_boxes[z]) for z in zones } for z in zones: writers[z] = cv2.VideoWriter( str(crop_dir / f"{z:05d}.avi"), fourcc, target_fps, (224, 224), ) shutil.copyfile(audio_path, crop_dir / f"{z:05d}.wav") frame_count = int(duration * target_fps) output_index = 0 input_index = 0 while output_index < frame_count: ok, img = cap.read() if not ok: break current_t = input_index / video_fps wanted_t = output_index / target_fps input_index += 1 if current_t + (0.5 / video_fps) < wanted_t: continue for z, writer in writers.items(): x, y, w, h = crop_rects[z] x1 = max(0, x) y1 = max(0, y) x2 = min(src_w, x + w) y2 = min(src_h, y + h) crop = np.full((h, w, 3), 110, dtype=np.uint8) dx = x1 - x dy = y1 - y if x2 > x1 and y2 > y1: crop[dy:dy + (y2 - y1), dx:dx + (x2 - x1)] = img[y1:y2, x1:x2] writer.write(cv2.resize(crop, (224, 224))) output_index += 1 cap.release() for writer in writers.values(): writer.release() scores_by_zone = [] for z in zones: _, audio = wavfile.read(str(crop_dir / f"{z:05d}.wav")) audio_feature = python_speech_features.mfcc( audio, 16000, numcep=13, winlen=0.025, winstep=0.010, ) video = cv2.VideoCapture(str(crop_dir / f"{z:05d}.avi")) video_feature = [] while video.isOpened(): ret, frame = video.read() if not ret: break face = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) face = cv2.resize(face, (224, 224))[56:168, 56:168] video_feature.append(face) video.release() if not video_feature: return None video_feature = np.array(video_feature) length = min( (audio_feature.shape[0] - audio_feature.shape[0] % 4) / 100, video_feature.shape[0] / target_fps, ) if length <= 1: return None audio_feature = audio_feature[:int(round(length * 100)), :] video_feature = video_feature[:int(round(length * target_fps)), :, :] zone_scores = [] duration_window = 2 batch_count = int(np.ceil(length / duration_window)) with torch.no_grad(): for i in range(batch_count): input_a = torch.FloatTensor( audio_feature[ i * duration_window * 100:(i + 1) * duration_window * 100, :, ] ).unsqueeze(0).to(model.device) input_v = torch.FloatTensor( video_feature[ i * duration_window * target_fps:(i + 1) * duration_window * target_fps, :, :, ] ).unsqueeze(0).to(model.device) embed_a = model.model.forward_audio_frontend(input_a) embed_v = model.model.forward_visual_frontend(input_v) embed_a, embed_v = model.model.forward_cross_attention(embed_a, embed_v) out = model.model.forward_audio_visual_backend(embed_a, embed_v) zone_scores.extend(model.lossAV.forward(out, labels=None)) scores_by_zone.append(np.array(zone_scores, dtype=float)) min_len = min(len(s) for s in scores_by_zone) if min_len < target_fps: return None score_matrix = np.vstack([s[:min_len] for s in scores_by_zone]).T np.savez( cache_path, scores=score_matrix, raw_mtime=int(raw_clip.stat().st_mtime), raw_size=int(raw_clip.stat().st_size), face_key=face_cache_key, ) motion_matrix = ( _fixed_face_motion_matrix(raw_clip, face_boxes, len(score_matrix), duration) if layout in {"panel2", "panel3", "panel4"} else None ) visibility_matrix = ( _fixed_face_visibility_matrix(raw_clip, face_boxes, len(score_matrix), duration) if layout in {"panel2", "panel3"} else None ) mouth_detail_matrix = ( _fixed_face_mouth_detail_matrix(raw_clip, face_boxes, len(score_matrix), duration) if layout == "panel3" else None ) speaker_segments = _build_segments_from_talknet_scores( score_matrix, duration, motion_scores=motion_matrix, mouth_visibility=visibility_matrix, mouth_detail=mouth_detail_matrix, face_boxes=face_boxes, src_h=src_h, ) if not speaker_segments: return None timeline = [] if layout == "panel2": crop_for_zone = _two_panel_crop_for_zone elif layout == "panel4": crop_for_zone = lambda w, h, zone: _four_panel_crop_for_zone( w, h, zone, face_boxes.get(zone) ) else: crop_for_zone = _panel_crop_for_zone for start, end, score_zone in speaker_segments: zone = zones[score_zone] timeline.append({ "t_start": start, "t_end": end, "layout": layout, **crop_for_zone(src_w, src_h, zone), }) timeline[0]["t_start"] = 0.0 timeline[-1]["t_end"] = duration return timeline except Exception as exc: print(f" → TalkNet fijo no disponible para este clip ({exc}); uso detector liviano") return None def detect_active_speaker_timeline(raw_clip: Path) -> list[dict] | None: """ Build a per-speaker dynamic zoom timeline using face-detection-based mouth-motion tracking. The broadcast always has exactly 3 journalists at FIXED horizontal positions (left / centre / right thirds of the frame). The algorithm: 1. Extract frames at 6 fps for fine temporal resolution. 2. Detect faces in a sample of frames to establish stable mouth ROIs for each of the 3 zones (using OpenCV Haar cascade). 3. For each consecutive frame pair, compute motion ONLY within the mouth ROI of each face (lower 40% of face bbox). This ignores hand gestures, head nods, and body movements. 4. Normalise each zone's mouth energy by its clip-wide mean. 5. Apply incumbent penalty + dominance ratio to prevent false switches. 6. Use onset-based transitions with minimum hold time. 7. Map each segment to one of 3 fixed crop positions. """ try: import cv2 import numpy as np except ImportError: return None # ── Probe clip ──────────────────────────────────────────────────────────── probe = subprocess.run([FFMPEG_BIN, "-i", str(raw_clip)], capture_output=True, text=True) dim_m = re.search(r"(\d{3,4})x(\d{3,4})", probe.stderr) dur_m = re.search(r"Duration:\s*(\d+):(\d+):([\d.]+)", probe.stderr) if not dim_m or not dur_m: return None src_w = int(dim_m.group(1)) src_h = int(dim_m.group(2)) duration = ( int(dur_m.group(1)) * 3600 + int(dur_m.group(2)) * 60 + float(dur_m.group(3)) ) # ── Fixed 3-zone crop positions ─────────────────────────────────────────── crop_h = int(src_h * PANEL_CROP_HEIGHT_RATIO) crop_w = int(crop_h * 9 / 16) if crop_w > src_w: crop_w = src_w crop_h = int(crop_w * 16 / 9) zone_w = src_w // 3 zone_centers = [ zone_w // 2, zone_w + zone_w // 2, 2 * zone_w + zone_w // 2, ] def zone_to_crop(zone_idx: int) -> dict: return _panel_crop_for_zone(src_w, src_h, zone_idx) # ── Tuneable constants ──────────────────────────────────────────────────── FPS = 6 # frame extraction rate MOTION_THRESHOLD = 250.0 # minimum speech-pixel count to register as motion INCUMBENT_PENALTY = 0.85 # multiplier on current zone's normalised score ONSET_FRAMES = 7 # consecutive frames needed to trigger a switch (~1.2s at 6fps) MIN_HOLD = 4.0 # seconds before allowing another switch DOMINANCE_RATIO = 2.0 # new zone must beat incumbent by this factor ABSOLUTE_RATIO = 1.0 # and also match/exceed raw mouth activity MIN_ABS_SHARE = 0.55 # ignore low-energy relative spikes from quiet panels STRONG_SWITCH_RAW = 1.25 # allow switch through weak Haar visibility on strong speech STRONG_SWITCH_MIN_SHARE = 0.42 with tempfile.TemporaryDirectory() as tmp_dir: fdir = Path(tmp_dir) # ── Step 1: Extract frames ─────────────────────────────────────────── max_frames = min(int(duration * FPS) + 4, 600) subprocess.run( [FFMPEG_BIN, "-i", str(raw_clip), "-vf", f"fps={FPS}", "-q:v", "5", "-vframes", str(max_frames), str(fdir / "f%04d.jpg")], capture_output=True, ) frame_files = sorted(fdir.glob("f*.jpg")) if len(frame_files) < 4: return None # ── Step 2: Detect faces and establish mouth ROIs ──────────────────── # Haar frontal-face detections are fast enough for this local workflow, # but they can produce false positives on microphones, hands, shirts or # sponsor graphics. Use several face cascades, then validate candidates # with an eye detector before trusting them as a mouth ROI. face_cascade = cv2.CascadeClassifier( cv2.data.haarcascades + "haarcascade_frontalface_default.xml" ) face_cascades = [ face_cascade, cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_alt2.xml"), cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_alt.xml"), cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_profileface.xml"), ] eye_cascades = [ cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_eye_tree_eyeglasses.xml"), cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_eye.xml"), ] def panel_face_candidates( gray, *, min_size: tuple[int, int], require_eyes: bool, ) -> list[tuple[int, int, int, int, int]]: candidates: list[tuple[int, int, int, int, int]] = [] seen: list[tuple[int, int, int, int]] = [] for cascade in face_cascades: if cascade.empty(): continue faces = cascade.detectMultiScale( gray, scaleFactor=1.05, minNeighbors=4, minSize=min_size ) for (fx, fy, fw, fh) in faces: cx = fx + fw // 2 cy = fy + fh // 2 # In the split-panel studio layout the usable faces live in # the upper/middle half. Lower detections are usually hands, # microphones, hoodies or sponsor marks. if cy > src_h * 0.62 or fy > src_h * 0.50: continue if fw < src_w * 0.045 or fh < src_h * 0.07: continue duplicate = False for sx, sy, sw, sh in seen: if abs(cx - (sx + sw // 2)) < max(fw, sw) * 0.28 and abs(cy - (sy + sh // 2)) < max(fh, sh) * 0.28: duplicate = True break if duplicate: continue seen.append((fx, fy, fw, fh)) upper = gray[fy:fy + int(fh * 0.62), fx:fx + fw] eye_count = 0 if upper.size: for eye_cascade in eye_cascades: if eye_cascade.empty(): continue eyes = eye_cascade.detectMultiScale( upper, scaleFactor=1.05, minNeighbors=3, minSize=(max(14, fw // 10), max(10, fh // 14)), ) eye_count = max(eye_count, len(eyes)) if require_eyes and eye_count <= 0: continue candidates.append((fx, fy, fw, fh, min(eye_count, 2))) return candidates panel_flags: list[bool] = [] four_panel_flags: list[bool] = [] two_panel_flags: list[bool] = [] for frame_path in frame_files: img = cv2.imread(str(frame_path)) if img is None: panel_flags.append(False) four_panel_flags.append(False) two_panel_flags.append(False) else: panel_flags.append(_is_split_panel_frame(img, src_w)) four_panel_flags.append(_is_four_panel_frame(img, src_w)) two_panel_flags.append(_is_two_panel_frame(img, src_w)) panel_indices = [i for i, is_panel in enumerate(panel_flags) if is_panel] four_panel_indices = [i for i, is_panel in enumerate(four_panel_flags) if is_panel] two_panel_indices = [i for i, is_panel in enumerate(two_panel_flags) if is_panel] panel_ratio = len(panel_indices) / len(frame_files) print(f" → Layout panel dividido: {len(panel_indices)}/{len(frame_files)} frames ({panel_ratio:.0%})") def fixed_panel_talknet_timeline( fixed_indices: list[int], panel_count: int, layout: str, ) -> list[dict] | None: zone_centers_fixed = _panel_zone_centers(src_w, panel_count) zone_w_fixed = src_w / panel_count sample_indices = np.array( [ fixed_indices[int(round(i))] for i in np.linspace(0, len(fixed_indices) - 1, min(12, len(fixed_indices))) ], dtype=int, ) faces_by_zone: dict[int, list[tuple[int, int, int, int]]] = { z: [] for z in range(panel_count) } separators = [src_w * i / panel_count for i in range(1, panel_count)] for si in sample_indices: img = cv2.imread(str(frame_files[si])) if img is None: continue gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = panel_face_candidates( gray, min_size=(max(60, src_w // 24), max(80, src_h // 13)), require_eyes=True, ) candidates_by_zone: dict[int, list[tuple[int, int, int, int, int]]] = { z: [] for z in range(panel_count) } for (fx, fy, fw, fh, eyes) in faces: cx = fx + fw // 2 if any(abs(cx - sep) < src_w * 0.025 for sep in separators): continue candidates_by_zone[_panel_zone_for_x_count(src_w, cx, panel_count)].append((fx, fy, fw, fh, eyes)) for z, candidates in candidates_by_zone.items(): if not candidates: continue def face_score(face: tuple[int, int, int, int, int]) -> tuple[float, float]: fx, fy, fw, fh, eyes = face cx = fx + fw / 2 cy = fy + fh / 2 center_dist = abs(cx - zone_centers_fixed[z]) / max(1, zone_w_fixed) high_penalty = max(0.0, (src_h * 0.24 - cy) / max(1, src_h * 0.24)) low_penalty = max(0.0, (cy - src_h * 0.60) / max(1, src_h * 0.40)) eye_bonus = eyes * 0.35 return (center_dist + high_penalty + low_penalty - eye_bonus, -fw * fh) fx, fy, fw, fh, _eyes = min(candidates, key=face_score) faces_by_zone[z].append((fx + fw // 2, fy, fw, fh)) face_boxes: dict[int, tuple[int, int, int, int]] = {} for z in range(panel_count): zone_faces = faces_by_zone[z] if not zone_faces: continue face_boxes[z] = ( int(np.median([f[0] for f in zone_faces])), int(np.median([f[1] for f in zone_faces])), int(np.median([f[2] for f in zone_faces])), int(np.median([f[3] for f in zone_faces])), ) cx, fy, fw, fh = face_boxes[z] print(f" → Cara panel {z + 1}/{panel_count}: cx={cx}, y={fy}, {fw}x{fh}px") if set(face_boxes) != set(range(panel_count)): print(f" → Detecté {len(face_boxes)}/{panel_count} caras del layout; no uso TalkNet fijo") return None talknet_segments = _detect_talknet_fixed_timeline( raw_clip, face_boxes, src_w, src_h, duration, layout=layout, ) if not talknet_segments: return None zone_names_by_count = { 2: ["izq", "der"], 4: ["izq", "ctr-izq", "ctr-der", "der"], } zone_names_fixed = zone_names_by_count.get( panel_count, [f"panel {z + 1}" for z in range(panel_count)], ) print(" → TalkNet fijo: speaker detectado con audio+video") print(f" → {len(talknet_segments)} segmento(s) con zoom dinámico:") for seg in talknet_segments: if panel_count == 2: zone_idx = _two_panel_zone_for_x(src_w, seg["x"] + seg["w"] // 2) else: zone_idx = _panel_zone_for_x_count(src_w, seg["x"] + seg["w"] // 2, panel_count) print( f" {seg['t_start']:.1f}s → {seg['t_end']:.1f}s " f"{zone_names_fixed[zone_idx]}" ) return talknet_segments # If there are no stable split-panel frames, this is a close-up/single # camera clip or the two-panel show layout. Try the two-panel active # speaker path before falling back to static face-aware zoom. if len(panel_indices) < 4: if len(four_panel_indices) >= 4: print(f" → Layout panel cuádruple: {len(four_panel_indices)}/{len(frame_files)} frames") four_timeline = fixed_panel_talknet_timeline(four_panel_indices, 4, "panel4") if four_timeline: return four_timeline if len(two_panel_indices) >= 4: print(f" → Layout panel doble: {len(two_panel_indices)}/{len(frame_files)} frames") two_timeline = fixed_panel_talknet_timeline(two_panel_indices, 2, "panel2") if two_timeline: return two_timeline print(" → No hay suficientes frames de panel dividido") return None # Track whether each panel still has a usable, visible face per frame. # Mouth-motion alone can be fooled by someone looking down at a phone, # a hand crossing the mouth ROI, or microphone movement. A new speaker # candidate must have a visible face during the onset before we cut to it. face_visible_zones: list[set[int]] = [] visibility_min_size = (src_w // 16, src_h // 10) for frame_path, is_panel in zip(frame_files, panel_flags): zones: set[int] = set() if is_panel: img = cv2.imread(str(frame_path)) if img is not None: gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) for (fx, fy, fw, fh, _eyes) in panel_face_candidates( gray, min_size=visibility_min_size, require_eyes=True, ): zones.add(_panel_zone_for_x(src_w, fx + fw // 2)) face_visible_zones.append(zones) def visible_ratio(frame_idx: int, zone_idx: int, window: int) -> float: start = max(0, frame_idx - window + 1) end = min(len(face_visible_zones), frame_idx + 1) panel_count = 0 visible_count = 0 for j in range(start, end): if not panel_flags[j]: continue panel_count += 1 if zone_idx in face_visible_zones[j]: visible_count += 1 if panel_count <= 0: return 0.0 return visible_count / panel_count # Sample only split-panel frames to find stable face positions. Close-up # shots often create false Haar detections in hands/wall texture and must # not define the left/centre/right mouth ROIs. sample_indices = np.array( [ panel_indices[int(round(i))] for i in np.linspace(0, len(panel_indices) - 1, min(10, len(panel_indices))) ], dtype=int, ) all_faces = [] for si in sample_indices: img = cv2.imread(str(frame_files[si])) if img is None: continue gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = panel_face_candidates( gray, min_size=(src_w // 14, src_h // 10), require_eyes=True, ) faces_by_zone: dict[int, list[tuple[int, int, int, int, int]]] = {0: [], 1: [], 2: []} for (fx, fy, fw, fh, eyes) in faces: cx = fx + fw // 2 faces_by_zone[_panel_zone_for_x(src_w, cx)].append((fx, fy, fw, fh, eyes)) # Haar can return duplicate/partial faces in the same panel, # especially when a microphone covers the mouth. Keep one face per # panel per sampled frame: the one closest to the fixed presenter # centre, with a small penalty for unusually low detections. for z, candidates in faces_by_zone.items(): if not candidates: continue def face_score(face: tuple[int, int, int, int, int]) -> tuple[float, float]: fx, fy, fw, fh, eyes = face cx = fx + fw / 2 cy = fy + fh / 2 center_dist = abs(cx - zone_centers[z]) / max(1, zone_w) low_penalty = max(0.0, (cy - src_h * 0.54) / max(1, src_h * 0.46)) eye_bonus = eyes * 0.35 return (center_dist + low_penalty - eye_bonus, -fw * fh) fx, fy, fw, fh, _eyes = min(candidates, key=face_score) all_faces.append((fx + fw // 2, fy, fw, fh)) # (center_x, y, w, h) if len(all_faces) < 3: print(f" → Solo {len(all_faces)} detecciones de cara, insuficiente") return None # Cluster faces into 3 zones by horizontal center face_xs = np.array([f[0] for f in all_faces]) zone_assignments = np.digitize(face_xs, [zone_w, 2 * zone_w]) # 0=izq, 1=ctr, 2=der # Build median mouth/head ROIs per zone. Speech should move the lower # face more than the upper face; head turns move both and are discounted. mouth_rois: dict[int, tuple[int, int, int, int] | None] = {} head_rois: dict[int, tuple[int, int, int, int] | None] = {} face_boxes: dict[int, tuple[int, int, int, int]] = {} available_zones: list[int] = [] for z in range(3): zone_faces = [all_faces[i] for i in range(len(all_faces)) if zone_assignments[i] == z] if not zone_faces: print(f" → No se detectaron caras en zona {z}; se ignora para tracking") mouth_rois[z] = None head_rois[z] = None continue available_zones.append(z) med_cx = int(np.median([f[0] for f in zone_faces])) med_y = int(np.median([f[1] for f in zone_faces])) med_w = int(np.median([f[2] for f in zone_faces])) med_h = int(np.median([f[3] for f in zone_faces])) face_boxes[z] = (med_cx, med_y, med_w, med_h) # Keep the mouth ROI inside the detected face. Extending below the # chin catches microphones, hands and phones, which caused false # switches to panelists looking down. mouth_y1 = med_y + int(med_h * 0.52) mouth_y2 = min(med_y + int(med_h * 0.88), src_h) mouth_x1 = max(0, med_cx - int(med_w * 0.30)) mouth_x2 = min(src_w, med_cx + int(med_w * 0.30)) mouth_rois[z] = (mouth_x1, mouth_y1, mouth_x2, mouth_y2) head_y1 = max(0, med_y + int(med_h * 0.15)) head_y2 = min(src_h, med_y + int(med_h * 0.50)) head_x1 = mouth_x1 head_x2 = mouth_x2 head_rois[z] = (head_x1, head_y1, head_x2, head_y2) if not available_zones: print(" → No se detectaron caras utilizables en panel") return None zone_names = ["izq", "ctr", "der"] for z in range(3): r = mouth_rois[z] if r is None: continue print(f" → Boca {zone_names[z]}: ({r[0]},{r[1]})-({r[2]},{r[3]}) " f"[{r[2]-r[0]}x{r[3]-r[1]}px]") talknet_segments = _detect_talknet_fixed_timeline( raw_clip, face_boxes, src_w, src_h, duration, ) if talknet_segments: print(" → TalkNet fijo: speaker detectado con audio+video") print(f" → {len(talknet_segments)} segmento(s) con zoom dinámico:") for seg in talknet_segments: zone_idx = _panel_zone_for_x(src_w, seg["x"] + seg["w"] // 2) print( f" {seg['t_start']:.1f}s → {seg['t_end']:.1f}s " f"{zone_names[zone_idx]}" ) return talknet_segments # ── Step 3: Collect per-frame MOUTH energy ─────────────────────────── # Only count pixels with MODERATE motion (speech range 8-80). # This filters out: # - static pixels (< 8): no motion / noise # - large object motion (> 80): glass, hand crossing mouth area # Speaking = many pixels with small motion; drinking = few pixels with huge motion SPEECH_LO = 8 # minimum pixel diff to count as motion SPEECH_HI = 80 # maximum pixel diff (above = object, not lips) all_e: list[tuple[float, list[float], bool]] = [] for idx in range(len(frame_files) - 1): t = idx / FPS img1 = cv2.imread(str(frame_files[idx])) img2 = cv2.imread(str(frame_files[idx + 1])) if img1 is None or img2 is None: continue is_panel = panel_flags[idx] and panel_flags[idx + 1] g1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY) g2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY) e = [] for z in range(3): if is_panel and mouth_rois[z] is not None: x1, y1, x2, y2 = mouth_rois[z] roi1 = g1[y1:y2, x1:x2] roi2 = g2[y1:y2, x1:x2] diff = cv2.absdiff(roi1, roi2).astype(np.float32) diff = cv2.GaussianBlur(diff, (7, 7), 0) # Count pixels in speech motion range (not object motion) speech_mask = (diff >= SPEECH_LO) & (diff <= SPEECH_HI) mouth_density = float(speech_mask.sum()) / max(1, speech_mask.size) head_density = 0.0 head_roi = head_rois.get(z) if head_roi is not None: hx1, hy1, hx2, hy2 = head_roi href1 = g1[hy1:hy2, hx1:hx2] href2 = g2[hy1:hy2, hx1:hx2] hdiff = cv2.absdiff(href1, href2).astype(np.float32) hdiff = cv2.GaussianBlur(hdiff, (7, 7), 0) head_mask = (hdiff >= SPEECH_LO) & (hdiff <= SPEECH_HI) head_density = float(head_mask.sum()) / max(1, head_mask.size) speech_density = max(0.0, mouth_density - head_density * 0.75) e.append(speech_density * speech_mask.size) else: e.append(0.0) all_e.append((t, e, is_panel)) if len(all_e) < 4: return None # ── Step 3b: Temporal smoothing to filter transient events ─────────── # A smile creates a 1-2 frame spike then settles. Speaking creates # sustained motion across many frames. Replace each frame's energy # with the MINIMUM of a sliding window — only sustained motion survives. SMOOTH_WIN = 3 # window size in frames (~0.5s at 6fps) smoothed: list[tuple[float, list[float], bool]] = [] for i in range(len(all_e)): t, _e, is_panel = all_e[i] win_start = max(0, i - SMOOTH_WIN // 2) win_end = min(len(all_e), i + SMOOTH_WIN // 2 + 1) se = [] for z in range(3): # Use median of window — filters out isolated spikes (smiles) # while preserving sustained activity (speech) vals = [all_e[j][1][z] for j in range(win_start, win_end) if all_e[j][2]] if not vals: vals = [0.0] se.append(float(np.median(vals))) smoothed.append((t, se, is_panel)) all_e = smoothed # ── Step 4: Normalise by zone mean ─────────────────────────────────── panel_energy = [e for _, e, is_panel in all_e if is_panel] if len(panel_energy) < 4: print(" → Muy poca energía de panel dividido") return None zone_means = [ max(float(np.mean([e[z] for e in panel_energy])), 1.0) for z in range(3) ] # ── Step 5: Raw classification (normalised + incumbent penalty) ────── # Smart start: pick the zone with the strongest absolute mouth energy in # the first seconds. Normalised scores are great for later switches, but # at clip start they can overvalue a quiet panel whose mean is tiny. startup_energy_items = [e for _, e, is_panel in all_e if is_panel] startup_frames = min(FPS * 3, len(startup_energy_items)) startup_abs = [0.0, 0.0, 0.0] startup_norm = [0.0, 0.0, 0.0] for e in startup_energy_items[:startup_frames]: for z in range(3): startup_abs[z] += e[z] startup_norm[z] += e[z] / zone_means[z] if max(startup_abs[z] for z in available_zones) <= 0 and 1 in available_zones: current_zone = 1 else: current_zone = max(available_zones, key=lambda z: (startup_abs[z], startup_norm[z])) raw_states: list[tuple[float, int, bool]] = [] for t, e, is_panel in all_e: if not is_panel: raw_states.append((t, 1, False)) continue if sum(e) < MOTION_THRESHOLD: raw_states.append((t, current_zone, True)) continue norm = [e[z] / zone_means[z] for z in range(3)] for z in range(3): if z not in available_zones: norm[z] = -1.0 norm[current_zone] *= INCUMBENT_PENALTY winner = int(np.argmax(norm)) # Require dominance in both normalised and absolute motion. # Normalisation alone can make a quiet panel "win" from a small # head/hand movement, even while the real speaker has far more # mouth activity. The raw-motion gates prevent those false jumps. if winner != current_zone: incumbent_score = norm[current_zone] raw_max = max(e[z] for z in available_zones) winner_abs = e[winner] current_abs = e[current_zone] candidate_visibility = visible_ratio(min(int(t * FPS), len(frame_files) - 1), winner, ONSET_FRAMES) current_visibility = visible_ratio(min(int(t * FPS), len(frame_files) - 1), current_zone, ONSET_FRAMES) strong_mouth_switch = ( winner_abs >= max(current_abs * STRONG_SWITCH_RAW, raw_max * STRONG_SWITCH_MIN_SHARE) and norm[winner] >= max(norm[current_zone] * DOMINANCE_RATIO, 1.0) ) if candidate_visibility < 0.35 and current_visibility >= 0.15 and not strong_mouth_switch: winner = current_zone elif raw_max > 0 and winner_abs < raw_max * MIN_ABS_SHARE: winner = current_zone elif current_abs > 0 and winner_abs / current_abs < ABSOLUTE_RATIO: winner = current_zone elif incumbent_score > 0 and norm[winner] / incumbent_score < DOMINANCE_RATIO: winner = current_zone current_zone = winner raw_states.append((t, winner, True)) # ── Step 5: Onset-based transitions with minimum hold ───────────────── active_zone = raw_states[0][1] active_panel = raw_states[0][2] last_switch_t = 0.0 transitions: list[tuple[float, int, bool]] = [(0.0, active_zone, active_panel)] for i in range(ONSET_FRAMES - 1, len(raw_states)): t, z, is_panel = raw_states[i] if is_panel != active_panel: transitions.append((t, z, is_panel)) active_zone = z active_panel = is_panel last_switch_t = t continue if not is_panel: continue if z == active_zone: continue # Need ONSET_FRAMES consecutive frames in the new zone if not all(raw_states[i - j][1] == z and raw_states[i - j][2] for j in range(ONSET_FRAMES)): continue # Do not cut to a panel where the face is not visibly usable during # the onset. This catches "looking down but moving" false positives. if visible_ratio(i, z, ONSET_FRAMES) < 0.35: continue # Enforce minimum hold if t - last_switch_t < MIN_HOLD: continue # Transition detected — backdate to onset start onset_t = raw_states[i - ONSET_FRAMES + 1][0] transitions.append((onset_t, z, True)) active_zone = z last_switch_t = t # ── Step 6: Build crop segments from transitions ────────────────────── segments: list[dict] = [] for i, (t_start, z, is_panel) in enumerate(transitions): t_end = transitions[i + 1][0] if i + 1 < len(transitions) else duration if is_panel: crop = zone_to_crop(z) layout = "panel" else: start_idx = max(0, int(t_start * FPS)) end_idx = min(len(frame_files) - 1, max(start_idx, int(t_end * FPS))) span = max(1, end_idx - start_idx) sample_closeup_indices = [ min(len(frame_files) - 1, start_idx + int(span * p)) for p in (0.25, 0.5, 0.75) ] crop = _safe_closeup_crop( frame_files, sample_closeup_indices, face_cascade, src_w, src_h, crop_w, crop_h, ) layout = "closeup" segments.append({ "t_start": round(t_start, 1), "t_end": round(t_end, 1), "layout": layout, **crop, }) if not segments: return None segments[0]["t_start"] = 0.0 segments[-1]["t_end"] = duration # Bridge short false-positive islands between two chunks of the same # speaker. A quiet panel can spike briefly from a head/hand movement; # if the crop immediately returns to the same journalist, keep the shot # stable instead of cutting away for a few seconds. SHORT_ISLAND = 5.0 bridged: list[dict] = [] i = 0 while i < len(segments): if 0 < i < len(segments) - 1 and bridged: cur = segments[i] nxt = segments[i + 1] prev = bridged[-1] same_surrounding_crop = ( prev["x"] == nxt["x"] and prev["y"] == nxt["y"] and prev["w"] == nxt["w"] and prev["h"] == nxt["h"] ) if same_surrounding_crop and cur["t_end"] - cur["t_start"] <= SHORT_ISLAND: prev["t_end"] = nxt["t_end"] i += 2 continue bridged.append(dict(segments[i])) i += 1 segments = bridged # Merge adjacent same-zone segments (safety net) merged = [dict(segments[0])] for seg in segments[1:]: if seg["x"] == merged[-1]["x"] and seg["y"] == merged[-1]["y"]: merged[-1]["t_end"] = seg["t_end"] else: merged.append(dict(seg)) merged[-1]["t_end"] = duration # Print detected timeline for debug zone_names = ["izq", "ctr", "der"] print(f" → {len(merged)} segmentos, crop_w={crop_w}px:") for s in merged: if s.get("layout") == "closeup": label = "primer-plano" else: zi = zone_centers.index( min(zone_centers, key=lambda c: abs(c - (s['x'] + crop_w // 2))) ) label = zone_names[zi] print(f" {s['t_start']:.1f}s → {s['t_end']:.1f}s {label} (x={s['x']})") return merged def zoom_plan_path_for_output(output_path: Path) -> Path: return output_path.with_suffix(".zoom.json") def _zoom_plan_matches(plan: dict, raw_clip: Path) -> bool: try: return ( int(plan.get("version", 0)) == 1 and int(plan.get("raw_mtime", -1)) == int(raw_clip.stat().st_mtime) and int(plan.get("raw_size", -1)) == int(raw_clip.stat().st_size) and isinstance(plan.get("segments"), list) and bool(plan["segments"]) ) except OSError: return False def load_zoom_plan(plan_path: Path, raw_clip: Path) -> list[dict] | None: if not plan_path.exists(): return None try: plan = json.loads(plan_path.read_text(encoding="utf-8")) except Exception: return None if not _zoom_plan_matches(plan, raw_clip): return None return normalize_zoom_segments(plan["segments"]) def save_zoom_plan(plan_path: Path, raw_clip: Path, segments: list[dict]) -> None: segments = normalize_zoom_segments(segments) plan_path.parent.mkdir(parents=True, exist_ok=True) payload = { "version": 1, "raw": raw_clip.name, "raw_mtime": int(raw_clip.stat().st_mtime), "raw_size": int(raw_clip.stat().st_size), "segments": segments, } plan_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") def same_zoom_crop(a: dict, b: dict) -> bool: return all(a.get(key) == b.get(key) for key in ("x", "y", "w", "h")) def normalize_zoom_segments(segments: list[dict]) -> list[dict]: """Remove tiny focus jumps before rendering dynamic speaker crops.""" cleaned = [dict(seg) for seg in segments if float(seg.get("t_end", 0)) > float(seg.get("t_start", 0))] if not cleaned: return [] cleaned.sort(key=lambda seg: float(seg["t_start"])) cleaned[0]["t_start"] = 0.0 # Bridge short false-positive islands when the crop returns to the same # journalist immediately after the blip. bridged: list[dict] = [] i = 0 while i < len(cleaned): if 0 < i < len(cleaned) - 1 and bridged: cur = cleaned[i] nxt = cleaned[i + 1] prev = bridged[-1] cur_len = float(cur["t_end"]) - float(cur["t_start"]) if same_zoom_crop(prev, nxt) and cur_len <= 1.25: prev["t_end"] = nxt["t_end"] i += 2 continue bridged.append(dict(cleaned[i])) i += 1 # Remove near-zero cuts even when they are not surrounded by the same crop. merged: list[dict] = [] for seg in bridged: seg_len = float(seg["t_end"]) - float(seg["t_start"]) if merged and same_zoom_crop(merged[-1], seg): merged[-1]["t_end"] = seg["t_end"] continue if merged and seg_len <= 0.75: merged[-1]["t_end"] = seg["t_end"] continue merged.append(dict(seg)) if len(merged) > 1 and float(merged[-1]["t_end"]) - float(merged[-1]["t_start"]) <= 0.75: merged[-2]["t_end"] = merged[-1]["t_end"] merged.pop() for prev, nxt in zip(merged, merged[1:]): nxt["t_start"] = prev["t_end"] return merged def encode_vertical_dynamic_zoom_from_segments( raw_clip: Path, ass_path: Path, output_path: Path, segments: list[dict], ) -> None: """Encode a vertical clip using a previously detected crop timeline.""" segments = normalize_zoom_segments(segments) print(f" → Reutilizando {len(segments)} plano(s) de encuadre guardados") with tempfile.TemporaryDirectory() as tmp: tmp_ass = Path(tmp) / "sub.ass" shutil.copy(ass_path, tmp_ass) esc = str(tmp_ass).replace("\\", "/").replace(":", r"\:") n = len(segments) # 1) Split input video into n copies split_out = "".join(f"[v{i}]" for i in range(n)) split_part = f"[0:v]split={n}{split_out}" # 2) Trim + crop + scale each copy seg_parts = [] dims = probe_video_dimensions(raw_clip) if dims: segments = [sanitize_dynamic_crop(seg, dims[0], dims[1]) for seg in segments] for i, seg in enumerate(segments): t0 = f"{seg['t_start']:.3f}" t1 = f"{seg['t_end']:.3f}" x, y, w, h = seg["x"], seg["y"], seg["w"], seg["h"] seg_parts.append( f"[v{i}]trim={t0}:{t1},setpts=PTS-STARTPTS," f"crop={w}:{h}:{x}:{y}," f"scale=1080:1920:force_original_aspect_ratio=increase:flags=lanczos," f"crop=1080:1920,setsar=1[s{i}]" ) # 3) Concat segments + normalise timestamps once + branding + burn subtitles fps_part = "[vc_raw]fps=fps=60000/1001[vc]" concat_in = "".join(f"[s{i}]" for i in range(n)) concat_part = f"{concat_in}concat=n={n}:v=1:a=0[vc_raw]" logo_path = pyd_logo_path() video_label = "vc" post_parts: list[str] = [] video_label = add_video_polish_filter(post_parts, video_label, "vc_polished") if logo_path: video_label = add_pyd_logo_filter(post_parts, video_label, 1, "branded", vertical=True) post_parts.append(f"[{video_label}]subtitles={esc}[vout]") audio_label = add_audio_polish_filter(post_parts, raw_clip) filter_complex = ( split_part + ";" + ";".join(seg_parts) + ";" + concat_part + ";" + fps_part + ";" + ";".join(post_parts) ) map_args = media_map_args(audio_label) run([ FFMPEG_BIN, "-y", "-i", str(raw_clip), *(["-i", str(logo_path)] if logo_path else []), "-filter_complex", filter_complex, *map_args, "-c:v", "libx264", "-preset", VIDEO_PRESET, "-crf", VIDEO_CRF, "-c:a", "aac", "-b:a", AUDIO_BITRATE, "-movflags", "+faststart", str(output_path), ]) def encode_vertical_dynamic_zoom( raw_clip: Path, ass_path: Path, output_path: Path, *, reuse_zoom_plan: bool = False, zoom_plan_path: Path | None = None, ) -> None: """ Produce 1080×1920 (9:16) clip with dynamic per-speaker zoom. Detects camera cuts + active speaker (mouth motion) to apply a different 9:16 crop for each segment. The audio stream is passed through unchanged. Falls back to static zoom → blurred background if detection yields nothing. ffmpeg strategy: split → N copies of the input video each copy: trim to segment timestamps, reset PTS, crop to speaker, scale to 1080×1920 concat → single continuous video stream subtitles → burned on top """ zoom_plan_path = zoom_plan_path or zoom_plan_path_for_output(output_path) if is_guest_interview_clip(raw_clip): try: zoom_plan_path.unlink() except FileNotFoundError: pass print(" → Layout con paneles chicos detectado; uso composición especial") encode_vertical_interview_layout(raw_clip, ass_path, output_path) return if reuse_zoom_plan: cached_segments = load_zoom_plan(zoom_plan_path, raw_clip) if cached_segments: try: encode_vertical_dynamic_zoom_from_segments(raw_clip, ass_path, output_path, cached_segments) return except (Exception, SystemExit) as exc: print(f" → El plan de encuadre guardado falló ({exc}); recalculando encuadre…") try: output_path.unlink() except FileNotFoundError: pass print(" → Detectando planos y speakers dinámicos…") segments = detect_active_speaker_timeline(raw_clip) if not segments: print(" → Sin cambios de plano detectados → zoom estático") encode_vertical_zoom(raw_clip, ass_path, output_path) return print(f" → {len(segments)} plano(s) con zoom dinámico:") for seg in segments: print(f" {seg['t_start']:.1f}s–{seg['t_end']:.1f}s " f"crop {seg['w']}×{seg['h']} @ ({seg['x']},{seg['y']})") save_zoom_plan(zoom_plan_path, raw_clip, segments) encode_vertical_dynamic_zoom_from_segments(raw_clip, ass_path, output_path, segments) def encode_horizontal(raw_clip: Path, ass_path: Path, output_path: Path, zoom: bool = False) -> None: """ Produce 1920×1080 (16:9) clip — full frame, no speaker crop. For a multi-person panel the 16:9 source already frames the scene correctly. Any crop narrow enough to show one person destroys the 16:9 aspect or bleeds into the adjacent person. The per-speaker zoom lives in the 9:16 version. The zoom parameter is accepted for API compatibility but intentionally unused. """ with tempfile.TemporaryDirectory() as tmp: tmp_ass = Path(tmp) / "sub.ass" shutil.copy(ass_path, tmp_ass) esc = str(tmp_ass).replace("\\", "/").replace(":", r"\:") logo_path = pyd_logo_path() logo_input = ["-i", str(logo_path)] if logo_path else [] parts = [ "[0:v]scale=1920:1080:force_original_aspect_ratio=decrease:flags=lanczos," "pad=1920:1080:(ow-iw)/2:(oh-ih)/2:black[base]" ] video_label = "base" video_label = add_video_polish_filter(parts, video_label, "polished") if logo_path: video_label = add_pyd_logo_filter(parts, video_label, 1, "branded", vertical=False) parts.append(f"[{video_label}]subtitles={esc}[vout]") audio_label = add_audio_polish_filter(parts, raw_clip) filter_complex = ";".join(parts) map_args = media_map_args(audio_label) run([ FFMPEG_BIN, "-y", "-i", str(raw_clip), *logo_input, "-filter_complex", filter_complex, *map_args, "-c:v", "libx264", "-preset", VIDEO_PRESET, "-crf", VIDEO_CRF, "-c:a", "aac", "-b:a", AUDIO_BITRATE, "-movflags", "+faststart", str(output_path), ]) # --------------------------------------------------------------------------- # Main orchestrator # --------------------------------------------------------------------------- def download_direct_video(video_url: str, output_dir: Path) -> Path: """Download a specific YouTube video by URL (supports watch?v=... and timestamps).""" print("\n[1/6] Downloading video…") # Extract clean video ID (strip timestamp params) match = re.search(r"(?:v=|youtu\.be/|/live/)([A-Za-z0-9_-]{11})", video_url) if not match: print("[ERROR] Could not extract video ID from URL", file=sys.stderr) sys.exit(1) video_id = match.group(1) clean_url = f"https://www.youtube.com/watch?v={video_id}" # Get title for logging result = run([*ytdlp_hq_cmd(), "--print", "%(title)s", clean_url], check=False) title = result.stdout.strip().split("\n")[0] if result.returncode == 0 else video_id print(f" → Video: [{video_id}] {title}") video_path = output_dir / f"{video_id}.mp4" if video_path.exists(): print(f" → Already downloaded, skipping.") return video_path run([ *ytdlp_hq_cmd(), "-f", YOUTUBE_HQ_FORMAT, "--merge-output-format", "mp4", "--concurrent-fragments", "8", "--retries", "infinite", "--fragment-retries", "infinite", "--retry-sleep", "fragment:exp=1:30", "--write-info-json", "-o", str(video_path), clean_url, ]) return video_path def main() -> None: parser = argparse.ArgumentParser( description="Clipper automático de livestreams de Peñarol para redes sociales", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Ejemplos: # Video directo: python clip_workflow.py --video "https://www.youtube.com/watch?v=yhgEBROpRiA" # Último stream del canal: python clip_workflow.py --channel "https://www.youtube.com/@TuCanal" # Con opciones: python clip_workflow.py --video "https://www.youtube.com/watch?v=..." --clips 5 --whisper-model turbo """, ) group = parser.add_mutually_exclusive_group(required=True) group.add_argument("--channel", help="URL del canal de YouTube (descarga el último stream)") group.add_argument("--video", help="URL directa del video de YouTube") parser.add_argument("--output-dir", default="./clips", help="Carpeta de salida (default: ./clips)") parser.add_argument("--clips", type=int, default=10, help="Cantidad de clips a generar (default: 10)") parser.add_argument( "--whisper-model", default="turbo", choices=["tiny", "base", "small", "medium", "large", "large-v1", "large-v2", "large-v3", "large-v3-turbo", "turbo"], help="Tamaño del modelo Whisper (default: turbo)", ) parser.add_argument("--force", action="store_true", help="Ignorar caché y reprocesar todo") parser.add_argument("--zoom", action="store_true", help="Aplicar zoom automático al speaker (detección de caras con OpenCV)") parser.add_argument("--horizontal", action="store_true", help="Generar también clips horizontales 16:9 (por defecto solo vertical)") args = parser.parse_args() # Note: ANTHROPIC_API_KEY is only needed for step 4 (moment selection). # If moments.json already exists in output_dir, the API call is skipped. # --- Directory structure --- output_dir = Path(args.output_dir).expanduser().resolve() raw_dir = output_dir / "raw" vertical_dir = output_dir / "vertical_9x16" # TikTok / Instagram Reels horizontal_dir = output_dir / "horizontal_16x9" # YouTube / reposts for d in [output_dir, raw_dir, vertical_dir, horizontal_dir]: d.mkdir(parents=True, exist_ok=True) # Clear cache if --force if args.force: for pattern in ["*.json", "*.wav"]: for f in output_dir.glob(pattern): f.unlink() print(" [force] Cache cleared.") # --- Pipeline --- if args.video: video_path = download_direct_video(args.video, output_dir) else: video_path = download_latest_video(args.channel, output_dir) audio_path = extract_audio(video_path, output_dir) transcript = transcribe_audio(audio_path, output_dir, args.whisper_model) moments = select_moments(transcript, args.clips, output_dir) print(f"\n[5-6/6] Cutting and encoding {len(moments)} clips…") segments = transcript.get("segments", []) for moment in sorted(moments, key=lambda m: m["rank"]): rank = moment["rank"] start = float(moment["start"]) end = float(moment["end"]) title = moment["title"] start = snap_start_to_segment(start, segments) # Safety clamp to the target social duration. snap_end_to_sentence may # extend a few seconds later only when it finds a cleaner ending. if end - start > TARGET_MAX_CLIP_DURATION: end = start + TARGET_MAX_CLIP_DURATION # Snap end to a complete phrase/pause near the selected range. end = snap_end_to_sentence(start, end, segments) end = min(end, start + ABSOLUTE_MAX_CLIP_DURATION) duration = end - start clip_name = f"{rank:02d}_{safe_name(title)}" print(f"\n ── Clip #{rank}: {title} ({duration:.0f}s) ──") raw_path = raw_dir / f"{clip_name}.mp4" ass_v_path = raw_dir / f"{clip_name}_v.ass" ass_h_path = raw_dir / f"{clip_name}_h.ass" v_path = vertical_dir / f"{clip_name}_9x16.mp4" h_path = horizontal_dir / f"{clip_name}_16x9.mp4" raw_changed = not clip_cache_matches(raw_path, video_path, start, end) if raw_changed: cut_clip(video_path, start, end, raw_path) write_clip_cache_meta(raw_path, video_path, start, end) # Generate ASS subtitle files (style embedded, no force_style needed) ass_v_changed = generate_ass(segments, start, end, ass_v_path, play_res_x=1080, play_res_y=1920, font_size=82, margin_v=285) if args.horizontal: ass_h_changed = generate_ass(segments, start, end, ass_h_path, play_res_x=1920, play_res_y=1080, font_size=66, margin_v=100) else: ass_h_changed = False if not v_path.exists() or raw_changed or ass_v_changed: if args.zoom: encode_vertical_dynamic_zoom(raw_path, ass_v_path, v_path) else: encode_vertical(raw_path, ass_v_path, v_path) if args.horizontal and (not h_path.exists() or raw_changed or ass_h_changed): encode_horizontal(raw_path, ass_h_path, h_path, zoom=args.zoom) # --- Summary --- print("\n" + "=" * 65) print(" CLIPS LISTOS PARA PUBLICAR") print("=" * 65) print(f"\n Carpeta base: {output_dir}") print(f" raw/ → cortes crudos (sin subtítulos)") print(f" vertical_9x16/ → TikTok / Instagram Reels (1080×1920)") print(f" horizontal_16x9/ → YouTube (1920×1080)") print(f"\n Momentos seleccionados:") for m in sorted(moments, key=lambda x: x["rank"]): dur = float(m["end"]) - float(m["start"]) print(f" #{m['rank']:2d} ({dur:.0f}s) {m['title']}") print(f" {m['reason']}") print(f"\n ✅ {len(moments)} clips generados. ¡A publicar!") if __name__ == "__main__": main()