#!/usr/bin/env python3 """ nexus/whisper_timecode.py — AUDIO = SOURCE OF TRUTH (v2 sync-correct). 1) faster-whisper word-level timestamps (true sync — matches the actual voice). 2) SILENCE-ALIGNED fallback: detects real pauses in the audio via ffmpeg silencedetect and aligns sentence boundaries to those pauses, then distributes words inside each sentence — subs now MATCH the voice even with expressive pauses / speed changes (flat WPM was the drift bug). 3) last resort: flat WPM (only if even silencedetect fails). """ from __future__ import annotations import json import re from pathlib import Path from typing import Optional from .config import load_settings from .utils import atomic_write_json, ffprobe_duration, log, run_cmd try: from faster_whisper import WhisperModel _WHISPER = None WHISPER_AVAILABLE = True except Exception: # noqa: BLE001 WHISPER_AVAILABLE = False def _get_model(): global _WHISPER if _WHISPER is None: _WHISPER = WhisperModel("base", device="cpu", compute_type="int8") return _WHISPER def transcribe(audio_path: Path, kind: str = "short", script_text: Optional[str] = None) -> dict: """ Returns {'words': [{word,start,end,conf}], 'segments': [...], 'engine': str, 'duration': float, 'text': str} """ audio_path = Path(audio_path) dur = ffprobe_duration(audio_path) or 0.0 # 1) faster-whisper — TRUE sync if WHISPER_AVAILABLE: try: model = _get_model() segs, info = model.transcribe(str(audio_path), word_timestamps=True, vad_filter=False) words = [] segments = [] for seg in segs: for w in (seg.words or []): if (w.end - w.start) < 0.03: continue words.append({"word": w.word.strip(), "start": round(w.start, 3), "end": round(w.end, 3), "conf": round(w.probability, 3)}) segments.append({"text": seg.text.strip(), "start": round(seg.start, 3), "end": round(seg.end, 3)}) if words: out = {"words": words, "segments": segments, "engine": "faster-whisper", "duration": dur, "text": " ".join(w["word"] for w in words)} _sync_validator(audio_path, words[-1]["end"]) return out except Exception as e: # noqa: BLE001 log.warning("faster-whisper failed (%s) — silence-aligned fallback", str(e)[:120]) # 2) silence-aligned estimate (sync-correct fallback) if script_text: words = _silence_aligned_estimate(audio_path, script_text) if words: log.info("Whisper fallback: silence-aligned (%d words) — sync matched to voice pauses", len(words)) return {"words": words, "segments": [], "engine": "silence-aligned", "duration": dur, "text": script_text} # 3) flat WPM (last resort) text = script_text or _extract_text(audio_path) words = _estimate_words(text, dur) log.info("Whisper last resort: flat WPM (%d words)", len(words)) return {"words": words, "segments": [], "engine": "wpm-estimate", "duration": dur, "text": text} # ─────────────────────── silence-aligned fallback ───────────────── def _silence_gaps(audio_path: Path, noise_db: float = -32.0, min_gap: float = 0.22) -> list: """Detect silence intervals with ffmpeg silencedetect.""" try: p = run_cmd(["ffmpeg", "-hide_banner", "-i", str(audio_path), "-af", "silencedetect=noise=%fdB:d=%f" % (noise_db, min_gap), "-f", "null", "-"], timeout=120) out = (p.stdout or "") + (p.stderr or "") starts = [float(m) for m in re.findall(r"silence_start: ([\d.]+)", out)] ends = [float(m) for m in re.findall(r"silence_end: ([\d.]+)", out)] gaps = [] for i, s in enumerate(starts): e = ends[i] if i < len(ends) else None gaps.append((s, e if e is not None else s + 0.4)) return gaps except Exception as e: # noqa: BLE001 log.debug("silencedetect failed: %s", str(e)[:100]) return [] def _silence_aligned_estimate(audio_path: Path, text: str) -> list: """Align sentence boundaries to real audio pauses, WPM inside sentences.""" dur = ffprobe_duration(audio_path) or 0.0 if dur <= 0: return [] sentences = [s.strip() for s in re.split(r"(?<=[.!?])\s+", text.strip()) if s.strip()] if not sentences: return [] gaps = _silence_gaps(audio_path) # sentence start times: prefer after a detected pause (speech resumes post-pause) starts = [] cursor = 0.0 for si, s in enumerate(sentences): # find next gap that starts after cursor t = cursor for (gs, ge) in gaps: if gs >= cursor - 0.05: t = ge + 0.06 # speech resumes slightly after silence end break starts.append(t) # estimate this sentence's duration by its word count nw = len(s.split()) dur_s = nw * (60.0 / 155.0) # slightly slower than 150wpm baseline cursor = t + dur_s # clamp to audio duration total_est = starts[-1] + len(sentences[-1].split()) * (60.0 / 155.0) scale = dur / max(total_est, 0.5) starts = [s * scale for s in starts] words = [] wpm = 155.0 for si, s in enumerate(sentences): toks = s.split() seg_start = starts[si] seg_end = (starts[si + 1] if si + 1 < len(starts) else dur) span = max(seg_end - seg_start, len(toks) * 0.08) per = span / max(len(toks), 1) t = seg_start for tok in toks: words.append({"word": tok, "start": round(t, 3), "end": round(min(t + per, dur), 3), "conf": 0.5}) t += per if words: _sync_validator(audio_path, words[-1]["end"]) return words # ─────────────────────── plain helpers ──────────────────────────── def _extract_text(audio_path: Path) -> str: side = Path(audio_path).with_suffix(".txt") if side.exists(): try: return side.read_text(encoding="utf-8", errors="ignore").strip() except OSError: pass return "" def _estimate_words(text: str, duration: float) -> list: tokens = re.findall(r"\S+", text) if not tokens or duration <= 0: return [] wpm = 150.0 per_word = 60.0 / wpm words = [] t = 0.0 for tok in tokens: words.append({"word": tok, "start": round(t, 3), "end": round(t + per_word, 3), "conf": 0.5}) t += per_word return words def _sync_validator(audio_path: Path, last_end: float) -> None: dur = ffprobe_duration(audio_path) or 0.0 delta = abs(dur - last_end) if delta > 0.8: log.warning("Sync check: end %.2fs vs ffprobe %.2fs (delta %.2fs)", last_end, dur, delta) else: log.info("Sync check: timecodes end %.2fs vs audio %.2fs (delta %.2fs) ✅", last_end, dur, delta) def save_timecodes(words: list, out_path: Path) -> None: atomic_write_json(out_path, {"words": words, "engine": "whisper", "generated": __import__("time").strftime("%Y-%m-%dT%H:%M:%SZ", __import__("time").gmtime())}) def load_timecodes(path: Path) -> Optional[dict]: from .utils import read_json return read_json(path)