diff --git a/backend/cli.py b/backend/cli.py index cf1c828..5ff373b 100644 --- a/backend/cli.py +++ b/backend/cli.py @@ -91,6 +91,52 @@ def _use_color(stream=None) -> bool: return hasattr(stream, "isatty") and stream.isatty() +def _yellow(text: str) -> str: + if not _use_color(): + return text + return f"\033[38;2;250;204;21m{text}\033[0m" + + +_WHISPERCPP_SPEAKERS_NOTE = ( + "Speaker detection needs the whisper-py engine plus HF_TOKEN. " + "Crop will use face tracking." +) + + +def _diarization_notice_lines(result: dict, no_speakers: bool) -> list[str]: + from services.transcription import DIARIZATION_DISABLED_WARNING + + if no_speakers: + return [] + if result.get("engine") == "whispercpp": + return [_WHISPERCPP_SPEAKERS_NOTE] + warning = result.get("diarization_warning") + if not warning or warning == DIARIZATION_DISABLED_WARNING: + return [] + return [line.rstrip() for line in str(warning).splitlines() if line.strip()] + + +def _print_diarization_notice(result: dict, no_speakers: bool) -> None: + for i, line in enumerate(_diarization_notice_lines(result, no_speakers)): + prefix = " ⚠ " if i == 0 else " " + print(_yellow(f"{prefix}{line}")) + + +def _crop_strategy_summary(results: list, requested: str) -> str | None: + counts: dict[str, int] = {} + for result in results: + used = result.get("crop_strategy_used") if isinstance(result, dict) else None + if used: + counts[used] = counts.get(used, 0) + 1 + if not counts: + return None + ordered = sorted(counts.items(), key=lambda item: (-item[1], item[0])) + line = "Crop used: " + ", ".join(f"{n} {name}" for name, n in ordered) + if "center" in counts and requested != "center": + return _yellow(line) + return line + + def _want_spinner() -> bool: if os.environ.get("NO_COLOR") or os.environ.get("PODCLI_QUIET"): return False @@ -1540,6 +1586,7 @@ def cmd_process(args): segments = cached["segments"] result = cached print(f" {len(segments)} segments, {len(words)} words") + _print_diarization_notice(result, config.get("no_speakers", False)) else: from services.engines import is_assemblyai_engine, normalize_engine engine_label = "AssemblyAI" if is_assemblyai_engine(os.environ.get("PODCLI_ENGINE", "")) else "Whisper" @@ -1601,6 +1648,7 @@ def _transcribe_progress(pct, msg): words = result["words"] segments = result["segments"] print(f" Done: {len(segments)} segments, {len(words)} words") + _print_diarization_notice(result, config.get("no_speakers", False)) save_cached_transcript_for_video( video_path, @@ -1658,9 +1706,6 @@ def _transcribe_progress(pct, msg): # Check speaker data availability (needed for smart cropping) speakers_in_words = set(w.get("speaker") for w in words if w.get("speaker")) - diarization_warning = result.get("diarization_warning") - if diarization_warning: - print(f" ⚠ {diarization_warning}") if len(speakers_in_words) > 1: print(f" Speakers detected: {len(speakers_in_words)} (crop will follow active speaker)") elif len(speakers_in_words) == 1: @@ -2203,6 +2248,9 @@ def _transcribe_progress(pct, msg): print(f"\n Interrupted with {success}/{len(clips)} completed clips in {elapsed:.1f}s") else: print(f"\n {success}/{len(clips)} clips exported in {elapsed:.1f}s") + crop_summary = _crop_strategy_summary(results, config.get("crop_strategy", "face")) + if crop_summary: + print(f" {crop_summary}") if _thumb_enabled: print(f" Thumbnails saved to {thumb_dir}/") diff --git a/backend/services/clip_generator.py b/backend/services/clip_generator.py index 6335ebd..fcff911 100644 --- a/backend/services/clip_generator.py +++ b/backend/services/clip_generator.py @@ -63,6 +63,69 @@ _SCENE_TIME_RE = re.compile(r"pts_time:([0-9]+(?:\.[0-9]+)?)") +_SENTENCE_ENDINGS = ".!?" +_SENTENCE_PAUSE = 0.6 +_START_PAD = 0.08 +_END_PAD = 0.15 + + +def _ends_sentence(word: dict) -> bool: + text = str(word.get("word", "")).strip().rstrip("\"')]}") + return bool(text) and text[-1] in _SENTENCE_ENDINGS + + +def _speaker_changed(a: dict, b: dict) -> bool: + return a.get("speaker") is not None and b.get("speaker") is not None and a.get("speaker") != b.get("speaker") + + +def _starts_sentence(ordered: list[dict], idx: int) -> bool: + if idx == 0: + return True + prev, word = ordered[idx - 1], ordered[idx] + return ( + _ends_sentence(prev) + or word["start"] - prev["end"] > _SENTENCE_PAUSE + or _speaker_changed(prev, word) + ) + + +def _snap_to_sentence_start( + transcript_words: list[dict], start_second: float, end_second: float, + max_back: float = 6.0, max_forward: float = 3.0, +) -> float: + ordered = sorted(transcript_words, key=lambda w: w["start"]) + first_idx = next( + (i for i, w in enumerate(ordered) if w["end"] > start_second and w["start"] < end_second), + None, + ) + if first_idx is None: + return start_second + + first = ordered[first_idx] + if _starts_sentence(ordered, first_idx): + if first["start"] >= start_second: + return start_second + return max(0.0, round(first["start"] - _START_PAD, 3)) + + for idx in range(first_idx - 1, -1, -1): + word = ordered[idx] + if word["start"] < start_second - max_back or _speaker_changed(word, first): + break + if _starts_sentence(ordered, idx): + return max(0.0, round(word["start"] - _START_PAD, 3)) + + for idx in range(first_idx + 1, len(ordered)): + word = ordered[idx] + if word["start"] > start_second + max_forward or word["start"] >= end_second - 0.5: + break + if _speaker_changed(first, word): + break + if _starts_sentence(ordered, idx): + return max(0.0, round(word["start"] - _START_PAD, 3)) + + return start_second + + def _trim_weak_opening( words: list[dict], start_second: float, @@ -422,35 +485,35 @@ def _auto_fix_transition_jumps( def _snap_to_sentence_end( transcript_words: list[dict], start_second: float, end_second: float, - max_extension: float = 3.0, + max_extension: float = 5.0, ) -> float: """Snap clip end_second forward to the nearest sentence boundary. - Forward-only. Stops at speaker changes to avoid bleeding into a reply. + Forward-only. A sentence-ending mark or a pause longer than 0.6s counts as + a boundary. Stops at speaker changes to avoid bleeding into a reply. """ - SENTENCE_ENDINGS = ".!?" - - clip_words = [w for w in transcript_words if w["end"] > start_second and w["start"] < end_second] + ordered = sorted(transcript_words, key=lambda x: x["start"]) + clip_words = [w for w in ordered if w["end"] > start_second and w["start"] < end_second] if not clip_words: return end_second last_clip_word = clip_words[-1] - last_word_text = last_clip_word.get("word", "").strip() - last_speaker = last_clip_word.get("speaker") - - if last_word_text and last_word_text[-1] in SENTENCE_ENDINGS: - return max(end_second, last_clip_word["end"]) + if _ends_sentence(last_clip_word): + return max(end_second, last_clip_word["end"] + _END_PAD) - for w in sorted(transcript_words, key=lambda x: x["start"]): + prev = last_clip_word + for w in ordered: if w["start"] < last_clip_word["end"]: continue if w["end"] > end_second + max_extension: break - if last_speaker is not None and w.get("speaker") is not None and w.get("speaker") != last_speaker: + if w["start"] - prev["end"] > _SENTENCE_PAUSE: + return max(end_second, prev["end"] + _END_PAD) + if _speaker_changed(last_clip_word, w): break - text = w.get("word", "").strip() - if text and text[-1] in SENTENCE_ENDINGS: - return w["end"] + if _ends_sentence(w): + return w["end"] + _END_PAD + prev = w return end_second @@ -1021,6 +1084,7 @@ def generate_clip( progress_callback=progress_callback, ) + snap_start = trim_opening is not False if trim_opening is None: trim_opening = not (keep_segments and len(keep_segments) > 0) @@ -1041,6 +1105,15 @@ def generate_clip( keep_segments = [s for s in keep_segments if s["end"] > s["start"]] keep_segments.sort(key=lambda s: s["start"]) + if snap_start and transcript_words: + snapped_start = _snap_to_sentence_start( + transcript_words, + keep_segments[0]["start"], + keep_segments[0]["end"], + ) + if snapped_start < keep_segments[0]["end"] - 0.5: + keep_segments[0]["start"] = snapped_start + if trim_opening and transcript_words: trimmed_start = _trim_weak_opening( transcript_words, @@ -1059,6 +1132,9 @@ def generate_clip( if snapped_end > keep_segments[-1]["end"]: keep_segments[-1]["end"] = snapped_end + end_second, keep_segments = _bound_range_to_source( + keep_segments[0]["start"], keep_segments[-1]["end"], keep_segments, source_duration + ) start_second = keep_segments[0]["start"] end_second = keep_segments[-1]["end"] @@ -1073,11 +1149,15 @@ def generate_clip( duration = sum(s["end"] - s["start"] for s in keep_segments) else: + if snap_start and transcript_words: + start_second = _snap_to_sentence_start(transcript_words, start_second, end_second) + if trim_opening and transcript_words: start_second = _trim_weak_opening(transcript_words, start_second, end_second) if transcript_words: end_second = _snap_to_sentence_end(transcript_words, start_second, end_second) + end_second, _ = _bound_range_to_source(start_second, end_second, None, source_duration) # Auto-build tight segments: cut long pauses and isolated fillers if transcript_words and clean_fillers: @@ -1219,6 +1299,7 @@ def generate_clip( ) if crop_keyframes else crop_keyframes cropped_path = os.path.join(work_dir, "cropped.mp4") + crop_report: dict = {} with timed("render", "crop", strategy=crop_strategy if spec.reframe else "fit"): if spec.reframe: crop_to_vertical( @@ -1229,9 +1310,11 @@ def generate_clip( face_map=face_map, crop_keyframes=playback_keyframes, target_dims=spec.dims, + report=crop_report, ) else: fit_to_frame(segment_path, cropped_path, target_dims=spec.dims) + crop_report["strategy_used"] = "fit" # Only Remotion draws the name card, and --fast forces the ASS renderer, # which cannot. Refusing beats returning a clip that quietly lacks the @@ -1607,6 +1690,7 @@ def generate_clip( "end_second": end_second, "caption_style": caption_style, "crop_strategy": crop_strategy, + "crop_strategy_used": crop_report.get("strategy_used"), "format": spec.name, **sidecar_paths, } diff --git a/backend/services/speaker_detection.py b/backend/services/speaker_detection.py index 2cf7694..34a7f08 100644 --- a/backend/services/speaker_detection.py +++ b/backend/services/speaker_detection.py @@ -118,15 +118,15 @@ def run_diarization( if not token: msg = ( - "HF_TOKEN not set: speaker detection requires a HuggingFace token.\n" + "HF_TOKEN not set, so speakers are not detected. Fix: podcli env set HF_TOKEN hf_...\n" "\n" " Setup (one-time):\n" " 1. Create a token at https://huggingface.co/settings/tokens\n" - " 2. Accept model terms at ALL THREE:\n" + " 2. Accept model terms at all three:\n" " → https://huggingface.co/pyannote/speaker-diarization-3.1\n" " → https://huggingface.co/pyannote/segmentation-3.0\n" " → https://huggingface.co/pyannote/speaker-diarization-community-1\n" - " 3. Set it: podcli env set HF_TOKEN hf_your_token_here\n" + " 3. Set it: podcli env set HF_TOKEN hf_...\n" " (or in the Web UI: Config → Secrets)" ) if progress_callback: diff --git a/backend/services/transcription.py b/backend/services/transcription.py index 1c55cb9..68d27eb 100644 --- a/backend/services/transcription.py +++ b/backend/services/transcription.py @@ -54,6 +54,8 @@ def _whispercpp_cli() -> Optional[str]: +DIARIZATION_DISABLED_WARNING = "Speaker detection disabled" + # "large" alone doesn't name a real ggml file (upstream ships v1/v2/v3/v3-turbo # builds); provisioning always fetches large-v3, so resolve the same way here. _WHISPERCPP_MODEL_ALIASES = {"large": "large-v3"} @@ -619,7 +621,7 @@ def _attach_speakers_and_faces( progress_callback(90, diarization_warning) else: if not speaker_segments: - diarization_warning = "Speaker detection disabled" + diarization_warning = DIARIZATION_DISABLED_WARNING face_map = None try: diff --git a/backend/services/video_processor.py b/backend/services/video_processor.py index b5f57eb..4524910 100644 --- a/backend/services/video_processor.py +++ b/backend/services/video_processor.py @@ -233,6 +233,7 @@ def crop_to_vertical( face_map: dict = None, crop_keyframes: list = None, target_dims: tuple = (1080, 1920), + report: Optional[dict] = None, ) -> str: """ Crop/scale video to 1080x1920 (9:16 vertical). @@ -248,8 +249,16 @@ def crop_to_vertical( transcript_words: Word dicts with 'speaker', 'start', 'end' keys (from Whisper+pyannote). Used by 'face' strategy when speaker data is available. clip_start: The start time of this clip in the original video (for timestamp alignment). + report: When a dict is passed, report["strategy_used"] is set to the strategy + that produced the frame: manual, speaker-hardcut, speaker, face or center. + A face or speaker request with speaker labels in the clip reports speaker. """ width, height = get_dimensions(input_path) + + def used(name: str) -> None: + if report is not None: + report["strategy_used"] = name + # What the caller asked for, kept because `strategy` is reassigned on the # way down the ladder. A clip that asked to follow the speaker and ended up # letterboxed should say so in those words, not report a centre crop as @@ -277,6 +286,7 @@ def crop_to_vertical( crop_y = max(0, (height - crop_h) // 2) x_expr = _manual_crop_x_expr(crop_keyframes, crop_w, width) vf = f"crop={crop_w}:{crop_h}:x='{x_expr}':y={crop_y},scale={target_w}:{target_h}" + used("manual") return _run_ffmpeg_with_fallback( cmd_parts_before_enc=["ffmpeg", "-y", "-i", input_path, "-vf", vf], cmd_parts_after_enc=["-c:a", "aac", "-b:a", "192k", "-ar", "44100", "-movflags", "+faststart"], @@ -302,6 +312,7 @@ def crop_to_vertical( crop_w = int(crop_h * target_ratio) crop_w = min(crop_w, width) vf = f"crop={crop_w}:{crop_h}:{x_expr}:{crop_y},scale={target_w}:{target_h}" + used("speaker-hardcut") return _run_ffmpeg_with_fallback( cmd_parts_before_enc=[ "ffmpeg", "-y", @@ -368,6 +379,7 @@ def crop_to_vertical( label="crop_local_reframe", ) if result: + used("speaker") return result log_event("crop", "fallback", reason="local_reframe_ffmpeg_failed") @@ -385,6 +397,7 @@ def crop_to_vertical( ) if result: log_event("crop", "chose=speaker-track", speakers=len(speakers_in_clip)) + used("speaker" if speakers_in_clip else "face") return result log_event("crop", "fallback", reason="speaker_track_failed", speakers=len(speakers_in_clip)) @@ -405,6 +418,7 @@ def crop_to_vertical( crop_w = int(crop_h * target_ratio) crop_w = min(crop_w, width) vf = f"crop={crop_w}:{crop_h}:{x_expr}:{crop_y},scale={target_w}:{target_h}" + used("face") return _run_ffmpeg_with_fallback( cmd_parts_before_enc=[ "ffmpeg", "-y", @@ -429,11 +443,13 @@ def crop_to_vertical( ) if result: log_event("crop", "chose=face-track") + used("face") return result log_event("crop", "fallback", reason="face_track_failed", to="center") strategy = "center" if strategy == "center": + used("center") if source_ratio > target_ratio: log_event("crop", "chose=center-blur-bg", source=f"{width}x{height}", asked=wanted) # The whole wide frame, shrunk into a band with a blur behind it. diff --git a/tests/test_cli.py b/tests/test_cli.py index ddd25b1..1648a80 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1,4 +1,6 @@ import argparse +import contextlib +import io import json import os import sys @@ -66,7 +68,14 @@ def _process_args(video_path, transcript_path, output_dir): class CliTranscriptTests(unittest.TestCase): - def _run_process(self, transcript_text, cached_transcript=None): + def _run_process( + self, + transcript_text, + cached_transcript=None, + use_cache=False, + generated_extra=None, + no_speakers=False, + ): """Run cmd_process with --transcript and return the generate_clip mock.""" clip = { "title": "Test clip", @@ -82,12 +91,17 @@ def _run_process(self, transcript_text, cached_transcript=None): with open(video_path, "wb") as video_file: video_file.write(b"video") with open(transcript_path, "w", encoding="utf-8") as transcript_file: - transcript_file.write(transcript_text) + transcript_file.write(transcript_text or "") generated = { "output_path": os.path.join(output_dir, "test-clip.mp4"), "file_size_mb": 1.0, + **(generated_extra or {}), } + args = _process_args(video_path, None if use_cache else transcript_path, output_dir) + args.no_cache = not use_cache + args.no_speakers = no_speakers + out = io.StringIO() with ( mock.patch.object(cli_mod, "kb_is_empty", return_value=False), @@ -101,6 +115,7 @@ def _run_process(self, transcript_text, cached_transcript=None): "services.claude_suggest._find_ai_cli", return_value=(None, None), ), + mock.patch("services.ai_provider.status", return_value={"providers": []}), mock.patch( "services.transcript_packer.load_cached_transcript_for_video", return_value=cached_transcript, @@ -114,9 +129,14 @@ def _run_process(self, transcript_text, cached_transcript=None): "services.clip_generator.generate_clip", return_value=generated, ) as generate_clip, + mock.patch.dict(os.environ), + contextlib.redirect_stdout(out), ): - cli_mod.cmd_process(_process_args(video_path, transcript_path, output_dir)) + os.environ.pop("NO_COLOR", None) + os.environ.pop("PODCLI_ENGINE", None) + cli_mod.cmd_process(args) + self.stdout = out.getvalue() generate_clip.assert_called_once() return generate_clip @@ -155,6 +175,46 @@ def test_json_transcript_face_map_wins_over_cache(self): self.assertEqual(generate_clip.call_args.kwargs["face_map"], FACE_MAP) + def _cached_whispercpp(self): + return { + "engine": "whispercpp", + "words": [{"word": "hello", "start": 0.0, "end": 0.5, "speaker": None}], + "segments": [{"start": 0.0, "end": 0.5, "text": "hello"}], + "diarization_warning": "Speaker detection disabled", + } + + def test_whispercpp_run_says_speakers_need_whisper_py_and_a_token(self): + self._run_process(None, cached_transcript=self._cached_whispercpp(), use_cache=True) + + note = "Speaker detection needs the whisper-py engine plus HF_TOKEN. Crop will use face tracking." + self.assertEqual(self.stdout.count(note), 1) + self.assertLess(self.stdout.index("1 segments, 1 words"), self.stdout.index(note)) + + def test_whispercpp_run_with_no_speakers_prints_no_note(self): + self._run_process( + None, cached_transcript=self._cached_whispercpp(), use_cache=True, no_speakers=True + ) + + self.assertNotIn("whisper-py engine", self.stdout) + + def test_a_diarization_failure_prints_once_with_the_fix(self): + cached = self._cached_whispercpp() + cached["engine"] = "whisper-py" + cached["diarization_warning"] = ( + "HF_TOKEN not set, so speakers are not detected. Fix: podcli env set HF_TOKEN hf_..." + ) + + self._run_process(None, cached_transcript=cached, use_cache=True) + + self.assertEqual(self.stdout.count("podcli env set HF_TOKEN hf_..."), 1) + + def test_summary_reports_the_crop_strategy_each_clip_used(self): + self._run_process( + SRT, generated_extra={"crop_strategy_used": "speaker"} + ) + + self.assertIn("Crop used: 1 speaker", self.stdout) + if __name__ == "__main__": unittest.main() diff --git a/tests/test_cli_helpers.py b/tests/test_cli_helpers.py index d7afd74..8180a3b 100644 --- a/tests/test_cli_helpers.py +++ b/tests/test_cli_helpers.py @@ -187,3 +187,102 @@ def test_emit_process_json_writes_one_object(self): self.assertEqual(payload["quality"], "high") self.assertEqual(payload["clips"][0]["title"], "A") self.assertEqual(payload["clips"][0]["path"], "/out/a.mp4") + + +class DiarizationNoticeTests(unittest.TestCase): + TOKEN_WARNING = ( + "HF_TOKEN not set, so speakers are not detected. Fix: podcli env set HF_TOKEN hf_...\n" + "\n" + " Setup (one-time):\n" + " 1. Create a token at https://huggingface.co/settings/tokens" + ) + + def _printed(self, result, no_speakers=False, env=None): + import io + from contextlib import redirect_stdout + + buf = io.StringIO() + with mock.patch.dict(os.environ, env or {}), redirect_stdout(buf): + if not env or "NO_COLOR" not in env: + os.environ.pop("NO_COLOR", None) + cli_mod._print_diarization_notice(result, no_speakers) + return buf.getvalue() + + def test_a_failure_warning_prints_on_its_own_line_with_the_fix(self): + out = self._printed({"engine": "whisper-py", "diarization_warning": self.TOKEN_WARNING}) + lines = out.splitlines() + self.assertEqual(lines[0].strip(), "\u26a0 HF_TOKEN not set, so speakers are not detected. Fix: podcli env set HF_TOKEN hf_...") + self.assertIn("Setup (one-time):", out) + self.assertNotIn("\n\n", out) + + def test_the_warning_is_yellow_when_color_is_on(self): + out = self._printed( + {"engine": "whisper-py", "diarization_warning": "Speaker detection failed: boom"}, + env={"FORCE_COLOR": "1"}, + ) + self.assertTrue(out.startswith("\033[38;2;250;204;21m")) + self.assertIn("Speaker detection failed: boom", out) + self.assertTrue(out.rstrip("\n").endswith("\033[0m")) + + def test_no_color_prints_plain_text(self): + out = self._printed( + {"engine": "whisper-py", "diarization_warning": "Speaker detection failed: boom"}, + env={"NO_COLOR": "1", "FORCE_COLOR": "1"}, + ) + self.assertNotIn("\033", out) + self.assertIn("Speaker detection failed: boom", out) + + def test_whispercpp_prints_one_line_about_the_engine_and_face_tracking(self): + out = self._printed({"engine": "whispercpp", "diarization_warning": "Speaker detection disabled"}) + self.assertEqual(len(out.splitlines()), 1) + self.assertIn("whisper-py", out) + self.assertIn("HF_TOKEN", out) + self.assertIn("face tracking", out) + + def test_whispercpp_stays_quiet_when_the_user_passed_no_speakers(self): + out = self._printed({"engine": "whispercpp", "diarization_warning": "Speaker detection disabled"}, no_speakers=True) + self.assertEqual(out, "") + + def test_a_failure_stays_quiet_when_the_user_passed_no_speakers(self): + out = self._printed({"engine": "whisper-py", "diarization_warning": "Speaker detection failed: boom"}, no_speakers=True) + self.assertEqual(out, "") + + def test_the_plain_disabled_marker_is_not_a_warning(self): + self.assertEqual(self._printed({"engine": "assemblyai", "diarization_warning": "Speaker detection disabled"}), "") + + def test_no_warning_prints_nothing(self): + self.assertEqual(self._printed({"engine": "whisper-py"}), "") + + +class CropStrategySummaryTests(unittest.TestCase): + def _summary(self, results, requested="face", env=None): + with mock.patch.dict(os.environ, env or {}): + if not env or "NO_COLOR" not in env: + os.environ.pop("NO_COLOR", None) + return cli_mod._crop_strategy_summary(results, requested) + + def test_counts_each_strategy_most_used_first(self): + results = [ + {"crop_strategy_used": "speaker"}, + {"crop_strategy_used": "center"}, + {"crop_strategy_used": "speaker"}, + {"crop_strategy_used": "face"}, + {"crop_strategy_used": "speaker"}, + ] + self.assertEqual(self._summary(results), "Crop used: 3 speaker, 1 center, 1 face") + + def test_failed_and_unreported_clips_are_skipped(self): + results = [{"status": "error", "error": "boom"}, {"output_path": "a.mp4"}, {"crop_strategy_used": "face"}] + self.assertEqual(self._summary(results), "Crop used: 1 face") + + def test_nothing_reported_means_no_line(self): + self.assertIsNone(self._summary([{"status": "error"}])) + self.assertIsNone(self._summary([])) + + def test_center_fallback_is_yellow_when_another_strategy_was_asked(self): + line = self._summary([{"crop_strategy_used": "center"}], requested="face", env={"FORCE_COLOR": "1"}) + self.assertTrue(line.startswith("\033[38;2;250;204;21m")) + + def test_center_is_plain_when_center_was_asked(self): + line = self._summary([{"crop_strategy_used": "center"}], requested="center", env={"FORCE_COLOR": "1"}) + self.assertEqual(line, "Crop used: 1 center") diff --git a/tests/test_clip_generator.py b/tests/test_clip_generator.py index 21618cc..06efa46 100644 --- a/tests/test_clip_generator.py +++ b/tests/test_clip_generator.py @@ -563,6 +563,213 @@ def test_all_keep_segments_dropped_falls_back_to_none(self): self.assertIsNone(segs) +def _word(text, start, end, speaker=None): + return {"word": text, "start": start, "end": end, "speaker": speaker} + + +def _two_sentences(): + return [ + _word("We", 0.05, 0.3), + _word("went", 0.3, 0.6), + _word("to", 0.6, 0.9), + _word("the", 0.9, 1.2), + _word("store.", 1.2, 1.8), + _word("Then", 2.0, 2.3), + _word("we", 2.3, 2.6), + _word("left", 2.6, 3.0), + _word("early", 3.0, 3.5), + _word("today.", 3.5, 4.0), + ] + + +def _run_on(count, speaker="A"): + return [_word(f"w{i}", i * 0.5, i * 0.5 + 0.5, speaker) for i in range(count)] + + +class SnapToSentenceStartTests(unittest.TestCase): + def test_mid_sentence_start_moves_back_to_the_sentence_start(self): + start = cg._snap_to_sentence_start(_two_sentences(), 2.4, 20.0) + self.assertAlmostEqual(start, 1.92, places=3) + + def test_start_right_after_a_long_pause_stays(self): + words = [ + _word("done.", 9.0, 10.0), + _word("So", 10.8, 11.1), + _word("anyway", 11.1, 11.6), + _word("then", 11.6, 12.0), + ] + self.assertEqual(cg._snap_to_sentence_start(words, 10.8, 20.0), 10.8) + + def test_start_in_the_gap_before_a_sentence_start_stays(self): + self.assertEqual(cg._snap_to_sentence_start(_two_sentences(), 1.9, 20.0), 1.9) + + def test_a_word_straddling_the_start_pulls_it_to_the_word_onset(self): + words = [_word("done.", 0.0, 1.0), _word("Hello", 3.0, 3.6), _word("there", 3.6, 4.0)] + start = cg._snap_to_sentence_start(words, 3.3, 20.0) + self.assertAlmostEqual(start, 2.92, places=3) + + def test_never_returns_below_zero(self): + words = [_word("Hello", 0.05, 0.4), _word("there", 0.4, 0.8), _word("friend", 0.8, 1.2)] + self.assertEqual(cg._snap_to_sentence_start(words, 0.5, 20.0), 0.0) + + def test_search_back_is_capped_at_six_seconds(self): + words = _run_on(20) + self.assertEqual(cg._snap_to_sentence_start(words, 7.1, 20.0), 7.1) + + def test_search_back_finds_a_start_inside_six_seconds(self): + words = _run_on(20) + words[8] = _word("w8.", 4.0, 4.5, "A") + start = cg._snap_to_sentence_start(words, 7.1, 20.0) + self.assertAlmostEqual(start, 4.42, places=3) + + def test_speaker_change_stops_the_forward_search(self): + words = _run_on(20) + [_word("Right.", 10.0, 10.5, "B")] + self.assertEqual(cg._snap_to_sentence_start(words, 7.1, 12.0), 7.1) + + def test_forward_search_finds_a_same_speaker_start(self): + words = _run_on(20) + words[18] = _word("w18.", 9.0, 9.5, "A") + start = cg._snap_to_sentence_start(words, 7.1, 20.0) + self.assertAlmostEqual(start, 9.42, places=3) + + def test_forward_search_is_capped_at_three_seconds(self): + words = _run_on(30) + words[22] = _word("w22.", 11.0, 11.5, "A") + self.assertEqual(cg._snap_to_sentence_start(words, 7.1, 20.0), 7.1) + + def test_forward_search_never_lands_inside_the_last_half_second(self): + words = _run_on(20) + words[18] = _word("w18.", 9.0, 9.5, "A") + self.assertEqual(cg._snap_to_sentence_start(words, 7.1, 9.8), 7.1) + + def test_no_words_in_range_returns_start_unchanged(self): + self.assertEqual(cg._snap_to_sentence_start(_two_sentences(), 50.0, 60.0), 50.0) + + +class SnapToSentenceEndTests(unittest.TestCase): + def test_end_extends_to_the_period_with_a_tail_pad(self): + end = cg._snap_to_sentence_end(_two_sentences(), 0.0, 2.2) + self.assertAlmostEqual(end, 4.15, places=3) + + def test_end_already_on_a_period_gets_the_tail_pad(self): + end = cg._snap_to_sentence_end(_two_sentences(), 0.0, 3.9) + self.assertAlmostEqual(end, 4.15, places=3) + + def test_end_past_the_tail_pad_is_left_alone(self): + end = cg._snap_to_sentence_end(_two_sentences(), 0.0, 4.5) + self.assertEqual(end, 4.5) + + def test_a_pause_over_six_tenths_is_a_boundary(self): + words = [ + _word("so", 4.0, 4.4), + _word("then", 4.4, 5.0), + _word("Next.", 5.9, 6.3), + ] + self.assertAlmostEqual(cg._snap_to_sentence_end(words, 4.0, 4.5), 5.15, places=3) + + def test_a_short_pause_is_not_a_boundary(self): + words = [ + _word("so", 4.0, 4.4), + _word("then", 4.4, 5.0), + _word("next.", 5.4, 5.8), + ] + self.assertAlmostEqual(cg._snap_to_sentence_end(words, 4.0, 4.5), 5.95, places=3) + + def test_extension_reaches_five_seconds_past_the_end(self): + words = _run_on(12) + words[10] = _word("w10.", 5.0, 5.5, "A") + end = cg._snap_to_sentence_end(words, 0.0, 0.5) + self.assertAlmostEqual(end, 5.65, places=3) + + def test_extension_stops_beyond_five_seconds(self): + words = _run_on(14) + words[12] = _word("w12.", 6.0, 6.5, "A") + self.assertEqual(cg._snap_to_sentence_end(words, 0.0, 0.5), 0.5) + + def test_speaker_change_stops_the_extension(self): + words = [ + _word("and", 1.0, 1.3, "A"), + _word("then", 1.3, 1.6, "A"), + _word("ok.", 1.6, 2.0, "B"), + ] + self.assertEqual(cg._snap_to_sentence_end(words, 0.5, 1.4), 1.4) + + def test_no_words_in_range_returns_end_unchanged(self): + self.assertEqual(cg._snap_to_sentence_end(_two_sentences(), 50.0, 60.0), 60.0) + + +class SentenceSnapRangeTests(unittest.TestCase): + def test_a_snapped_end_past_the_source_is_clamped(self): + words = _two_sentences() + end = cg._snap_to_sentence_end(words, 0.0, 2.2) + bounded, _ = cg._bound_range_to_source(0.0, end, None, source_duration=4.05) + self.assertAlmostEqual(end, 4.15, places=3) + self.assertEqual(bounded, 4.05) + + +class SentenceSnapOrderTests(unittest.TestCase): + class _Stop(Exception): + pass + + def _generate(self, **kwargs): + calls = [] + + def recording(name, fn): + def wrapper(*args, **kw): + calls.append(name) + return fn(*args, **kw) + return wrapper + + cut = mock.Mock(side_effect=self._Stop()) + with tempfile.TemporaryDirectory() as td: + video = os.path.join(td, "ep.mp4") + with open(video, "wb") as fh: + fh.write(b"x") + with mock.patch.object(cg, "_get_media_duration", return_value=4.05), \ + mock.patch.object(cg, "probe_has_audio_stream", return_value=True), \ + mock.patch("services.audiogram.is_audio_only", return_value=False), \ + mock.patch.object(cg, "cut_segment", cut), \ + mock.patch.object(cg, "_snap_to_sentence_start", recording("start", cg._snap_to_sentence_start)), \ + mock.patch.object(cg, "_trim_weak_opening", recording("trim", cg._trim_weak_opening)), \ + mock.patch.object(cg, "_snap_to_sentence_end", recording("end", cg._snap_to_sentence_end)): + with self.assertRaises(self._Stop): + cg.generate_clip( + video_path=video, + transcript_words=_two_sentences(), + clean_fillers=False, + output_dir=td, + **kwargs, + ) + return calls, cut + + def test_single_range_snaps_start_then_trims_then_snaps_end(self): + calls, cut = self._generate(start_second=2.4, end_second=3.2, trim_opening=True) + + self.assertEqual(calls, ["start", "trim", "end"]) + args = cut.call_args.args + self.assertAlmostEqual(args[2], 1.92, places=3) + self.assertEqual(args[3], 4.05) + + def test_explicit_trim_opening_false_keeps_the_requested_start(self): + calls, cut = self._generate(start_second=2.4, end_second=3.2, trim_opening=False) + + self.assertEqual(calls, ["end"]) + self.assertEqual(cut.call_args.args[2], 2.4) + + def test_keep_segments_snap_start_then_trim_then_snap_end(self): + calls, cut = self._generate( + start_second=2.4, + end_second=3.2, + keep_segments=[{"start": 2.4, "end": 3.2}], + trim_opening=True, + ) + + self.assertEqual(calls, ["start", "trim", "end"]) + args = cut.call_args.args + self.assertAlmostEqual(args[2], 1.92, places=3) + self.assertEqual(args[3], 4.05) + + @unittest.skipUnless( shutil.which("ffmpeg") and shutil.which("ffprobe"), "ffmpeg/ffprobe not installed" ) @@ -622,6 +829,8 @@ def test_writes_sidecars_and_clean_variant(self): ) self.assertTrue(os.path.exists(result["output_path"])) + self.assertEqual(result["crop_strategy"], "center") + self.assertEqual(result["crop_strategy_used"], "center") self.assertIn("srt_path", result) self.assertTrue(os.path.exists(result["srt_path"])) @@ -680,6 +889,24 @@ def test_duration_is_content_length_not_the_file_with_intro_included(self): self.assertAlmostEqual(result["output_duration"], 3.5, delta=0.3) self.assertGreater(result["output_duration"], result["duration"]) + def test_non_reframing_format_reports_fit(self): + from services import clip_generator as cg + + result = cg.generate_clip( + video_path=self.src, + start_second=0, + end_second=2.0, + caption_style="subtle", + crop_strategy="face", + format="horizontal", + title="fit_test", + output_dir=os.path.join(self.tmpdir, "out_fit"), + captions=False, + clean_fillers=False, + ) + self.assertEqual(result["crop_strategy"], "face") + self.assertEqual(result["crop_strategy_used"], "fit") + def test_video_only_source_does_not_require_an_audio_stream(self): from services import clip_generator as cg diff --git a/tests/test_speaker_assignment.py b/tests/test_speaker_assignment.py index 76fe50f..6a5cb28 100644 --- a/tests/test_speaker_assignment.py +++ b/tests/test_speaker_assignment.py @@ -3,13 +3,14 @@ import os import sys import unittest +from unittest import mock ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) BACKEND_ROOT = os.path.join(ROOT, "backend") if BACKEND_ROOT not in sys.path: sys.path.insert(0, BACKEND_ROOT) -from services.speaker_detection import assign_speakers_to_words +from services.speaker_detection import assign_speakers_to_words, run_diarization class AssignSpeakersToWordsTests(unittest.TestCase): @@ -57,5 +58,21 @@ def test_word_outside_all_segments_is_none(self): self.assertIsNone(out[0]["speaker"]) +class MissingTokenMessageTests(unittest.TestCase): + def test_missing_token_error_carries_the_exact_fix(self): + fake_pyannote = mock.MagicMock() + with mock.patch.dict(os.environ), \ + mock.patch.dict(sys.modules, {"pyannote": fake_pyannote, "pyannote.audio": fake_pyannote.audio}): + os.environ.pop("HF_TOKEN", None) + with self.assertRaises(PermissionError) as ctx: + run_diarization("episode.wav") + + message = str(ctx.exception) + first_line = message.splitlines()[0] + self.assertIn("podcli env set HF_TOKEN hf_...", first_line) + self.assertNotIn("\u2014", message) + self.assertNotIn("\u2013", message) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_video_processor.py b/tests/test_video_processor.py index c4d305f..c084d70 100644 --- a/tests/test_video_processor.py +++ b/tests/test_video_processor.py @@ -793,6 +793,80 @@ def test_crop_to_vertical_falls_back_to_a_scanned_face_map_when_tracking_fails(s self.assertEqual(result, "ok.mp4") face_map_crop.assert_called_once() + def _crop(self, strategy, words, face_map=None, keyframes=None, track=None, face_x="456"): + report = {} + with mock.patch.object(vp, "get_dimensions", return_value=(1920, 1080)), \ + mock.patch.object(vp, "_use_face_map", return_value=face_x), \ + mock.patch.object(vp, "_track_and_crop", return_value=track) as track_crop, \ + mock.patch.object(vp, "_run_ffmpeg_with_fallback", return_value="ok.mp4"): + vp.crop_to_vertical( + input_path="in.mp4", + output_path="out.mp4", + strategy=strategy, + transcript_words=words, + clip_start=0.0, + face_map=face_map, + crop_keyframes=keyframes, + report=report, + ) + return report, track_crop + + def test_face_request_with_speaker_labels_runs_and_reports_the_speaker_path(self): + words = [{"word": "hi", "start": 0.0, "end": 0.4, "speaker": "SPEAKER_00"}] + for requested in ("face", "speaker"): + report, track_crop = self._crop(requested, words, track="tracked.mp4") + self.assertEqual(report, {"strategy_used": "speaker"}) + track_crop.assert_called_once() + + def test_speaker_labels_without_a_face_map_still_use_the_speaker_path(self): + words = [{"word": "hi", "start": 0.0, "end": 0.4, "speaker": "SPEAKER_01"}] + report, _ = self._crop("face", words, face_map=None, track="tracked.mp4") + self.assertEqual(report["strategy_used"], "speaker") + + def test_face_request_without_labels_reports_face_when_tracking_succeeds(self): + words = [{"word": "hi", "start": 0.0, "end": 0.4, "speaker": None}] + report, _ = self._crop("face", words, track="tracked.mp4") + self.assertEqual(report["strategy_used"], "face") + + def test_failed_speaker_track_falls_back_to_the_face_map(self): + words = [{"word": "hi", "start": 0.0, "end": 0.4, "speaker": "SPEAKER_00"}] + face_map = {"clusters": [{"center_x": 100, "crop_x": 0}], "video_width": 1920} + report, track_crop = self._crop("speaker", words, face_map=face_map, track=None) + self.assertEqual(report["strategy_used"], "face") + track_crop.assert_called_once() + + def test_everything_failing_reports_center(self): + words = [{"word": "hi", "start": 0.0, "end": 0.4, "speaker": "SPEAKER_00"}] + report, track_crop = self._crop("speaker", words, face_map=None, track=None) + self.assertEqual(report["strategy_used"], "center") + self.assertEqual(track_crop.call_count, 2) + + def test_center_request_reports_center_without_tracking(self): + report, track_crop = self._crop("center", [], track="tracked.mp4") + self.assertEqual(report["strategy_used"], "center") + track_crop.assert_not_called() + + def test_manual_request_with_keyframes_reports_manual(self): + keyframes = [{"time": 0.0, "x": 0.5}] + with mock.patch.object(vp, "_manual_crop_x_expr", return_value="100"): + report, _ = self._crop("manual", [], keyframes=keyframes) + self.assertEqual(report["strategy_used"], "manual") + + def test_manual_without_keyframes_reports_what_it_fell_back_to(self): + report, _ = self._crop("manual", [], track="tracked.mp4") + self.assertEqual(report["strategy_used"], "face") + + def test_hardcut_reports_hardcut_when_the_face_map_places_the_frame(self): + face_map = {"clusters": [{"center_x": 100, "crop_x": 0}], "video_width": 1920} + report, _ = self._crop("speaker-hardcut", [], face_map=face_map) + self.assertEqual(report["strategy_used"], "speaker-hardcut") + + def test_report_is_optional(self): + with mock.patch.object(vp, "get_dimensions", return_value=(1920, 1080)), \ + mock.patch.object(vp, "_run_ffmpeg_with_fallback", return_value="ok.mp4"): + result = vp.crop_to_vertical("in.mp4", "out.mp4", strategy="center") + self.assertEqual(result, "ok.mp4") + if __name__ == "__main__": unittest.main()