perf(pipeline): GPU cut, CPU VAD, cheap blur, hook+captions in one pass, 6 clip workers
Same clips to the eye (SSIM 0.990-0.9998 vs before, audio identical,
frames checked by eye), faster:
- Cut on the card end to end (NVDEC -> NVENC, hwaccel_output_format cuda)
for 8-bit 4:2:0 h264/hevc/vp9/av1 sources; byte-identical decoded frames
to the CPU cut, -64% CPU. Anything else, or a failed GPU cut, decodes on
the CPU as before.
- Silero VAD on one CPU thread instead of CUDA (one 32 ms chunk per launch):
transcription 2-3x faster (9 min audio: 28 -> 9 s). Over 3,939 words one
changed ("claudio" -> "cloud", said "Claude") and a few times moved <=48 ms.
- The blurred backdrop is blurred at quarter size and scaled up
(ffmpeg_utils.blurred_backdrop): ~45% less CPU on those segments.
- hooked_ and subtitled_ come out of ONE ffmpeg (hooks.add_hook_to_video
also=...), one decode instead of two; subtitled_ is one generation fewer.
Same filenames, so the editor's walk-back is unchanged. Falls back to the
two passes if the combined one fails.
- CLIP_WORKERS default 3 -> 6: -14-16% wall per job at load 48-67, same CPU,
peak VRAM 12 GB of 20.
Bench on balrog (3 Carlos Gracia videos, old/new side by side).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
90b10c1902
commit
6e660d8f92
9 changed files with 263 additions and 52 deletions
|
|
@ -20,6 +20,8 @@ them with margin.
|
|||
"""
|
||||
import os
|
||||
|
||||
from ffmpeg_utils import blurred_backdrop
|
||||
|
||||
CORNER_MARGIN = 0.20 # a subject this far from an edge (as a fraction of the
|
||||
# frame) still counts as anchored to it
|
||||
|
||||
|
|
@ -281,8 +283,7 @@ def inset_filtergraph(orig_w, orig_h, out_w, out_h, box, camera_ratio=None):
|
|||
# Blurred backdrop so the leftover strip is not a black bar. Scaled by
|
||||
# HEIGHT: scaling a 16:9 source to 1080 wide gives 608 tall, and there
|
||||
# is no 1920-tall crop to take out of that.
|
||||
f"[bga]scale=-2:{out_h},crop=w=min(iw\\,{out_w}):h={out_h},"
|
||||
f"scale={out_w}:{out_h},gblur=sigma=14[bg];"
|
||||
f"[bga]{blurred_backdrop(out_w, out_h, 14)}[bg];"
|
||||
f"[sa]scale={out_w}:{screen_h}[screen];"
|
||||
f"[ca]crop=w={w}:h={h}:x={x}:y={y},scale={out_w}:{cam_h}[cam];"
|
||||
f"[bg][screen]overlay=x=0:y={filler_h // 2}[withscreen];"
|
||||
|
|
|
|||
|
|
@ -206,6 +206,22 @@ def video_encode_args(tier=QUALITY):
|
|||
return list((_NVENC_ARGS if use_nvenc else _X264_ARGS)[tier])
|
||||
|
||||
|
||||
def blurred_backdrop(out_w, out_h, sigma):
|
||||
"""Filter chain (no labels) filling out_w x out_h with a blurred copy.
|
||||
|
||||
The blur runs at a quarter of the output size and is scaled up afterwards:
|
||||
a blurred picture has no detail to lose, the result looks the same (SSIM
|
||||
0.994-0.998 against the full-size gblur on prod clips) and the segment
|
||||
encode needs ~45% less CPU. ``sigma`` is the full-size one.
|
||||
"""
|
||||
small_w = max(2, out_w // 4 - (out_w // 4) % 2)
|
||||
small_h = max(2, out_h // 4 - (out_h // 4) % 2)
|
||||
return (
|
||||
f"scale=-2:{small_h},crop=w=min(iw\\,{small_w}):h={small_h},"
|
||||
f"gblur=sigma={sigma / 4:g},scale={out_w}:{out_h}"
|
||||
)
|
||||
|
||||
|
||||
def escape_filter_value(value):
|
||||
r"""Escape a path/value for use inside a quoted FFmpeg filter argument.
|
||||
|
||||
|
|
@ -239,6 +255,42 @@ MIN_CUT_BYTES = 1024
|
|||
# encode, another job finishes and gives back.
|
||||
CUT_RETRY_WAITS = (3, 9)
|
||||
|
||||
# The cut can stay on the card end to end: NVDEC decodes into GPU memory and
|
||||
# NVENC encodes from it, so the CPU never touches a frame. Measured on a real
|
||||
# 1080p source: byte-identical decoded frames to the CPU-decoded cut, 64% less
|
||||
# CPU (25-sep-2026). Only for 8-bit 4:2:0 in codecs the card decodes: anything
|
||||
# else would reach nvenc in a pixel format a delivered H.264 must not have, so
|
||||
# it keeps the CPU decode. FFMPEG_GPU_CUT=0 turns it off.
|
||||
_GPU_CUT_CODECS = {"h264", "hevc", "vp9", "av1"}
|
||||
_gpu_cut_sources = {}
|
||||
|
||||
|
||||
def _source_format(path):
|
||||
"""(codec, pix_fmt) of the first video stream, or None."""
|
||||
if not os.path.exists(path):
|
||||
return None
|
||||
try:
|
||||
out = subprocess.check_output(
|
||||
["ffprobe", "-v", "error", "-select_streams", "v:0",
|
||||
"-show_entries", "stream=codec_name,pix_fmt", "-of", "csv=p=0", path],
|
||||
stderr=subprocess.DEVNULL, timeout=60, text=True).strip()
|
||||
codec, pix_fmt = out.split(",")[:2]
|
||||
return codec, pix_fmt
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _gpu_cut_ok(input_video):
|
||||
if os.environ.get("FFMPEG_GPU_CUT", "1").strip() == "0":
|
||||
return False
|
||||
if os.environ.get("FFMPEG_ENCODER", "x264").strip().lower() not in ("nvenc", "auto"):
|
||||
return False
|
||||
if input_video not in _gpu_cut_sources:
|
||||
fmt = _source_format(input_video) if nvenc_available() else None
|
||||
_gpu_cut_sources[input_video] = bool(
|
||||
fmt and fmt[0] in _GPU_CUT_CODECS and fmt[1] == "yuv420p")
|
||||
return _gpu_cut_sources[input_video]
|
||||
|
||||
|
||||
def cut_clip(input_video, clip_temp_path, start, end, clip_number):
|
||||
"""Cut [start, end] out of the source into ``clip_temp_path``.
|
||||
|
|
@ -268,9 +320,20 @@ def cut_clip(input_video, clip_temp_path, start, end, clip_number):
|
|||
*audio_encode_args(),
|
||||
clip_temp_path
|
||||
]
|
||||
gpu_command = None
|
||||
if _gpu_cut_ok(input_video):
|
||||
# CUDA frames are already 4:2:0 (nv12); -pix_fmt would force a copy
|
||||
# back to system memory.
|
||||
gpu_args = list(encode_args)
|
||||
if "-pix_fmt" in gpu_args:
|
||||
i = gpu_args.index("-pix_fmt")
|
||||
del gpu_args[i:i + 2]
|
||||
gpu_command = ['ffmpeg', '-y', '-hwaccel', 'cuda', '-hwaccel_output_format', 'cuda',
|
||||
'-ss', str(start), '-to', str(end), '-i', input_video,
|
||||
*gpu_args, *audio_encode_args(), clip_temp_path]
|
||||
|
||||
def _run():
|
||||
result = subprocess.run(command, stdout=subprocess.DEVNULL,
|
||||
def _run_one(cmd):
|
||||
result = subprocess.run(cmd, stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.PIPE, text=True, errors="replace")
|
||||
# ffmpeg has been seen exiting 0 having written nothing, so the file
|
||||
# itself is the verdict, not just the return code.
|
||||
|
|
@ -278,6 +341,18 @@ def cut_clip(input_video, clip_temp_path, start, end, clip_number):
|
|||
ok = result.returncode == 0 and size >= MIN_CUT_BYTES
|
||||
return ok, f"exit {result.returncode}, {size} bytes\n{(result.stderr or '').strip()[-800:]}"
|
||||
|
||||
def _run():
|
||||
nonlocal gpu_command
|
||||
if gpu_command:
|
||||
ok, report = _run_one(gpu_command)
|
||||
if ok:
|
||||
return ok, report
|
||||
# Not worth a second try on this source: back to the CPU decode.
|
||||
print(f" ⚠️ GPU cut of clip {clip_number} failed — decoding on the CPU.")
|
||||
gpu_command = None
|
||||
_gpu_cut_sources[input_video] = False
|
||||
return _run_one(command)
|
||||
|
||||
for attempt, wait in enumerate(CUT_RETRY_WAITS + (None,), start=1):
|
||||
ok, report = _run()
|
||||
if ok:
|
||||
|
|
|
|||
30
hooks.py
30
hooks.py
|
|
@ -370,12 +370,17 @@ def create_hook_image(text, target_width, output_image_path="hook_overlay.png",
|
|||
img.save(output_image_path)
|
||||
return output_image_path, canvas_w, canvas_h
|
||||
|
||||
def add_hook_to_video(video_path, text, output_path, position="top", font_scale=1.0, duration=None, style="classic"):
|
||||
def add_hook_to_video(video_path, text, output_path, position="top", font_scale=1.0, duration=None, style="classic",
|
||||
also=None):
|
||||
"""
|
||||
Overlays text hook onto video.
|
||||
position: 'top', 'center', 'bottom'
|
||||
font_scale: float multiplier (1.0 = default)
|
||||
style: hook look (see HOOK_STYLES)
|
||||
also: optional (vf, path): ALSO write ``path`` = the hooked picture with
|
||||
``vf`` applied (the captions), from the same decode. The job pipeline
|
||||
needs both files (the editor re-captions from the hooked one), and one
|
||||
ffmpeg with two outputs saves a full decode + pass per clip.
|
||||
"""
|
||||
if not os.path.exists(video_path):
|
||||
raise FileNotFoundError(f"Video {video_path} not found")
|
||||
|
|
@ -424,16 +429,27 @@ def add_hook_to_video(video_path, text, output_path, position="top", font_scale=
|
|||
# 4. FFmpeg Command
|
||||
print(f"🎬 Overlaying hook: '{text}' at {overlay_x},{overlay_y}")
|
||||
|
||||
overlay = (f"[0:v][1:v]overlay={overlay_x}:{overlay_y}"
|
||||
+ (f":enable='between(t,0,{float(duration)})'" if duration else ""))
|
||||
tail = ['-c:a', 'copy', *video_encode_args(QUALITY), *METADATA_SCRUB,
|
||||
'-movflags', '+faststart']
|
||||
if also:
|
||||
extra_vf, extra_path = also
|
||||
ffmpeg_cmd = [
|
||||
'ffmpeg', '-y',
|
||||
'-i', video_path,
|
||||
'-i', img_path,
|
||||
'-filter_complex', f"[0:v][1:v]overlay={overlay_x}:{overlay_y}"
|
||||
+ (f":enable='between(t,0,{float(duration)})'" if duration else ""),
|
||||
'-c:a', 'copy',
|
||||
*video_encode_args(QUALITY),
|
||||
*METADATA_SCRUB,
|
||||
'-movflags', '+faststart',
|
||||
'-filter_complex', f"{overlay},split=2[h][c];[c]{extra_vf}[s]",
|
||||
'-map', '[h]', '-map', '0:a?', *tail, output_path,
|
||||
'-map', '[s]', '-map', '0:a?', *tail, extra_path,
|
||||
]
|
||||
else:
|
||||
ffmpeg_cmd = [
|
||||
'ffmpeg', '-y',
|
||||
'-i', video_path,
|
||||
'-i', img_path,
|
||||
'-filter_complex', overlay,
|
||||
*tail,
|
||||
output_path
|
||||
]
|
||||
|
||||
|
|
|
|||
60
main.py
60
main.py
|
|
@ -1072,7 +1072,8 @@ def finalize_clip_passthrough(input_video, final_output_video):
|
|||
return True
|
||||
|
||||
|
||||
def auto_caption_clip(clip_path, transcript, clip_start, clip_end, split_ranges=None):
|
||||
def auto_caption_clip(clip_path, transcript, clip_start, clip_end, split_ranges=None,
|
||||
plan_only=False):
|
||||
"""Burn the default caption style onto a finished clip.
|
||||
|
||||
``split_ranges``: (start, end) stretches, in clip seconds, rendered with
|
||||
|
|
@ -1092,6 +1093,9 @@ def auto_caption_clip(clip_path, transcript, clip_start, clip_end, split_ranges=
|
|||
Returns the captioned path, or None when captions were skipped (silent
|
||||
video, no words in range, AUTO_CAPTIONS=0, or any failure — a caption
|
||||
problem must never cost the user the clip they already paid for).
|
||||
|
||||
``plan_only`` writes the .ass but burns nothing: returns (vf,
|
||||
generation_id) for auto_hook_clip to burn in the same pass as the hook.
|
||||
"""
|
||||
if os.environ.get("AUTO_CAPTIONS", "1").strip() == "0":
|
||||
return None
|
||||
|
|
@ -1144,6 +1148,12 @@ def auto_caption_clip(clip_path, transcript, clip_start, clip_end, split_ranges=
|
|||
print(" ℹ️ No words in range — clip ships without captions.")
|
||||
return None
|
||||
|
||||
if plan_only:
|
||||
vf = _subs.subtitles_filter(
|
||||
ass_path, alignment=style["alignment"], fontsize=style["font_size"],
|
||||
font_name=style["font_name"], font_color=style["font_color"],
|
||||
border_color=style["border_color"], border_width=style["border_width"])
|
||||
return vf, generation_id
|
||||
_subs.burn_subtitles(
|
||||
clip_path, ass_path, out_path,
|
||||
alignment=style["alignment"], fontsize=style["font_size"],
|
||||
|
|
@ -1157,7 +1167,7 @@ def auto_caption_clip(clip_path, transcript, clip_start, clip_end, split_ranges=
|
|||
return None
|
||||
|
||||
|
||||
def auto_hook_clip(clip_path, clip):
|
||||
def auto_hook_clip(clip_path, clip, captions=None):
|
||||
"""Burn the clip's Gemini hook text as a DERIVED file (AUTO_HOOK=1).
|
||||
|
||||
Writes ``hooked_<ts>_<clip filename>`` next to the canonical clip, exactly
|
||||
|
|
@ -1168,7 +1178,13 @@ def auto_hook_clip(clip_path, clip):
|
|||
|
||||
Returns (hooked_path, hook_config), or None when skipped or failed — a
|
||||
hook problem must never cost the user the clip itself (same fail-open
|
||||
contract as auto_caption_clip)."""
|
||||
contract as auto_caption_clip).
|
||||
|
||||
``captions`` = (vf, generation_id) from auto_caption_clip(plan_only=True):
|
||||
the captioned ``subtitled_<id>_hooked_...`` file is written by the same
|
||||
ffmpeg, from the same decode, and its path lands in hook_config under
|
||||
"_captioned" (popped by the caller). If that combined pass fails, the hook
|
||||
is burned alone and the caller captions the way it always did."""
|
||||
text = (clip.get('viral_hook_text') or '').strip()
|
||||
if not text:
|
||||
return None
|
||||
|
|
@ -1184,11 +1200,26 @@ def auto_hook_clip(clip_path, clip):
|
|||
output_dir = os.path.dirname(clip_path)
|
||||
out_path = os.path.join(
|
||||
output_dir, f"hooked_{int(time.time())}_{os.path.basename(clip_path)}")
|
||||
config = {"text": text, "style": style, "position": "top",
|
||||
"duration_seconds": seconds}
|
||||
if captions:
|
||||
vf, generation_id = captions
|
||||
captioned = os.path.join(
|
||||
output_dir, f"subtitled_{generation_id}_{os.path.basename(out_path)}")
|
||||
try:
|
||||
add_hook_to_video(clip_path, text, out_path, position="top",
|
||||
duration=seconds, style=style, also=(vf, captioned))
|
||||
print(f" 🪝 Hook + 💬 captions burned in one pass ({style}, {seconds:g}s): {text}")
|
||||
return out_path, {**config, "_captioned": captioned}
|
||||
except Exception as e:
|
||||
print(f" ⚠️ Combined hook+captions pass failed ({type(e).__name__}: {e}) — "
|
||||
f"burning them one at a time.")
|
||||
if os.path.exists(captioned):
|
||||
os.remove(captioned) # never leave a half-written subtitled_ behind
|
||||
add_hook_to_video(clip_path, text, out_path, position="top",
|
||||
duration=seconds, style=style)
|
||||
print(f" 🪝 Hook burned ({style}, {seconds:g}s): {text}")
|
||||
return out_path, {"text": text, "style": style, "position": "top",
|
||||
"duration_seconds": seconds}
|
||||
return out_path, config
|
||||
except Exception as e:
|
||||
print(f" ⚠️ Auto-hook failed ({type(e).__name__}: {e}) — "
|
||||
f"delivering the clip without it.")
|
||||
|
|
@ -2214,14 +2245,24 @@ if __name__ == '__main__':
|
|||
# and title from three of its frames BEFORE burning them.
|
||||
if success and hook_grounding.wanted(clip['layout_ranges'], end - start):
|
||||
hook_grounding.reground(clip_final_path, clip, transcript, start, end)
|
||||
captioned = None
|
||||
split_ranges = _layouts.split_ranges(clip['layout_ranges'])
|
||||
if success and os.environ.get("AUTO_HOOK") == "1":
|
||||
hooked = auto_hook_clip(clip_final_path, clip)
|
||||
# Captions ride the hook's ffmpeg (one decode, two
|
||||
# outputs) when both are on; see auto_hook_clip.
|
||||
plan = None
|
||||
if (clip.get('viral_hook_text') or '').strip():
|
||||
plan = auto_caption_clip(clip_final_path, transcript, start, end,
|
||||
split_ranges=split_ranges, plan_only=True)
|
||||
hooked = auto_hook_clip(clip_final_path, clip, captions=plan)
|
||||
if hooked:
|
||||
deliver_path, clip['auto_hook'] = hooked
|
||||
captioned = clip['auto_hook'].pop("_captioned", None)
|
||||
if success:
|
||||
if not captioned:
|
||||
captioned = auto_caption_clip(
|
||||
deliver_path, transcript, start, end,
|
||||
split_ranges=_layouts.split_ranges(clip['layout_ranges']))
|
||||
split_ranges=split_ranges)
|
||||
print(f" ✅ Clip {i+1} ready: {clip_final_path}")
|
||||
# Hand the API the file to actually serve for this clip.
|
||||
# Without it the status poller guesses the clean reframe
|
||||
|
|
@ -2238,7 +2279,10 @@ if __name__ == '__main__':
|
|||
if os.path.exists(clip_temp_path):
|
||||
os.remove(clip_temp_path)
|
||||
|
||||
clip_workers = max(int(os.environ.get("CLIP_WORKERS", "3")), 1)
|
||||
# 6, not 3: measured side by side on balrog at load 48-67, a 7-clip
|
||||
# job finished 16% sooner with the same CPU, and the peak VRAM stayed
|
||||
# at 12 GB of 20 (bench, 25-sep-2026).
|
||||
clip_workers = max(int(os.environ.get("CLIP_WORKERS", "6")), 1)
|
||||
shorts = clips_data['shorts']
|
||||
failed = []
|
||||
with ThreadPoolExecutor(max_workers=min(clip_workers, len(shorts))) as pool:
|
||||
|
|
|
|||
|
|
@ -27,8 +27,8 @@ import punch_in
|
|||
import screencast_layout
|
||||
import layout_ranges
|
||||
import split_layout
|
||||
from ffmpeg_utils import (video_encode_args, escape_filter_value, QUALITY_FAST,
|
||||
METADATA_SCRUB)
|
||||
from ffmpeg_utils import (video_encode_args, blurred_backdrop, escape_filter_value,
|
||||
QUALITY_FAST, METADATA_SCRUB)
|
||||
|
||||
ANALYSIS_MAX_WIDTH = 640
|
||||
|
||||
|
|
@ -157,8 +157,7 @@ def general_filtergraph(out_w, out_h, content_h=None, orig_w=None, orig_h=None):
|
|||
fg_h += fg_h % 2
|
||||
return (
|
||||
f"[0:v]split=2[bga][fga];"
|
||||
f"[bga]scale=-2:{out_h},crop=w=min(iw\\,{out_w}):h={out_h},"
|
||||
f"scale={out_w}:{out_h},gblur=sigma=12[bg];"
|
||||
f"[bga]{blurred_backdrop(out_w, out_h, 12)}[bg];"
|
||||
# Scale by HEIGHT, then trim any overflow to the output width. crop
|
||||
# centres by default, and min() makes it a no-op when the scaled source
|
||||
# is already narrower than the frame (portrait/square sources).
|
||||
|
|
|
|||
27
subtitles.py
27
subtitles.py
|
|
@ -481,16 +481,11 @@ def _sanitize_font_name(name):
|
|||
return cleaned or "Verdana"
|
||||
|
||||
|
||||
def burn_subtitles(video_path, srt_path, output_path, alignment=2, fontsize=16,
|
||||
def subtitles_filter(srt_path, alignment=2, fontsize=16,
|
||||
font_name="Verdana", font_color="#FFFFFF",
|
||||
border_color="#000000", border_width=2,
|
||||
bg_color="#000000", bg_opacity=0.0):
|
||||
"""
|
||||
Burns subtitles into the video using FFmpeg.
|
||||
Supports two modes:
|
||||
- Outline mode (bg_opacity=0): Text with colored outline/border
|
||||
- Box mode (bg_opacity>0): Text with semi-transparent background box
|
||||
"""
|
||||
"""The -vf string burn_subtitles uses (also fed to hooks.add_hook_to_video)."""
|
||||
# Position mapping
|
||||
ass_alignment = 2
|
||||
align_lower = str(alignment).lower()
|
||||
|
|
@ -561,6 +556,24 @@ def burn_subtitles(video_path, srt_path, output_path, alignment=2, fontsize=16,
|
|||
vf = (f"subtitles=filename='{safe_srt_path}':fontsdir='{safe_fonts_dir}'"
|
||||
f":charenc=UTF-8:force_style='{style_string}'")
|
||||
|
||||
return vf
|
||||
|
||||
|
||||
def burn_subtitles(video_path, srt_path, output_path, alignment=2, fontsize=16,
|
||||
font_name="Verdana", font_color="#FFFFFF",
|
||||
border_color="#000000", border_width=2,
|
||||
bg_color="#000000", bg_opacity=0.0):
|
||||
"""
|
||||
Burns subtitles into the video using FFmpeg.
|
||||
Supports two modes:
|
||||
- Outline mode (bg_opacity=0): Text with colored outline/border
|
||||
- Box mode (bg_opacity>0): Text with semi-transparent background box
|
||||
"""
|
||||
vf = subtitles_filter(srt_path, alignment=alignment, fontsize=fontsize,
|
||||
font_name=font_name, font_color=font_color,
|
||||
border_color=border_color, border_width=border_width,
|
||||
bg_color=bg_color, bg_opacity=bg_opacity)
|
||||
|
||||
cmd = [
|
||||
'ffmpeg', '-y',
|
||||
'-i', video_path,
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ from ffmpeg_utils import (
|
|||
METADATA_SCRUB,
|
||||
QUALITY,
|
||||
QUALITY_FAST,
|
||||
blurred_backdrop,
|
||||
mark_ai_generated,
|
||||
reset_encoder_cache,
|
||||
video_encode_args,
|
||||
|
|
@ -18,6 +19,7 @@ from ffmpeg_utils import (
|
|||
@pytest.fixture(autouse=True)
|
||||
def _clean_encoder_state(monkeypatch):
|
||||
monkeypatch.delenv("FFMPEG_ENCODER", raising=False)
|
||||
monkeypatch.setattr(ffmpeg_utils, "_gpu_cut_sources", {})
|
||||
reset_encoder_cache()
|
||||
yield
|
||||
reset_encoder_cache()
|
||||
|
|
@ -208,3 +210,40 @@ def test_every_attempt_failing_raises_with_ffmpeg_stderr(_cut):
|
|||
with pytest.raises(RuntimeError, match="Invalid data found"):
|
||||
_cut([(1, 0, "Invalid data found when processing input")] * attempts)
|
||||
assert _cut.slept == list(ffmpeg_utils.CUT_RETRY_WAITS)
|
||||
|
||||
|
||||
def test_backdrop_blurs_at_quarter_size_and_fills_the_frame():
|
||||
chain = blurred_backdrop(1080, 1920, 12)
|
||||
assert "scale=-2:480,crop=w=min(iw\\,270):h=480" in chain
|
||||
assert "gblur=sigma=3," in chain
|
||||
assert chain.endswith("scale=1080:1920")
|
||||
|
||||
|
||||
def _gpu_source(monkeypatch, codec_pix):
|
||||
monkeypatch.setattr(ffmpeg_utils, "_gpu_cut_sources", {})
|
||||
monkeypatch.setattr(ffmpeg_utils, "_source_format",
|
||||
lambda path: tuple(codec_pix.split(",")))
|
||||
|
||||
|
||||
def test_cut_stays_on_the_gpu_for_8bit_420(_cut, monkeypatch):
|
||||
_gpu_source(monkeypatch, "h264,yuv420p")
|
||||
cmd = _cut([(0, 5_000_000, "")]).commands[0]
|
||||
assert cmd[cmd.index("-hwaccel") + 1] == "cuda"
|
||||
assert cmd[cmd.index("-hwaccel_output_format") + 1] == "cuda"
|
||||
assert "-pix_fmt" not in cmd
|
||||
assert "h264_nvenc" in cmd
|
||||
|
||||
|
||||
def test_cut_decodes_10bit_sources_on_the_cpu(_cut, monkeypatch):
|
||||
_gpu_source(monkeypatch, "hevc,yuv420p10le")
|
||||
cmd = _cut([(0, 5_000_000, "")]).commands[0]
|
||||
assert "-hwaccel" not in cmd
|
||||
assert cmd[cmd.index("-pix_fmt") + 1] == "yuv420p"
|
||||
|
||||
|
||||
def test_failed_gpu_cut_falls_back_to_the_cpu_decode(_cut, monkeypatch):
|
||||
_gpu_source(monkeypatch, "av1,yuv420p")
|
||||
fake = _cut([(1, 0, "cuvid error"), (0, 5_000_000, "")])
|
||||
assert "-hwaccel" in fake.commands[0]
|
||||
assert "-hwaccel" not in fake.commands[1]
|
||||
assert len(fake.commands) == 2
|
||||
|
|
|
|||
|
|
@ -348,12 +348,14 @@ class TestParakeetMemorySettings:
|
|||
assert opts["cudnn_conv_use_max_workspace"] == "0"
|
||||
|
||||
|
||||
def test_parakeet_threads_sleep_but_the_vad_keeps_its_defaults(monkeypatch):
|
||||
"""Spinning ORT threads were most of a job's CPU; the VAD must stay on
|
||||
load_vad's defaults (any options there change the transcript)."""
|
||||
def test_parakeet_threads_sleep_and_the_vad_runs_on_one_cpu_thread(monkeypatch):
|
||||
"""Spinning ORT threads were most of a job's CPU, and Silero on CUDA most
|
||||
of a transcription's wall time."""
|
||||
class FakeOptions:
|
||||
def __init__(self):
|
||||
self.entries = {}
|
||||
self.intra_op_num_threads = 0
|
||||
self.inter_op_num_threads = 0
|
||||
|
||||
def add_session_config_entry(self, key, value):
|
||||
self.entries[key] = value
|
||||
|
|
@ -382,7 +384,11 @@ def test_parakeet_threads_sleep_but_the_vad_keeps_its_defaults(monkeypatch):
|
|||
|
||||
tb._get_parakeet_model()
|
||||
|
||||
entries = calls["model"]["sess_options"].entries
|
||||
assert entries == {"session.intra_op.allow_spinning": "0",
|
||||
no_spin = {"session.intra_op.allow_spinning": "0",
|
||||
"session.inter_op.allow_spinning": "0"}
|
||||
assert calls["vad"] == (("silero",), {})
|
||||
assert calls["model"]["sess_options"].entries == no_spin
|
||||
args, kw = calls["vad"]
|
||||
assert args == ("silero",)
|
||||
assert kw["providers"] == ["CPUExecutionProvider"]
|
||||
assert kw["sess_options"].entries == no_spin
|
||||
assert kw["sess_options"].intra_op_num_threads == 1
|
||||
|
|
|
|||
|
|
@ -288,9 +288,7 @@ def parakeet_session_options():
|
|||
(prod bench 25-sep-2026). Without it: ~35 CPU-s, and the transcript is
|
||||
byte-identical (text and every word timestamp, 3 real videos).
|
||||
|
||||
Parakeet only: the VAD must keep ``load_vad``'s defaults. Passing it any
|
||||
options, even an empty SessionOptions, makes onnx_asr drop its default
|
||||
providers, the VAD falls to the CPU, and a word and 16 timestamps change.
|
||||
The VAD gets its own options (vad_load_kwargs).
|
||||
"""
|
||||
import onnxruntime as rt
|
||||
opts = rt.SessionOptions()
|
||||
|
|
@ -299,6 +297,26 @@ def parakeet_session_options():
|
|||
return opts
|
||||
|
||||
|
||||
def vad_load_kwargs():
|
||||
"""Silero VAD on the CPU, one sleeping thread.
|
||||
|
||||
load_vad's default puts Silero on CUDA, where it runs one 32 ms chunk at a
|
||||
time with a host/device copy around each: most of a transcription's wall
|
||||
time. On one CPU thread the whole transcription is 2-3x faster (9 min of
|
||||
audio: 28 s -> 9 s) and cheaper in CPU too. The VAD's numbers are not
|
||||
bit-identical across devices: over 3 real videos (3,939 words) one word
|
||||
changed ("claudio" -> "cloud", for "Claude") and a few word times moved by
|
||||
up to 48 ms (bench, 25-sep-2026).
|
||||
"""
|
||||
import onnxruntime as rt
|
||||
opts = rt.SessionOptions()
|
||||
opts.intra_op_num_threads = 1
|
||||
opts.inter_op_num_threads = 1
|
||||
opts.add_session_config_entry("session.intra_op.allow_spinning", "0")
|
||||
opts.add_session_config_entry("session.inter_op.allow_spinning", "0")
|
||||
return {"sess_options": opts, "providers": ["CPUExecutionProvider"]}
|
||||
|
||||
|
||||
def _get_parakeet_model():
|
||||
global _parakeet_model
|
||||
with _parakeet_lock:
|
||||
|
|
@ -306,7 +324,7 @@ def _get_parakeet_model():
|
|||
import onnx_asr
|
||||
model = onnx_asr.load_model(PARAKEET_MODEL_ID, providers=parakeet_providers(),
|
||||
sess_options=parakeet_session_options())
|
||||
vad = onnx_asr.load_vad("silero")
|
||||
vad = onnx_asr.load_vad("silero", **vad_load_kwargs())
|
||||
_parakeet_model = model.with_vad(
|
||||
vad, batch_size=PARAKEET_VAD_BATCH).with_timestamps()
|
||||
return _parakeet_model
|
||||
|
|
|
|||
Loading…
Reference in a new issue