Skip to content

The truly free, open-source, local-first, cross-platform CapCut replacement. Scriptable through a JSON-RPC API & MCP.

chore: the Python prototypes under test/ go

Jareer6932a65dc040
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 042f1451..85a032d0 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -40,7 +40,6 @@ Slint UI - is one Cargo workspace under `src/`.
| Path | What lives there |
|---|---|
| `src/crates/` | The engine (core, media, render, export, project), the host layer (`concat-host`, `concat-speech`), the CLI, and `concat`, the Slint editor window |
-| `test/` | Python prototypes of analyses, kept for reference (see `test/README.md`); no fixtures and no automated tests |
[`src/README.md`](src/README.md) explains how the crates fit together and
where the sharp edges are. Read it before touching the engine.
diff --git a/test/.gitignore b/test/.gitignore
deleted file mode 100644
index 1001b771..00000000
--- a/test/.gitignore
+++ /dev/null
@@ -1,9 +0,0 @@
-# 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.md
deleted file mode 100644
index 5ee340fd..00000000
--- a/test/README.md
+++ /dev/null
@@ -1,53 +0,0 @@
-# Feature experiments
-
-One-off Python prototypes probing candidate Concat 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 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 "Sweet" voice 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: `concat-export`'s catalogue,
- `concat-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.py
deleted file mode 100644
index d6fb1eba..00000000
--- a/test/black_frames/detect_black_frames.py
+++ /dev/null
@@ -1,124 +0,0 @@
-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 file
diff --git a/test/deflicker/diagnose.py b/test/deflicker/diagnose.py
deleted file mode 100644
index 66144fcd..00000000
--- a/test/deflicker/diagnose.py
+++ /dev/null
@@ -1,725 +0,0 @@
-#!/usr/bin/env python3
-
-import sys
-import cv2
-import numpy as np
-
-RINGS = 20
-ANALYSIS_W = 320
-SECTORS = 4
-
-SECTOR_NAMES = [
- "RIGHT",
- "BOTTOM",
- "LEFT",
- "TOP",
-]
-
-
-def luminance(frame):
- f = frame.astype(np.float32) / 255.0
-
- return (
- 0.0722 * f[:, :, 0]
- + 0.7152 * f[:, :, 1]
- + 0.2126 * f[:, :, 2]
- )
-
-
-def robust_median(values):
- if values.size == 0:
- return np.nan
-
- lo = np.percentile(values, 10)
- hi = np.percentile(values, 90)
-
- trimmed = values[
- (values >= lo) &
- (values <= hi)
- ]
-
- if trimmed.size == 0:
- return float(np.median(values))
-
- return float(np.median(trimmed))
-
-
-def make_geometry(h, w):
- """
- Elliptical radius instead of corner-normalized Euclidean radius.
-
- radius = 1 at:
- left/right image edge
- top/bottom image edge
-
- This means every radial ring contains meaningful pixels on a
- rectangular video.
- """
-
- y, x = np.mgrid[0:h, 0:w].astype(np.float32)
-
- cx = (w - 1) * 0.5
- cy = (h - 1) * 0.5
-
- nx = (x - cx) / max(cx, 1.0)
- ny = (y - cy) / max(cy, 1.0)
-
- radius = np.sqrt(
- nx * nx +
- ny * ny
- )
-
- # Angle:
- #
- # 0 = right
- # pi/2 = bottom
- # +/- pi = left
- # -pi/2 = top
-
- angle = np.arctan2(
- ny,
- nx
- )
-
- return radius, angle
-
-
-def sector_masks(angle):
- """
- Divide frame into four 90-degree directional sectors.
- """
-
- pi = np.pi
-
- right = (
- (angle >= -pi / 4) &
- (angle < pi / 4)
- )
-
- bottom = (
- (angle >= pi / 4) &
- (angle < 3 * pi / 4)
- )
-
- left = (
- (angle >= 3 * pi / 4) |
- (angle < -3 * pi / 4)
- )
-
- top = (
- (angle >= -3 * pi / 4) &
- (angle < -pi / 4)
- )
-
- return [
- right,
- bottom,
- left,
- top,
- ]
-
-
-def safe_std(x):
- x = x[np.isfinite(x)]
-
- if len(x) == 0:
- return 0.0
-
- return float(np.std(x))
-
-
-def run_pca(X):
- """
- PCA via SVD.
-
- Rows = frames
- Columns = spatial measurements
- """
-
- X = X.copy()
-
- column_mean = np.nanmean(
- X,
- axis=0,
- keepdims=True
- )
-
- X -= column_mean
-
- X = np.nan_to_num(
- X,
- nan=0.0,
- posinf=0.0,
- neginf=0.0
- )
-
- U, S, Vt = np.linalg.svd(
- X,
- full_matrices=False
- )
-
- variance = S * S
-
- total = np.sum(variance)
-
- if total <= 0:
- explained = np.zeros_like(variance)
- else:
- explained = variance / total
-
- return explained, U, S, Vt
-
-
-def correlation(a, b):
- mask = (
- np.isfinite(a) &
- np.isfinite(b)
- )
-
- a = a[mask]
- b = b[mask]
-
- if len(a) < 3:
- return 0.0
-
- if np.std(a) < 1e-8:
- return 0.0
-
- if np.std(b) < 1e-8:
- return 0.0
-
- return float(
- np.corrcoef(a, b)[0, 1]
- )
-
-
-def main():
- if len(sys.argv) != 2:
- print(
- "Usage: python diagnose.py input.mp4"
- )
- sys.exit(1)
-
- path = sys.argv[1]
-
- cap = cv2.VideoCapture(path)
-
- if not cap.isOpened():
- raise RuntimeError(
- f"Cannot open {path}"
- )
-
- fps = cap.get(
- cv2.CAP_PROP_FPS
- )
-
- width = int(
- cap.get(
- cv2.CAP_PROP_FRAME_WIDTH
- )
- )
-
- height = int(
- cap.get(
- cv2.CAP_PROP_FRAME_HEIGHT
- )
- )
-
- frame_count = int(
- cap.get(
- cv2.CAP_PROP_FRAME_COUNT
- )
- )
-
- analysis_h = max(
- 96,
- round(
- ANALYSIS_W *
- height /
- width
- )
- )
-
- radius, angle = make_geometry(
- analysis_h,
- ANALYSIS_W
- )
-
- sectors = sector_masks(
- angle
- )
-
- ring_edges = np.linspace(
- 0.0,
- 1.0,
- RINGS + 1
- )
-
- radial_profiles = []
- sector_profiles = []
-
- print()
- print(
- f"Input: {width}x{height} "
- f"@ {fps:.3f} fps"
- )
-
- print(
- f"Frames: {frame_count}"
- )
-
- print(
- f"Analysis: "
- f"{ANALYSIS_W}x{analysis_h}"
- )
-
- print(
- f"Radial rings: {RINGS}"
- )
-
- print(
- "Directional sectors: "
- "RIGHT / BOTTOM / LEFT / TOP"
- )
-
- print()
- print("Analyzing...")
-
- frame_index = 0
-
- while True:
- ok, frame = cap.read()
-
- if not ok:
- break
-
- small = cv2.resize(
- frame,
- (
- ANALYSIS_W,
- analysis_h
- ),
- interpolation=cv2.INTER_AREA
- )
-
- lum = luminance(
- small
- )
-
- radial = []
-
- directional = np.full(
- (
- SECTORS,
- RINGS
- ),
- np.nan,
- dtype=np.float32
- )
-
- for r in range(RINGS):
-
- ring_mask = (
- (radius >= ring_edges[r]) &
- (radius < ring_edges[r + 1])
- )
-
- radial.append(
- robust_median(
- lum[ring_mask]
- )
- )
-
- for s in range(SECTORS):
-
- mask = (
- ring_mask &
- sectors[s]
- )
-
- directional[s, r] = (
- robust_median(
- lum[mask]
- )
- )
-
- radial_profiles.append(
- radial
- )
-
- sector_profiles.append(
- directional
- )
-
- frame_index += 1
-
- if frame_index % 30 == 0:
-
- print(
- f"\r{frame_index}/"
- f"{frame_count}",
- end="",
- flush=True
- )
-
- cap.release()
-
- print()
-
- radial_profiles = np.asarray(
- radial_profiles,
- dtype=np.float32
- )
-
- sector_profiles = np.asarray(
- sector_profiles,
- dtype=np.float32
- )
-
- # ========================================================
- # Normalize using central region.
- #
- # This removes global exposure variation from the
- # diagnostic and isolates spatial changes.
- # ========================================================
-
- center = np.nanmedian(
- radial_profiles[:, :3],
- axis=1
- )
-
- center = np.maximum(
- center,
- 1e-5
- )
-
- radial_norm = (
- radial_profiles /
- center[:, None]
- )
-
- sector_norm = (
- sector_profiles /
- center[:, None, None]
- )
-
- # ========================================================
- # Radial instability
- # ========================================================
-
- radial_std = np.nanstd(
- radial_norm,
- axis=0
- )
-
- radial_range = (
- np.nanmax(
- radial_norm,
- axis=0
- )
- -
- np.nanmin(
- radial_norm,
- axis=0
- )
- )
-
- print()
- print(
- "RADIAL TEMPORAL INSTABILITY"
- )
-
- print()
- print(
- "Ring Radius STD Range"
- )
-
- print(
- "-------------------------------------"
- )
-
- for r in range(RINGS):
-
- print(
- f"{r:02d} "
- f"{ring_edges[r]:.2f}-"
- f"{ring_edges[r + 1]:.2f} "
- f"{radial_std[r]:.4f} "
- f"{radial_range[r]:.4f}"
- )
-
- # ========================================================
- # Directional signals
- #
- # Use outer 30% of image.
- # ========================================================
-
- outer_start = int(
- RINGS * 0.70
- )
-
- directional_signals = []
-
- print()
- print(
- "OUTER-REGION TEMPORAL INSTABILITY"
- )
-
- print()
-
- for s in range(SECTORS):
-
- signal = np.nanmedian(
- sector_norm[
- :,
- s,
- outer_start:
- ],
- axis=1
- )
-
- directional_signals.append(
- signal
- )
-
- print(
- f" {SECTOR_NAMES[s]:6s}: "
- f"STD {safe_std(signal):.4f}"
- )
-
- directional_signals = np.asarray(
- directional_signals
- )
-
- # ========================================================
- # Correlations
- #
- # If all directions strongly correlate, that supports a
- # coherent radial/vignette-like temporal effect.
- # ========================================================
-
- print()
- print(
- "DIRECTIONAL CORRELATIONS"
- )
-
- print()
-
- for a in range(SECTORS):
-
- for b in range(
- a + 1,
- SECTORS
- ):
-
- c = correlation(
- directional_signals[a],
- directional_signals[b]
- )
-
- print(
- f" "
- f"{SECTOR_NAMES[a]:6s} vs "
- f"{SECTOR_NAMES[b]:6s}: "
- f"{c:+.3f}"
- )
-
- # ========================================================
- # Radial PCA
- # ========================================================
-
- radial_explained, _, _, radial_modes = (
- run_pca(
- radial_norm
- )
- )
-
- print()
- print(
- "RADIAL PCA"
- )
-
- print()
-
- for i in range(
- min(
- 5,
- len(radial_explained)
- )
- ):
-
- print(
- f" component {i + 1}: "
- f"{radial_explained[i] * 100:.2f}%"
- )
-
- # ========================================================
- # Full radial + directional PCA
- #
- # This tells us whether one coherent spatial mode also
- # explains directional variation.
- # ========================================================
-
- flattened = sector_norm.reshape(
- sector_norm.shape[0],
- -1
- )
-
- spatial_explained, _, _, spatial_modes = (
- run_pca(
- flattened
- )
- )
-
- print()
- print(
- "RADIAL + DIRECTIONAL PCA"
- )
-
- print()
-
- for i in range(
- min(
- 5,
- len(spatial_explained)
- )
- ):
-
- print(
- f" component {i + 1}: "
- f"{spatial_explained[i] * 100:.2f}%"
- )
-
- # ========================================================
- # Interpretation
- # ========================================================
-
- correlations = []
-
- for a in range(SECTORS):
-
- for b in range(
- a + 1,
- SECTORS
- ):
-
- correlations.append(
- correlation(
- directional_signals[a],
- directional_signals[b]
- )
- )
-
- median_corr = float(
- np.median(
- correlations
- )
- )
-
- pc1 = float(
- spatial_explained[0]
- )
-
- print()
- print(
- "SUMMARY"
- )
-
- print()
- print(
- f"Median directional correlation: "
- f"{median_corr:+.3f}"
- )
-
- print(
- f"Dominant spatial PCA mode: "
- f"{pc1 * 100:.2f}%"
- )
-
- print()
-
- if (
- median_corr > 0.75
- and pc1 > 0.65
- ):
-
- print(
- "RESULT:"
- )
-
- print(
- "Strong evidence for one coherent "
- "time-varying vignette/spatial effect."
- )
-
- print(
- "A low-dimensional parametric/PCA "
- "remover is worth building."
- )
-
- elif (
- median_corr > 0.45
- or pc1 > 0.50
- ):
-
- print(
- "RESULT:"
- )
-
- print(
- "There is meaningful coherent spatial "
- "flicker, but it is not purely radial."
- )
-
- print(
- "Use a multi-mode spatial model or "
- "blind neural deflickering."
- )
-
- else:
-
- print(
- "RESULT:"
- )
-
- print(
- "The artifact is not well explained "
- "by a coherent vignette-like model."
- )
-
- print(
- "Prioritize blind neural deflickering "
- "rather than radial correction."
- )
-
- # ========================================================
- # Save everything
- # ========================================================
-
- np.savez(
- "diagnostic_v2.npz",
-
- radial_profiles=radial_norm,
-
- sector_profiles=sector_norm,
-
- radial_pca_modes=radial_modes,
-
- spatial_pca_modes=spatial_modes,
-
- directional_signals=directional_signals,
-
- ring_edges=ring_edges,
-
- fps=np.float32(fps)
- )
-
- print()
- print(
- "Saved: diagnostic_v2.npz"
- )
- print()
-
-
-if __name__ == "__main__":
- main()
\ No newline at end of file
diff --git a/test/deflicker/fast_dvd.py b/test/deflicker/fast_dvd.py
deleted file mode 100644
index 2c1f07db..00000000
--- a/test/deflicker/fast_dvd.py
+++ /dev/null
@@ -1,172 +0,0 @@
-#!/usr/bin/env python3
-
-import argparse
-import subprocess
-import tempfile
-import shutil
-from pathlib import Path
-
-
-def run(cmd):
- print("+", " ".join(map(str, cmd)))
- subprocess.run(cmd, check=True)
-
-
-def main():
- parser = argparse.ArgumentParser(
- description="Quick FastDVDnet experiment on a real video."
- )
- parser.add_argument("input", help="Input video")
- parser.add_argument("output", help="Output video")
- parser.add_argument(
- "--sigma",
- type=float,
- default=15,
- help="FastDVDnet noise sigma. Try 5, 10, 15, 25."
- )
- parser.add_argument(
- "--cpu",
- action="store_true",
- help="Force CPU instead of CUDA/MPS."
- )
- args = parser.parse_args()
-
- input_video = Path(args.input).resolve()
- output_video = Path(args.output).resolve()
-
- if not input_video.exists():
- raise FileNotFoundError(input_video)
-
- repo = Path(__file__).resolve().parent
-
- if not (repo / "test_fastdvdnet.py").exists():
- raise RuntimeError(
- "Put this script in the FastDVDnet repository root."
- )
-
- work = Path(tempfile.mkdtemp(prefix="fastdvdnet_"))
-
- frames = work / "frames"
- processed = work / "processed"
-
- frames.mkdir()
- processed.mkdir()
-
- try:
- # ---------------------------------------------------------
- # 1. Get original FPS
- # ---------------------------------------------------------
-
- probe = subprocess.run(
- [
- "ffprobe",
- "-v", "error",
- "-select_streams", "v:0",
- "-show_entries", "stream=r_frame_rate",
- "-of", "default=noprint_wrappers=1:nokey=1",
- str(input_video)
- ],
- capture_output=True,
- text=True,
- check=True
- )
-
- ratio = probe.stdout.strip().split("/")
-
- if len(ratio) == 2:
- fps = float(ratio[0]) / float(ratio[1])
- else:
- fps = float(ratio[0])
-
- print(f"\nInput FPS: {fps:.3f}")
- print(f"FastDVDnet sigma: {args.sigma}")
-
- # ---------------------------------------------------------
- # 2. Decode video losslessly to PNG
- # ---------------------------------------------------------
-
- run([
- "ffmpeg",
- "-y",
- "-i", str(input_video),
- "-vsync", "0",
- str(frames / "%08d.png")
- ])
-
- # ---------------------------------------------------------
- # 3. Run FastDVDnet
- # ---------------------------------------------------------
-
- cmd = [
- "python",
- str(repo / "test_fastdvdnet.py"),
- "--test_path", str(frames),
- "--noise_sigma", str(args.sigma),
- "--save_path", str(processed),
- "--model_file", str(repo / "model.pth"),
- ]
-
- if args.cpu:
- cmd.append("--no_gpu")
-
- run(cmd)
-
- # ---------------------------------------------------------
- # Find where FastDVDnet actually put its output
- # ---------------------------------------------------------
-
- output_frames = sorted(processed.rglob("*.png"))
-
- if not output_frames:
- raise RuntimeError(
- f"FastDVDnet produced no PNG frames in {processed}"
- )
-
- # Normalize filenames because the repo can create
- # its own directory structure.
- normalized = work / "normalized"
- normalized.mkdir()
-
- for i, frame in enumerate(output_frames, start=1):
- shutil.copy2(
- frame,
- normalized / f"{i:08d}.png"
- )
-
- print(f"\nProcessed {len(output_frames)} frames.")
-
- # ---------------------------------------------------------
- # 4. Encode output
- # ---------------------------------------------------------
-
- run([
- "ffmpeg",
- "-y",
- "-framerate", str(fps),
- "-i", str(normalized / "%08d.png"),
- "-i", str(input_video),
- "-map", "0:v:0",
- "-map", "1:a?",
- "-c:v", "libx264",
- "-crf", "16",
- "-preset", "medium",
- "-pix_fmt", "yuv420p",
- "-c:a", "copy",
- "-shortest",
- str(output_video)
- ])
-
- print("\n================================")
- print("DONE")
- print("================================")
- print(f"Input : {input_video}")
- print(f"Output: {output_video}")
- print(f"Sigma : {args.sigma}")
- print()
-
- finally:
- shutil.rmtree(work, ignore_errors=True)
-
-
-if __name__ == "__main__":
- main()
\ No newline at end of file
diff --git a/test/deflicker/fft_pwm.py b/test/deflicker/fft_pwm.py
deleted file mode 100644
index e5a602ea..00000000
--- a/test/deflicker/fft_pwm.py
+++ /dev/null
@@ -1,201 +0,0 @@
-#!/usr/bin/env python3
-
-import sys
-import cv2
-import numpy as np
-
-
-GRID_X = 8
-GRID_Y = 5
-
-MIN_FLICKER_HZ = 3.0
-MAX_FLICKER_HZ = 14.0
-
-SUPPRESSION = 0.90
-
-MIN_GAIN = 0.65
-MAX_GAIN = 1.60
-
-
-def luminance(frame):
- f = frame.astype(np.float32) / 255.0
-
- return (
- 0.0722 * f[:, :, 0] +
- 0.7152 * f[:, :, 1] +
- 0.2126 * f[:, :, 2]
- )
-
-
-def main():
- if len(sys.argv) != 3:
- print("Usage: python fft_pwm.py input.mp4 output.mp4")
- sys.exit(1)
-
- src, dst = sys.argv[1], sys.argv[2]
-
- cap = cv2.VideoCapture(src)
-
- if not cap.isOpened():
- raise RuntimeError(f"Cannot open {src}")
-
- fps = cap.get(cv2.CAP_PROP_FPS)
- width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
- height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
- count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
-
- print(f"Input: {width}x{height} @ {fps:.3f} fps")
- print(f"Frames: {count}")
- print(f"Grid: {GRID_X}x{GRID_Y}")
- print()
-
- frames = []
- signals = []
-
- print("Analyzing regional brightness...")
-
- while True:
- ok, frame = cap.read()
-
- if not ok:
- break
-
- frames.append(frame)
-
- lum = luminance(frame)
-
- # Downsample directly into regional brightness cells.
- grid = cv2.resize(
- lum,
- (GRID_X, GRID_Y),
- interpolation=cv2.INTER_AREA
- )
-
- signals.append(grid)
-
- cap.release()
-
- signals = np.stack(signals)
-
- n = signals.shape[0]
-
- corrected_signals = np.zeros_like(signals)
-
- frequencies = np.fft.rfftfreq(
- n,
- d=1.0 / fps
- )
-
- flicker_band = (
- (frequencies >= MIN_FLICKER_HZ) &
- (frequencies <= MAX_FLICKER_HZ)
- )
-
- print("Filtering temporal frequencies...")
-
- detected_peaks = []
-
- for y in range(GRID_Y):
- for x in range(GRID_X):
-
- signal = signals[:, y, x]
-
- spectrum = np.fft.rfft(signal)
-
- magnitude = np.abs(spectrum)
-
- band_indices = np.where(
- flicker_band
- )[0]
-
- if len(band_indices):
- strongest = band_indices[
- np.argmax(magnitude[band_indices])
- ]
-
- detected_peaks.append(
- frequencies[strongest]
- )
-
- spectrum[flicker_band] *= (
- 1.0 - SUPPRESSION
- )
-
- corrected = np.fft.irfft(
- spectrum,
- n=n
- )
-
- corrected_signals[:, y, x] = corrected
-
- if detected_peaks:
- print(
- "Median strongest frequency: "
- f"{np.median(detected_peaks):.2f} Hz"
- )
-
- print("Correcting frames...")
-
- writer = cv2.VideoWriter(
- dst,
- cv2.VideoWriter_fourcc(*"mp4v"),
- fps,
- (width, height)
- )
-
- for i, frame in enumerate(frames):
-
- original = signals[i]
- target = corrected_signals[i]
-
- gain = target / np.maximum(
- original,
- 0.03
- )
-
- gain = np.clip(
- gain,
- MIN_GAIN,
- MAX_GAIN
- )
-
- gain = cv2.GaussianBlur(
- gain,
- (0, 0),
- 1.2
- )
-
- gain_full = cv2.resize(
- gain,
- (width, height),
- interpolation=cv2.INTER_CUBIC
- )
-
- corrected = (
- frame.astype(np.float32) *
- gain_full[:, :, None]
- )
-
- corrected = np.clip(
- corrected,
- 0,
- 255
- ).astype(np.uint8)
-
- writer.write(corrected)
-
- if (i + 1) % 30 == 0:
- print(
- f"\r{i + 1}/{n}",
- end="",
- flush=True
- )
-
- writer.release()
-
- print()
- print(f"Done: {dst}")
-
-
-if __name__ == "__main__":
- main()
\ No newline at end of file
diff --git a/test/deflicker/illumination.py b/test/deflicker/illumination.py
deleted file mode 100644
index 9ee42fea..00000000
--- a/test/deflicker/illumination.py
+++ /dev/null
@@ -1,163 +0,0 @@
-#!/usr/bin/env python3
-
-import sys
-import cv2
-import numpy as np
-
-
-ANALYSIS_W = 128
-BLUR_SIGMA = 10.0
-MAX_GAIN = 2.5
-MIN_GAIN = 0.60
-REFERENCE_PERCENTILE = 90
-
-
-def luminance(frame):
- f = frame.astype(np.float32) / 255.0
- return (
- 0.0722 * f[:, :, 0] +
- 0.7152 * f[:, :, 1] +
- 0.2126 * f[:, :, 2]
- )
-
-
-def main():
- if len(sys.argv) != 3:
- print("Usage: python illumination.py input.mp4 output.mp4")
- sys.exit(1)
-
- src, dst = sys.argv[1], sys.argv[2]
-
- cap = cv2.VideoCapture(src)
-
- if not cap.isOpened():
- raise RuntimeError(f"Cannot open {src}")
-
- fps = cap.get(cv2.CAP_PROP_FPS)
- width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
- height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
- count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
-
- analysis_h = max(
- 64,
- round(ANALYSIS_W * height / width)
- )
-
- print(f"Input: {width}x{height} @ {fps:.3f} fps")
- print(f"Frames: {count}")
- print(f"Analysis: {ANALYSIS_W}x{analysis_h}")
- print()
- print("Reading frames...")
-
- small_lums = []
- frames = []
-
- while True:
- ok, frame = cap.read()
-
- if not ok:
- break
-
- frames.append(frame)
-
- small = cv2.resize(
- frame,
- (ANALYSIS_W, analysis_h),
- interpolation=cv2.INTER_AREA
- )
-
- lum = luminance(small)
-
- # Remove high-frequency image detail.
- lum = cv2.GaussianBlur(
- lum,
- (0, 0),
- BLUR_SIGMA
- )
-
- small_lums.append(lum)
-
- cap.release()
-
- lums = np.stack(small_lums)
-
- print("Building temporal reference...")
-
- # Bright temporal reference helps reconstruct areas
- # temporarily darkened by the flickering effect.
- reference = np.percentile(
- lums,
- REFERENCE_PERCENTILE,
- axis=0
- ).astype(np.float32)
-
- reference = cv2.GaussianBlur(
- reference,
- (0, 0),
- BLUR_SIGMA
- )
-
- print("Correcting frames...")
-
- fourcc = cv2.VideoWriter_fourcc(*"mp4v")
-
- writer = cv2.VideoWriter(
- dst,
- fourcc,
- fps,
- (width, height)
- )
-
- for i, frame in enumerate(frames):
-
- current = lums[i]
-
- gain = reference / np.maximum(current, 0.03)
-
- gain = np.clip(
- gain,
- MIN_GAIN,
- MAX_GAIN
- )
-
- # Smooth the gain field itself.
- gain = cv2.GaussianBlur(
- gain,
- (0, 0),
- 5.0
- )
-
- gain_full = cv2.resize(
- gain,
- (width, height),
- interpolation=cv2.INTER_CUBIC
- )
-
- corrected = (
- frame.astype(np.float32) *
- gain_full[:, :, None]
- )
-
- corrected = np.clip(
- corrected,
- 0,
- 255
- ).astype(np.uint8)
-
- writer.write(corrected)
-
- if (i + 1) % 30 == 0:
- print(
- f"\r{i + 1}/{len(frames)}",
- end="",
- flush=True
- )
-
- writer.release()
-
- print()
- print(f"Done: {dst}")
-
-
-if __name__ == "__main__":
- main()
\ No newline at end of file
diff --git a/test/deflicker/main.py b/test/deflicker/main.py
deleted file mode 100644
index aea4cf15..00000000
--- a/test/deflicker/main.py
+++ /dev/null
@@ -1,489 +0,0 @@
-#!/usr/bin/env python3
-
-import sys
-import cv2
-import numpy as np
-
-
-# ============================================================
-# Configuration
-# ============================================================
-
-ANALYSIS_W = 160
-
-CENTER_RADIUS = 0.28
-
-EDGE_RADIUS_MIN = 0.62
-EDGE_RADIUS_MAX = 0.92
-
-CORRECTION_START_RADIUS = 0.25
-
-TARGET_PERCENTILE = 98.0
-
-MAX_GAIN = 2.5
-
-
-# ============================================================
-# Image analysis
-# ============================================================
-
-def luminance(frame):
- """
- BGR uint8 -> luminance float32.
- """
- f = frame.astype(np.float32)
-
- b = f[:, :, 0]
- g = f[:, :, 1]
- r = f[:, :, 2]
-
- return (
- 0.0722 * b +
- 0.7152 * g +
- 0.2126 * r
- )
-
-
-def radial_map(h, w):
- """
- Normalized radial distance.
-
- center = 0
- corners = ~1
- """
- y, x = np.mgrid[0:h, 0:w].astype(np.float32)
-
- cx = (w - 1) * 0.5
- cy = (h - 1) * 0.5
-
- x = (x - cx) / max(cx, 1.0)
- y = (y - cy) / max(cy, 1.0)
-
- radius = np.sqrt(x * x + y * y)
-
- return radius / np.sqrt(2.0)
-
-
-def robust_mean(values):
- """
- Trim bright/dark outliers before calculating mean.
-
- Helps prevent lamps, shadows, skateboarder, etc.
- from dominating the measurement.
- """
- if values.size == 0:
- return 0.0
-
- lo = np.percentile(values, 20)
- hi = np.percentile(values, 80)
-
- trimmed = values[
- (values >= lo) &
- (values <= hi)
- ]
-
- if trimmed.size == 0:
- return float(np.mean(values))
-
- return float(np.mean(trimmed))
-
-
-def measure_vignette(frame, radius_small):
- """
- Measure edge brightness relative to center brightness.
- """
-
- h, w = radius_small.shape
-
- small = cv2.resize(
- frame,
- (w, h),
- interpolation=cv2.INTER_AREA
- )
-
- lum = luminance(small)
-
- center_mask = radius_small < CENTER_RADIUS
-
- edge_mask = (
- (radius_small > EDGE_RADIUS_MIN) &
- (radius_small < EDGE_RADIUS_MAX)
- )
-
- center = robust_mean(
- lum[center_mask]
- )
-
- edge = robust_mean(
- lum[edge_mask]
- )
-
- if center < 1.0:
- return 1.0, center, edge
-
- ratio = edge / center
-
- return ratio, center, edge
-
-
-# ============================================================
-# Main
-# ============================================================
-
-def main():
-
- if len(sys.argv) != 3:
- print()
- print("Usage:")
- print(
- " python main.py "
- "input.mp4 output.mp4"
- )
- print()
- sys.exit(1)
-
- input_path = sys.argv[1]
- output_path = sys.argv[2]
-
- # --------------------------------------------------------
- # Open source
- # --------------------------------------------------------
-
- cap = cv2.VideoCapture(input_path)
-
- if not cap.isOpened():
- raise RuntimeError(
- f"Could not open: {input_path}"
- )
-
- fps = cap.get(cv2.CAP_PROP_FPS)
-
- width = int(
- cap.get(cv2.CAP_PROP_FRAME_WIDTH)
- )
-
- height = int(
- cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
- )
-
- frame_count = int(
- cap.get(cv2.CAP_PROP_FRAME_COUNT)
- )
-
- print()
- print(
- f"Input: {width}x{height} "
- f"@ {fps:.3f} fps"
- )
-
- print(
- f"Frames: {frame_count}"
- )
-
- # ========================================================
- # PASS 1
- #
- # Analyze the brightness relationship between the
- # center and edges.
- #
- # This operates at very low resolution because we're
- # measuring low-frequency illumination, not detail.
- # ========================================================
-
- analysis_h = max(
- 64,
- round(
- ANALYSIS_W *
- height /
- width
- )
- )
-
- analysis_radius = radial_map(
- analysis_h,
- ANALYSIS_W
- )
-
- ratios = []
- centers = []
- edges = []
-
- print()
- print("Analyzing vignette...")
-
- while True:
-
- ok, frame = cap.read()
-
- if not ok:
- break
-
- ratio, center, edge = measure_vignette(
- frame,
- analysis_radius
- )
-
- ratios.append(ratio)
- centers.append(center)
- edges.append(edge)
-
- cap.release()
-
- ratios = np.asarray(
- ratios,
- dtype=np.float32
- )
-
- if len(ratios) == 0:
- raise RuntimeError(
- "No video frames decoded."
- )
-
- # --------------------------------------------------------
- # Determine what an almost-unvignetted frame looks like.
- #
- # We use the 98th percentile instead of maximum because
- # one abnormal frame shouldn't determine the target.
- # --------------------------------------------------------
-
- target_ratio = float(
- np.percentile(
- ratios,
- TARGET_PERCENTILE
- )
- )
-
- print()
- print("Edge/center ratio:")
- print(
- f" min: "
- f"{ratios.min():.4f}"
- )
- print(
- f" median: "
- f"{np.median(ratios):.4f}"
- )
- print(
- f" max: "
- f"{ratios.max():.4f}"
- )
- print(
- f" target: "
- f"{target_ratio:.4f}"
- )
-
- # --------------------------------------------------------
- # IMPORTANT:
- #
- # No temporal smoothing.
- #
- # The unwanted vignette itself changes rapidly, so we
- # want to react to each individual frame.
- # --------------------------------------------------------
-
- measured = ratios
-
- # --------------------------------------------------------
- # Calculate how much brighter the edge needs to become.
- #
- # Example:
- #
- # target = 0.80
- # frame = 0.40
- #
- # gain = 0.80 / 0.40
- # = 2.0
- # --------------------------------------------------------
-
- required_edge_gain = (
- target_ratio /
- np.maximum(
- measured,
- 0.10
- )
- )
-
- required_edge_gain = np.clip(
- required_edge_gain,
- 1.0,
- MAX_GAIN
- )
-
- print()
- print(
- "Correction gain:"
- )
-
- print(
- f" min: "
- f"{required_edge_gain.min():.3f}x"
- )
-
- print(
- f" max: "
- f"{required_edge_gain.max():.3f}x"
- )
-
- # ========================================================
- # Build full-resolution radial correction weighting.
- # ========================================================
-
- full_radius = radial_map(
- height,
- width
- )
-
- radial_weight = (
- full_radius -
- CORRECTION_START_RADIUS
- ) / (
- 1.0 -
- CORRECTION_START_RADIUS
- )
-
- radial_weight = np.clip(
- radial_weight,
- 0.0,
- 1.0
- )
-
- # --------------------------------------------------------
- # Smoothstep
- #
- # x²(3 - 2x)
- #
- # Gives us a smooth transition from the untouched center
- # to the corrected edges.
- # --------------------------------------------------------
-
- radial_weight = (
- radial_weight *
- radial_weight *
- (
- 3.0 -
- 2.0 * radial_weight
- )
- )
-
- # ========================================================
- # PASS 2
- #
- # Apply per-frame correction.
- # ========================================================
-
- cap = cv2.VideoCapture(
- input_path
- )
-
- if not cap.isOpened():
- raise RuntimeError(
- "Could not reopen input video."
- )
-
- fourcc = cv2.VideoWriter_fourcc(
- *"mp4v"
- )
-
- writer = cv2.VideoWriter(
- output_path,
- fourcc,
- fps,
- (
- width,
- height
- )
- )
-
- if not writer.isOpened():
- raise RuntimeError(
- "Could not create output video."
- )
-
- print()
- print("Correcting frames...")
-
- frame_index = 0
-
- while True:
-
- ok, frame = cap.read()
-
- if not ok:
- break
-
- edge_gain = required_edge_gain[
- min(
- frame_index,
- len(required_edge_gain) - 1
- )
- ]
-
- # ----------------------------------------------------
- # Construct gain map.
- #
- # Center:
- #
- # gain = 1.0
- #
- # Edge:
- #
- # gain = calculated edge correction
- # ----------------------------------------------------
-
- gain_map = (
- 1.0 +
- radial_weight *
- (
- edge_gain -
- 1.0
- )
- )
-
- corrected = frame.astype(
- np.float32
- )
-
- corrected *= gain_map[
- :, :, None
- ]
-
- corrected = np.clip(
- corrected,
- 0.0,
- 255.0
- )
-
- corrected = corrected.astype(
- np.uint8
- )
-
- writer.write(
- corrected
- )
-
- frame_index += 1
-
- if frame_index % 30 == 0:
-
- print(
- f"\r"
- f"{frame_index}/"
- f"{len(ratios)} frames",
- end="",
- flush=True
- )
-
- print()
-
- cap.release()
- writer.release()
-
- print()
- print(
- f"Done: {output_path}"
- )
- print()
-
-
-if __name__ == "__main__":
- main()
\ No newline at end of file
diff --git a/test/deflicker/optical_flow.py b/test/deflicker/optical_flow.py
deleted file mode 100644
index 5bf2ae97..00000000
--- a/test/deflicker/optical_flow.py
+++ /dev/null
@@ -1,318 +0,0 @@
-#!/usr/bin/env python3
-
-import sys
-import cv2
-import numpy as np
-
-
-ANALYSIS_W = 320
-
-SPATIAL_SIGMA = 18.0
-
-MIN_GAIN = 0.60
-MAX_GAIN = 2.20
-
-CONFIDENCE_THRESHOLD = 0.20
-
-
-def luminance(frame):
- f = frame.astype(np.float32) / 255.0
-
- return (
- 0.0722 * f[:, :, 0] +
- 0.7152 * f[:, :, 1] +
- 0.2126 * f[:, :, 2]
- )
-
-
-def flow_warp(source, target):
- """
- Warp SOURCE toward TARGET.
-
- Flow is calculated from target -> source so that
- remap tells us where each target pixel came from.
- """
-
- target8 = np.clip(
- target * 255,
- 0,
- 255
- ).astype(np.uint8)
-
- source8 = np.clip(
- source * 255,
- 0,
- 255
- ).astype(np.uint8)
-
- flow = cv2.calcOpticalFlowFarneback(
- target8,
- source8,
- None,
- 0.5,
- 4,
- 21,
- 5,
- 7,
- 1.5,
- 0
- )
-
- h, w = target.shape
-
- x, y = np.meshgrid(
- np.arange(w),
- np.arange(h)
- )
-
- map_x = (
- x.astype(np.float32) +
- flow[:, :, 0]
- )
-
- map_y = (
- y.astype(np.float32) +
- flow[:, :, 1]
- )
-
- warped = cv2.remap(
- source,
- map_x,
- map_y,
- cv2.INTER_LINEAR,
- borderMode=cv2.BORDER_REFLECT
- )
-
- return warped
-
-
-def main():
- if len(sys.argv) != 3:
- print(
- "Usage: python optical_flow.py "
- "input.mp4 output.mp4"
- )
- sys.exit(1)
-
- src, dst = sys.argv[1], sys.argv[2]
-
- cap = cv2.VideoCapture(src)
-
- if not cap.isOpened():
- raise RuntimeError(f"Cannot open {src}")
-
- fps = cap.get(cv2.CAP_PROP_FPS)
- width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
- height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
- count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
-
- analysis_h = max(
- 96,
- round(
- ANALYSIS_W *
- height /
- width
- )
- )
-
- print(
- f"Input: {width}x{height} "
- f"@ {fps:.3f} fps"
- )
-
- print(f"Frames: {count}")
-
- print(
- f"Flow analysis: "
- f"{ANALYSIS_W}x{analysis_h}"
- )
-
- frames = []
- lums = []
-
- print()
- print("Reading frames...")
-
- while True:
-
- ok, frame = cap.read()
-
- if not ok:
- break
-
- frames.append(frame)
-
- small = cv2.resize(
- frame,
- (ANALYSIS_W, analysis_h),
- interpolation=cv2.INTER_AREA
- )
-
- lums.append(
- luminance(small)
- )
-
- cap.release()
-
- n = len(frames)
-
- writer = cv2.VideoWriter(
- dst,
- cv2.VideoWriter_fourcc(*"mp4v"),
- fps,
- (width, height)
- )
-
- print()
- print("Motion-compensated correction...")
-
- for i in range(n):
-
- current = lums[i]
-
- ratio_maps = []
-
- neighbors = []
-
- if i > 0:
- neighbors.append(i - 1)
-
- if i + 1 < n:
- neighbors.append(i + 1)
-
- for j in neighbors:
-
- warped = flow_warp(
- lums[j],
- current
- )
-
- # ------------------------------------------------
- # Estimate multiplicative illumination difference.
- # ------------------------------------------------
-
- ratio = (
- warped + 0.02
- ) / (
- current + 0.02
- )
-
- # ------------------------------------------------
- # Reject pixels where correspondence is obviously
- # suspicious.
- # ------------------------------------------------
-
- residual = np.abs(
- warped - current
- )
-
- confidence = np.exp(
- -residual / 0.12
- )
-
- valid = (
- confidence >
- CONFIDENCE_THRESHOLD
- )
-
- ratio = np.where(
- valid,
- ratio,
- 1.0
- )
-
- ratio_maps.append(
- ratio
- )
-
- if not ratio_maps:
-
- writer.write(frames[i])
- continue
-
- ratios = np.stack(
- ratio_maps
- )
-
- # Robust consensus between previous/next frames.
- illumination = np.median(
- ratios,
- axis=0
- )
-
- # ----------------------------------------------------
- # Illumination should be spatially smooth.
- #
- # This is crucial: we don't want to "correct" textures,
- # skateboarder details, etc.
- # ----------------------------------------------------
-
- illumination = cv2.GaussianBlur(
- illumination,
- (0, 0),
- SPATIAL_SIGMA
- )
-
- illumination = np.clip(
- illumination,
- MIN_GAIN,
- MAX_GAIN
- )
-
- # ----------------------------------------------------
- # We only want to remove rapid deviation.
- #
- # Split the difference because neighbors may themselves
- # sit on opposite phases of the flicker.
- # ----------------------------------------------------
-
- gain = np.sqrt(
- np.maximum(
- illumination,
- 0.01
- )
- )
-
- gain = np.clip(
- gain,
- MIN_GAIN,
- MAX_GAIN
- )
-
- gain_full = cv2.resize(
- gain,
- (width, height),
- interpolation=cv2.INTER_CUBIC
- )
-
- corrected = (
- frames[i].astype(np.float32) *
- gain_full[:, :, None]
- )
-
- corrected = np.clip(
- corrected,
- 0,
- 255
- ).astype(np.uint8)
-
- writer.write(
- corrected
- )
-
- if (i + 1) % 10 == 0:
-
- print(
- f"\r{i + 1}/{n}",
- end="",
- flush=True
- )
-
- writer.release()
-
- print()
- print(f"Done: {dst}")
-
-
-if __name__ == "__main__":
- main()
\ No newline at end of file
diff --git a/test/enhance_voice.py b/test/enhance_voice.py
deleted file mode 100644
index fc4a623a..00000000
--- a/test/enhance_voice.py
+++ /dev/null
@@ -1,392 +0,0 @@
-#!/usr/bin/env python3
-"""
-enhance_voice.py -- "Enhance voice" pipeline for a single audio file.
-
-Stage order (this order is the whole trick):
- 1. decode -> 48 kHz mono float32
- 2. de-plosive (time-varying LF suppression, surgical)
- 3. de-click (transient detect + LPC interpolation, surgical)
- 4. neural denoise + dereverb (DeepFilterNet3 or MossFormer2_SE_48K)
- 5. polish chain via ffmpeg: HPF -> de-ess -> EQ -> compress -> limit -> loudnorm
-
-Surgical repairs go BEFORE the network: clicks and plosives are impulsive and
-out-of-distribution for models trained on additive noise, and a network will
-smear them across neighbouring frames instead of removing them. Dynamics and
-loudness go AFTER: the network output has arbitrary gain.
-
-usage:
- python enhance_voice.py audio.mp3 -o out.wav
- python enhance_voice.py audio.mp3 -o out.wav --backend clearvoice --lufs -14
- python enhance_voice.py audio.mp3 -o out.wav --backend none # DSP only
-"""
-
-import argparse
-import os
-import shutil
-import subprocess
-import sys
-import tempfile
-
-import numpy as np
-from scipy import signal as sps
-from scipy.linalg import toeplitz
-
-SR = 48000
-
-
-# ---------------------------------------------------------------- io helpers
-
-def run(cmd):
- p = subprocess.run(cmd, capture_output=True, text=True)
- if p.returncode != 0:
- raise RuntimeError(f"{cmd[0]} failed:\n{p.stderr[-4000:]}")
- return p.stderr
-
-
-def decode(path, sr=SR):
- """Decode anything ffmpeg understands to mono float32 at `sr`."""
- p = subprocess.run(
- ["ffmpeg", "-v", "error", "-i", path, "-f", "f32le",
- "-acodec", "pcm_f32le", "-ac", "1", "-ar", str(sr), "-"],
- capture_output=True,
- )
- if p.returncode != 0:
- raise RuntimeError(f"decode failed:\n{p.stderr.decode()[-4000:]}")
- return np.frombuffer(p.stdout, dtype="<f4").astype(np.float64)
-
-
-def write_wav(x, path, sr=SR):
- x = np.clip(x, -1.0, 1.0).astype("<f4")
- p = subprocess.run(
- ["ffmpeg", "-y", "-v", "error", "-f", "f32le", "-ar", str(sr),
- "-ac", "1", "-i", "pipe:0", "-c:a", "pcm_f32le", path],
- input=x.tobytes(), capture_output=True,
- )
- if p.returncode != 0:
- raise RuntimeError(f"write failed:\n{p.stderr.decode()[-4000:]}")
-
-
-# ------------------------------------------------------------- 2. de-plosive
-
-def deplosive(x, sr=SR, lo=20.0, hi=120.0, thresh_db=9.0, floor_db=-24.0):
- """
- Plosives are short bursts of energy below ~120 Hz that are far louder than
- the speech band. Detect frames where the LF/mid energy ratio spikes above
- its own running median, then duck only the LF band over those frames with
- a smooth gain envelope. This is a dynamic high-pass, not a static one --
- a static HPF steep enough to kill a pop also thins every voiced sound.
- """
- n = 1024
- hop = n // 4
- win = sps.get_window("hann", n, fftbins=True)
- f, t, Z = sps.stft(x, sr, window=win, nperseg=n, noverlap=n - hop,
- boundary="zeros", padded=True)
- mag2 = (np.abs(Z) ** 2) + 1e-20
-
- lf = (f >= lo) & (f < hi)
- mid = (f >= 300) & (f < 3500)
- ratio_db = 10 * np.log10(mag2[lf].sum(0) / mag2[mid].sum(0))
-
- # running median baseline over ~2 s, so a steady rumble is not treated as
- # a plosive but a sudden burst is
- k = max(3, int(2.0 * sr / hop) | 1)
- base = sps.medfilt(ratio_db, kernel_size=min(k, len(ratio_db) - (1 - len(ratio_db) % 2)))
- excess = ratio_db - base
-
- # soft knee: 0 dB duck at threshold, floor_db at threshold+12
- duck_db = np.clip((excess - thresh_db) / 12.0, 0.0, 1.0) * floor_db
- # widen + smooth so the gain moves over ~15 ms, avoiding zipper artefacts
- w = max(3, int(0.015 * sr / hop) | 1)
- duck_db = sps.medfilt(duck_db, kernel_size=3)
- duck_db = np.convolve(duck_db, np.hanning(w) / np.hanning(w).sum(), mode="same")
-
- gain = 10 ** (duck_db / 20.0)
- # taper the gain across frequency so the cut fades out by `hi`
- prof = np.ones_like(f)
- band = (f >= lo) & (f <= hi * 1.5)
- prof[band] = np.clip((hi * 1.5 - f[band]) / (hi * 1.5 - lo), 0, 1)
- prof[f < lo] = 1.0
-
- G = 1.0 + (gain[None, :] - 1.0) * prof[:, None]
- _, y = sps.istft(Z * G, sr, window=win, nperseg=n, noverlap=n - hop)
- return y[: len(x)], int((duck_db < -1.0).sum())
-
-
-# --------------------------------------------------------------- 3. de-click
-
-def _lpc(x, order):
- """Autocorrelation-method LPC. Returns a with a[0] == 1."""
- x = np.asarray(x, dtype=np.float64)
- if len(x) < order * 2:
- return None
- r = np.correlate(x, x, "full")[len(x) - 1: len(x) + order]
- if r[0] <= 0:
- return None
- r = r.copy()
- r[0] *= 1.0 + 1e-4 # ridge, keeps the Toeplitz solve stable
- try:
- a = np.linalg.solve(toeplitz(r[:order]), r[1: order + 1])
- except np.linalg.LinAlgError:
- return None
- return np.concatenate(([1.0], -a))
-
-
-def _repair(x, s, e, order=32, ctx=1536):
- """
- Replace x[s:e] with the least-squares AR interpolation given surrounding
- context (Janssen/Vaseghi). Minimises LPC residual energy over the gap, so
- the fill inherits the local formant structure instead of being a straight
- line or a fade.
- """
- l0, r1 = max(0, s - ctx), min(len(x), e + ctx)
- context = np.concatenate([x[l0:s], x[e:r1]])
- a = _lpc(context, order)
- if a is None:
- # Degenerate context: the gap sits in (near-)silence, where LPC is
- # undefined. The correct fill there is the silence itself, reached with
- # a raised-cosine ramp so the repair introduces no step discontinuity.
- n = e - s
- ramp = 0.5 * (1 + np.cos(np.linspace(0, np.pi, n)))
- edge = (x[s - 1] if s > 0 else 0.0)
- x[s:e] = edge * ramp
- return True
-
- n0, n1 = max(0, s - order), min(len(x), e + order)
- seg = x[n0:n1].copy()
- N, rows = len(seg), len(seg) - order
- if rows <= 0:
- return False
-
- A = np.zeros((rows, N))
- ar = a[::-1]
- for i in range(rows):
- A[i, i: i + order + 1] = ar
-
- unk = np.arange(s - n0, e - n0)
- kn = np.setdiff1d(np.arange(N), unk)
- try:
- sol, *_ = np.linalg.lstsq(A[:, unk], -A[:, kn] @ seg[kn], rcond=None)
- except np.linalg.LinAlgError:
- return False
- if not np.all(np.isfinite(sol)):
- return False
-
- seg[unk] = sol
- x[n0:n1] = seg
- return True
-
-
-def _smooth_env(x, sr, ms):
- w = max(3, int(ms * 1e-3 * sr))
- k = np.ones(w) / w
- return np.sqrt(np.convolve(x * x, k, mode="same") + 1e-20)
-
-
-def declick(x, sr=SR, sens=8.0, max_ms=2.5, gate_db=-22.0):
- """
- Mouth clicks are wideband transients of a few hundred microseconds to ~2 ms.
- Two things make detection hard:
-
- * the LPC residual of voiced speech is *already* full of large spikes --
- those are glottal pulses, and a naive threshold shreds them;
- * real clicks are audible mostly because they sit in quiet passages
- (breath gaps, pre-onset silence), where nothing masks them.
-
- So detection is gated to frames whose broadband level sits `gate_db` below
- the running speech level, and inside those frames we threshold the
- high-band LPC residual against a robust local scale. Repair is by AR
- interpolation, not gating -- muting a click leaves an audible hole.
- """
- x = x.copy()
- slow = _smooth_env(x, sr, 25.0)
- speech_level = np.percentile(slow, 90)
- if speech_level <= 0:
- return x, 0
- quiet = slow < speech_level * 10 ** (gate_db / 20.0)
- if not quiet.any():
- return x, 0
-
- b, a = sps.butter(4, 2500 / (sr / 2), btype="high")
- hp = sps.filtfilt(b, a, x)
-
- # whiten: short-term LPC residual, so tonal content is predicted away and
- # only genuinely unpredictable energy survives
- blk = int(0.032 * sr)
- res = np.zeros_like(hp)
- for i in range(0, len(hp) - blk, blk):
- seg = hp[i: i + blk + 32]
- c = _lpc(seg, 16)
- res[i: i + blk] = (sps.lfilter(c, [1.0], seg)[:blk] if c is not None
- else seg[:blk])
-
- fast = _smooth_env(res, sr, 0.5)
-
- # Robust local scale. The MAD of the quiet residual alone collapses to zero
- # on digitally-silent gaps, which would make every sample a "click", so it
- # is floored against the signal's own residual dynamic range.
- mad = np.median(np.abs(res[quiet])) * 1.4826
- floor = max(mad, 1e-3 * np.percentile(np.abs(res), 99.0), 1e-9)
- thresh = sens * floor
-
- # Peak-pick rather than group contiguous runs: a run-based grouping merges
- # a whole quiet passage into one giant "click" the moment the floor is low.
- det = np.where(quiet, fast, 0.0)
- peaks, _ = sps.find_peaks(det, height=thresh,
- distance=max(1, int(0.002 * sr)))
-
- pad = int(0.0004 * sr)
- max_len = int(max_ms * 1e-3 * sr)
- fixed = 0
- for p in peaks:
- # grow outward while still above half-threshold, capped at max_ms
- lo = hi = p
- lim = max_len // 2
- while lo > 0 and p - lo < lim and det[lo - 1] > thresh * 0.5:
- lo -= 1
- while hi < len(det) - 1 and hi - p < lim and det[hi + 1] > thresh * 0.5:
- hi += 1
- s, e = max(0, lo - pad), min(len(x), hi + 1 + pad)
- if e - s > max_len: # clamp around the peak; padding
- s = max(0, p - max_len // 2) # must not push a valid detection
- e = min(len(x), s + max_len) # over the length limit
- if _repair(x, s, e):
- fixed += 1
- return x, fixed
-
-
-# ------------------------------------------------- 4. neural denoise/dereverb
-
-def neural(inp, outp, backend):
- if backend == "none":
- shutil.copy(inp, outp)
- return "skipped"
-
- if backend == "deepfilternet":
- from df.enhance import enhance, init_df, load_audio, save_audio
- import torch
- model, state, _ = init_df()
- audio, _ = load_audio(inp, sr=state.sr())
- with torch.no_grad():
- out = enhance(model, state, audio)
- save_audio(outp, out, state.sr())
- return "DeepFilterNet3"
-
- if backend == "clearvoice":
- from clearvoice import ClearVoice
- cv = ClearVoice(task="speech_enhancement",
- model_names=["MossFormer2_SE_48K"])
- cv(input_path=inp, online_write=True, output_path=outp)
- return "MossFormer2_SE_48K"
-
- raise ValueError(backend)
-
-
-# ----------------------------------------------------------- 5. polish chain
-
-def polish(inp, outp, lufs=-16.0, tp=-1.0, deess=True):
- """
- De-ess, corrective EQ, gentle compression, true-peak limit, then two-pass
- EBU R128 normalisation. ffmpeg's implementations of all of these are solid
- and vectorised; there is no reason to hand-roll them.
- """
- chain = [
- "highpass=f=75:poles=2", # rumble the NN left behind
- ]
- if deess:
- chain.append("deesser=i=0.35:m=0.5:f=0.5:s=o")
- chain += [
- "equalizer=f=300:t=q:w=1.2:g=-2", # box / mud
- "equalizer=f=2800:t=q:w=1.0:g=1.5", # intelligibility
- "equalizer=f=9000:t=h:w=0.7:g=2", # air
- "acompressor=threshold=-20dB:ratio=2.5:attack=8:release=180:makeup=2",
- ]
- filt = ",".join(chain)
-
- # pass 1: measure
- err = subprocess.run(
- ["ffmpeg", "-v", "info", "-i", inp, "-af",
- f"{filt},loudnorm=I={lufs}:TP={tp - 0.5}:LRA=9:print_format=json",
- "-f", "null", "-"],
- capture_output=True, text=True,
- ).stderr
- import json, re
- m = re.search(r"\{[^{}]*input_i[^{}]*\}", err, re.S)
- meas = json.loads(m.group(0)) if m else None
-
- ln = f"loudnorm=I={lufs}:TP={tp - 0.5}:LRA=9"
- if meas:
- ln += (f":measured_I={meas['input_i']}:measured_TP={meas['input_tp']}"
- f":measured_LRA={meas['input_lra']}"
- f":measured_thresh={meas['input_thresh']}"
- f":offset={meas['target_offset']}:linear=true")
-
- # limiter goes AFTER normalisation: put it first and loudnorm can no longer
- # raise level without clipping, and lands short of the target
- lim = f"alimiter=limit={10 ** (tp / 20.0):.4f}:attack=5:release=50:level=disabled"
- run(["ffmpeg", "-y", "-v", "error", "-i", inp, "-af",
- f"{filt},{ln},{lim}", "-ar", str(SR), "-c:a", "pcm_s24le", outp])
- return meas
-
-
-# ---------------------------------------------------------------------- main
-
-def main():
- ap = argparse.ArgumentParser(description="Studio-quality voice enhancement")
- ap.add_argument("input")
- ap.add_argument("-o", "--output", default="enhanced.wav")
- ap.add_argument("--backend", default="deepfilternet",
- choices=["deepfilternet", "clearvoice", "none"])
- ap.add_argument("--lufs", type=float, default=-16.0,
- help="-16 podcast/voiceover, -14 YouTube/Spotify")
- ap.add_argument("--true-peak", type=float, default=-1.0)
- ap.add_argument("--no-deplosive", action="store_true")
- ap.add_argument("--no-declick", action="store_true")
- ap.add_argument("--declick-after", action="store_true",
- help="run de-click on the network output instead; use when "
- "the source is so reverberant that the quiet-gate "
- "never opens on the raw input")
- ap.add_argument("--no-deess", action="store_true")
- args = ap.parse_args()
-
- tmp = tempfile.mkdtemp(prefix="enh_")
- try:
- x = decode(args.input)
- dur = len(x) / SR
- print(f"[1/5] decoded {dur:.1f}s @ {SR} Hz mono", file=sys.stderr)
-
- x -= x.mean() # DC offset
- peak = np.max(np.abs(x)) or 1.0
- x *= 0.7 / peak # headroom for repairs
-
- if not args.no_deplosive:
- x, nfr = deplosive(x)
- print(f"[2/5] de-plosive: ducked {nfr} frames", file=sys.stderr)
-
- if not args.no_declick and not args.declick_after:
- x, nc = declick(x)
- print(f"[3/5] de-click: repaired {nc} transients", file=sys.stderr)
-
- pre = os.path.join(tmp, "pre.wav")
- mid = os.path.join(tmp, "mid.wav")
- write_wav(x, pre)
-
- name = neural(pre, mid, args.backend)
- print(f"[4/5] denoise/dereverb: {name}", file=sys.stderr)
-
- if not args.no_declick and args.declick_after:
- y, nc = declick(decode(mid))
- write_wav(y, mid)
- print(f"[3/5] de-click (post): repaired {nc} transients",
- file=sys.stderr)
-
- meas = polish(mid, args.output, args.lufs, args.true_peak,
- deess=not args.no_deess)
- print(f"[5/5] polished -> {args.output}"
- + (f" (in {float(meas['input_i']):.1f} LUFS"
- f" -> {args.lufs} LUFS)" if meas else ""), file=sys.stderr)
- finally:
- shutil.rmtree(tmp, ignore_errors=True)
-
-
-if __name__ == "__main__":
- main()
\ No newline at end of file
diff --git a/test/face_blur/face_blur.py b/test/face_blur/face_blur.py
deleted file mode 100644
index 7a835e14..00000000
--- a/test/face_blur/face_blur.py
+++ /dev/null
@@ -1,155 +0,0 @@
-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 file
diff --git a/test/hardware_analysis/analyze_hardware.py b/test/hardware_analysis/analyze_hardware.py
deleted file mode 100644
index ea73ddc3..00000000
--- a/test/hardware_analysis/analyze_hardware.py
+++ /dev/null
@@ -1,640 +0,0 @@
-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 file
diff --git a/test/rnnoise/test_denoise.py b/test/rnnoise/test_denoise.py
deleted file mode 100644
index 86703fc2..00000000
--- a/test/rnnoise/test_denoise.py
+++ /dev/null
@@ -1,95 +0,0 @@
-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 file
diff --git a/test/scene_detect/test_scene_detect.py b/test/scene_detect/test_scene_detect.py
deleted file mode 100644
index 3bd8516c..00000000
--- a/test/scene_detect/test_scene_detect.py
+++ /dev/null
@@ -1,129 +0,0 @@
-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 file
diff --git a/test/silero_vad/test_vad.py b/test/silero_vad/test_vad.py
deleted file mode 100644
index 6e550376..00000000
--- a/test/silero_vad/test_vad.py
+++ /dev/null
@@ -1,120 +0,0 @@
-# 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
diff --git a/test/sweet_voice.py b/test/sweet_voice.py
deleted file mode 100644
index d9ad4945..00000000
--- a/test/sweet_voice.py
+++ /dev/null
@@ -1,125 +0,0 @@
-#!/usr/bin/env python3
-"""Apply the "Sweet" voice effect using a local FFmpeg install."""
-
-from __future__ import annotations
-
-import argparse
-import json
-import shutil
-import subprocess
-import sys
-from pathlib import Path
-
-
-def probe(path: Path) -> dict:
- command = [
- "ffprobe", "-v", "error", "-show_streams", "-of", "json", str(path)
- ]
- try:
- return json.loads(subprocess.check_output(command, text=True))
- except subprocess.CalledProcessError as exc:
- raise RuntimeError(f"ffprobe could not read {path}") from exc
-
-
-def sweet_filter(amount: float, pitch: float | None) -> str:
- strength = max(0.0, min(100.0, amount)) / 100.0
- semitones = pitch if pitch is not None else 1.2 + (1.5 * strength)
- ratio = 2.0 ** (semitones / 12.0)
-
- presence = 0.8 + (1.5 * strength)
- air = 1.0 + (2.0 * strength)
- deess = 0.18 + (0.22 * strength)
- echo = 0.012 + (0.018 * strength)
-
- # Raising the sample rate shifts pitch and formants; atempo restores duration.
- return ",".join([
- "aresample=48000",
- f"asetrate={48000.0 * ratio:.6f}",
- "aresample=48000",
- f"atempo={1.0 / ratio:.8f}",
- "highpass=f=85",
- "equalizer=f=300:t=q:w=1.1:g=-1.4",
- f"equalizer=f=4200:t=q:w=0.8:g={presence:.3f}",
- f"equalizer=f=10500:t=q:w=0.7:g={air:.3f}",
- "compand=attacks=0.010:decays=0.180:points=-80/-80|-30/-24|-18/-13|-8/-5|0/-1.5:soft-knee=5:gain=1",
- f"deesser=i={deess:.3f}:m=0.45:f=0.55",
- f"aecho=0.8:0.82:38:{echo:.4f}",
- "alimiter=limit=0.94:attack=5:release=60",
- ])
-
-
-def output_audio_codec(path: Path) -> list[str]:
- suffix = path.suffix.lower()
- if suffix == ".wav":
- return ["-c:a", "pcm_s24le"]
- if suffix == ".flac":
- return ["-c:a", "flac"]
- if suffix == ".mp3":
- return ["-c:a", "libmp3lame", "-q:a", "2"]
- if suffix in {".webm", ".ogg", ".opus"}:
- return ["-c:a", "libopus", "-b:a", "192k"]
- return ["-c:a", "aac", "-b:a", "256k"]
-
-
-def main() -> int:
- parser = argparse.ArgumentParser(
- description="Apply the bright, soft, slightly higher Sweet voice effect."
- )
- parser.add_argument("input", type=Path, help="Input audio or video file")
- parser.add_argument("output", type=Path, nargs="?", help="Output path")
- parser.add_argument("--amount", type=float, default=65, metavar="0-100")
- parser.add_argument("--pitch", type=float, help="Pitch shift in semitones")
- parser.add_argument("--overwrite", action="store_true")
- parser.add_argument("--dry-run", action="store_true", help="Print FFmpeg command only")
- args = parser.parse_args()
-
- if not shutil.which("ffmpeg") or not shutil.which("ffprobe"):
- parser.error("FFmpeg and ffprobe must be installed and available on PATH")
- if not args.input.is_file():
- parser.error(f"input does not exist: {args.input}")
- if not 0 <= args.amount <= 100:
- parser.error("--amount must be between 0 and 100")
-
- info = probe(args.input)
- streams = info.get("streams", [])
- has_audio = any(s.get("codec_type") == "audio" for s in streams)
- has_video = any(s.get("codec_type") == "video" for s in streams)
- if not has_audio:
- parser.error("input contains no audio stream")
-
- output = args.output
- if output is None:
- output = args.input.with_name(f"{args.input.stem}_sweet{args.input.suffix}")
- if output.resolve() == args.input.resolve():
- parser.error("output must be different from input")
- output.parent.mkdir(parents=True, exist_ok=True)
-
- command = ["ffmpeg", "-hide_banner", "-y" if args.overwrite else "-n", "-i", str(args.input)]
- if has_video:
- command += ["-map", "0:v:0", "-map", "0:a:0", "-c:v", "copy"]
- else:
- command += ["-map", "0:a:0"]
- command += ["-af", sweet_filter(args.amount, args.pitch)]
- command += output_audio_codec(output)
- command += ["-map_metadata", "0"]
- if has_video:
- command += ["-shortest"]
- if output.suffix.lower() in {".mp4", ".m4v", ".mov"}:
- command += ["-movflags", "+faststart"]
- command += [str(output)]
-
- if args.dry_run:
- import shlex
- print(shlex.join(command))
- return 0
-
- print(f"Creating: {output}")
- completed = subprocess.run(command)
- if completed.returncode:
- return completed.returncode
- print(f"Done: {output}")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())