remove bullcrap
Browse files- .hfignore +0 -1
- README.md +0 -23
- normalizer_audios.py +0 -494
.hfignore
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
sound_audios_original/**
|
|
|
|
|
|
README.md
DELETED
|
@@ -1,23 +0,0 @@
|
|
| 1 |
-
dataset_info:
|
| 2 |
-
features:
|
| 3 |
-
- name: audio
|
| 4 |
-
dtype: audio
|
| 5 |
-
<<<<<<< Updated upstream
|
| 6 |
-
- name: label
|
| 7 |
-
dtype: class_label
|
| 8 |
-
names: ["bip_sound_unlock_door", "bipping_ecg", "breathing", "breathing_heavily", "close_book", "close_door", "close_metallic_closet", "close_metallic_drawer", "close_microwave_door", "close_plastic_drawer", "close_wooden_drawer", "elevator_door_close", "elevator_door_open", "fast_keyboard_typing", "filling_cup_with_water", "hand_dryer", "hanging_up_landline_telephone", "keyboard_typing", "knock_door", "lighter", "machine_bipping", "marker_cap_action", "mouse_clicking", "moving_pen_tool_metal_holder", "open_book", "open_bottle", "open_door", "open_metallic_closet", "open_metallic_drawer", "open_microwave_door", "open_plastic_drawer", "open_small_metallic_drawer", "open_wooden_drawer", "open_zip", "paper_drawing", "pen_clicking", "pen_writting_on_paper", "picking_up_landline_telephone", "plastic_bag", "press_computer_button", "press_sanitizer_dispenser", "press_soap_dispenser", "press_space_bar_keyboard", "press_spray", "printer_initialization", "pull_down_door_knob", "pull_scotch_tape", "pull_up_door_knob", "pulling_pill_out", "pulling_wooden_chair_in", "pulling_wooden_chair_out", "scrolling_mouse_wheel", "searching_wooden_drawer", "sitting_wooden_chair", "sneezing", "sigh", "spoon_drop_in_cup", "stapling_papers", "switch_light_off", "switch_light_on", "tearing_ripping_medical_roll_paper", "turn_fan_on", "turn_microwave_on_and_off", "turning_or_sorting_papers", "walking", "water_falling_in_sink"]
|
| 9 |
-
- name: description
|
| 10 |
-
dtype: string
|
| 11 |
-
task_categories:
|
| 12 |
-
- audio-classification
|
| 13 |
-
pretty_name: sound_events
|
| 14 |
-
size_categories:
|
| 15 |
-
- n<1K
|
| 16 |
-
---
|
| 17 |
-
=======
|
| 18 |
-
configs:
|
| 19 |
-
- config_name: default
|
| 20 |
-
data_files:
|
| 21 |
-
- split: train
|
| 22 |
-
path: metadata.jsonl
|
| 23 |
-
>>>>>>> Stashed changes
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
normalizer_audios.py
DELETED
|
@@ -1,494 +0,0 @@
|
|
| 1 |
-
#!/usr/bin/env python3
|
| 2 |
-
"""
|
| 3 |
-
All-in-one audio processing pipeline for sound event files.
|
| 4 |
-
|
| 5 |
-
Pipeline: 1) Normalize -> 2) Trim silence -> 3) Verify cuts
|
| 6 |
-
|
| 7 |
-
1. NORMALIZE – scale every file to a target RMS (or peak) level in dBFS
|
| 8 |
-
so all events share a consistent loudness.
|
| 9 |
-
2. TRIM – remove leading / trailing silence using an energy-based detector
|
| 10 |
-
with a configurable safety margin.
|
| 11 |
-
3. VERIFY – check every trimmed file for corruption, suspiciously short
|
| 12 |
-
duration, or abrupt start/end (which would indicate a bad cut).
|
| 13 |
-
|
| 14 |
-
Usage examples
|
| 15 |
-
--------------
|
| 16 |
-
# Full pipeline with defaults (in-place, -20 dBFS RMS):
|
| 17 |
-
python normalizer_audios.py
|
| 18 |
-
|
| 19 |
-
# Normalize to -25 dBFS, wider trim margin:
|
| 20 |
-
python normalizer_audios.py --target-db -25 --margin-ms 50
|
| 21 |
-
|
| 22 |
-
# Peak-normalize instead of RMS:
|
| 23 |
-
python normalizer_audios.py --mode peak --target-db -1
|
| 24 |
-
|
| 25 |
-
# Preview everything without writing:
|
| 26 |
-
python normalizer_audios.py --dry-run
|
| 27 |
-
|
| 28 |
-
# Skip normalization (trim + verify only):
|
| 29 |
-
python normalizer_audios.py --skip-normalize
|
| 30 |
-
|
| 31 |
-
# Skip trimming (normalize + verify only):
|
| 32 |
-
python normalizer_audios.py --skip-trim
|
| 33 |
-
"""
|
| 34 |
-
|
| 35 |
-
import argparse
|
| 36 |
-
import json
|
| 37 |
-
import logging
|
| 38 |
-
import math
|
| 39 |
-
import os
|
| 40 |
-
import struct
|
| 41 |
-
import sys
|
| 42 |
-
import wave
|
| 43 |
-
from pathlib import Path
|
| 44 |
-
|
| 45 |
-
import numpy as np
|
| 46 |
-
import soundfile as sf
|
| 47 |
-
|
| 48 |
-
logging.basicConfig(
|
| 49 |
-
level=logging.INFO,
|
| 50 |
-
format="%(asctime)s | %(levelname)s | %(message)s",
|
| 51 |
-
datefmt="%H:%M:%S",
|
| 52 |
-
)
|
| 53 |
-
log = logging.getLogger(__name__)
|
| 54 |
-
|
| 55 |
-
AUDIO_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "sound_audios")
|
| 56 |
-
|
| 57 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
| 58 |
-
# Shared I/O (stdlib wave – used by trimmer & verifier)
|
| 59 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
| 60 |
-
|
| 61 |
-
def _wav_fmt(sampwidth):
|
| 62 |
-
if sampwidth == 1:
|
| 63 |
-
return "B"
|
| 64 |
-
elif sampwidth == 2:
|
| 65 |
-
return "h"
|
| 66 |
-
elif sampwidth == 4:
|
| 67 |
-
return "i"
|
| 68 |
-
raise ValueError(f"Unsupported sample width: {sampwidth}")
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
def read_wav_stdlib(filepath):
|
| 72 |
-
"""Read a WAV file with the stdlib *wave* module.
|
| 73 |
-
Returns (samples_list, sample_rate, sampwidth, nchannels)."""
|
| 74 |
-
with wave.open(filepath, "rb") as wf:
|
| 75 |
-
nchannels = wf.getnchannels()
|
| 76 |
-
sampwidth = wf.getsampwidth()
|
| 77 |
-
sr = wf.getframerate()
|
| 78 |
-
nframes = wf.getnframes()
|
| 79 |
-
raw = wf.readframes(nframes)
|
| 80 |
-
fmt = _wav_fmt(sampwidth)
|
| 81 |
-
n_samples = nframes * nchannels
|
| 82 |
-
samples = list(struct.unpack(f"<{n_samples}{fmt}", raw))
|
| 83 |
-
return samples, sr, sampwidth, nchannels
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
def write_wav_stdlib(filepath, samples, sr, sampwidth, nchannels):
|
| 87 |
-
"""Write samples to a WAV file with the stdlib *wave* module."""
|
| 88 |
-
fmt = _wav_fmt(sampwidth)
|
| 89 |
-
raw = struct.pack(f"<{len(samples)}{fmt}", *samples)
|
| 90 |
-
with wave.open(filepath, "wb") as wf:
|
| 91 |
-
wf.setnchannels(nchannels)
|
| 92 |
-
wf.setsampwidth(sampwidth)
|
| 93 |
-
wf.setframerate(sr)
|
| 94 |
-
wf.writeframes(raw)
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
def collect_wav_files(audio_dir):
|
| 98 |
-
"""Return a sorted list of all .wav paths under *audio_dir*."""
|
| 99 |
-
wav_files = []
|
| 100 |
-
for root, _dirs, files in os.walk(audio_dir):
|
| 101 |
-
for f in sorted(files):
|
| 102 |
-
if f.lower().endswith(".wav"):
|
| 103 |
-
wav_files.append(os.path.join(root, f))
|
| 104 |
-
return sorted(wav_files)
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
# ═════════════════════════════════════════════════════════════════════════════
|
| 108 |
-
# STEP 1 – NORMALIZE
|
| 109 |
-
# ═════════════════════════════════════════════════════════════════════════════
|
| 110 |
-
|
| 111 |
-
def rms_db(signal: np.ndarray) -> float:
|
| 112 |
-
rms = np.sqrt(np.mean(signal.astype(np.float64) ** 2))
|
| 113 |
-
return -np.inf if rms == 0 else 20 * np.log10(rms)
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
def peak_db(signal: np.ndarray) -> float:
|
| 117 |
-
peak = np.max(np.abs(signal.astype(np.float64)))
|
| 118 |
-
return -np.inf if peak == 0 else 20 * np.log10(peak)
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
def _apply_gain(signal: np.ndarray, current_db: float, target_db: float) -> np.ndarray:
|
| 122 |
-
if current_db == -np.inf:
|
| 123 |
-
return signal
|
| 124 |
-
gain_linear = 10 ** ((target_db - current_db) / 20)
|
| 125 |
-
out = signal.astype(np.float64) * gain_linear
|
| 126 |
-
peak = np.max(np.abs(out))
|
| 127 |
-
if peak > 1.0:
|
| 128 |
-
log.warning(" Clipping detected (peak %.2f dB), applying limiter.", 20 * np.log10(peak))
|
| 129 |
-
out /= peak
|
| 130 |
-
return out
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
def step_normalize(audio_dir, target_db, mode, dry_run):
|
| 134 |
-
"""Normalize all .wav files in *audio_dir* in-place."""
|
| 135 |
-
print("\n" + "=" * 70)
|
| 136 |
-
print(" STEP 1 / 3 — NORMALIZE")
|
| 137 |
-
print("=" * 70)
|
| 138 |
-
|
| 139 |
-
input_dir = Path(audio_dir).resolve()
|
| 140 |
-
measure_fn = rms_db if mode == "rms" else peak_db
|
| 141 |
-
mode_label = "RMS" if mode == "rms" else "Peak"
|
| 142 |
-
|
| 143 |
-
wav_files = sorted(input_dir.rglob("*.wav"))
|
| 144 |
-
if not wav_files:
|
| 145 |
-
log.error("No .wav files found under %s", input_dir)
|
| 146 |
-
return
|
| 147 |
-
|
| 148 |
-
log.info("Found %d .wav files", len(wav_files))
|
| 149 |
-
log.info("Mode: %s | Target: %.1f dBFS | dry_run=%s", mode_label, target_db, dry_run)
|
| 150 |
-
|
| 151 |
-
stats = []
|
| 152 |
-
n_clipped = 0
|
| 153 |
-
|
| 154 |
-
for wav_path in wav_files:
|
| 155 |
-
rel = wav_path.relative_to(input_dir)
|
| 156 |
-
signal, sr = sf.read(wav_path, dtype="float64")
|
| 157 |
-
mono = signal.mean(axis=1) if signal.ndim == 2 else signal
|
| 158 |
-
|
| 159 |
-
orig_db = measure_fn(mono)
|
| 160 |
-
orig_peak = peak_db(mono)
|
| 161 |
-
entry = {
|
| 162 |
-
"file": str(rel),
|
| 163 |
-
"sr": sr,
|
| 164 |
-
"duration_s": round(len(mono) / sr, 3),
|
| 165 |
-
f"original_{mode}_db": round(orig_db, 2),
|
| 166 |
-
"original_peak_db": round(orig_peak, 2),
|
| 167 |
-
}
|
| 168 |
-
|
| 169 |
-
if orig_db == -np.inf:
|
| 170 |
-
log.warning(" Skipping silent file: %s", rel)
|
| 171 |
-
entry["status"] = "skipped_silent"
|
| 172 |
-
stats.append(entry)
|
| 173 |
-
continue
|
| 174 |
-
|
| 175 |
-
normed = _apply_gain(signal, orig_db, target_db)
|
| 176 |
-
new_mono = normed if normed.ndim == 1 else normed.mean(axis=1)
|
| 177 |
-
new_db = measure_fn(new_mono)
|
| 178 |
-
new_peak = peak_db(new_mono)
|
| 179 |
-
if new_peak >= 0.0:
|
| 180 |
-
n_clipped += 1
|
| 181 |
-
|
| 182 |
-
entry[f"new_{mode}_db"] = round(new_db, 2)
|
| 183 |
-
entry["new_peak_db"] = round(new_peak, 2)
|
| 184 |
-
entry["gain_db"] = round(target_db - orig_db, 2)
|
| 185 |
-
entry["status"] = "ok"
|
| 186 |
-
stats.append(entry)
|
| 187 |
-
|
| 188 |
-
log.info(
|
| 189 |
-
"%-55s %s: %+6.1f -> %+6.1f dBFS (gain %+.1f dB)",
|
| 190 |
-
str(rel), mode_label, orig_db, new_db, target_db - orig_db,
|
| 191 |
-
)
|
| 192 |
-
|
| 193 |
-
if not dry_run:
|
| 194 |
-
sf.write(str(wav_path), normed, sr, subtype="PCM_16")
|
| 195 |
-
|
| 196 |
-
# Summary
|
| 197 |
-
orig_levels = [s[f"original_{mode}_db"] for s in stats if s["status"] == "ok"]
|
| 198 |
-
new_levels = [s[f"new_{mode}_db"] for s in stats if s["status"] == "ok"]
|
| 199 |
-
|
| 200 |
-
print("-" * 70)
|
| 201 |
-
log.info("Normalized %d / %d files", len(orig_levels), len(wav_files))
|
| 202 |
-
if orig_levels:
|
| 203 |
-
log.info(
|
| 204 |
-
"Original %s — min: %.1f max: %.1f mean: %.1f std: %.1f dBFS",
|
| 205 |
-
mode_label, np.min(orig_levels), np.max(orig_levels),
|
| 206 |
-
np.mean(orig_levels), np.std(orig_levels),
|
| 207 |
-
)
|
| 208 |
-
log.info(
|
| 209 |
-
"After norm %s — min: %.1f max: %.1f mean: %.1f std: %.1f dBFS",
|
| 210 |
-
mode_label, np.min(new_levels), np.max(new_levels),
|
| 211 |
-
np.mean(new_levels), np.std(new_levels),
|
| 212 |
-
)
|
| 213 |
-
if n_clipped:
|
| 214 |
-
log.warning("%d file(s) required limiting to avoid clipping.", n_clipped)
|
| 215 |
-
|
| 216 |
-
if not dry_run:
|
| 217 |
-
stats_path = os.path.join(audio_dir, "normalization_stats.json")
|
| 218 |
-
with open(stats_path, "w") as f:
|
| 219 |
-
json.dump(
|
| 220 |
-
{"mode": mode, "target_db": target_db,
|
| 221 |
-
"n_files": len(wav_files), "n_processed": len(orig_levels),
|
| 222 |
-
"n_clipped": n_clipped, "files": stats},
|
| 223 |
-
f, indent=2,
|
| 224 |
-
)
|
| 225 |
-
log.info("Stats written to %s", stats_path)
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
# ═════════════════════════════════════════════════════════════════════════════
|
| 229 |
-
# STEP 2 – TRIM SILENCE
|
| 230 |
-
# ═════════════════════════════════════════════════════════════════════════════
|
| 231 |
-
|
| 232 |
-
def _to_mono_abs(samples, nchannels, nframes):
|
| 233 |
-
if nchannels == 1:
|
| 234 |
-
return [abs(s) for s in samples]
|
| 235 |
-
mono = []
|
| 236 |
-
for i in range(nframes):
|
| 237 |
-
val = sum(abs(samples[i * nchannels + ch]) for ch in range(nchannels))
|
| 238 |
-
mono.append(val // nchannels)
|
| 239 |
-
return mono
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
def trim_silence(samples, sr, nchannels, threshold_ratio=0.02,
|
| 243 |
-
margin_ms=30, frame_ms=10):
|
| 244 |
-
"""Return (trimmed_samples, original_ms, new_ms)."""
|
| 245 |
-
nframes = len(samples) // nchannels
|
| 246 |
-
mono = _to_mono_abs(samples, nchannels, nframes)
|
| 247 |
-
|
| 248 |
-
peak = max(mono) if mono else 0
|
| 249 |
-
if peak == 0:
|
| 250 |
-
dur = nframes / sr * 1000
|
| 251 |
-
return samples, dur, dur
|
| 252 |
-
|
| 253 |
-
threshold = peak * threshold_ratio
|
| 254 |
-
frame_len = max(1, int(sr * frame_ms / 1000))
|
| 255 |
-
hop = max(1, frame_len // 2)
|
| 256 |
-
|
| 257 |
-
first_loud = last_loud = None
|
| 258 |
-
pos = 0
|
| 259 |
-
while pos + frame_len <= nframes:
|
| 260 |
-
window = mono[pos:pos + frame_len]
|
| 261 |
-
rms = math.sqrt(sum(s * s for s in window) / frame_len)
|
| 262 |
-
if rms > threshold:
|
| 263 |
-
if first_loud is None:
|
| 264 |
-
first_loud = pos
|
| 265 |
-
last_loud = pos + frame_len
|
| 266 |
-
pos += hop
|
| 267 |
-
|
| 268 |
-
if first_loud is None:
|
| 269 |
-
dur = nframes / sr * 1000
|
| 270 |
-
return samples, dur, dur
|
| 271 |
-
|
| 272 |
-
margin_samp = int(sr * margin_ms / 1000)
|
| 273 |
-
start = max(0, first_loud - margin_samp)
|
| 274 |
-
end = min(nframes, last_loud + margin_samp)
|
| 275 |
-
|
| 276 |
-
trimmed = samples[start * nchannels : end * nchannels]
|
| 277 |
-
return trimmed, nframes / sr * 1000, (end - start) / sr * 1000
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
def step_trim(audio_dir, threshold_ratio, margin_ms, dry_run):
|
| 281 |
-
"""Trim leading/trailing silence from every .wav in *audio_dir*."""
|
| 282 |
-
print("\n" + "=" * 70)
|
| 283 |
-
print(" STEP 2 / 3 — TRIM SILENCE")
|
| 284 |
-
print("=" * 70)
|
| 285 |
-
|
| 286 |
-
wav_files = collect_wav_files(audio_dir)
|
| 287 |
-
if not wav_files:
|
| 288 |
-
log.error("No .wav files found in %s", audio_dir)
|
| 289 |
-
return
|
| 290 |
-
|
| 291 |
-
log.info("Found %d .wav files", len(wav_files))
|
| 292 |
-
log.info("Settings: threshold=%.3f, margin=%gms, dry_run=%s",
|
| 293 |
-
threshold_ratio, margin_ms, dry_run)
|
| 294 |
-
print("-" * 70)
|
| 295 |
-
|
| 296 |
-
total_saved = 0
|
| 297 |
-
trimmed_count = 0
|
| 298 |
-
|
| 299 |
-
for i, fpath in enumerate(wav_files, 1):
|
| 300 |
-
rel = os.path.relpath(fpath, audio_dir)
|
| 301 |
-
try:
|
| 302 |
-
samples, sr, sw, nch = read_wav_stdlib(fpath)
|
| 303 |
-
except Exception as e:
|
| 304 |
-
log.error("[%d/%d] ERROR reading %s: %s", i, len(wav_files), rel, e)
|
| 305 |
-
continue
|
| 306 |
-
|
| 307 |
-
trimmed, orig_ms, new_ms = trim_silence(
|
| 308 |
-
samples, sr, nch, threshold_ratio, margin_ms)
|
| 309 |
-
saved = orig_ms - new_ms
|
| 310 |
-
|
| 311 |
-
if saved > 1:
|
| 312 |
-
trimmed_count += 1
|
| 313 |
-
total_saved += saved
|
| 314 |
-
tag = "DRY-RUN" if dry_run else "TRIMMED"
|
| 315 |
-
log.info("[%d/%d] %s %s: %dms -> %dms (cut %dms)",
|
| 316 |
-
i, len(wav_files), tag, rel,
|
| 317 |
-
int(orig_ms), int(new_ms), int(saved))
|
| 318 |
-
if not dry_run:
|
| 319 |
-
write_wav_stdlib(fpath, trimmed, sr, sw, nch)
|
| 320 |
-
else:
|
| 321 |
-
log.info("[%d/%d] OK %s: %dms (no silence)",
|
| 322 |
-
i, len(wav_files), rel, int(orig_ms))
|
| 323 |
-
|
| 324 |
-
print("-" * 70)
|
| 325 |
-
log.info("Trimmed %d/%d files, saved %.1fs total.",
|
| 326 |
-
trimmed_count, len(wav_files), total_saved / 1000)
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
# ═════════════════════════════════════════════════════════════════════════════
|
| 330 |
-
# STEP 3 – VERIFY CUTS
|
| 331 |
-
# ═════════════════════════════════════════════════════════════════════════════
|
| 332 |
-
|
| 333 |
-
MIN_DURATION_MS = 50
|
| 334 |
-
EDGE_CHECK_MS = 5
|
| 335 |
-
EDGE_AMPLITUDE_RATIO = 0.5
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
def _check_one_file(filepath, audio_dir):
|
| 339 |
-
"""Return (duration_ms, [warnings])."""
|
| 340 |
-
warnings = []
|
| 341 |
-
try:
|
| 342 |
-
samples, sr, sw, nch = read_wav_stdlib(filepath)
|
| 343 |
-
except Exception as e:
|
| 344 |
-
return 0, [f"CORRUPT: {e}"]
|
| 345 |
-
|
| 346 |
-
nframes = len(samples) // nch
|
| 347 |
-
dur = nframes / sr * 1000
|
| 348 |
-
|
| 349 |
-
if nframes == 0:
|
| 350 |
-
return 0, ["EMPTY: 0 frames"]
|
| 351 |
-
|
| 352 |
-
if dur < MIN_DURATION_MS:
|
| 353 |
-
warnings.append(f"VERY SHORT: {dur:.0f}ms (< {MIN_DURATION_MS}ms)")
|
| 354 |
-
|
| 355 |
-
mono = _to_mono_abs(samples, nch, nframes)
|
| 356 |
-
peak = max(mono) if mono else 0
|
| 357 |
-
if peak == 0:
|
| 358 |
-
warnings.append("SILENT: completely silent")
|
| 359 |
-
return dur, warnings
|
| 360 |
-
|
| 361 |
-
edge_n = max(1, int(sr * EDGE_CHECK_MS / 1000))
|
| 362 |
-
|
| 363 |
-
start_max = max(mono[:edge_n])
|
| 364 |
-
if start_max > peak * EDGE_AMPLITUDE_RATIO:
|
| 365 |
-
warnings.append(
|
| 366 |
-
f"ABRUPT START: first {EDGE_CHECK_MS}ms at "
|
| 367 |
-
f"{start_max/peak*100:.0f}% of peak")
|
| 368 |
-
|
| 369 |
-
end_max = max(mono[-edge_n:])
|
| 370 |
-
if end_max > peak * EDGE_AMPLITUDE_RATIO:
|
| 371 |
-
warnings.append(
|
| 372 |
-
f"ABRUPT END: last {EDGE_CHECK_MS}ms at "
|
| 373 |
-
f"{end_max/peak*100:.0f}% of peak")
|
| 374 |
-
|
| 375 |
-
return dur, warnings
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
def step_verify(audio_dir):
|
| 379 |
-
"""Verify all trimmed .wav files for quality issues."""
|
| 380 |
-
print("\n" + "=" * 70)
|
| 381 |
-
print(" STEP 3 / 3 — VERIFY CUTS")
|
| 382 |
-
print("=" * 70)
|
| 383 |
-
|
| 384 |
-
wav_files = collect_wav_files(audio_dir)
|
| 385 |
-
if not wav_files:
|
| 386 |
-
log.error("No .wav files found in %s", audio_dir)
|
| 387 |
-
return
|
| 388 |
-
|
| 389 |
-
log.info("Verifying %d .wav files", len(wav_files))
|
| 390 |
-
print("-" * 70)
|
| 391 |
-
|
| 392 |
-
flagged = []
|
| 393 |
-
total_dur = 0
|
| 394 |
-
|
| 395 |
-
for i, fpath in enumerate(wav_files, 1):
|
| 396 |
-
rel = os.path.relpath(fpath, audio_dir)
|
| 397 |
-
dur, warns = _check_one_file(fpath, audio_dir)
|
| 398 |
-
total_dur += dur
|
| 399 |
-
if warns:
|
| 400 |
-
flagged.append((rel, dur, warns))
|
| 401 |
-
log.warning("[%d/%d] WARNING %s (%dms)", i, len(wav_files), rel, int(dur))
|
| 402 |
-
for w in warns:
|
| 403 |
-
log.warning(" -> %s", w)
|
| 404 |
-
else:
|
| 405 |
-
log.info("[%d/%d] OK %s (%dms)", i, len(wav_files), rel, int(dur))
|
| 406 |
-
|
| 407 |
-
print("=" * 70)
|
| 408 |
-
log.info("Total files: %d | Duration: %.1fs", len(wav_files), total_dur / 1000)
|
| 409 |
-
log.info("Files OK: %d | Flagged: %d", len(wav_files) - len(flagged), len(flagged))
|
| 410 |
-
|
| 411 |
-
if flagged:
|
| 412 |
-
print("\n--- FLAGGED FILES (review manually) ---")
|
| 413 |
-
for rel, dur, warns in flagged:
|
| 414 |
-
print(f"\n {rel} ({dur:.0f}ms):")
|
| 415 |
-
for w in warns:
|
| 416 |
-
print(f" - {w}")
|
| 417 |
-
else:
|
| 418 |
-
print("\nAll files look good!")
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
# ═════════════════════════════════════════════════════════════════════════════
|
| 422 |
-
# MAIN
|
| 423 |
-
# ═════════════════════════════════════════════════════════════════════════════
|
| 424 |
-
|
| 425 |
-
def main():
|
| 426 |
-
parser = argparse.ArgumentParser(
|
| 427 |
-
description="Audio pipeline: Normalize -> Trim silence -> Verify cuts",
|
| 428 |
-
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 429 |
-
)
|
| 430 |
-
|
| 431 |
-
# General
|
| 432 |
-
parser.add_argument(
|
| 433 |
-
"--audio-dir", type=str, default=AUDIO_DIR,
|
| 434 |
-
help="Root directory containing event sub-folders with .wav files "
|
| 435 |
-
f"(default: {AUDIO_DIR})",
|
| 436 |
-
)
|
| 437 |
-
parser.add_argument(
|
| 438 |
-
"--dry-run", action="store_true",
|
| 439 |
-
help="Preview all steps without writing any files.",
|
| 440 |
-
)
|
| 441 |
-
|
| 442 |
-
# Normalize options
|
| 443 |
-
norm = parser.add_argument_group("Normalization (step 1)")
|
| 444 |
-
norm.add_argument("--skip-normalize", action="store_true",
|
| 445 |
-
help="Skip the normalization step.")
|
| 446 |
-
norm.add_argument("--target-db", type=float, default=-20.0,
|
| 447 |
-
help="Target level in dBFS (default: -20).")
|
| 448 |
-
norm.add_argument("--mode", choices=["rms", "peak"], default="rms",
|
| 449 |
-
help="Normalization mode (default: rms).")
|
| 450 |
-
|
| 451 |
-
# Trim options
|
| 452 |
-
trim = parser.add_argument_group("Trimming (step 2)")
|
| 453 |
-
trim.add_argument("--skip-trim", action="store_true",
|
| 454 |
-
help="Skip the silence trimming step.")
|
| 455 |
-
trim.add_argument("--threshold", type=float, default=0.02,
|
| 456 |
-
help="Silence threshold as fraction of peak (default: 0.02).")
|
| 457 |
-
trim.add_argument("--margin-ms", type=float, default=30,
|
| 458 |
-
help="Margin in ms to keep around the sound (default: 30).")
|
| 459 |
-
|
| 460 |
-
# Verify options
|
| 461 |
-
verify = parser.add_argument_group("Verification (step 3)")
|
| 462 |
-
verify.add_argument("--skip-verify", action="store_true",
|
| 463 |
-
help="Skip the verification step.")
|
| 464 |
-
|
| 465 |
-
args = parser.parse_args()
|
| 466 |
-
audio_dir = args.audio_dir
|
| 467 |
-
|
| 468 |
-
log.info("Audio directory: %s", audio_dir)
|
| 469 |
-
|
| 470 |
-
# ── Step 1 ──
|
| 471 |
-
if not args.skip_normalize:
|
| 472 |
-
step_normalize(audio_dir, args.target_db, args.mode, args.dry_run)
|
| 473 |
-
else:
|
| 474 |
-
log.info("Skipping normalization (--skip-normalize).")
|
| 475 |
-
|
| 476 |
-
# ── Step 2 ──
|
| 477 |
-
if not args.skip_trim:
|
| 478 |
-
step_trim(audio_dir, args.threshold, args.margin_ms, args.dry_run)
|
| 479 |
-
else:
|
| 480 |
-
log.info("Skipping trimming (--skip-trim).")
|
| 481 |
-
|
| 482 |
-
# ── Step 3 ──
|
| 483 |
-
if not args.skip_verify:
|
| 484 |
-
step_verify(audio_dir)
|
| 485 |
-
else:
|
| 486 |
-
log.info("Skipping verification (--skip-verify).")
|
| 487 |
-
|
| 488 |
-
print("\n" + "=" * 70)
|
| 489 |
-
log.info("Pipeline complete.")
|
| 490 |
-
print("=" * 70)
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
if __name__ == "__main__":
|
| 494 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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