From 9fcc1bf526515a1a46b4b2dd4c114d287b4c0bc5 Mon Sep 17 00:00:00 2001 From: Nika Siradze Date: Mon, 23 Nov 2026 23:06:23 +0400 Subject: [PATCH 1/5] Stop a split multi-byte character from crashing whisper.cpp transcription whisper.cpp can cut one character across two tokens, leaving invalid UTF-8 in its JSON output. Reading that file as strict UTF-8 raised UnicodeDecodeError and ended the whole run. Read the bytes with surrogateescape and rejoin them when the tokens are concatenated into words and segment text. --- backend/services/transcription_whispercpp.py | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/backend/services/transcription_whispercpp.py b/backend/services/transcription_whispercpp.py index c9af547..a26efe8 100644 --- a/backend/services/transcription_whispercpp.py +++ b/backend/services/transcription_whispercpp.py @@ -49,6 +49,18 @@ def _extract_wav(media_path: str, wav_path: str, ffmpeg: str = "ffmpeg") -> None ) +def _load_whisper_json(path: str) -> dict: + # whisper.cpp can split one multi-byte character across two tokens, which + # leaves invalid UTF-8 in the file. surrogateescape keeps those bytes so + # _heal_utf8 can rejoin them once the tokens are concatenated. + with open(path, encoding="utf-8", errors="surrogateescape") as f: + return json.load(f) + + +def _heal_utf8(text: str) -> str: + return text.encode("utf-8", "surrogateescape").decode("utf-8", "replace") + + def _tokens_to_words(tokens: list[dict]) -> list[dict]: """Merge whisper.cpp subword tokens into words with start/end seconds.""" words: list[dict] = [] @@ -58,7 +70,7 @@ def _tokens_to_words(tokens: list[dict]) -> list[dict]: def flush(): nonlocal cur_text, cur_start, cur_end - text = cur_text.strip().lstrip("▁").strip() + text = _heal_utf8(cur_text.strip().lstrip("▁").strip()) if text and cur_start is not None: words.append({ "word": text, @@ -221,8 +233,7 @@ def transcribe_file( cmd += ["-l", language or "auto"] subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True, timeout=7200) - with open(out_base + ".json", encoding="utf-8") as f: - data = json.load(f) + data = _load_whisper_json(out_base + ".json") transcription = data.get("transcription", []) segments, words = [], [] @@ -232,7 +243,7 @@ def transcribe_file( "id": i, "start": round((off.get("from") or 0) / 1000.0, 3), "end": round((off.get("to") or 0) / 1000.0, 3), - "text": (seg.get("text") or "").strip(), + "text": _heal_utf8((seg.get("text") or "").strip()), "speaker": None, }) words.extend(_tokens_to_words(seg.get("tokens", []))) From 0f58e1d9b900a327be20a74829933c997aae18f7 Mon Sep 17 00:00:00 2001 From: Nika Siradze Date: Mon, 23 Nov 2026 23:17:15 +0400 Subject: [PATCH 2/5] Generate clip titles and descriptions while the clips render Each clip's AI title and description call only needs the clip and the transcript, but it ran after that clip finished rendering, one clip at a time. Start all of them (three at once) before the render loop and read each result when its clip is done. On a 2-clip export the per-clip wait after rendering fell from about 25s to the thumbnail step alone. --- backend/cli.py | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/backend/cli.py b/backend/cli.py index 57b51c1..26dc3b3 100644 --- a/backend/cli.py +++ b/backend/cli.py @@ -1950,6 +1950,17 @@ def _transcribe_progress(pct, msg): _ai_label = " (+ AI titles)" if (_ai_cli_path and config.get("generate_content", True)) else "" print(f"\n [4/4] Exporting {len(clips)} clips{_ai_label} to {output_dir}/") + _content_pool = None + _content_jobs = {} + if _ai_cli_path and config.get("generate_content", True): + from concurrent.futures import ThreadPoolExecutor + from services.content_generator import generate_clip_content + + _content_pool = ThreadPoolExecutor(max_workers=3) + _content_jobs = { + idx: _content_pool.submit(generate_clip_content, clip=c, transcript_segments=segments) + for idx, c in enumerate(clips) + } results = [] t0 = time.time() _skip_review = ( @@ -2053,13 +2064,9 @@ def _transcribe_progress(pct, msg): print(f" ⚠ thumbnail: {e}") # Generate titles, descriptions, tags for this clip immediately - if _ai_cli_path and config.get("generate_content", True) and result.get("output_path"): + if i in _content_jobs and result.get("output_path"): try: - from services.content_generator import generate_clip_content - content_result = generate_clip_content( - clip=clip, - transcript_segments=segments, - ) + content_result = _content_jobs[i].result() if content_result and content_result.get("raw_text"): # Save per-clip content to file _content_path = result["output_path"].replace(".mp4", "_content.md") @@ -2249,6 +2256,9 @@ def _transcribe_progress(pct, msg): except KeyboardInterrupt: interrupted = True print(f"\n ⚠ Render interrupted: keeping completed clips") + finally: + if _content_pool: + _content_pool.shutdown(wait=False, cancel_futures=True) elapsed = time.time() - t0 success = sum(1 for r in results if "output_path" in r) From a8345c1bfe3cfe1b5ccd486a68834e17fdb5e67f Mon Sep 17 00:00:00 2001 From: Nika Siradze Date: Mon, 23 Nov 2026 23:23:25 +0400 Subject: [PATCH 3/5] Cut clips with the veryfast x264 preset The per-clip cut is an intermediate encode at CRF 16. veryfast takes about half the time of fast on a 1080p podcast cut (5.1s against 10.3s for 40s of video) with SSIM within 0.001 of fast against the source, identical duration and start offset, and a smaller file. End to end, cut time on a 2-clip export fell from 13.4s and 8.3s to 6.0s and 4.2s, with identical clip durations and caption files. --- backend/services/video_cut.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/backend/services/video_cut.py b/backend/services/video_cut.py index 9c84030..652abc4 100644 --- a/backend/services/video_cut.py +++ b/backend/services/video_cut.py @@ -27,8 +27,8 @@ def cut_segment( silently emits up to a full GOP of earlier content while the duration still checks out, which offsets every burned-in caption. CRF 16 keeps this intermediate visually lossless through the later crop/caption/audio - re-encodes; the fast preset holds the speed cost to a few percent - over the old CRF 18 pass. + re-encodes. veryfast cuts about half the time of fast at the same CRF + (SSIM within 0.001 on a 1080p podcast cut), and the file is smaller. """ duration = end_second - start_second @@ -37,7 +37,7 @@ def cut_segment( "-ss", str(start_second), "-i", input_path, "-t", str(duration), - "-c:v", "libx264", "-crf", "16", "-preset", "fast", "-profile:v", "high", + "-c:v", "libx264", "-crf", "16", "-preset", "veryfast", "-profile:v", "high", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "192k", "-avoid_negative_ts", "make_zero", From 19e06851976790126a99248117a86d30a18a4981 Mon Sep 17 00:00:00 2001 From: Nika Siradze Date: Mon, 23 Nov 2026 23:43:17 +0400 Subject: [PATCH 4/5] Encode the crop-stage intermediates with the veryfast x264 preset The mixed-layout crop encodes each speaker run, joins them with a dissolve, and runs a layout-flash guard pass, all at CRF 18 with the fast preset. Every one of them feeds the caption render and a later encode. veryfast takes about half the time at the same CRF on a 1080p to 1080x1920 crop (13.3s against 6.7s for 40s), with SSIM within 0.001 against a lossless reference and a smaller file. On a 2-clip export the mixed-layout crop stage fell from 52s to 32s, with identical durations and caption files. --- backend/services/video_processor.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/backend/services/video_processor.py b/backend/services/video_processor.py index 4524910..bec0b15 100644 --- a/backend/services/video_processor.py +++ b/backend/services/video_processor.py @@ -215,7 +215,7 @@ def _replace_layout_flash_frames(video_path: str, cut_times: list[float], durati parts.append("".join(labels) + f"concat=n={len(labels)}:v=1:a=0[v]") temp = video_path + ".layout-guard.mp4" cmd = ["ffmpeg", "-y", "-i", video_path, "-filter_complex", ";".join(parts), - "-map", "[v]", "-map", "0:a?", "-c:v", "libx264", "-crf", "18", "-preset", "fast", "-pix_fmt", "yuv420p", + "-map", "[v]", "-map", "0:a?", "-c:v", "libx264", "-crf", "18", "-preset", "veryfast", "-pix_fmt", "yuv420p", "-c:a", "copy", "-t", f"{duration:.3f}", "-movflags", "+faststart", temp] result = proc_run(cmd, timeout=_FFMPEG_TIMEOUT, check=False) if result.returncode != 0 or not os.path.exists(temp): @@ -1796,7 +1796,7 @@ def _run_center(cxs: list[float]) -> float: "-i", input_path, "-vf", seg_vf, "-an", - "-c:v", "libx264", "-crf", "18", "-preset", "fast", + "-c:v", "libx264", "-crf", "18", "-preset", "veryfast", "-pix_fmt", "yuv420p", "-avoid_negative_ts", "make_zero", part_path, @@ -1861,7 +1861,7 @@ def _run_center(cxs: list[float]) -> float: if _has_audio_stream(input_path): cmd += ["-map", f"{source_index}:a", "-c:a", "aac", "-b:a", "192k"] cmd += [ - "-c:v", "libx264", "-crf", "18", "-preset", "fast", + "-c:v", "libx264", "-crf", "18", "-preset", "veryfast", # xfade answers format negotiation with yuv444p even # when both of its inputs are yuv420p, and nothing here # asked for a format, so this wrote High 4:4:4 @@ -1905,7 +1905,7 @@ def _run_center(cxs: list[float]) -> float: "-i", input_path, "-vf", (f"crop={crop_w}:{crop_h}:{_crop_for(r_cx)}:{crop_y}," f"scale={target_w}:{target_h}"), - "-c:v", "libx264", "-crf", "18", "-preset", "fast", + "-c:v", "libx264", "-crf", "18", "-preset", "veryfast", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "192k", "-ar", "44100", "-avoid_negative_ts", "make_zero", @@ -2422,7 +2422,7 @@ def _is_segment_split(seg_start_t): "-ss", str(start_t), "-t", str(seg_duration), "-i", input_path, "-vf", vf, - "-c:v", "libx264", "-crf", "18", "-preset", "fast", + "-c:v", "libx264", "-crf", "18", "-preset", "veryfast", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "192k", "-avoid_negative_ts", "make_zero", From 1b7ee9a789d2f6f94fa8ee34672f38ca044263f2 Mon Sep 17 00:00:00 2001 From: Nika Siradze Date: Tue, 24 Nov 2026 02:23:20 +0400 Subject: [PATCH 5/5] Keep an interrupted export from waiting on title requests still in flight Titles and descriptions are generated on a pool while clips render. A thread pool's threads are joined when the interpreter exits, so Ctrl+C left the command alive until the running requests finished, up to their timeout. Run them on daemon threads, still three at a time and read in clip order, so an interrupted export exits at once. --- backend/cli.py | 64 ++++++++++++++++++++++++++++++----- tests/test_background_jobs.py | 63 ++++++++++++++++++++++++++++++++++ 2 files changed, 118 insertions(+), 9 deletions(-) create mode 100644 tests/test_background_jobs.py diff --git a/backend/cli.py b/backend/cli.py index 26dc3b3..40044b0 100644 --- a/backend/cli.py +++ b/backend/cli.py @@ -13,6 +13,8 @@ import argparse import json import os +import threading +import queue from utils.log import warn as log_warn import re import shlex @@ -1950,17 +1952,14 @@ def _transcribe_progress(pct, msg): _ai_label = " (+ AI titles)" if (_ai_cli_path and config.get("generate_content", True)) else "" print(f"\n [4/4] Exporting {len(clips)} clips{_ai_label} to {output_dir}/") - _content_pool = None _content_jobs = {} if _ai_cli_path and config.get("generate_content", True): - from concurrent.futures import ThreadPoolExecutor from services.content_generator import generate_clip_content - _content_pool = ThreadPoolExecutor(max_workers=3) - _content_jobs = { - idx: _content_pool.submit(generate_clip_content, clip=c, transcript_segments=segments) - for idx, c in enumerate(clips) - } + _content_jobs = _start_background_jobs( + {idx: (lambda c=c: generate_clip_content(clip=c, transcript_segments=segments)) for idx, c in enumerate(clips)}, + workers=3, + ) results = [] t0 = time.time() _skip_review = ( @@ -2257,8 +2256,8 @@ def _transcribe_progress(pct, msg): interrupted = True print(f"\n ⚠ Render interrupted: keeping completed clips") finally: - if _content_pool: - _content_pool.shutdown(wait=False, cancel_futures=True) + for job in _content_jobs.values(): + job.cancel() elapsed = time.time() - t0 success = sum(1 for r in results if "output_path" in r) @@ -2355,6 +2354,53 @@ def _wrap_text(text: str, indent: str) -> str: return textwrap.fill(text, width=width, initial_indent=indent, subsequent_indent=indent) +class _BackgroundJob: + """A result computed on a daemon thread, so an interrupted run can exit while it is still going.""" + + def __init__(self, work): + self._work = work + self._done = threading.Event() + self._cancelled = False + self._value = None + self._error = None + + def run(self): + if not self._cancelled: + try: + self._value = self._work() + except BaseException as exc: + self._error = exc + self._done.set() + + def cancel(self): + self._cancelled = True + + def result(self): + self._done.wait() + if self._error is not None: + raise self._error + return self._value + + +def _start_background_jobs(works: dict, workers: int) -> dict: + """Start the jobs in order, at most `workers` at a time, on daemon threads.""" + jobs = {key: _BackgroundJob(work) for key, work in works.items()} + pending = queue.Queue() + for job in jobs.values(): + pending.put(job) + + def drain(): + while True: + try: + pending.get_nowait().run() + except queue.Empty: + return + + for _ in range(min(workers, len(jobs))): + threading.Thread(target=drain, daemon=True).start() + return jobs + + def _print_clips(clips: list): """Print clip list in the standard format.""" width = min(shutil.get_terminal_size((100, 24)).columns, 100) diff --git a/tests/test_background_jobs.py b/tests/test_background_jobs.py new file mode 100644 index 0000000..0c5dfdf --- /dev/null +++ b/tests/test_background_jobs.py @@ -0,0 +1,63 @@ +import os +import subprocess +import sys +import threading +import time +import unittest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +BACKEND_ROOT = os.path.join(ROOT, "backend") +if BACKEND_ROOT not in sys.path: + sys.path.insert(0, BACKEND_ROOT) +import cli as cli_mod + + +class BackgroundJobTests(unittest.TestCase): + def test_jobs_run_together_up_to_the_worker_limit_and_return_their_own_results(self): + running = 0 + peak = 0 + lock = threading.Lock() + + def work(value): + def run(): + nonlocal running, peak + with lock: + running += 1 + peak = max(peak, running) + time.sleep(0.05) + with lock: + running -= 1 + return value + return run + + jobs = cli_mod._start_background_jobs({i: work(i * 10) for i in range(8)}, workers=3) + + self.assertEqual([jobs[i].result() for i in range(8)], [i * 10 for i in range(8)]) + self.assertEqual(peak, 3) + + def test_a_failure_is_raised_for_that_job_only(self): + def boom(): + raise ValueError("no") + + jobs = cli_mod._start_background_jobs({"a": lambda: 1, "b": boom}, workers=2) + + self.assertEqual(jobs["a"].result(), 1) + with self.assertRaises(ValueError): + jobs["b"].result() + + def test_a_job_still_running_does_not_keep_the_process_alive(self): + code = ( + "import sys, time\n" + f"sys.path.insert(0, {BACKEND_ROOT!r})\n" + "import cli\n" + "cli._start_background_jobs({0: lambda: time.sleep(60)}, workers=1)\n" + "time.sleep(0.2)\n" + ) + started = time.time() + subprocess.run([sys.executable, "-c", code], check=True, timeout=30, capture_output=True) + + self.assertLess(time.time() - started, 20) + + +if __name__ == "__main__": + unittest.main()