#!/usr/bin/env python3 """ Sibilant Duration Reducer Automatically detects and shortens excessively long sibilant ("SSS") sounds in audio recordings by cutting out the middle portion and crossfading. """ import argparse from pathlib import Path import numpy as np import soundfile as sf from scipy.signal import stft from tqdm import tqdm # Default parameters SIBILANT_FREQ_LOW = 4000 # Hz SIBILANT_FREQ_HIGH = 10000 # Hz MAX_SIBILANT_DURATION = 0.070 # seconds (70ms) CROSSFADE_DURATION = 0.010 # seconds (10ms) DETECTION_THRESHOLD = 0.1 # relative energy threshold MIN_GAP_DURATION = 0.020 # seconds - gaps smaller than this merge regions def detect_sibilants( samples: np.ndarray, sr: int, freq_low: float, freq_high: float, threshold: float, min_gap: float, ) -> list[tuple[int, int]]: """ Detect sibilant regions in audio by analyzing high-frequency energy. Returns list of (start_sample, end_sample) tuples for detected sibilants. """ # STFT parameters nperseg = 512 noverlap = nperseg // 2 hop = nperseg - noverlap # Compute STFT freqs, times, Zxx = stft(samples, fs=sr, nperseg=nperseg, noverlap=noverlap) # Find frequency bin indices for sibilant band freq_mask = (freqs >= freq_low) & (freqs <= freq_high) # Calculate energy in sibilant band for each frame sibilant_energy = np.sum(np.abs(Zxx[freq_mask, :]) ** 2, axis=0) # Normalize energy if sibilant_energy.max() > 0: sibilant_energy = sibilant_energy / sibilant_energy.max() else: return [] # Threshold to find sibilant frames is_sibilant = sibilant_energy > threshold # Convert frame indices to sample indices frame_to_sample = lambda f: int(f * hop) # Find contiguous regions regions = [] in_region = False start_frame = 0 for i, is_sib in enumerate(is_sibilant): if is_sib and not in_region: start_frame = i in_region = True elif not is_sib and in_region: regions.append((frame_to_sample(start_frame), frame_to_sample(i))) in_region = False # Handle region extending to end if in_region: regions.append((frame_to_sample(start_frame), frame_to_sample(len(is_sibilant)))) # Merge regions with small gaps min_gap_samples = int(min_gap * sr) merged_regions = [] for start, end in regions: if merged_regions and start - merged_regions[-1][1] < min_gap_samples: # Merge with previous region merged_regions[-1] = (merged_regions[-1][0], end) else: merged_regions.append((start, end)) # Clamp to valid sample range merged_regions = [ (max(0, start), min(len(samples), end)) for start, end in merged_regions ] return merged_regions def shorten_sibilant( samples: np.ndarray, start: int, end: int, sr: int, max_duration: float, crossfade_duration: float, ) -> tuple[np.ndarray, int]: """ Shorten a sibilant region by cutting out the middle and crossfading. Returns (shortened_segment, samples_removed). """ segment = samples[start:end] segment_duration = len(segment) / sr if segment_duration <= max_duration: return segment, 0 # Calculate how many samples to keep max_samples = int(max_duration * sr) crossfade_samples = int(crossfade_duration * sr) # Ensure we have enough samples for crossfade if max_samples < 2 * crossfade_samples: crossfade_samples = max_samples // 4 # Split: keep beginning and end, remove middle keep_each_side = max_samples // 2 before = segment[:keep_each_side] after = segment[-keep_each_side:] # Apply crossfade at the junction if crossfade_samples > 0 and len(before) >= crossfade_samples and len(after) >= crossfade_samples: fade_out = np.linspace(1.0, 0.0, crossfade_samples) fade_in = np.linspace(0.0, 1.0, crossfade_samples) # Crossfade the overlapping portion before_fade = before[-crossfade_samples:] * fade_out after_fade = after[:crossfade_samples] * fade_in crossfaded = before_fade + after_fade # Construct shortened segment shortened = np.concatenate([ before[:-crossfade_samples], crossfaded, after[crossfade_samples:] ]) else: # No crossfade possible, just concatenate shortened = np.concatenate([before, after]) samples_removed = len(segment) - len(shortened) return shortened, samples_removed def process_audio( samples: np.ndarray, sr: int, freq_low: float, freq_high: float, threshold: float, max_duration: float, crossfade_duration: float, min_gap: float, ) -> tuple[np.ndarray, int, int]: """ Process audio to shorten long sibilants. Returns (processed_samples, num_sibilants_shortened, total_samples_removed). """ # Detect sibilants regions = detect_sibilants(samples, sr, freq_low, freq_high, threshold, min_gap) # Filter to only long sibilants max_samples = int(max_duration * sr) long_regions = [(s, e) for s, e in regions if (e - s) > max_samples] if not long_regions: return samples, 0, 0 # Process regions from end to start (to preserve indices) result = samples.copy() total_removed = 0 for start, end in reversed(long_regions): shortened, removed = shorten_sibilant( result, start, end, sr, max_duration, crossfade_duration ) # Replace the region with shortened version result = np.concatenate([result[:start], shortened, result[end:]]) total_removed += removed return result, len(long_regions), total_removed def main(): parser = argparse.ArgumentParser( description="Reduce duration of harsh sibilant sounds in audio files" ) parser.add_argument( "--input-dir", type=Path, default=Path("wav"), help="Input directory containing WAV files (default: wav)", ) parser.add_argument( "--output-dir", type=Path, default=Path("wav_deessed"), help="Output directory for processed files (default: wav_deessed)", ) parser.add_argument( "--threshold", type=float, default=DETECTION_THRESHOLD, help=f"Detection sensitivity 0-1 (default: {DETECTION_THRESHOLD})", ) parser.add_argument( "--max-duration", type=float, default=MAX_SIBILANT_DURATION * 1000, help=f"Maximum sibilant duration in ms (default: {MAX_SIBILANT_DURATION * 1000})", ) parser.add_argument( "--crossfade", type=float, default=CROSSFADE_DURATION * 1000, help=f"Crossfade duration in ms (default: {CROSSFADE_DURATION * 1000})", ) parser.add_argument( "--freq-low", type=float, default=SIBILANT_FREQ_LOW, help=f"Lower frequency bound in Hz (default: {SIBILANT_FREQ_LOW})", ) parser.add_argument( "--freq-high", type=float, default=SIBILANT_FREQ_HIGH, help=f"Upper frequency bound in Hz (default: {SIBILANT_FREQ_HIGH})", ) args = parser.parse_args() # Convert ms to seconds max_duration = args.max_duration / 1000 crossfade_duration = args.crossfade / 1000 # Find input files input_dir = args.input_dir output_dir = args.output_dir if not input_dir.exists(): print(f"Error: Input directory '{input_dir}' does not exist") return 1 wav_files = list(input_dir.glob("*.wav")) if not wav_files: print(f"No WAV files found in '{input_dir}'") return 1 # Create output directory output_dir.mkdir(parents=True, exist_ok=True) print(f"Processing {len(wav_files)} file(s)...") print(f"Settings: threshold={args.threshold}, max_duration={args.max_duration}ms, " f"freq_range={args.freq_low}-{args.freq_high}Hz") print() total_shortened = 0 total_time_removed = 0.0 for wav_file in tqdm(wav_files, desc="Processing files"): # Load audio samples, sr = sf.read(wav_file) # Handle stereo by processing each channel if samples.ndim == 2: # Process each channel separately processed_channels = [] file_shortened = 0 file_removed = 0 for ch in range(samples.shape[1]): processed, shortened, removed = process_audio( samples[:, ch], sr, args.freq_low, args.freq_high, args.threshold, max_duration, crossfade_duration, MIN_GAP_DURATION, ) processed_channels.append(processed) file_shortened = max(file_shortened, shortened) file_removed = max(file_removed, removed) # Find minimum length and trim all channels to match min_len = min(len(ch) for ch in processed_channels) processed = np.column_stack([ch[:min_len] for ch in processed_channels]) else: # Mono processed, file_shortened, file_removed = process_audio( samples, sr, args.freq_low, args.freq_high, args.threshold, max_duration, crossfade_duration, MIN_GAP_DURATION, ) # Save processed audio output_path = output_dir / wav_file.name sf.write(output_path, processed, sr) if file_shortened > 0: time_removed = file_removed / sr total_shortened += file_shortened total_time_removed += time_removed tqdm.write(f" {wav_file.name}: shortened {file_shortened} sibilant(s), " f"removed {time_removed*1000:.1f}ms") print() print(f"Done! Processed {len(wav_files)} file(s)") print(f"Total: {total_shortened} sibilant(s) shortened, " f"{total_time_removed*1000:.1f}ms removed") print(f"Output saved to: {output_dir}/") return 0 if __name__ == "__main__": exit(main())