The truly free, open-source, local-first, cross-platform CapCut replacement. Scriptable through a JSON-RPC API & MCP.
Rust ffmpegfree-video-editormodel-context-protocolnon-linear-editoroffline-firstopen-source-video-editorself-hostedvideo-editingvideo-editing-automationvideo-editing-softwarevideo-editing-toolsvideo-editorvoice-cloningyoutube-automationyoutube-shorts
chore(test): commit the feature experiments, documented and patched
Jareerfc66abd51c66
diff --git a/test/.gitignore b/test/.gitignorenew file mode 100644index 00000000..1001b771--- /dev/null+++ b/test/.gitignore@@ -0,0 +1,9 @@+# Experiment inputs/outputs and model weights - the scripts are the record,+# their artifacts are not. (test/assets/ is already ignored repo-wide.)+*.wav+*.mp3+*.mp4+*.onnx+*.json+denoised.*+enhanced.*diff --git a/test/README.md b/test/README.mdnew file mode 100644index 00000000..63775754--- /dev/null+++ b/test/README.md@@ -0,0 +1,53 @@+# Feature experiments++One-off Python prototypes probing candidate WolfCut features before any of+them earns a Rust implementation. Each measures the thing that decides+shippability - speed against realtime on ordinary hardware, and output+quality by ear/eye - because per decision 0010 nothing ships that makes the+user install tools or wait on a server.++These are research scripts, not product code: run them from this directory,+point them at anything in `assets/` (gitignored), and read the numbers.++| Experiment | Probes | Candidate feature |+| --- | --- | --- |+| `silero_vad/test_vad.py` | Silero VAD speech regions + speed | silence removal, caption pre-pass |+| `rnnoise/test_denoise.py` | RNNoise denoise quality + speed | one-click "reduce noise" on a clip |+| `enhance_voice.py` | full repair chain: de-plosive, de-click (LPC interpolation), DeepFilterNet3/MossFormer2, ffmpeg polish | "Enhance voice" button |+| `sweet_voice.py` | the CapCut-style "Sweet" chain as pure ffmpeg filters | shipped as the `sweet` entry in the filters catalogue |+| `scene_detect/test_scene_detect.py` | PySceneDetect cut detection + speed | auto-split at scene cuts |+| `black_frames/detect_black_frames.py` | luminance-threshold black segment detection | trim dead frames, sanity-check exports |+| `face_blur/face_blur.py` | YuNet detection + Gaussian blur per frame | face blur effect |+| `hardware_analysis/analyze_hardware.py` | CPU/GPU/codec/hwaccel capability probe + tier score | first-run quality tier defaults (Rust port would use CPUID/wgpu, not subprocess probes) |++## Dependencies++Python 3.11+. Everything is per-experiment - install only what you're+poking at:++```sh+pip install silero-vad # silero_vad (pulls onnxruntime, torch-free)+pip install pyrnnoise # rnnoise+pip install numpy scipy # enhance_voice (DSP stages)+pip install deepfilternet torch # enhance_voice --backend deepfilternet+pip install clearvoice # enhance_voice --backend clearvoice+pip install scenedetect[opencv] # scene_detect+pip install opencv-python numpy # black_frames, face_blur+pip install psutil # hardware_analysis+```++`sweet_voice.py` and the polish stage of `enhance_voice.py` only need+`ffmpeg`/`ffprobe` on PATH. `face_blur` additionally needs the YuNet model+file (`face_detection_yunet_*.onnx` from the OpenCV zoo) beside it or via+`--model`.++## Findings worth keeping++- The `sweet` chain graduated: `desktop/src/lib/filters.ts` and+ `wolfcut-export::chains` carry it verbatim.+- `enhance_voice.py`'s stage *order* is the finding: surgical repairs+ (clicks, plosives) must run before the neural pass - networks trained on+ additive noise smear impulses instead of removing them - and loudness+ after it, because network output has arbitrary gain.+- Every detector here comfortably beats realtime on CPU except the neural+ denoisers, which are the reason a "processing..." progress bar exists.diff --git a/test/black_frames/detect_black_frames.py b/test/black_frames/detect_black_frames.pynew file mode 100644index 00000000..d6fb1eba--- /dev/null+++ b/test/black_frames/detect_black_frames.py@@ -0,0 +1,124 @@+from __future__ import annotations++import argparse+import time+from pathlib import Path++import cv2+import numpy as np+++def main() -> int:+ parser = argparse.ArgumentParser(+ description="Detect black or near-black regions in a video."+ )+ parser.add_argument("input", type=Path)++ parser.add_argument(+ "--threshold",+ type=int,+ default=16,+ help="Pixel luminance considered black. Default: 16/255.",+ )++ parser.add_argument(+ "--black-percent",+ type=float,+ default=0.98,+ help="Fraction of pixels that must be black. Default: 0.98.",+ )++ parser.add_argument(+ "--min-duration",+ type=float,+ default=0.10,+ help="Minimum black segment duration in seconds.",+ )++ args = parser.parse_args()++ if not args.input.exists():+ raise FileNotFoundError(args.input)++ cap = cv2.VideoCapture(str(args.input))++ if not cap.isOpened():+ raise RuntimeError(f"Could not open {args.input}")++ # Some containers report no rate; 30 keeps the timestamps usable rather+ # than dividing by zero on the first frame.+ fps = cap.get(cv2.CAP_PROP_FPS) or 30.0+ frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))+ duration = frame_count / fps++ black_segments: list[tuple[float, float]] = []++ segment_start: float | None = None++ frame_index = 0+ start_time = time.perf_counter()++ while True:+ ok, frame = cap.read()++ if not ok:+ break++ gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)++ black_ratio = np.count_nonzero(gray <= args.threshold) / gray.size+ is_black = black_ratio >= args.black_percent++ timestamp = frame_index / fps++ if is_black:+ if segment_start is None:+ segment_start = timestamp++ elif segment_start is not None:+ segment_end = timestamp++ if segment_end - segment_start >= args.min_duration:+ black_segments.append((segment_start, segment_end))++ segment_start = None++ frame_index += 1++ if segment_start is not None:+ segment_end = frame_index / fps++ if segment_end - segment_start >= args.min_duration:+ black_segments.append((segment_start, segment_end))++ elapsed = time.perf_counter() - start_time++ cap.release()++ speed = duration / elapsed if elapsed else 0.0+ processing_fps = frame_index / elapsed if elapsed else 0.0++ print()+ print("Black Frame Detection")+ print("---------------------")+ print(f"Input: {args.input}")+ print(f"Duration: {duration:.2f}s")+ print(f"Frames: {frame_index}")+ print(f"Processing: {elapsed:.2f}s")+ print(f"Processing FPS: {processing_fps:.1f}")+ print(f"Speed: {speed:.1f}x realtime")+ print(f"Black segments: {len(black_segments)}")+ print()++ for i, (start, end) in enumerate(black_segments, 1):+ print(+ f"{i:03d} | "+ f"{start:8.3f}s -> {end:8.3f}s | "+ f"{end - start:6.3f}s"+ )++ return 0+++if __name__ == "__main__":+ raise SystemExit(main())\ No newline at end of filediff --git a/test/face_blur/face_blur.py b/test/face_blur/face_blur.pynew file mode 100644index 00000000..7a835e14--- /dev/null+++ b/test/face_blur/face_blur.py@@ -0,0 +1,155 @@+from __future__ import annotations++import argparse+import time+from pathlib import Path++import cv2+++def clamp(value: int, low: int, high: int) -> int:+ return max(low, min(value, high))+++def main() -> int:+ parser = argparse.ArgumentParser(+ description="Detect faces with YuNet and blur them."+ )+ parser.add_argument("input", type=Path)+ parser.add_argument("output", type=Path)+ parser.add_argument(+ "--model",+ type=Path,+ default=Path("face_detection_yunet_2026may.onnx"),+ )+ parser.add_argument(+ "--confidence",+ type=float,+ default=0.85,+ )+ parser.add_argument(+ "--padding",+ type=float,+ default=0.18,+ help="Extra padding around detected faces.",+ )++ args = parser.parse_args()++ if not args.input.exists():+ raise FileNotFoundError(args.input)++ if not args.model.exists():+ raise FileNotFoundError(args.model)++ capture = cv2.VideoCapture(str(args.input))++ if not capture.isOpened():+ raise RuntimeError(f"Could not open {args.input}")++ width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH))+ height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))+ # Some containers report no rate; 30 keeps the writer producing a+ # playable file rather than one with a zero timebase.+ fps = capture.get(cv2.CAP_PROP_FPS) or 30.0+ frame_count = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))++ duration = frame_count / fps++ detector = cv2.FaceDetectorYN.create(+ str(args.model),+ "",+ (width, height),+ args.confidence,+ 0.3,+ 5000,+ )++ writer = cv2.VideoWriter(+ str(args.output),+ cv2.VideoWriter_fourcc(*"mp4v"),+ fps,+ (width, height),+ )++ if not writer.isOpened():+ raise RuntimeError("Could not create output video")++ processed = 0+ detected_faces = 0++ start_time = time.perf_counter()++ while True:+ ok, frame = capture.read()++ if not ok:+ break++ detector.setInputSize((frame.shape[1], frame.shape[0]))++ _, faces = detector.detect(frame)++ if faces is not None:+ for face in faces:+ x, y, w, h = face[:4]++ x = int(x)+ y = int(y)+ w = int(w)+ h = int(h)++ pad_x = int(w * args.padding)+ pad_y = int(h * args.padding)++ x1 = clamp(x - pad_x, 0, width)+ y1 = clamp(y - pad_y, 0, height)+ x2 = clamp(x + w + pad_x, 0, width)+ y2 = clamp(y + h + pad_y, 0, height)++ region = frame[y1:y2, x1:x2]++ if region.size == 0:+ continue++ # Kernel roughly proportional to face size.+ kernel = max(15, min(w, h) // 3)+ kernel |= 1 # Gaussian kernel must be odd.++ blurred = cv2.GaussianBlur(+ region,+ (kernel, kernel),+ 0,+ )++ frame[y1:y2, x1:x2] = blurred+ detected_faces += 1++ writer.write(frame)+ processed += 1++ elapsed = time.perf_counter() - start_time++ capture.release()+ writer.release()++ processing_fps = processed / elapsed if elapsed else 0.0+ realtime_speed = duration / elapsed if elapsed else 0.0++ print()+ print("YuNet Face Blur")+ print("---------------")+ print(f"Resolution: {width}x{height}")+ print(f"Frames: {processed}")+ print(f"Duration: {duration:.2f}s")+ print(f"Faces detected: {detected_faces}")+ print(f"Processing time: {elapsed:.2f}s")+ print(f"Processing FPS: {processing_fps:.1f}")+ print(f"Speed: {realtime_speed:.2f}x realtime")+ print(f"Output: {args.output}")++ return 0+++if __name__ == "__main__":+ raise SystemExit(main())\ No newline at end of filediff --git a/test/hardware_analysis/analyze_hardware.py b/test/hardware_analysis/analyze_hardware.pynew file mode 100644index 00000000..ea73ddc3--- /dev/null+++ b/test/hardware_analysis/analyze_hardware.py@@ -0,0 +1,640 @@+from __future__ import annotations++import json+import os+import platform+import shutil+import subprocess+from dataclasses import asdict, dataclass, field+from pathlib import Path+from typing import Optional++import psutil+++@dataclass+class CPUInfo:+ model: str+ architecture: str+ physical_cores: Optional[int]+ logical_cores: Optional[int]+ frequency_mhz: Optional[float]+ flags: list[str] = field(default_factory=list)++ avx: bool = False+ avx2: bool = False+ sse4_1: bool = False+ sse4_2: bool = False+++@dataclass+class MemoryInfo:+ total_gb: float+ available_gb: float+++@dataclass+class DiskInfo:+ path: str+ total_gb: float+ free_gb: float+++@dataclass+class GPUInfo:+ name: str+ vendor: Optional[str] = None+ vram_mb: Optional[int] = None++ cuda: bool = False+ vulkan: bool = False+ directml_possible: bool = False+ metal_possible: bool = False+++@dataclass+class CodecCapabilities:+ ffmpeg_available: bool = False++ h264_decode: bool = False+ hevc_decode: bool = False+ av1_decode: bool = False++ h264_encode: bool = False+ hevc_encode: bool = False+ av1_encode: bool = False++ nvenc: bool = False+ qsv: bool = False+ vaapi: bool = False+ videotoolbox: bool = False+ amf: bool = False+++@dataclass+class HardwareProfile:+ os: str+ os_version: str++ cpu: CPUInfo+ memory: MemoryInfo+ disks: list[DiskInfo]++ gpus: list[GPUInfo]+ codecs: CodecCapabilities++ suggested_tier: str+ notes: list[str] = field(default_factory=list)+++def run_command(command: list[str]) -> str:+ try:+ result = subprocess.run(+ command,+ capture_output=True,+ text=True,+ timeout=5,+ check=False,+ )++ if result.returncode == 0:+ return result.stdout.strip()++ except Exception:+ pass++ return ""+++def get_cpu_model() -> str:+ system = platform.system()++ if system == "Windows":+ output = run_command([+ "powershell",+ "-NoProfile",+ "-Command",+ "(Get-CimInstance Win32_Processor).Name",+ ])++ if output:+ return output.splitlines()[0].strip()++ elif system == "Darwin":+ output = run_command([+ "sysctl",+ "-n",+ "machdep.cpu.brand_string",+ ])++ if output:+ return output++ output = run_command([+ "sysctl",+ "-n",+ "hw.model",+ ])++ if output:+ return output++ elif system == "Linux":+ try:+ cpuinfo = Path("/proc/cpuinfo").read_text(+ encoding="utf-8",+ errors="ignore",+ )++ for line in cpuinfo.splitlines():+ if line.lower().startswith("model name"):+ return line.split(":", 1)[1].strip()++ except Exception:+ pass++ return platform.processor() or "Unknown CPU"+++def get_cpu_flags() -> list[str]:+ system = platform.system()++ if system == "Linux":+ try:+ cpuinfo = Path("/proc/cpuinfo").read_text(+ encoding="utf-8",+ errors="ignore",+ )++ for line in cpuinfo.splitlines():+ if line.lower().startswith(("flags", "features")):+ return line.split(":", 1)[1].lower().split()++ except Exception:+ pass++ if system == "Darwin":+ output = run_command([+ "sysctl",+ "-n",+ "machdep.cpu.features",+ ])++ output += " " + run_command([+ "sysctl",+ "-n",+ "machdep.cpu.leaf7_features",+ ])++ return output.lower().split()++ # Windows CPU-feature detection is intentionally incomplete here.+ # A Rust version should use CPUID directly.+ return []+++def detect_cpu() -> CPUInfo:+ flags = get_cpu_flags()++ freq = psutil.cpu_freq()++ return CPUInfo(+ model=get_cpu_model(),+ architecture=platform.machine(),+ physical_cores=psutil.cpu_count(logical=False),+ logical_cores=psutil.cpu_count(logical=True),+ frequency_mhz=freq.max if freq else None,+ flags=flags,+ avx="avx" in flags,+ avx2="avx2" in flags,+ sse4_1="sse4_1" in flags or "sse4.1" in flags,+ sse4_2="sse4_2" in flags or "sse4.2" in flags,+ )+++def detect_memory() -> MemoryInfo:+ memory = psutil.virtual_memory()++ return MemoryInfo(+ total_gb=round(memory.total / (1024 ** 3), 2),+ available_gb=round(memory.available / (1024 ** 3), 2),+ )+++def detect_disks() -> list[DiskInfo]:+ disks: list[DiskInfo] = []++ seen = set()++ for partition in psutil.disk_partitions(all=False):+ path = partition.mountpoint++ if path in seen:+ continue++ seen.add(path)++ try:+ usage = psutil.disk_usage(path)++ disks.append(+ DiskInfo(+ path=path,+ total_gb=round(+ usage.total / (1024 ** 3),+ 2,+ ),+ free_gb=round(+ usage.free / (1024 ** 3),+ 2,+ ),+ )+ )++ except Exception:+ pass++ return disks+++def gpu_vendor(name: str) -> Optional[str]:+ lower = name.lower()++ if "nvidia" in lower:+ return "NVIDIA"++ if "amd" in lower or "radeon" in lower:+ return "AMD"++ if "intel" in lower:+ return "Intel"++ if "apple" in lower:+ return "Apple"++ return None+++def detect_nvidia_gpus() -> list[GPUInfo]:+ if shutil.which("nvidia-smi") is None:+ return []++ output = run_command([+ "nvidia-smi",+ "--query-gpu=name,memory.total",+ "--format=csv,noheader,nounits",+ ])++ gpus = []++ for line in output.splitlines():+ if not line.strip():+ continue++ parts = [part.strip() for part in line.split(",")]++ try:+ name = parts[0]+ vram_mb = int(parts[1])++ gpus.append(+ GPUInfo(+ name=name,+ vendor="NVIDIA",+ vram_mb=vram_mb,+ cuda=True,+ vulkan=True,+ directml_possible=platform.system() == "Windows",+ )+ )++ except Exception:+ continue++ return gpus+++def detect_windows_gpus() -> list[GPUInfo]:+ output = run_command([+ "powershell",+ "-NoProfile",+ "-Command",+ """+ Get-CimInstance Win32_VideoController |+ Select-Object Name,AdapterRAM |+ ConvertTo-Json+ """,+ ])++ if not output:+ return []++ try:+ parsed = json.loads(output)++ if isinstance(parsed, dict):+ parsed = [parsed]++ result = []++ for gpu in parsed:+ name = gpu.get("Name") or "Unknown GPU"+ ram = gpu.get("AdapterRAM")++ vram_mb = None++ if isinstance(ram, int):+ vram_mb = int(ram / (1024 ** 2))++ result.append(+ GPUInfo(+ name=name,+ vendor=gpu_vendor(name),+ vram_mb=vram_mb,+ directml_possible=True,+ )+ )++ return result++ except Exception:+ return []+++def detect_macos_gpu() -> list[GPUInfo]:+ output = run_command([+ "system_profiler",+ "SPDisplaysDataType",+ ])++ if not output:+ return []++ result = []++ for line in output.splitlines():+ line = line.strip()++ if line.startswith("Chipset Model:"):+ name = line.split(":", 1)[1].strip()++ result.append(+ GPUInfo(+ name=name,+ vendor=gpu_vendor(name),+ metal_possible=True,+ )+ )++ return result+++def detect_linux_gpus() -> list[GPUInfo]:+ output = run_command([+ "lspci",+ ])++ result = []++ for line in output.splitlines():+ lower = line.lower()++ if "vga compatible controller" not in lower \+ and "3d controller" not in lower:+ continue++ name = line.split(":", 2)[-1].strip()++ result.append(+ GPUInfo(+ name=name,+ vendor=gpu_vendor(name),+ )+ )++ return result+++def detect_vulkan_support() -> bool:+ if shutil.which("vulkaninfo") is None:+ return False++ output = run_command([+ "vulkaninfo",+ "--summary",+ ])++ return bool(output)+++def detect_gpus() -> list[GPUInfo]:+ system = platform.system()++ gpus: list[GPUInfo] = []++ # Prefer NVIDIA SMI because VRAM reporting is useful.+ gpus.extend(detect_nvidia_gpus())++ existing_names = {+ gpu.name.lower()+ for gpu in gpus+ }++ if system == "Windows":+ platform_gpus = detect_windows_gpus()++ elif system == "Darwin":+ platform_gpus = detect_macos_gpu()++ elif system == "Linux":+ platform_gpus = detect_linux_gpus()++ else:+ platform_gpus = []++ for gpu in platform_gpus:+ if gpu.name.lower() not in existing_names:+ gpus.append(gpu)++ vulkan = detect_vulkan_support()++ for gpu in gpus:+ if vulkan:+ gpu.vulkan = True++ if system == "Windows":+ gpu.directml_possible = True++ if system == "Darwin":+ gpu.metal_possible = True++ return gpus+++def detect_ffmpeg_capabilities() -> CodecCapabilities:+ caps = CodecCapabilities()++ if shutil.which("ffmpeg") is None:+ return caps++ caps.ffmpeg_available = True++ decoders = run_command([+ "ffmpeg",+ "-hide_banner",+ "-decoders",+ ]).lower()++ encoders = run_command([+ "ffmpeg",+ "-hide_banner",+ "-encoders",+ ]).lower()++ hwaccels = run_command([+ "ffmpeg",+ "-hide_banner",+ "-hwaccels",+ ]).lower()++ caps.h264_decode = " h264 " in decoders+ caps.hevc_decode = " hevc " in decoders+ caps.av1_decode = " av1 " in decoders++ caps.h264_encode = "libx264" in encoders+ caps.hevc_encode = "libx265" in encoders+ caps.av1_encode = (+ "libaom-av1" in encoders+ or "svt-av1" in encoders+ )++ caps.nvenc = "_nvenc" in encoders+ caps.qsv = "_qsv" in encoders or "qsv" in hwaccels+ caps.vaapi = "_vaapi" in encoders or "vaapi" in hwaccels+ caps.videotoolbox = (+ "_videotoolbox" in encoders+ or "videotoolbox" in hwaccels+ )+ caps.amf = "_amf" in encoders++ return caps+++def classify_hardware(+ cpu: CPUInfo,+ memory: MemoryInfo,+ gpus: list[GPUInfo],+) -> tuple[str, list[str]]:+ score = 0+ notes = []++ logical = cpu.logical_cores or 0++ if logical >= 16:+ score += 3+ elif logical >= 8:+ score += 2+ elif logical >= 4:+ score += 1++ if memory.total_gb >= 32:+ score += 3+ elif memory.total_gb >= 16:+ score += 2+ elif memory.total_gb >= 8:+ score += 1++ best_vram = max(+ (+ gpu.vram_mb or 0+ for gpu in gpus+ ),+ default=0,+ )++ has_discrete = any(+ gpu.vendor in {"NVIDIA", "AMD"}+ for gpu in gpus+ )++ if best_vram >= 8000:+ score += 4++ elif best_vram >= 4000:+ score += 3++ elif has_discrete:+ score += 2++ elif gpus:+ score += 1++ if memory.total_gb < 8:+ notes.append(+ "Low system memory: prefer proxies and lightweight models."+ )++ if not has_discrete:+ notes.append(+ "No obvious discrete GPU: favor CPU/iGPU-friendly inference."+ )++ if best_vram and best_vram < 4000:+ notes.append(+ "Limited VRAM: avoid large GPU-resident models."+ )++ if score <= 3:+ tier = "low"++ elif score <= 6:+ tier = "mainstream"++ elif score <= 9:+ tier = "high"++ else:+ tier = "enthusiast"++ return tier, notes+++def build_profile() -> HardwareProfile:+ cpu = detect_cpu()+ memory = detect_memory()+ disks = detect_disks()+ gpus = detect_gpus()+ codecs = detect_ffmpeg_capabilities()++ tier, notes = classify_hardware(+ cpu,+ memory,+ gpus,+ )++ return HardwareProfile(+ os=platform.system(),+ os_version=platform.platform(),+ cpu=cpu,+ memory=memory,+ disks=disks,+ gpus=gpus,+ codecs=codecs,+ suggested_tier=tier,+ notes=notes,+ )+++def main() -> None:+ profile = build_profile()++ print(+ json.dumps(+ asdict(profile),+ indent=2,+ )+ )+++if __name__ == "__main__":+ main()\ No newline at end of filediff --git a/test/rnnoise/test_denoise.py b/test/rnnoise/test_denoise.pynew file mode 100644index 00000000..86703fc2--- /dev/null+++ b/test/rnnoise/test_denoise.py@@ -0,0 +1,95 @@+from __future__ import annotations++import argparse+import time+import wave+from pathlib import Path++from pyrnnoise import RNNoise+++def wav_facts(path: Path) -> tuple[float, int]:+ """Duration in seconds and the file's actual sample rate."""+ with wave.open(str(path), "rb") as wav:+ frames = wav.getnframes()+ rate = wav.getframerate()+ return frames / float(rate), rate+++def main() -> int:+ parser = argparse.ArgumentParser(+ description="Benchmark RNNoise speech denoising."+ )+ parser.add_argument("input", type=Path)+ parser.add_argument(+ "output",+ type=Path,+ nargs="?",+ default=Path("denoised.wav"),+ )++ args = parser.parse_args()++ if not args.input.exists():+ raise FileNotFoundError(args.input)++ duration, sample_rate = wav_facts(args.input)++ print()+ print("RNNoise benchmark")+ print("-----------------")+ print(f"Input: {args.input}")+ print(f"Output: {args.output}")+ print(f"Audio duration: {duration:.2f}s")+ print(f"Sample rate: {sample_rate} Hz")++ # The file's own rate, not a hardcoded 48000: RNNoise resamples+ # internally to its 48k frames either way, but lying about the input+ # rate time-stretches the output.+ denoiser = RNNoise(sample_rate=sample_rate)++ start = time.perf_counter()++ speech_prob_sum = 0.0+ speech_prob_count = 0++ for probabilities in denoiser.denoise_wav(+ str(args.input),+ str(args.output),+ ):+ # stereo may return more than one probability+ try:+ values = list(probabilities)+ except TypeError:+ values = [float(probabilities)]++ for value in values:+ speech_prob_sum += float(value)+ speech_prob_count += 1++ elapsed = time.perf_counter() - start++ realtime_factor = elapsed / duration if duration else 0.0+ speed = duration / elapsed if elapsed else 0.0++ print(f"Processing time: {elapsed:.3f}s")+ print(f"Realtime factor: {realtime_factor:.4f}x")+ print(f"Speed: {speed:.1f}x realtime")++ if speech_prob_count:+ print(+ f"Avg speech prob: "+ f"{speech_prob_sum / speech_prob_count:.3f}"+ )++ print()+ print("Done.")+ print("Listen to A/B:")+ print(f" original: {args.input}")+ print(f" denoised: {args.output}")++ return 0+++if __name__ == "__main__":+ raise SystemExit(main())\ No newline at end of filediff --git a/test/scene_detect/test_scene_detect.py b/test/scene_detect/test_scene_detect.pynew file mode 100644index 00000000..3bd8516c--- /dev/null+++ b/test/scene_detect/test_scene_detect.py@@ -0,0 +1,129 @@+from __future__ import annotations++import argparse+import json+import time+from pathlib import Path++from scenedetect import ContentDetector, SceneManager, open_video+++def main() -> int:+ parser = argparse.ArgumentParser(+ description="Detect scene cuts and benchmark processing speed."+ )+ parser.add_argument("input", type=Path)++ parser.add_argument(+ "--threshold",+ type=float,+ default=27.0,+ help="Higher = fewer cuts. Default: 27.",+ )++ parser.add_argument(+ "--min-scene-frames",+ type=int,+ default=15,+ help="Minimum scene length in frames.",+ )++ parser.add_argument(+ "--json",+ type=Path,+ default=None,+ )++ args = parser.parse_args()++ if not args.input.exists():+ raise FileNotFoundError(args.input)++ video = open_video(str(args.input))++ duration_seconds = video.duration.get_seconds()+ fps = video.frame_rate++ manager = SceneManager()++ manager.add_detector(+ ContentDetector(+ threshold=args.threshold,+ min_scene_len=args.min_scene_frames,+ )+ )++ start = time.perf_counter()++ frames_processed = manager.detect_scenes(+ video=video,+ show_progress=True,+ )++ elapsed = time.perf_counter() - start++ scenes = manager.get_scene_list()++ speed = duration_seconds / elapsed if elapsed else 0+ processing_fps = frames_processed / elapsed if elapsed else 0++ print()+ print("Scene Detection")+ print("---------------")+ print(f"Input: {args.input}")+ print(f"Duration: {duration_seconds:.2f}s")+ print(f"Source FPS: {fps:.2f}")+ print(f"Frames: {frames_processed}")+ print(f"Scenes: {len(scenes)}")+ print(f"Processing: {elapsed:.3f}s")+ print(f"Speed: {speed:.1f}x realtime")+ print(f"Analysis FPS: {processing_fps:.1f}")+ print()++ results = []++ for index, (start_tc, end_tc) in enumerate(scenes, start=1):+ start_sec = start_tc.get_seconds()+ end_sec = end_tc.get_seconds()++ results.append(+ {+ "scene": index,+ "start": start_sec,+ "end": end_sec,+ "duration": end_sec - start_sec,+ }+ )++ print(+ f"{index:03d} | "+ f"{start_sec:8.3f}s -> "+ f"{end_sec:8.3f}s | "+ f"{end_sec - start_sec:7.3f}s"+ )++ if args.json:+ args.json.parent.mkdir(parents=True, exist_ok=True)++ args.json.write_text(+ json.dumps(+ {+ "input": str(args.input),+ "threshold": args.threshold,+ "duration_seconds": duration_seconds,+ "processing_seconds": elapsed,+ "speed_realtime": speed,+ "scenes": results,+ },+ indent=2,+ ),+ encoding="utf-8",+ )++ print(f"\nSaved: {args.json}")++ return 0+++if __name__ == "__main__":+ raise SystemExit(main())\ No newline at end of filediff --git a/test/silero_vad/test_vad.py b/test/silero_vad/test_vad.pynew file mode 100644index 00000000..6e550376--- /dev/null+++ b/test/silero_vad/test_vad.py@@ -0,0 +1,120 @@+# test/silero_vad/test_vad.py++from __future__ import annotations++import argparse+import json+import time+from pathlib import Path++from silero_vad import (+ load_silero_vad,+ read_audio,+ get_speech_timestamps,+)+++def main() -> int:+ parser = argparse.ArgumentParser(+ description="Benchmark Silero VAD and print detected speech regions."+ )+ parser.add_argument("input", type=Path, help="Input audio file")+ parser.add_argument(+ "--threshold",+ type=float,+ default=0.5,+ help="Speech probability threshold (default: 0.5)",+ )+ parser.add_argument(+ "--json",+ type=Path,+ default=None,+ help="Optional path to save detected regions as JSON",+ )++ args = parser.parse_args()++ if not args.input.exists():+ raise FileNotFoundError(args.input)++ model_start = time.perf_counter()+ model = load_silero_vad(onnx=True)+ model_load_time = time.perf_counter() - model_start++ audio_start = time.perf_counter()+ audio = read_audio(str(args.input), sampling_rate=16000)+ audio_load_time = time.perf_counter() - audio_start++ duration_seconds = len(audio) / 16000.0++ inference_start = time.perf_counter()++ segments = get_speech_timestamps(+ audio,+ model,+ sampling_rate=16000,+ threshold=args.threshold,+ return_seconds=True,+ )++ inference_time = time.perf_counter() - inference_start++ speech_seconds = sum(+ float(segment["end"]) - float(segment["start"])+ for segment in segments+ )++ realtime_factor = (+ inference_time / duration_seconds+ if duration_seconds > 0+ else 0.0+ )++ print()+ print("Silero VAD")+ print("----------")+ print(f"File: {args.input}")+ print(f"Audio duration: {duration_seconds:.2f}s")+ print(f"Model load: {model_load_time:.3f}s")+ print(f"Audio load: {audio_load_time:.3f}s")+ print(f"Inference: {inference_time:.3f}s")+ print(f"Realtime factor:{realtime_factor:.4f}x")+ print(f"Speed: {1 / realtime_factor:.1f}x realtime"+ if realtime_factor > 0 else "Speed: n/a")+ print(f"Speech: {speech_seconds:.2f}s")+ print(f"Segments: {len(segments)}")+ print()++ for i, segment in enumerate(segments, start=1):+ start = float(segment["start"])+ end = float(segment["end"])++ print(+ f"{i:03d} | "+ f"{start:8.3f}s -> {end:8.3f}s | "+ f"{end - start:6.3f}s"+ )++ if args.json:+ args.json.parent.mkdir(parents=True, exist_ok=True)++ result = {+ "input": str(args.input),+ "duration_seconds": duration_seconds,+ "inference_seconds": inference_time,+ "realtime_factor": realtime_factor,+ "speech_seconds": speech_seconds,+ "segments": segments,+ }++ args.json.write_text(+ json.dumps(result, indent=2),+ encoding="utf-8",+ )++ print(f"\nSaved: {args.json}")++ return 0++if __name__ == "__main__":+ raise SystemExit(main())\ No newline at end of file