Repository navigation
Add a clip benchmark script #282
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,116 @@ | ||
| 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") | ||
|
|
||
| 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 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, 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) | ||
| 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, | ||
| "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": 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["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) | ||
| 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 if clip_rows else 1 | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| sys.exit(main()) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| import csv | ||
| import importlib.util | ||
| 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) | ||
|
|
||
|
|
||
|
|
||
| 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 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 = { | ||
| "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(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"], "") | ||
| 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__": | ||
| unittest.main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.