From 63ca474bd54f21ad498ef90d46b5c49b01b10965 Mon Sep 17 00:00:00 2001 From: Nika Siradze Date: Thu, 19 Nov 2026 01:35:03 +0400 Subject: [PATCH 1/2] Add a clip benchmark script scripts/bench_clips.py runs podcli process on one episode for each format, times each stage, and writes clips.csv with the engine, model and crop strategy per clip, plus a blank scores.csv for judging. The process JSON now carries the crop strategy each clip used. --- backend/cli.py | 1 + scripts/bench_clips.py | 132 ++++++++++++++++++++++++++++++++++++++ tests/test_bench_clips.py | 95 +++++++++++++++++++++++++++ 3 files changed, 228 insertions(+) create mode 100644 scripts/bench_clips.py create mode 100644 tests/test_bench_clips.py diff --git a/backend/cli.py b/backend/cli.py index b66dcc5..21070a0 100644 --- a/backend/cli.py +++ b/backend/cli.py @@ -1210,6 +1210,7 @@ def _emit_process_json(*, json_out, video_path, output_dir, quality, clips, resu "start_second": result.get("start_second", clip.get("start_second")), "end_second": result.get("end_second", clip.get("end_second")), "score": clip.get("score"), + "crop_strategy": result.get("crop_strategy_used"), "file_size_mb": result.get("file_size_mb"), "status": result.get("status", "ok" if path else "error"), "error": result.get("error"), diff --git a/scripts/bench_clips.py b/scripts/bench_clips.py new file mode 100644 index 0000000..052b72b --- /dev/null +++ b/scripts/bench_clips.py @@ -0,0 +1,132 @@ +import argparse +import csv +import json +import os +import re +import subprocess +import sys +import time + +ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) +BACKEND = os.path.join(ROOT, "backend") +sys.path.insert(0, BACKEND) + +STAGE_RE = re.compile(r"\[([1-4])/4\]") +STAGE_NAMES = {"1": "transcribe", "2": "audio", "3": "select", "4": "render"} +CLIP_FIELDS = [ + "clip_id", "format", "start", "end", "duration", "title", "crop_strategy", + "engine", "model", "transcribe_s", "audio_s", "select_s", "render_s", "total_s", +] +SCORE_FIELDS = [ + "clip_id", "file", "start_clean", "end_clean", "hook", "standalone", + "captions", "framing", "post_as_is", "notes", +] + + +def stage_times(marks: list[tuple[str, float]], finished: float) -> dict[str, float]: + times = {name: 0.0 for name in STAGE_NAMES.values()} + for i, (stage, started) in enumerate(marks): + ended = marks[i + 1][1] if i + 1 < len(marks) else finished + times[STAGE_NAMES[stage]] += ended - started + return {k: round(v, 1) for k, v in times.items()} + + +def transcript_info(video: str) -> tuple[str, str]: + from config.paths import paths + from services.transcript_packer import compute_cache_hash + + cache_dir = paths["transcripts"] + cache_hash = compute_cache_hash(video) + try: + names = [n for n in os.listdir(cache_dir) if n.startswith(cache_hash) and n.endswith(".json")] + except FileNotFoundError: + return "", "" + if not names: + return "", "" + newest = max(names, key=lambda n: os.path.getmtime(os.path.join(cache_dir, n))) + with open(os.path.join(cache_dir, newest), encoding="utf-8") as f: + data = json.load(f) + model_match = re.search(r"-m([a-z0-9]+)", newest[len(cache_hash):]) + model = data.get("model_size") or (model_match.group(1) if model_match else "base") + return data.get("engine") or "whisper-py", model + + +def run_format(video: str, fmt: str, out_dir: str, top: int) -> tuple[dict, dict[str, float], float]: + cmd = [ + sys.executable, os.path.join(BACKEND, "cli.py"), "process", video, + "--format", fmt, "--output", out_dir, "--top", str(top), + "--no-resume", "--json", "--yes", + ] + marks: list[tuple[str, float]] = [] + started = time.perf_counter() + proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1) + assert proc.stderr is not None + for line in proc.stderr: + sys.stderr.write(line) + match = STAGE_RE.search(line) + if match and (not marks or marks[-1][0] != match.group(1)): + marks.append((match.group(1), time.perf_counter())) + stdout = proc.stdout.read() if proc.stdout else "" + proc.wait() + finished = time.perf_counter() + if proc.returncode != 0: + raise SystemExit(f"podcli process failed for format {fmt} (exit {proc.returncode})") + payload = json.loads(stdout.strip().splitlines()[-1]) + return payload, stage_times(marks, finished), round(finished - started, 1) + + +def main() -> int: + parser = argparse.ArgumentParser(description="Run podcli on one episode and write benchmark CSVs.") + parser.add_argument("video") + parser.add_argument("output_dir") + parser.add_argument("--formats", default="vertical,topic") + parser.add_argument("--top", type=int, default=5) + args = parser.parse_args() + + video = os.path.abspath(args.video) + if not os.path.exists(video): + print(f"File not found: {video}", file=sys.stderr) + return 1 + os.makedirs(args.output_dir, exist_ok=True) + + clip_rows, score_rows = [], [] + for fmt in [f.strip() for f in args.formats.split(",") if f.strip()]: + fmt_dir = os.path.join(os.path.abspath(args.output_dir), fmt) + payload, times, total = run_format(video, fmt, fmt_dir, args.top) + engine, model = transcript_info(video) + for clip in payload.get("clips", []): + clip_id = f"{fmt}-{clip.get('index')}" + clip_rows.append({ + "clip_id": clip_id, + "format": fmt, + "start": clip.get("start_second"), + "end": clip.get("end_second"), + "duration": clip.get("output_duration") or clip.get("duration"), + "title": clip.get("title"), + "crop_strategy": clip.get("crop_strategy", ""), + "engine": engine, + "model": model, + "transcribe_s": times["transcribe"], + "audio_s": times["audio"], + "select_s": times["select"], + "render_s": times["render"], + "total_s": total, + }) + score_rows.append({"clip_id": clip_id, "file": clip.get("path", "")}) + + clips_csv = os.path.join(args.output_dir, "clips.csv") + scores_csv = os.path.join(args.output_dir, "scores.csv") + with open(clips_csv, "w", newline="", encoding="utf-8") as f: + writer = csv.DictWriter(f, fieldnames=CLIP_FIELDS) + writer.writeheader() + writer.writerows(clip_rows) + with open(scores_csv, "w", newline="", encoding="utf-8") as f: + writer = csv.DictWriter(f, fieldnames=SCORE_FIELDS) + writer.writeheader() + writer.writerows(score_rows) + print(f"{len(clip_rows)} clips. Wrote {clips_csv} and {scores_csv}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test_bench_clips.py b/tests/test_bench_clips.py new file mode 100644 index 0000000..b9c8314 --- /dev/null +++ b/tests/test_bench_clips.py @@ -0,0 +1,95 @@ +import csv +import importlib.util +import json +import os +import shutil +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) +spec = importlib.util.spec_from_file_location("bench_clips", os.path.join(ROOT, "scripts", "bench_clips.py")) +bench = importlib.util.module_from_spec(spec) +spec.loader.exec_module(bench) + +from services import transcript_packer as tp + + +class StageTimesTests(unittest.TestCase): + def test_each_stage_runs_until_the_next_one_starts(self): + marks = [("1", 0.0), ("2", 30.0), ("3", 35.0), ("4", 95.0)] + self.assertEqual( + bench.stage_times(marks, 215.0), + {"transcribe": 30.0, "audio": 5.0, "select": 60.0, "render": 120.0}, + ) + + def test_a_skipped_stage_reports_zero(self): + self.assertEqual( + bench.stage_times([("1", 0.0), ("3", 2.0), ("4", 12.0)], 20.0), + {"transcribe": 2.0, "audio": 0.0, "select": 10.0, "render": 8.0}, + ) + + +class TranscriptInfoTests(unittest.TestCase): + def setUp(self): + self._tmp = tempfile.mkdtemp() + self.video = os.path.join(self._tmp, "ep.mp4") + with open(self.video, "wb") as f: + f.write(b"episode bytes" * 50) + self.cache = os.path.join(self._tmp, "transcripts") + os.makedirs(self.cache) + patcher = mock.patch.dict("config.paths.paths", {"transcripts": self.cache}) + patcher.start() + self.addCleanup(patcher.stop) + + def tearDown(self): + shutil.rmtree(self._tmp, ignore_errors=True) + + def _write(self, suffix, data): + name = f"{tp.compute_cache_hash(self.video)}{suffix}.json" + with open(os.path.join(self.cache, name), "w", encoding="utf-8") as f: + json.dump(data, f) + + def test_reads_engine_and_model_from_the_cached_transcript(self): + self._write("-whispercpp-msmall", {"engine": "whispercpp"}) + self.assertEqual(bench.transcript_info(self.video), ("whispercpp", "small")) + + def test_bare_key_means_base(self): + self._write("", {"engine": "whispercpp"}) + self.assertEqual(bench.transcript_info(self.video), ("whispercpp", "base")) + + def test_no_transcript_is_blank(self): + self.assertEqual(bench.transcript_info(self.video), ("", "")) + + +class MainWritesCsvTests(unittest.TestCase): + def test_writes_one_clip_row_and_one_blank_score_row_per_clip(self): + tmp = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, tmp, True) + video = os.path.join(tmp, "ep.mp4") + with open(video, "wb") as f: + f.write(b"x") + payload = {"clips": [{"index": 1, "title": "Why we quit", "start_second": 61.2, "end_second": 98.4, + "duration": 37.2, "crop_strategy": "speaker", "path": "/out/1.mp4"}]} + times = {"transcribe": 40.0, "audio": 3.0, "select": 50.0, "render": 20.0} + with mock.patch.object(bench, "run_format", return_value=(payload, times, 113.0)), \ + mock.patch.object(bench, "transcript_info", return_value=("whispercpp", "small")), \ + mock.patch.object(sys, "argv", ["bench_clips.py", video, tmp, "--formats", "topic"]): + self.assertEqual(bench.main(), 0) + with open(os.path.join(tmp, "clips.csv"), encoding="utf-8") as f: + rows = list(csv.DictReader(f)) + self.assertEqual(rows, [{ + "clip_id": "topic-1", "format": "topic", "start": "61.2", "end": "98.4", "duration": "37.2", + "title": "Why we quit", "crop_strategy": "speaker", "engine": "whispercpp", "model": "small", + "transcribe_s": "40.0", "audio_s": "3.0", "select_s": "50.0", "render_s": "20.0", "total_s": "113.0", + }]) + with open(os.path.join(tmp, "scores.csv"), encoding="utf-8") as f: + scores = list(csv.DictReader(f)) + self.assertEqual(scores[0]["clip_id"], "topic-1") + self.assertEqual(scores[0]["file"], "/out/1.mp4") + self.assertEqual(scores[0]["post_as_is"], "") + + +if __name__ == "__main__": + unittest.main() From 1a035c89875e545e66bd57bc83f8c2ad470c55e3 Mon Sep 17 00:00:00 2001 From: Nika Siradze Date: Thu, 19 Nov 2026 03:49:32 +0400 Subject: [PATCH 2/2] Report the transcript a run used and skip failed clips in the bench CSVs process --json now carries the engine and model of the transcript the run actually used, so bench_clips.py stops guessing from the newest cache file. Clips that failed to export are listed on stderr instead of getting a judging row, and the script exits 1 when nothing rendered. --- backend/cli.py | 9 +++++- scripts/bench_clips.py | 38 ++++++++----------------- tests/test_bench_clips.py | 58 ++++++++++++++------------------------- tests/test_cli_helpers.py | 2 ++ 4 files changed, 42 insertions(+), 65 deletions(-) diff --git a/backend/cli.py b/backend/cli.py index 21070a0..57b51c1 100644 --- a/backend/cli.py +++ b/backend/cli.py @@ -1181,7 +1181,7 @@ def _parse_content_text(raw: str) -> dict: } -def _emit_process_json(*, json_out, video_path, output_dir, quality, clips, results, interrupted): +def _emit_process_json(*, json_out, video_path, output_dir, quality, clips, results, interrupted, transcript=None): payload_clips = [] for i, result in enumerate(results): clip = clips[i] if i < len(clips) else {} @@ -1225,6 +1225,7 @@ def _emit_process_json(*, json_out, video_path, output_dir, quality, clips, resu "video": video_path, "output_dir": output_dir, "quality": quality, + "transcript": transcript, "clips": payload_clips, } print(json.dumps(payload, ensure_ascii=False), file=json_out, flush=True) @@ -1660,6 +1661,11 @@ def _transcribe_progress(pct, msg): language=config.get("language"), ) + transcript_info = None if args.transcript or not result.get("words") else { + "engine": result.get("engine") or cache_key["engine"], + "model": result.get("model_size") or cache_key["model_size"], + } + # Apply word corrections (Whisper misheard proper nouns, brand names) from services.corrections import apply_corrections apply_corrections(words, segments) @@ -2275,6 +2281,7 @@ def _transcribe_progress(pct, msg): clips=clips, results=results, interrupted=interrupted, + transcript=transcript_info, ) # ── Post-render iteration ── diff --git a/scripts/bench_clips.py b/scripts/bench_clips.py index 052b72b..7c2aa9c 100644 --- a/scripts/bench_clips.py +++ b/scripts/bench_clips.py @@ -9,7 +9,6 @@ ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) BACKEND = os.path.join(ROOT, "backend") -sys.path.insert(0, BACKEND) STAGE_RE = re.compile(r"\[([1-4])/4\]") STAGE_NAMES = {"1": "transcribe", "2": "audio", "3": "select", "4": "render"} @@ -31,26 +30,6 @@ def stage_times(marks: list[tuple[str, float]], finished: float) -> dict[str, fl return {k: round(v, 1) for k, v in times.items()} -def transcript_info(video: str) -> tuple[str, str]: - from config.paths import paths - from services.transcript_packer import compute_cache_hash - - cache_dir = paths["transcripts"] - cache_hash = compute_cache_hash(video) - try: - names = [n for n in os.listdir(cache_dir) if n.startswith(cache_hash) and n.endswith(".json")] - except FileNotFoundError: - return "", "" - if not names: - return "", "" - newest = max(names, key=lambda n: os.path.getmtime(os.path.join(cache_dir, n))) - with open(os.path.join(cache_dir, newest), encoding="utf-8") as f: - data = json.load(f) - model_match = re.search(r"-m([a-z0-9]+)", newest[len(cache_hash):]) - model = data.get("model_size") or (model_match.group(1) if model_match else "base") - return data.get("engine") or "whisper-py", model - - def run_format(video: str, fmt: str, out_dir: str, top: int) -> tuple[dict, dict[str, float], float]: cmd = [ sys.executable, os.path.join(BACKEND, "cli.py"), "process", video, @@ -89,12 +68,15 @@ def main() -> int: return 1 os.makedirs(args.output_dir, exist_ok=True) - clip_rows, score_rows = [], [] + clip_rows, score_rows, failed = [], [], [] for fmt in [f.strip() for f in args.formats.split(",") if f.strip()]: fmt_dir = os.path.join(os.path.abspath(args.output_dir), fmt) payload, times, total = run_format(video, fmt, fmt_dir, args.top) - engine, model = transcript_info(video) + transcript = payload.get("transcript") or {} for clip in payload.get("clips", []): + if clip.get("status") != "ok" or not clip.get("path"): + failed.append(f"{fmt}-{clip.get('index')}: {clip.get('error') or 'no output file'}") + continue clip_id = f"{fmt}-{clip.get('index')}" clip_rows.append({ "clip_id": clip_id, @@ -104,15 +86,15 @@ def main() -> int: "duration": clip.get("output_duration") or clip.get("duration"), "title": clip.get("title"), "crop_strategy": clip.get("crop_strategy", ""), - "engine": engine, - "model": model, + "engine": transcript.get("engine", ""), + "model": transcript.get("model", ""), "transcribe_s": times["transcribe"], "audio_s": times["audio"], "select_s": times["select"], "render_s": times["render"], "total_s": total, }) - score_rows.append({"clip_id": clip_id, "file": clip.get("path", "")}) + score_rows.append({"clip_id": clip_id, "file": clip["path"]}) clips_csv = os.path.join(args.output_dir, "clips.csv") scores_csv = os.path.join(args.output_dir, "scores.csv") @@ -124,8 +106,10 @@ def main() -> int: writer = csv.DictWriter(f, fieldnames=SCORE_FIELDS) writer.writeheader() writer.writerows(score_rows) + for line in failed: + print(f"Failed export, not scored: {line}", file=sys.stderr) print(f"{len(clip_rows)} clips. Wrote {clips_csv} and {scores_csv}") - return 0 + return 0 if clip_rows else 1 if __name__ == "__main__": diff --git a/tests/test_bench_clips.py b/tests/test_bench_clips.py index b9c8314..e2789d5 100644 --- a/tests/test_bench_clips.py +++ b/tests/test_bench_clips.py @@ -1,6 +1,5 @@ import csv import importlib.util -import json import os import shutil import sys @@ -13,7 +12,6 @@ bench = importlib.util.module_from_spec(spec) spec.loader.exec_module(bench) -from services import transcript_packer as tp class StageTimesTests(unittest.TestCase): @@ -31,38 +29,6 @@ def test_a_skipped_stage_reports_zero(self): ) -class TranscriptInfoTests(unittest.TestCase): - def setUp(self): - self._tmp = tempfile.mkdtemp() - self.video = os.path.join(self._tmp, "ep.mp4") - with open(self.video, "wb") as f: - f.write(b"episode bytes" * 50) - self.cache = os.path.join(self._tmp, "transcripts") - os.makedirs(self.cache) - patcher = mock.patch.dict("config.paths.paths", {"transcripts": self.cache}) - patcher.start() - self.addCleanup(patcher.stop) - - def tearDown(self): - shutil.rmtree(self._tmp, ignore_errors=True) - - def _write(self, suffix, data): - name = f"{tp.compute_cache_hash(self.video)}{suffix}.json" - with open(os.path.join(self.cache, name), "w", encoding="utf-8") as f: - json.dump(data, f) - - def test_reads_engine_and_model_from_the_cached_transcript(self): - self._write("-whispercpp-msmall", {"engine": "whispercpp"}) - self.assertEqual(bench.transcript_info(self.video), ("whispercpp", "small")) - - def test_bare_key_means_base(self): - self._write("", {"engine": "whispercpp"}) - self.assertEqual(bench.transcript_info(self.video), ("whispercpp", "base")) - - def test_no_transcript_is_blank(self): - self.assertEqual(bench.transcript_info(self.video), ("", "")) - - class MainWritesCsvTests(unittest.TestCase): def test_writes_one_clip_row_and_one_blank_score_row_per_clip(self): tmp = tempfile.mkdtemp() @@ -70,11 +36,16 @@ def test_writes_one_clip_row_and_one_blank_score_row_per_clip(self): video = os.path.join(tmp, "ep.mp4") with open(video, "wb") as f: f.write(b"x") - payload = {"clips": [{"index": 1, "title": "Why we quit", "start_second": 61.2, "end_second": 98.4, - "duration": 37.2, "crop_strategy": "speaker", "path": "/out/1.mp4"}]} + payload = { + "transcript": {"engine": "whispercpp", "model": "small"}, + "clips": [ + {"index": 1, "title": "Why we quit", "start_second": 61.2, "end_second": 98.4, "duration": 37.2, + "crop_strategy": "speaker", "path": "/out/1.mp4", "status": "ok"}, + {"index": 2, "title": "Broken", "status": "error", "error": "ffmpeg died"}, + ], + } times = {"transcribe": 40.0, "audio": 3.0, "select": 50.0, "render": 20.0} with mock.patch.object(bench, "run_format", return_value=(payload, times, 113.0)), \ - mock.patch.object(bench, "transcript_info", return_value=("whispercpp", "small")), \ mock.patch.object(sys, "argv", ["bench_clips.py", video, tmp, "--formats", "topic"]): self.assertEqual(bench.main(), 0) with open(os.path.join(tmp, "clips.csv"), encoding="utf-8") as f: @@ -89,6 +60,19 @@ def test_writes_one_clip_row_and_one_blank_score_row_per_clip(self): self.assertEqual(scores[0]["clip_id"], "topic-1") self.assertEqual(scores[0]["file"], "/out/1.mp4") self.assertEqual(scores[0]["post_as_is"], "") + self.assertEqual(len(scores), 1) + + def test_exits_with_failure_when_no_clip_rendered(self): + tmp = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, tmp, True) + video = os.path.join(tmp, "ep.mp4") + with open(video, "wb") as f: + f.write(b"x") + payload = {"clips": [{"index": 1, "status": "error", "error": "ffmpeg died"}]} + times = {"transcribe": 1.0, "audio": 1.0, "select": 1.0, "render": 1.0} + with mock.patch.object(bench, "run_format", return_value=(payload, times, 4.0)), \ + mock.patch.object(sys, "argv", ["bench_clips.py", video, tmp, "--formats", "vertical"]): + self.assertEqual(bench.main(), 1) if __name__ == "__main__": diff --git a/tests/test_cli_helpers.py b/tests/test_cli_helpers.py index 8180a3b..45dd007 100644 --- a/tests/test_cli_helpers.py +++ b/tests/test_cli_helpers.py @@ -181,9 +181,11 @@ def test_emit_process_json_writes_one_object(self): clips=[{"title": "A", "start_second": 1, "end_second": 12, "score": 9}], results=[{"output_path": "/out/a.mp4", "duration": 11, "status": "ok"}], interrupted=False, + transcript={"engine": "whispercpp", "model": "base"}, ) payload = json.loads(buf.getvalue()) self.assertTrue(payload["ok"]) + self.assertEqual(payload["transcript"], {"engine": "whispercpp", "model": "base"}) self.assertEqual(payload["quality"], "high") self.assertEqual(payload["clips"][0]["title"], "A") self.assertEqual(payload["clips"][0]["path"], "/out/a.mp4")