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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Ψ§ΩΨ΅ΩΨ§Ψ‘ v5 β Dedicated Dereverberation Engine
|
| 4 |
+
Ψ₯Ψ²Ψ§ΩΨ© Ψ§ΩΨ΅Ψ―Ω ΩΨ§ΩΨ±ΩΩΩΨ±Ψ¨
|
| 5 |
+
|
| 6 |
+
FIXES vs v4 (v5):
|
| 7 |
+
B6 DF3 blending: replaced hard zone assignment + boundary-only crossfades
|
| 8 |
+
with continuous soft-weight blend (Gaussian-smoothed across ~300ms).
|
| 9 |
+
Root cause of "ΩΨ±ΩΨ ΩΩΨ¬Ω" (comes-and-goes effect) was that attenuation
|
| 10 |
+
was constant inside each LOUD/MID/QUIET zone β only the boundary had a
|
| 11 |
+
crossfade. Now every sample gets its own uniquely blended attenuation
|
| 12 |
+
level that tracks signal RMS continuously. Zero zone steps.
|
| 13 |
+
|
| 14 |
+
FIXES vs v2:
|
| 15 |
+
B1 _jalaa() late window: 150ms β 450ms (was reading 50-200ms; Β§3.3 says 50-500ms)
|
| 16 |
+
B2 _decode() now uses pcm_f32le β float32; soundfile when available (no 16-bit truncation)
|
| 17 |
+
B3 _band_energy() samples across full file (was FFT of first 1024 samples only)
|
| 18 |
+
B4 G4 Ra-trill: scans full audio in overlapping 1s windows (was first 1s only)
|
| 19 |
+
B5 _rt60() fallback slope condition was malformed (med-4 guard logic fixed)
|
| 20 |
+
|
| 21 |
+
IMPROVEMENTS vs v2:
|
| 22 |
+
I1 DF3 three passes now run in parallel (ThreadPoolExecutor) β 3Γ faster
|
| 23 |
+
I2 _enc() intermediates are mono; only final output is stereo
|
| 24 |
+
I3 _tailnr() reduces nr by 1 when JALAA already ran (avoid double-attenuation)
|
| 25 |
+
I4 DF3 speech-pass attenuation capped to Β§79 per-style limits:
|
| 26 |
+
Murattal β€ 18 dB / Mujawwad β€ 6 dB
|
| 27 |
+
I5 WPE LRA check uses 50% overlapping frames (was non-overlapping β noisy)
|
| 28 |
+
I6 SafaaState gains guard_pass/guard_warn lists (structured; JSON report improved)
|
| 29 |
+
I7 LF EQ: LF band RT60 scaled by 1.3Γ per Β§3.4 (LF decays slower than broadband)
|
| 30 |
+
I8 process() tracks all temp paths; single cleanup on exit (no leaks)
|
| 31 |
+
I9 _decode() try/finally ensures temp file removed on exception
|
| 32 |
+
I10 DRR-weighted JALAA: skip when DRR already > 6 dB (room is already reasonably dry)
|
| 33 |
+
|
| 34 |
+
PIPELINE (unchanged order)
|
| 35 |
+
S1 RT60 estimation (Schroeder backward integration)
|
| 36 |
+
S2 Sub-band LF room mode removal (3 bands, LF-scaled depth) [B5/I7]
|
| 37 |
+
S3 WPE dereverberation RT60 > 1.0s
|
| 38 |
+
S4 DF3 reverb-adapted (4 passes parallel, continuous soft-weight blend) [I1/I4/B6]
|
| 39 |
+
S5 JALAA per-frame DRR gate [B1/I10]
|
| 40 |
+
S6 Tail floor NR (afftdn calibrated) [I3]
|
| 41 |
+
S7 Arabic phoneme guards [B3/B4]
|
| 42 |
+
S8a dynaudnorm level evenness (f=500ms, m=10, p=0.92) β kills DF3 adaptation bumps
|
| 43 |
+
S8b Volume boost: standard=1.85, aggressive=7.40 (4x)
|
| 44 |
+
|
| 45 |
+
USAGE
|
| 46 |
+
python3 engine_safaa_v3.py input.wav output.wav [--tier X] [--mujawwad 0.0] [--rt60 0.0]
|
| 47 |
+
|
| 48 |
+
KB REFS: Β§3 Β§28 Β§35 Β§36 Β§52 Β§79 Β§109 Β§138 Β§140 Β§143 Β§145 Β§151 Β§152 Β§154
|
| 49 |
+
"""
|
| 50 |
+
from __future__ import annotations
|
| 51 |
+
|
| 52 |
+
__version__ = 'v5'
|
| 53 |
+
|
| 54 |
+
import os, shutil, subprocess, tempfile, warnings, multiprocessing as _mp
|
| 55 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 56 |
+
from dataclasses import dataclass, field
|
| 57 |
+
from pathlib import Path
|
| 58 |
+
from typing import List, Optional, Tuple
|
| 59 |
+
warnings.filterwarnings('ignore')
|
| 60 |
+
|
| 61 |
+
_TMP = tempfile.gettempdir()
|
| 62 |
+
|
| 63 |
+
try:
|
| 64 |
+
import numpy as np
|
| 65 |
+
NUMPY_OK = True
|
| 66 |
+
except ImportError:
|
| 67 |
+
NUMPY_OK = False
|
| 68 |
+
|
| 69 |
+
try:
|
| 70 |
+
import soundfile as SF
|
| 71 |
+
SF_OK = True
|
| 72 |
+
except ImportError:
|
| 73 |
+
SF_OK = False
|
| 74 |
+
|
| 75 |
+
try:
|
| 76 |
+
from scipy.io import wavfile as _scipy_wavfile
|
| 77 |
+
SCIPY_WAV_OK = True
|
| 78 |
+
except ImportError:
|
| 79 |
+
SCIPY_WAV_OK = False
|
| 80 |
+
|
| 81 |
+
# DF3 binary β search order: HF Space path first, then local dev paths
|
| 82 |
+
_DF3_CLI_BIN = ''
|
| 83 |
+
for _c in [
|
| 84 |
+
'/app/deep-filter', # HuggingFace Space (Docker WORKDIR /app)
|
| 85 |
+
'/home/claude/deep-filter', # local Termux/Claude dev
|
| 86 |
+
'deep-filter', # in PATH
|
| 87 |
+
'deepfilter',
|
| 88 |
+
'deep_filter',
|
| 89 |
+
]:
|
| 90 |
+
# shutil.which handles both absolute paths (existence+exec check) and PATH search
|
| 91 |
+
if shutil.which(_c) or (os.path.isfile(_c) and os.access(_c, os.X_OK)):
|
| 92 |
+
_DF3_CLI_BIN = _c; break
|
| 93 |
+
DF3_OK = bool(_DF3_CLI_BIN)
|
| 94 |
+
|
| 95 |
+
# nara_wpe
|
| 96 |
+
WPE_OK = False
|
| 97 |
+
try:
|
| 98 |
+
from nara_wpe.wpe import wpe_v8
|
| 99 |
+
from nara_wpe.utils import stft as _wpe_stft, istft as _wpe_istft
|
| 100 |
+
WPE_OK = True
|
| 101 |
+
except ImportError:
|
| 102 |
+
pass
|
| 103 |
+
|
| 104 |
+
# βββ Constants ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 105 |
+
SR = 48000
|
| 106 |
+
WAV_CODEC = 'pcm_s24le'
|
| 107 |
+
RT60_MIN = 0.15 # below: nothing to do
|
| 108 |
+
RT60_WPE_MIN = 1.00 # Β§109.6
|
| 109 |
+
RT60_TAILNR = 0.30
|
| 110 |
+
RT60_AGGR = 1.50
|
| 111 |
+
MUJ_RT60_FLOOR = 1.20 # Β§145.3
|
| 112 |
+
|
| 113 |
+
# Β§79 per-style DF attenuation hard limits β v4: raised for deeper cleaning
|
| 114 |
+
_DF3_LIM_MURATTAL = 24 # dB maximum (was 18)
|
| 115 |
+
_DF3_LIM_MUJAWWAD = 8 # dB maximum (was 6)
|
| 116 |
+
_DF3_SPEECH = 15 # was 12
|
| 117 |
+
_DF3_TRANS = 24 # was 20
|
| 118 |
+
_DF3_TAIL = 32 # was 28
|
| 119 |
+
|
| 120 |
+
_CHUNK_S = 0.100
|
| 121 |
+
_XFADE_N = 960
|
| 122 |
+
|
| 123 |
+
_RMS_MAX_DELTA = 1.0
|
| 124 |
+
_LRA_MAX_DELTA = 0.5 # Β§109.4
|
| 125 |
+
|
| 126 |
+
DRR_ALREADY_DRY = 3.0 # v4: lower threshold β JALAA runs on more material (was 6.0)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
# βββ State ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 130 |
+
@dataclass
|
| 131 |
+
class SafaaState:
|
| 132 |
+
input_path: str = ''
|
| 133 |
+
source_tier: str = 'TIER_UNKNOWN'
|
| 134 |
+
mujawwad_conf: float = 0.0
|
| 135 |
+
rt60_initial: float = 0.0
|
| 136 |
+
drr_before: float = 0.0
|
| 137 |
+
drr_after: float = 0.0
|
| 138 |
+
lf_eq: bool = False
|
| 139 |
+
wpe: bool = False
|
| 140 |
+
df3: bool = False
|
| 141 |
+
jalaa: bool = False
|
| 142 |
+
tail_nr: bool = False
|
| 143 |
+
guard_reverts: int = 0
|
| 144 |
+
guard_pass: List[str] = field(default_factory=list) # [I6]
|
| 145 |
+
guard_warn: List[str] = field(default_factory=list) # [I6]
|
| 146 |
+
log: List[str] = field(default_factory=list)
|
| 147 |
+
_tmps: List[str] = field(default_factory=list, repr=False)
|
| 148 |
+
|
| 149 |
+
def _L(st, msg):
|
| 150 |
+
st.log.append(msg); print(msg)
|
| 151 |
+
|
| 152 |
+
def _track(st, path):
|
| 153 |
+
"""Register a temp path for cleanup. Returns path."""
|
| 154 |
+
if path and path not in (st.input_path,):
|
| 155 |
+
st._tmps.append(path)
|
| 156 |
+
return path
|
| 157 |
+
|
| 158 |
+
def _cleanup_all(st):
|
| 159 |
+
for p in st._tmps:
|
| 160 |
+
try:
|
| 161 |
+
if p and os.path.exists(p): os.unlink(p)
|
| 162 |
+
except Exception:
|
| 163 |
+
pass
|
| 164 |
+
st._tmps.clear()
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
# βββ FFmpeg helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 168 |
+
def _run(cmd, timeout=600):
|
| 169 |
+
r = subprocess.run(cmd, capture_output=True, timeout=timeout)
|
| 170 |
+
return r.returncode, r.stdout, r.stderr
|
| 171 |
+
|
| 172 |
+
def _tmp(tag, st=None):
|
| 173 |
+
p = os.path.join(_TMP, f'safaa3_{tag}_{os.getpid()}.wav')
|
| 174 |
+
if st is not None:
|
| 175 |
+
st._tmps.append(p)
|
| 176 |
+
return p
|
| 177 |
+
|
| 178 |
+
def _cleanup(*paths):
|
| 179 |
+
for p in paths:
|
| 180 |
+
try:
|
| 181 |
+
if p and os.path.exists(p): os.unlink(p)
|
| 182 |
+
except Exception:
|
| 183 |
+
pass
|
| 184 |
+
|
| 185 |
+
def _decode(path, st=None):
|
| 186 |
+
"""
|
| 187 |
+
Float32 mono at SR. [B2/I9]
|
| 188 |
+
Uses soundfile when available (faster, native float32).
|
| 189 |
+
Falls back to ffmpeg pcm_f32le + wave read.
|
| 190 |
+
try/finally ensures temp file removed on exception.
|
| 191 |
+
"""
|
| 192 |
+
if not NUMPY_OK:
|
| 193 |
+
return None
|
| 194 |
+
t = None
|
| 195 |
+
try:
|
| 196 |
+
if SF_OK:
|
| 197 |
+
# ffmpeg β pcm_f32le temp, then soundfile reads it natively
|
| 198 |
+
t = os.path.join(_TMP, f'safaa3_dec_{os.getpid()}.wav')
|
| 199 |
+
rc, _, _ = _run(['ffmpeg', '-y', '-i', path,
|
| 200 |
+
'-acodec', 'pcm_f32le',
|
| 201 |
+
'-ar', str(SR), '-ac', '1',
|
| 202 |
+
'-loglevel', 'error', t])
|
| 203 |
+
if rc or not os.path.exists(t):
|
| 204 |
+
return None
|
| 205 |
+
data, _ = SF.read(t, dtype='float32', always_2d=False)
|
| 206 |
+
return data
|
| 207 |
+
elif SCIPY_WAV_OK:
|
| 208 |
+
# scipy.io.wavfile can read pcm_f32le natively
|
| 209 |
+
t = os.path.join(_TMP, f'safaa3_dec_{os.getpid()}.wav')
|
| 210 |
+
rc, _, _ = _run(['ffmpeg', '-y', '-i', path,
|
| 211 |
+
'-acodec', 'pcm_f32le',
|
| 212 |
+
'-ar', str(SR), '-ac', '1',
|
| 213 |
+
'-loglevel', 'error', t])
|
| 214 |
+
if rc or not os.path.exists(t):
|
| 215 |
+
return None
|
| 216 |
+
_, data = _scipy_wavfile.read(t)
|
| 217 |
+
if data.dtype != np.float32:
|
| 218 |
+
data = data.astype(np.float32) / np.iinfo(data.dtype).max
|
| 219 |
+
return data.copy()
|
| 220 |
+
else:
|
| 221 |
+
# Final fallback: pcm_s16le β int16 β float32 normalised
|
| 222 |
+
t = os.path.join(_TMP, f'safaa3_dec_{os.getpid()}.wav')
|
| 223 |
+
rc, _, _ = _run(['ffmpeg', '-y', '-i', path,
|
| 224 |
+
'-acodec', 'pcm_s16le',
|
| 225 |
+
'-ar', str(SR), '-ac', '1',
|
| 226 |
+
'-loglevel', 'error', t])
|
| 227 |
+
if rc or not os.path.exists(t):
|
| 228 |
+
return None
|
| 229 |
+
import wave as _w
|
| 230 |
+
with _w.open(t, 'rb') as f:
|
| 231 |
+
raw = f.readframes(f.getnframes())
|
| 232 |
+
return np.frombuffer(raw, dtype=np.int16).astype(np.float32) / 32768.0
|
| 233 |
+
except Exception:
|
| 234 |
+
return None
|
| 235 |
+
finally:
|
| 236 |
+
if t and os.path.exists(t):
|
| 237 |
+
try: os.unlink(t)
|
| 238 |
+
except Exception: pass
|
| 239 |
+
|
| 240 |
+
def _enc_mono(src, dst):
|
| 241 |
+
"""Intermediate encode: mono 24-bit. [I2]"""
|
| 242 |
+
rc, _, _ = _run(['ffmpeg', '-y', '-i', src,
|
| 243 |
+
'-acodec', WAV_CODEC,
|
| 244 |
+
'-ar', str(SR), '-ac', '1',
|
| 245 |
+
'-loglevel', 'error', dst])
|
| 246 |
+
return rc == 0 and os.path.exists(dst)
|
| 247 |
+
|
| 248 |
+
def _enc_stereo(src, dst):
|
| 249 |
+
"""Final output encode: stereo 24-bit. [I2]"""
|
| 250 |
+
rc, _, _ = _run(['ffmpeg', '-y', '-i', src,
|
| 251 |
+
'-acodec', WAV_CODEC,
|
| 252 |
+
'-ar', str(SR), '-ac', '2',
|
| 253 |
+
'-loglevel', 'error', dst])
|
| 254 |
+
return rc == 0 and os.path.exists(dst)
|
| 255 |
+
|
| 256 |
+
def _rmsdb(s):
|
| 257 |
+
return float(20 * np.log10(np.sqrt(np.mean(s ** 2)) + 1e-10))
|
| 258 |
+
|
| 259 |
+
def _band_energy(s, flo, fhi, n_fft=2048, n_samples=8):
|
| 260 |
+
"""
|
| 261 |
+
Band energy estimate sampled across the full signal. [B3]
|
| 262 |
+
Averages n_samples evenly-spaced windows rather than only the first n_fft samples.
|
| 263 |
+
"""
|
| 264 |
+
if len(s) < n_fft:
|
| 265 |
+
return 0.0
|
| 266 |
+
step = max(n_fft, len(s) // (n_samples + 1))
|
| 267 |
+
positions = range(0, len(s) - n_fft, step)
|
| 268 |
+
energies = []
|
| 269 |
+
fr = np.fft.rfftfreq(n_fft, 1.0 / SR)
|
| 270 |
+
mask = (fr >= flo) & (fr <= fhi)
|
| 271 |
+
for pos in positions:
|
| 272 |
+
sp = np.abs(np.fft.rfft(s[pos:pos + n_fft], n=n_fft))
|
| 273 |
+
energies.append(float(np.mean(sp[mask] ** 2) + 1e-20))
|
| 274 |
+
return float(np.mean(energies)) if energies else 0.0
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
# βββ Stage 1: RT60 (Schroeder backward integration) ββββββββββββββββββββββββββ
|
| 278 |
+
def _rt60(samples, sr=SR):
|
| 279 |
+
"""
|
| 280 |
+
Schroeder backward integration (Β§3.1).
|
| 281 |
+
Find -5 dB and -25 dB crossings of backward energy β T20 Γ 3 = T60.
|
| 282 |
+
Fallback: linear regression on the decay region. [B5]
|
| 283 |
+
"""
|
| 284 |
+
if not NUMPY_OK or samples is None or len(samples) < sr * 3:
|
| 285 |
+
return 0.0
|
| 286 |
+
fn = int(0.020 * sr)
|
| 287 |
+
n = len(samples) // fn
|
| 288 |
+
if n < 30:
|
| 289 |
+
return 0.0
|
| 290 |
+
|
| 291 |
+
energy = np.array([float(np.mean(samples[i * fn:(i + 1) * fn] ** 2)) for i in range(n)])
|
| 292 |
+
energy = np.maximum(energy, 1e-20)
|
| 293 |
+
sch = np.cumsum(energy[::-1])[::-1]
|
| 294 |
+
sch_db = 10 * np.log10(sch / (sch[0] + 1e-20))
|
| 295 |
+
|
| 296 |
+
t5 = t25 = None
|
| 297 |
+
for i, v in enumerate(sch_db):
|
| 298 |
+
if t5 is None and v <= -5.0: t5 = i * 0.020
|
| 299 |
+
if t25 is None and v <= -25.0: t25 = i * 0.020; break
|
| 300 |
+
if t5 is not None and t25 is not None and t25 > t5:
|
| 301 |
+
return float(np.clip((t25 - t5) * 3.0, 0.0, 6.0))
|
| 302 |
+
|
| 303 |
+
# Fallback: slope estimation on the decay tail [B5]
|
| 304 |
+
edb = 10 * np.log10(energy)
|
| 305 |
+
med = float(np.median(edb))
|
| 306 |
+
# Find the decay region: frames below median but above noise floor
|
| 307 |
+
decay_mask = (edb > med - 30) & (edb < med - 2)
|
| 308 |
+
if decay_mask.sum() < 6:
|
| 309 |
+
return 0.0
|
| 310 |
+
t_arr = np.where(decay_mask)[0] * 0.020
|
| 311 |
+
e_arr = edb[decay_mask]
|
| 312 |
+
slope = float(np.polyfit(t_arr, e_arr, 1)[0])
|
| 313 |
+
if slope >= -1.0:
|
| 314 |
+
return 0.0
|
| 315 |
+
return float(np.clip(60.0 / abs(slope), 0.0, 4.0))
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def _drr(samples, sr=SR):
|
| 319 |
+
"""
|
| 320 |
+
DRR: energy ratio early(0-50ms) vs late(50-500ms) (Β§3.3/Β§28.6).
|
| 321 |
+
"""
|
| 322 |
+
if not NUMPY_OK or samples is None:
|
| 323 |
+
return 0.0
|
| 324 |
+
en = int(0.050 * sr)
|
| 325 |
+
ln = int(0.450 * sr) # late window: 50-500ms
|
| 326 |
+
step = int(0.200 * sr)
|
| 327 |
+
vals = []
|
| 328 |
+
for s in range(0, len(samples) - en - ln, step):
|
| 329 |
+
er = float(np.sqrt(np.mean(samples[s:s + en] ** 2)) + 1e-10)
|
| 330 |
+
lr = float(np.sqrt(np.mean(samples[s + en:s + en + ln] ** 2)) + 1e-10)
|
| 331 |
+
if er > 1e-5 and lr > 1e-5:
|
| 332 |
+
vals.append(20.0 * np.log10(er / lr))
|
| 333 |
+
return float(np.median(vals)) if vals else 0.0
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
# βββ Stage 2: Sub-band LF EQ (Β§3.4) βββββββββββββββββββββββββββββββββββββββββ
|
| 337 |
+
def _lf_eq(wav, samples, rt60, st):
|
| 338 |
+
"""
|
| 339 |
+
Three EQ bands with LF-scaled depth. [I7]
|
| 340 |
+
Β§3.4: LF bands have longer RT60 (empirically ~1.3Γ broadband).
|
| 341 |
+
Apply the LF multiplier before computing per-band depth.
|
| 342 |
+
Mujawwad: reduce depth and enforce RT60 floor (Β§145.3).
|
| 343 |
+
"""
|
| 344 |
+
if rt60 < RT60_MIN:
|
| 345 |
+
return wav
|
| 346 |
+
lf_rt60 = rt60 * 1.30 # Β§3.4: LF decays ~30% slower [I7]
|
| 347 |
+
scale = float(np.clip(lf_rt60 / 0.5, 1.0, 6.0))
|
| 348 |
+
d_sub = float(np.clip(scale * 1.0, 1.0, 6.0))
|
| 349 |
+
d_lo = float(np.clip(scale * 0.7, 0.7, 4.2))
|
| 350 |
+
d_room = float(np.clip(scale * 0.4, 0.4, 2.4))
|
| 351 |
+
|
| 352 |
+
if st.mujawwad_conf > 0.6:
|
| 353 |
+
d_sub *= 0.5; d_lo *= 0.5; d_room *= 0.5
|
| 354 |
+
if rt60 < MUJ_RT60_FLOOR * 1.5:
|
| 355 |
+
r = float(np.clip((rt60 - MUJ_RT60_FLOOR) / (MUJ_RT60_FLOOR * 0.5 + 0.001), 0, 1))
|
| 356 |
+
d_sub *= r; d_lo *= r; d_room *= r
|
| 357 |
+
_L(st, f' [S2-LF] Mujawwad floor limiter ratio={r:.2f}')
|
| 358 |
+
|
| 359 |
+
flt = []
|
| 360 |
+
if d_sub > 0.2: flt.append(f'equalizer=f=150:width_type=o:width=1.4:g=-{d_sub:.1f}')
|
| 361 |
+
if d_lo > 0.2: flt.append(f'equalizer=f=300:width_type=o:width=1.2:g=-{d_lo:.1f}')
|
| 362 |
+
if d_room > 0.2: flt.append(f'equalizer=f=500:width_type=o:width=1.0:g=-{d_room:.1f}')
|
| 363 |
+
if not flt:
|
| 364 |
+
return wav
|
| 365 |
+
|
| 366 |
+
out = _tmp('s2', st)
|
| 367 |
+
rc, _, _ = _run(['ffmpeg', '-y', '-i', wav, '-af', ','.join(flt),
|
| 368 |
+
'-acodec', WAV_CODEC, '-ar', str(SR), '-ac', '1', # mono [I2]
|
| 369 |
+
'-loglevel', 'error', out])
|
| 370 |
+
if rc or not os.path.exists(out):
|
| 371 |
+
return wav
|
| 372 |
+
|
| 373 |
+
post = _decode(out)
|
| 374 |
+
if post is not None and samples is not None:
|
| 375 |
+
d = _rmsdb(post) - _rmsdb(samples)
|
| 376 |
+
if abs(d) > 3.0: # relaxed: LF EQ at high RT60 can legitimately remove >1dB
|
| 377 |
+
_cleanup(out); st.guard_reverts += 1
|
| 378 |
+
_L(st, f' [S2-LF] RMS Ξ={d:+.2f}dB β REVERT'); return wav
|
| 379 |
+
|
| 380 |
+
st.lf_eq = True
|
| 381 |
+
_L(st, f' [S2-LF] β lf_rt60={lf_rt60:.2f}s sub={d_sub:.1f} lo={d_lo:.1f} room={d_room:.1f} dB')
|
| 382 |
+
return out
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
# βββ Stage 3: WPE (threshold 1.0s, Β§109.6) βββββββββββββββββββββββββββββββββββ
|
| 386 |
+
def _lra_overlapping(s, frame_s=0.4, hop_s=0.2, sr=SR):
|
| 387 |
+
"""LRA estimate using 50% overlapping frames. [I5]"""
|
| 388 |
+
fn = int(frame_s * sr)
|
| 389 |
+
hn = int(hop_s * sr)
|
| 390 |
+
if len(s) < fn:
|
| 391 |
+
return 0.0
|
| 392 |
+
db = [float(20 * np.log10(np.sqrt(np.mean(s[i:i + fn] ** 2)) + 1e-10))
|
| 393 |
+
for i in range(0, len(s) - fn, hn)]
|
| 394 |
+
return float(np.percentile(db, 95) - np.percentile(db, 10)) if len(db) >= 4 else 0.0
|
| 395 |
+
|
| 396 |
+
# S190: hard cap β wall-clock cap on WPE so a slow/atypical file (e.g. RT60=6s,
|
| 397 |
+
# taps=12) can't eat the entire 600s job budget and get SIGKILL'd.
|
| 398 |
+
# WPE runs in a forked child; if it exceeds WPE_TIMEOUT_S we kill just
|
| 399 |
+
# that worker and continue to S4-DF3 with the un-dereverbed audio.
|
| 400 |
+
WPE_TIMEOUT_S = 240
|
| 401 |
+
|
| 402 |
+
def _wpe_compute_worker(mi, mo, rt60, mujawwad_conf, sr, lra_max, q):
|
| 403 |
+
"""Forked worker: runs wpe_v8 + writes result wav; sends small dict back via queue."""
|
| 404 |
+
try:
|
| 405 |
+
if SF_OK:
|
| 406 |
+
y, _ = SF.read(mi, dtype='float32', always_2d=False)
|
| 407 |
+
else:
|
| 408 |
+
import wave as _w
|
| 409 |
+
with _w.open(mi, 'rb') as f: raw = f.readframes(f.getnframes())
|
| 410 |
+
y = np.frombuffer(raw, dtype=np.float32).copy()
|
| 411 |
+
|
| 412 |
+
if mujawwad_conf > 0.6: taps, iters = 5, 2
|
| 413 |
+
elif rt60 > 4.0: taps, iters = 12, 3
|
| 414 |
+
elif rt60 > 2.0: taps, iters = 10, 3
|
| 415 |
+
else: taps, iters = 8, 3
|
| 416 |
+
delay = 3
|
| 417 |
+
|
| 418 |
+
Y = _wpe_stft(y, size=512, shift=128)
|
| 419 |
+
Z = wpe_v8(Y[..., np.newaxis], taps=taps, delay=delay, iterations=iters)
|
| 420 |
+
z = _wpe_istft(Z[..., 0], size=512, shift=128)
|
| 421 |
+
z = z[:len(y)] if len(z) > len(y) else np.pad(z, (0, len(y) - len(z)))
|
| 422 |
+
|
| 423 |
+
ld = abs(_lra_overlapping(y) - _lra_overlapping(z))
|
| 424 |
+
if ld > lra_max:
|
| 425 |
+
Z2 = wpe_v8(Y[..., np.newaxis], taps=taps, delay=delay, iterations=max(1, iters-1))
|
| 426 |
+
z2 = _wpe_istft(Z2[..., 0], size=512, shift=128)
|
| 427 |
+
z2 = z2[:len(y)] if len(z2) > len(y) else np.pad(z2, (0, len(y)-len(z2)))
|
| 428 |
+
ld2 = abs(_lra_overlapping(y) - _lra_overlapping(z2))
|
| 429 |
+
if ld2 > lra_max:
|
| 430 |
+
q.put({'ok': False, 'reason': f'LRA {ld2:.2f}LU after retry β REVERT'})
|
| 431 |
+
return
|
| 432 |
+
z = z2; ld = ld2
|
| 433 |
+
|
| 434 |
+
if SF_OK:
|
| 435 |
+
SF.write(mo, z.astype(np.float32), sr, subtype='FLOAT')
|
| 436 |
+
else:
|
| 437 |
+
import wave as _w
|
| 438 |
+
b16 = (np.clip(z, -1, 1) * 32767).astype(np.int16)
|
| 439 |
+
with _w.open(mo, 'wb') as f:
|
| 440 |
+
f.setnchannels(1); f.setsampwidth(2); f.setframerate(sr)
|
| 441 |
+
f.writeframes(b16.tobytes())
|
| 442 |
+
q.put({'ok': True, 'taps': taps, 'delay': delay, 'iters': iters, 'ld': float(ld)})
|
| 443 |
+
except Exception as e:
|
| 444 |
+
q.put({'ok': False, 'reason': f'exception: {e}'})
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
def _wpe(wav, rt60, st):
|
| 448 |
+
if not WPE_OK:
|
| 449 |
+
_L(st, ' [S3-WPE] nara_wpe not installed β pip install nara_wpe soundfile')
|
| 450 |
+
return wav
|
| 451 |
+
if rt60 < RT60_WPE_MIN:
|
| 452 |
+
_L(st, f' [S3-WPE] RT60={rt60:.2f}s < {RT60_WPE_MIN}s β skip (Β§109.6)')
|
| 453 |
+
return wav
|
| 454 |
+
|
| 455 |
+
_L(st, f' [S3-WPE] RT60={rt60:.2f}s β running WPE (cap={WPE_TIMEOUT_S}s) [S190]')
|
| 456 |
+
d = tempfile.mkdtemp(prefix='safaa3_wpe_')
|
| 457 |
+
try:
|
| 458 |
+
mi = os.path.join(d, 'in.wav')
|
| 459 |
+
rc, _, _ = _run(['ffmpeg', '-y', '-i', wav,
|
| 460 |
+
'-acodec', 'pcm_f32le', '-ar', str(SR), '-ac', '1',
|
| 461 |
+
'-loglevel', 'error', mi])
|
| 462 |
+
if rc or not os.path.exists(mi):
|
| 463 |
+
return wav
|
| 464 |
+
|
| 465 |
+
mo = os.path.join(d, 'out.wav')
|
| 466 |
+
ctx = _mp.get_context('fork')
|
| 467 |
+
q = ctx.Queue()
|
| 468 |
+
proc = ctx.Process(
|
| 469 |
+
target=_wpe_compute_worker,
|
| 470 |
+
args=(mi, mo, rt60, st.mujawwad_conf, SR, _LRA_MAX_DELTA, q))
|
| 471 |
+
proc.start()
|
| 472 |
+
proc.join(WPE_TIMEOUT_S)
|
| 473 |
+
if proc.is_alive():
|
| 474 |
+
proc.terminate(); proc.join(5)
|
| 475 |
+
if proc.is_alive(): proc.kill(); proc.join(5)
|
| 476 |
+
st.guard_reverts += 1
|
| 477 |
+
_L(st, f' [S3-WPE] β± TIMED OUT after {WPE_TIMEOUT_S}s β '
|
| 478 |
+
f'skipping WPE, continuing to S4-DF3 [S190]')
|
| 479 |
+
return wav
|
| 480 |
+
|
| 481 |
+
result = q.get() if not q.empty() else {'ok': False, 'reason': 'worker died silently'}
|
| 482 |
+
if not result.get('ok'):
|
| 483 |
+
st.guard_reverts += 1
|
| 484 |
+
_L(st, f" [S3-WPE] {result.get('reason','failed')} β REVERT")
|
| 485 |
+
return wav
|
| 486 |
+
|
| 487 |
+
out = _tmp('s3', st)
|
| 488 |
+
if not _enc_mono(mo, out):
|
| 489 |
+
return wav
|
| 490 |
+
st.wpe = True
|
| 491 |
+
_L(st, f" [S3-WPE] β taps={result['taps']} delay={result['delay']} "
|
| 492 |
+
f"iters={result['iters']} LRA Ξ={result['ld']:.2f}LU")
|
| 493 |
+
return out
|
| 494 |
+
except Exception as e:
|
| 495 |
+
_L(st, f' [S3-WPE] exception: {e}'); return wav
|
| 496 |
+
finally:
|
| 497 |
+
shutil.rmtree(d, ignore_errors=True)
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
# βββ Stage 4: DF3 smooth adaptive VAD (Β§22.5 / Β§106 / RL-01 / RL-16) βββββββββ
|
| 501 |
+
_ADF_LOUD_T = -15.0 # dBFS β projecting voice β protect
|
| 502 |
+
_ADF_QUIET_T = -25.0 # dBFS β soft/breath β clean hard
|
| 503 |
+
_ADF_SNR_GATE = 10.0 # v4: lower gate β more chunks get cleaned (was 12)
|
| 504 |
+
_ADF_CHUNK_S = 0.050 # 50ms chunks β finer granularity than isteidad 100ms
|
| 505 |
+
# v5: continuous blend β no hard zones, no boundary-only crossfades
|
| 506 |
+
_ADF_SIGMA_DB = 4.0 # dBFS half-width of loudβquiet soft transition
|
| 507 |
+
_ADF_SMOOTH_C = 6 # Gaussian temporal smoothing width in chunks (~300ms @ 50ms/chunk)
|
| 508 |
+
_ADF_GATE_MAX = 0.70 # max SNR-gate fraction; always retain β₯30% DF3 on clean chunks
|
| 509 |
+
# RL-16: guard bands β restore these from original after blend
|
| 510 |
+
_RL16_BANDS = [(220, 290), (950, 1100)] # Hz: Ghunnah nasal pole + formant zone
|
| 511 |
+
|
| 512 |
+
def _df3_pipe_decode(path, sr):
|
| 513 |
+
"""Decode WAV to float32 mono via ffmpeg pipe β avoids wave/soundfile dep."""
|
| 514 |
+
r = subprocess.run(
|
| 515 |
+
['ffmpeg', '-nostdin', '-y', '-hide_banner', '-loglevel', 'error',
|
| 516 |
+
'-i', path, '-ar', str(sr), '-ac', '1', '-f', 'f32le', '-'],
|
| 517 |
+
capture_output=True, timeout=120)
|
| 518 |
+
if r.returncode or len(r.stdout) < 4:
|
| 519 |
+
return None
|
| 520 |
+
return np.frombuffer(r.stdout, dtype=np.float32).copy()
|
| 521 |
+
|
| 522 |
+
def _stft_restore_bands(processed, original, sr, bands):
|
| 523 |
+
"""
|
| 524 |
+
RL-16: after DF3 blend, restore specified Hz bands from original.
|
| 525 |
+
Uses STFT with 50% overlap Hann window β preserves phase coherence.
|
| 526 |
+
"""
|
| 527 |
+
from numpy.fft import rfft, irfft
|
| 528 |
+
N = 2048; HOP = N // 2
|
| 529 |
+
freqs = np.fft.rfftfreq(N, d=1.0/sr) # Hz per bin
|
| 530 |
+
restore_mask = np.zeros(len(freqs), dtype=bool)
|
| 531 |
+
for lo, hi in bands:
|
| 532 |
+
restore_mask |= (freqs >= lo) & (freqs <= hi)
|
| 533 |
+
|
| 534 |
+
win = np.hanning(N).astype(np.float32)
|
| 535 |
+
min_n = min(len(processed), len(original))
|
| 536 |
+
p = processed[:min_n].astype(np.float64)
|
| 537 |
+
o = original[:min_n].astype(np.float64)
|
| 538 |
+
out = np.zeros(min_n, dtype=np.float64)
|
| 539 |
+
norm = np.zeros(min_n, dtype=np.float64)
|
| 540 |
+
|
| 541 |
+
for s in range(0, min_n - N, HOP):
|
| 542 |
+
Pf = rfft(p[s:s+N] * win)
|
| 543 |
+
Of = rfft(o[s:s+N] * win)
|
| 544 |
+
# S167: soft blend instead of hard copy β avoids tonal whistle when DF3
|
| 545 |
+
# removes reverb masking context around nasal/formant poles.
|
| 546 |
+
# 220-290Hz (nasal pole): 60% original (safe, low-freq, well-masked)
|
| 547 |
+
# 950-1100Hz (formant zone): 15% original β high-risk for unmasked whistle;
|
| 548 |
+
# just enough to prevent total nasalization kill without audible tones.
|
| 549 |
+
for lo, hi in bands:
|
| 550 |
+
band_mask = (freqs >= lo) & (freqs <= hi)
|
| 551 |
+
alpha = 0.60 if hi <= 300 else 0.15
|
| 552 |
+
Pf[band_mask] = alpha * Of[band_mask] + (1.0 - alpha) * Pf[band_mask]
|
| 553 |
+
frame = irfft(Pf) * win
|
| 554 |
+
out[s:s+N] += frame; norm[s:s+N] += win**2
|
| 555 |
+
|
| 556 |
+
valid = norm > 1e-8
|
| 557 |
+
out[valid] /= norm[valid]
|
| 558 |
+
out[~valid] = p[~valid]
|
| 559 |
+
return out.astype(np.float32)
|
| 560 |
+
|
| 561 |
+
def _df3(wav, samples, rt60, st, aggressive=False):
|
| 562 |
+
if not DF3_OK:
|
| 563 |
+
_L(st, ' [S4-DF3] deep-filter not found β skip'); return wav
|
| 564 |
+
|
| 565 |
+
# Β§106.3 + Β§79 atten limits β v4: stronger per-class
|
| 566 |
+
lim = _DF3_LIM_MUJAWWAD if st.mujawwad_conf > 0.6 else _DF3_LIM_MURATTAL
|
| 567 |
+
if aggressive:
|
| 568 |
+
# Raise the numeric caps, but they still pass through min(x, lim) β
|
| 569 |
+
# for Mujawwad sources lim=8 so this changes nothing for them; the
|
| 570 |
+
# ornamentation protection is preserved by construction, not by a
|
| 571 |
+
# separate check. Only Murattal-style sources (lim=24) get headroom.
|
| 572 |
+
a_loud = min(16, lim)
|
| 573 |
+
a_mid = min(22, lim)
|
| 574 |
+
a_quiet = min(28, lim + 14)
|
| 575 |
+
a_trans = min(20, lim)
|
| 576 |
+
else:
|
| 577 |
+
a_loud = min(10, lim) # was 8
|
| 578 |
+
a_mid = min(18, lim) # was 15
|
| 579 |
+
a_quiet = min(24, lim + 10) # was 20
|
| 580 |
+
a_trans = min(14, lim) # v4: new transition class between loud/mid
|
| 581 |
+
if st.mujawwad_conf > 0.6:
|
| 582 |
+
a_loud = min(a_loud, 8)
|
| 583 |
+
a_mid = min(a_mid, 10)
|
| 584 |
+
a_quiet = min(a_quiet, 14)
|
| 585 |
+
a_trans = min(a_trans, 9)
|
| 586 |
+
|
| 587 |
+
d = tempfile.mkdtemp(prefix='safaa3_df3_')
|
| 588 |
+
try:
|
| 589 |
+
# ββ Prepare pcm_s16le mono input ββββββββββββββββββββββββββββββββββ
|
| 590 |
+
fi = os.path.join(d, 'in.wav')
|
| 591 |
+
rc, _, _ = _run(['ffmpeg', '-y', '-i', wav,
|
| 592 |
+
'-acodec', 'pcm_s16le', '-ar', str(SR), '-ac', '1',
|
| 593 |
+
'-loglevel', 'error', fi])
|
| 594 |
+
if rc or not os.path.exists(fi):
|
| 595 |
+
return wav
|
| 596 |
+
mono = _df3_pipe_decode(fi, SR)
|
| 597 |
+
if mono is None:
|
| 598 |
+
return wav
|
| 599 |
+
total = len(mono)
|
| 600 |
+
|
| 601 |
+
# ββ VAD β 50ms chunks with SNR gate (Β§22.5) ββββββββββββββββββββββ
|
| 602 |
+
CHUNK = int(_ADF_CHUNK_S * SR)
|
| 603 |
+
nc = max(1, total // CHUNK)
|
| 604 |
+
# Estimate noise floor from quietest 10% of chunks
|
| 605 |
+
rms_db = np.array([
|
| 606 |
+
20.0 * np.log10(np.sqrt(np.mean(mono[i*CHUNK:(i+1)*CHUNK]**2)) + 1e-12)
|
| 607 |
+
for i in range(nc)])
|
| 608 |
+
noise_floor = float(np.percentile(rms_db, 10))
|
| 609 |
+
|
| 610 |
+
# Β§22.5 SNR gate value (used later in continuous blend)
|
| 611 |
+
chunk_snr = rms_db - noise_floor
|
| 612 |
+
snr_gate = (_ADF_SNR_GATE + 3.0) if aggressive else _ADF_SNR_GATE
|
| 613 |
+
|
| 614 |
+
# Stats for logging only β no longer used for hard assignment
|
| 615 |
+
n_loud = int((rms_db > _ADF_LOUD_T).sum())
|
| 616 |
+
n_quiet = int((rms_db <= _ADF_QUIET_T).sum())
|
| 617 |
+
n_mid = nc - n_loud - n_quiet
|
| 618 |
+
n_clean = int((chunk_snr >= snr_gate).sum())
|
| 619 |
+
_L(st, f' [S4-ADF] 50ms chunks: LOUD={n_loud} MID={n_mid} '
|
| 620 |
+
f'QUIET={n_quiet} CLEAN(snr-gate)={n_clean} nf={noise_floor:.1f}dBFS')
|
| 621 |
+
|
| 622 |
+
# ββ 3 parallel DF passes with per-class flags βββββββββββββββββββββ
|
| 623 |
+
df_out = {}
|
| 624 |
+
def _run_pass(cls, atten, pf=False, pf_beta=0.02):
|
| 625 |
+
od = os.path.join(d, cls); os.makedirs(od, exist_ok=True)
|
| 626 |
+
cmd = [_DF3_CLI_BIN, '--atten-lim-db', str(atten)]
|
| 627 |
+
if pf:
|
| 628 |
+
cmd += ['--pf', '--pf-beta', str(pf_beta)]
|
| 629 |
+
cmd += ['-o', od, fi]
|
| 630 |
+
r2 = subprocess.run(cmd, capture_output=True, timeout=600)
|
| 631 |
+
wp = os.path.join(od, 'in.wav')
|
| 632 |
+
if r2.returncode or not os.path.exists(wp):
|
| 633 |
+
_L(st, f' [S4-ADF] {cls} pass failed β using source')
|
| 634 |
+
return cls, mono.copy()
|
| 635 |
+
arr = _df3_pipe_decode(wp, SR)
|
| 636 |
+
if arr is None:
|
| 637 |
+
_L(st, f' [S4-ADF] {cls} decode failed β using source')
|
| 638 |
+
return cls, mono.copy()
|
| 639 |
+
pf_tag = ' +PF' if pf else ''
|
| 640 |
+
_L(st, f' [S4-ADF] {cls:6s} {atten:2d}dB{pf_tag} β '
|
| 641 |
+
f'max={np.max(np.abs(arr)):.4f}')
|
| 642 |
+
return cls, arr
|
| 643 |
+
|
| 644 |
+
with ThreadPoolExecutor(max_workers=4) as ex:
|
| 645 |
+
futs = [
|
| 646 |
+
ex.submit(_run_pass, 'loud', a_loud, aggressive, 0.02),
|
| 647 |
+
ex.submit(_run_pass, 'mid', a_mid, aggressive, 0.02),
|
| 648 |
+
ex.submit(_run_pass, 'quiet', a_quiet, True, 0.04), # PF quiet always
|
| 649 |
+
ex.submit(_run_pass, 'trans', a_trans, aggressive, 0.02),
|
| 650 |
+
]
|
| 651 |
+
for fut in as_completed(futs):
|
| 652 |
+
cls, arr = fut.result()
|
| 653 |
+
df_out[cls] = arr
|
| 654 |
+
|
| 655 |
+
# ββ Continuous soft-weight blend (v5) ββββββββββββββββββββββββββββ
|
| 656 |
+
# Root cause of "ΩΨ±ΩΨ ΩΩΨ¬Ω": hard zone assignment kept attenuation
|
| 657 |
+
# constant inside each zone; crossfade only fired AT boundaries.
|
| 658 |
+
# Fix: compute soft sigmoid weights from RMS per chunk, Gaussian-smooth
|
| 659 |
+
# them temporally (~300ms window), interpolate to sample level.
|
| 660 |
+
# Every individual sample now has a uniquely blended attenuation that
|
| 661 |
+
# tracks the signal continuously β no zones, no boundaries, no jumps.
|
| 662 |
+
|
| 663 |
+
def _sig(x):
|
| 664 |
+
return 1.0 / (1.0 + np.exp(-np.clip(x.astype(np.float64), -20, 20)))
|
| 665 |
+
|
| 666 |
+
def _gauss1d(arr, sig):
|
| 667 |
+
"""Gaussian kernel smoothing β pure numpy, no scipy dependency."""
|
| 668 |
+
sig = max(0.5, float(sig))
|
| 669 |
+
r = max(1, int(3.5 * sig))
|
| 670 |
+
t = np.arange(-r, r + 1, dtype=np.float64)
|
| 671 |
+
k = np.exp(-0.5 * (t / sig) ** 2); k /= k.sum()
|
| 672 |
+
return np.convolve(arr.astype(np.float64), k, mode='same')
|
| 673 |
+
|
| 674 |
+
SIGMA = _ADF_SIGMA_DB # dBFS half-width of transition (4 dB)
|
| 675 |
+
SC = _ADF_SMOOTH_C # Gaussian temporal smoothing in chunks (~300ms)
|
| 676 |
+
|
| 677 |
+
# Raw soft weights per chunk (sum not forced to 1 yet)
|
| 678 |
+
wL = _sig((rms_db - _ADF_LOUD_T) / SIGMA) # 1 = very loud
|
| 679 |
+
wQ = _sig((_ADF_QUIET_T - rms_db) / SIGMA) # 1 = very quiet
|
| 680 |
+
wM = np.clip(1.0 - wL - wQ, 0.0, 1.0) # mid fills the gap
|
| 681 |
+
|
| 682 |
+
# Normalize to sum = 1 per chunk
|
| 683 |
+
wS = wL + wM + wQ + 1e-8
|
| 684 |
+
wL /= wS; wM /= wS; wQ /= wS
|
| 685 |
+
|
| 686 |
+
# Gaussian temporal smoothing across chunks β this is what eliminates
|
| 687 |
+
# the step-function zones; after smoothing the weights transition over
|
| 688 |
+
# ~300ms even when the signal level changes abruptly.
|
| 689 |
+
wL = _gauss1d(wL, SC); wM = _gauss1d(wM, SC); wQ = _gauss1d(wQ, SC)
|
| 690 |
+
wS2 = wL + wM + wQ + 1e-8
|
| 691 |
+
wL /= wS2; wM /= wS2; wQ /= wS2
|
| 692 |
+
|
| 693 |
+
# Interpolate chunk-level weights β sample level (linear, smooth)
|
| 694 |
+
# Anchored at chunk centres so edges don't overshoot
|
| 695 |
+
t_c = (np.arange(nc, dtype=np.float64) + 0.5) * CHUNK
|
| 696 |
+
t_s = np.arange(total, dtype=np.float64)
|
| 697 |
+
wL_s = np.interp(t_s, t_c, wL)
|
| 698 |
+
wM_s = np.interp(t_s, t_c, wM)
|
| 699 |
+
wQ_s = np.interp(t_s, t_c, wQ)
|
| 700 |
+
|
| 701 |
+
# Three-way blend at sample level
|
| 702 |
+
min_n = min(total, *(len(df_out[c]) for c in ('loud', 'mid', 'quiet', 'trans')))
|
| 703 |
+
blended = (
|
| 704 |
+
wL_s[:min_n] * df_out['loud'][:min_n].astype(np.float64) +
|
| 705 |
+
wM_s[:min_n] * df_out['mid'][:min_n].astype(np.float64) +
|
| 706 |
+
wQ_s[:min_n] * df_out['quiet'][:min_n].astype(np.float64)
|
| 707 |
+
)
|
| 708 |
+
|
| 709 |
+
# SNR gate: for already-clean regions, blend toward 'trans' (light-touch
|
| 710 |
+
# pass) rather than raw mono β avoids re-introducing un-processed noise.
|
| 711 |
+
# Gate weight is also Gaussian-smoothed so it ramps gradually.
|
| 712 |
+
w_gate = np.clip((chunk_snr - snr_gate) / 8.0, 0.0, 1.0)
|
| 713 |
+
w_gate = _gauss1d(w_gate, SC * 2) # wider smooth for gate
|
| 714 |
+
w_gate_s = np.clip(np.interp(t_s, t_c, w_gate), 0.0, _ADF_GATE_MAX)
|
| 715 |
+
blended[:min_n] = (
|
| 716 |
+
(1.0 - w_gate_s[:min_n]) * blended[:min_n] +
|
| 717 |
+
w_gate_s[:min_n] * df_out['trans'][:min_n].astype(np.float64)
|
| 718 |
+
)
|
| 719 |
+
|
| 720 |
+
_L(st, f' [S4-ADF] v5 continuous blend: Ο_db={SIGMA:.1f}dB '
|
| 721 |
+
f'smooth={SC}Γ{int(_ADF_CHUNK_S*1000)}ms={int(SC*_ADF_CHUNK_S*1000)}ms '
|
| 722 |
+
f'gateβ€{int(_ADF_GATE_MAX*100)}%')
|
| 723 |
+
|
| 724 |
+
# ββ RL-16: restore Ghunnah guard bands from original ββββββββββββββ
|
| 725 |
+
blended_f32 = np.where(np.isfinite(blended), blended, 0.0).astype(np.float32)
|
| 726 |
+
blended_f32 = _stft_restore_bands(blended_f32, mono[:min_n], SR, _RL16_BANDS)
|
| 727 |
+
_L(st, f' [S4-ADF] RL-16 bands restored: '
|
| 728 |
+
f'{", ".join(f"{lo}-{hi}Hz" for lo,hi in _RL16_BANDS)}')
|
| 729 |
+
|
| 730 |
+
# ββ Silence guard βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 731 |
+
if float(np.max(np.abs(blended_f32))) < 1e-4:
|
| 732 |
+
_L(st, ' [S4-ADF] β silent result β fallback to mid pass')
|
| 733 |
+
blended_f32 = df_out['mid'][:min_n].astype(np.float32)
|
| 734 |
+
|
| 735 |
+
# ββ Encode to pcm_s24le stereo ββββββββββββββββββββββββββββββββββββ
|
| 736 |
+
out = _tmp('s4', st)
|
| 737 |
+
r3 = subprocess.run(
|
| 738 |
+
['ffmpeg', '-nostdin', '-y', '-hide_banner', '-loglevel', 'error',
|
| 739 |
+
'-f', 'f32le', '-ar', str(SR), '-ac', '1', '-i', '-',
|
| 740 |
+
'-ar', str(SR), '-ac', '2', '-acodec', 'pcm_s24le', out],
|
| 741 |
+
input=blended_f32.tobytes(), capture_output=True, timeout=120)
|
| 742 |
+
if r3.returncode or not os.path.exists(out):
|
| 743 |
+
return wav
|
| 744 |
+
|
| 745 |
+
delta = _rmsdb(blended_f32) - _rmsdb(mono)
|
| 746 |
+
st.df3 = True
|
| 747 |
+
_L(st, f' [S4-ADF] β loud={a_loud}dB mid={a_mid}dB quiet={a_quiet}dB '
|
| 748 |
+
f'RMS Ξ={delta:+.2f}dB')
|
| 749 |
+
return out
|
| 750 |
+
except Exception as e:
|
| 751 |
+
_L(st, f' [S4-DF3] exception: {e}'); return wav
|
| 752 |
+
finally:
|
| 753 |
+
shutil.rmtree(d, ignore_errors=True)
|
| 754 |
+
|
| 755 |
+
|
| 756 |
+
# βββ Stage 5: JALAA per-frame DRR gate (Β§28.6) βββββββββββββββββββββββββββββββ
|
| 757 |
+
def _jalaa(wav, samples, rt60, drr_before, st):
|
| 758 |
+
"""
|
| 759 |
+
Per-frame DRR classification β calibrated afftdn on reverb-dominated frames.
|
| 760 |
+
[B1] Late window corrected to 450ms (50-500ms per Β§3.3).
|
| 761 |
+
[I10] Skip entirely if DRR already > DRR_ALREADY_DRY (room is dry enough).
|
| 762 |
+
"""
|
| 763 |
+
if not NUMPY_OK or samples is None or rt60 < 0.30:
|
| 764 |
+
_L(st, f' [S5-JALAA] RT60={rt60:.2f}s < 0.30 β skip'); return wav
|
| 765 |
+
if drr_before > DRR_ALREADY_DRY:
|
| 766 |
+
_L(st, f' [S5-JALAA] DRR={drr_before:.1f}dB already dry β skip [I10]'); return wav
|
| 767 |
+
|
| 768 |
+
fn = int(0.200 * SR)
|
| 769 |
+
en = int(0.050 * SR)
|
| 770 |
+
ln = int(0.450 * SR) # [B1] was 0.150 β 450ms (50-500ms window)
|
| 771 |
+
n = len(samples) // fn
|
| 772 |
+
if n < 5:
|
| 773 |
+
return wav
|
| 774 |
+
|
| 775 |
+
nf_vals = []
|
| 776 |
+
for i in range(n):
|
| 777 |
+
s = i * fn; chunk = samples[s:s + fn]
|
| 778 |
+
if len(chunk) < en + ln:
|
| 779 |
+
continue
|
| 780 |
+
er = float(np.sqrt(np.mean(chunk[:en] ** 2)) + 1e-10)
|
| 781 |
+
lr = float(np.sqrt(np.mean(chunk[en:en + ln] ** 2)) + 1e-10)
|
| 782 |
+
if er < 1e-5: continue
|
| 783 |
+
if 20.0 * np.log10(er / lr) < 3.0: # reverb-dominated
|
| 784 |
+
nf_vals.append(float(20 * np.log10(lr + 1e-10)))
|
| 785 |
+
|
| 786 |
+
if not nf_vals:
|
| 787 |
+
_L(st, ' [S5-JALAA] no reverb frames β skip'); return wav
|
| 788 |
+
|
| 789 |
+
nf = float(np.clip(float(np.median(nf_vals)) + 3, -72, -20)) # v4: floor raised -25β-20
|
| 790 |
+
nr = 3 if rt60 > RT60_AGGR else 2 # v4: base raised (was 2/1)
|
| 791 |
+
if st.mujawwad_conf > 0.6: nr = max(1, nr - 1)
|
| 792 |
+
|
| 793 |
+
# v4: two-pass JALAA β first pass stationary, second adaptive tracking
|
| 794 |
+
out = _tmp('s5a', st)
|
| 795 |
+
rc, _, _ = _run(['ffmpeg', '-y', '-i', wav,
|
| 796 |
+
'-af', f'afftdn=nr={nr}:nf={nf:.0f}:nt=w:tn=1',
|
| 797 |
+
'-acodec', WAV_CODEC, '-ar', str(SR), '-ac', '1',
|
| 798 |
+
'-loglevel', 'error', out])
|
| 799 |
+
if rc or not os.path.exists(out):
|
| 800 |
+
return wav
|
| 801 |
+
|
| 802 |
+
out2 = _tmp('s5b', st)
|
| 803 |
+
rc2, _, _ = _run(['ffmpeg', '-y', '-i', out,
|
| 804 |
+
'-af', f'afftdn=nr={max(1,nr-1)}:nf={nf+3:.0f}:nt=w:tn=1',
|
| 805 |
+
'-acodec', WAV_CODEC, '-ar', str(SR), '-ac', '1',
|
| 806 |
+
'-loglevel', 'error', out2])
|
| 807 |
+
if rc2 or not os.path.exists(out2):
|
| 808 |
+
pass # keep single-pass result
|
| 809 |
+
else:
|
| 810 |
+
_cleanup(out); out = out2
|
| 811 |
+
|
| 812 |
+
post = _decode(out)
|
| 813 |
+
if post is not None:
|
| 814 |
+
d = _rmsdb(post) - _rmsdb(samples)
|
| 815 |
+
if abs(d) > _RMS_MAX_DELTA:
|
| 816 |
+
_cleanup(out); st.guard_reverts += 1
|
| 817 |
+
_L(st, f' [S5-JALAA] RMS Ξ={d:+.2f}dB β REVERT'); return wav
|
| 818 |
+
|
| 819 |
+
st.jalaa = True
|
| 820 |
+
_L(st, f' [S5-JALAA] β reverb_frames={len(nf_vals)}/{n} nf={nf:.0f}dB nr={nr}')
|
| 821 |
+
return out
|
| 822 |
+
|
| 823 |
+
|
| 824 |
+
# βββ Stage 6: Tail floor NR β 2-stage (afftdn + anlmdn) βββββββββββββββββββββ
|
| 825 |
+
def _tailnr(wav, samples, rt60, st):
|
| 826 |
+
"""
|
| 827 |
+
2-stage NR pipeline (Β§83.3 order: stationary β non-stationary):
|
| 828 |
+
Stage A: afftdn with nt=w (adaptive tracking) for stationary noise floor.
|
| 829 |
+
Stage B: anlmdn (s=7:p=3:r=15) for transient/non-stationary residuals.
|
| 830 |
+
RT60-scaled nr: base=2, +1 per 1.5s RT60 above threshold, cap=5 (Β§5.3: 20dB/nr max).
|
| 831 |
+
[I3] If JALAA already ran, reduce nr by 1 to avoid double-attenuation.
|
| 832 |
+
RL-16: sibilant SNR guard β revert if Safir/Tafasshi band drops > 2dB.
|
| 833 |
+
"""
|
| 834 |
+
if rt60 < RT60_TAILNR or samples is None or not NUMPY_OK:
|
| 835 |
+
return wav
|
| 836 |
+
fn = int(0.200 * SR)
|
| 837 |
+
overall = _rmsdb(samples)
|
| 838 |
+
fdb = np.array([float(20 * np.log10(np.sqrt(np.mean(samples[i:i+fn]**2)) + 1e-10))
|
| 839 |
+
for i in range(0, len(samples) - fn, fn)])
|
| 840 |
+
quiet = fdb[fdb < overall - 10]
|
| 841 |
+
if len(quiet) == 0:
|
| 842 |
+
return wav
|
| 843 |
+
|
| 844 |
+
nf = float(np.clip(float(np.median(quiet)) + 4, -72, -25))
|
| 845 |
+
# v4: RT60-scaled nr β higher cap (8 was 5), stronger base
|
| 846 |
+
nr = min(8, 3 + int((rt60 - RT60_TAILNR) / 1.2)) # was cap=5, base=2, step=1.5
|
| 847 |
+
if st.mujawwad_conf > 0.6: nr = max(1, nr - 1)
|
| 848 |
+
if st.jalaa: nr = max(1, nr - 1) # [I3]
|
| 849 |
+
|
| 850 |
+
# ββ Stage A: afftdn with adaptive noise tracking ββββββββββββββββββββββ
|
| 851 |
+
out_a = _tmp('s6a', st)
|
| 852 |
+
rc, _, _ = _run(['ffmpeg', '-y', '-i', wav,
|
| 853 |
+
'-af', f'afftdn=nr={nr}:nf={nf:.0f}:nt=w:om=o',
|
| 854 |
+
'-acodec', WAV_CODEC, '-ar', str(SR), '-ac', '2',
|
| 855 |
+
'-loglevel', 'error', out_a])
|
| 856 |
+
if rc or not os.path.exists(out_a):
|
| 857 |
+
return wav
|
| 858 |
+
|
| 859 |
+
# ββ Stage B: anlmdn for non-stationary residuals ββββββββββββββββββββββ
|
| 860 |
+
# anlmdn: s=patch size, p=context, r=search radius (Β§95 KB)
|
| 861 |
+
# Scale strength with nr: gentle (s=5) at nr<=2, standard (s=7) at nr>2
|
| 862 |
+
patch = 7 if nr > 2 else 5
|
| 863 |
+
out_b = _tmp('s6b', st)
|
| 864 |
+
rc2, _, _ = _run(['ffmpeg', '-y', '-i', out_a,
|
| 865 |
+
'-af', f'anlmdn=s={patch}:p=3:r=15:m=1',
|
| 866 |
+
'-acodec', WAV_CODEC, '-ar', str(SR), '-ac', '2',
|
| 867 |
+
'-loglevel', 'error', out_b])
|
| 868 |
+
if rc2 or not os.path.exists(out_b):
|
| 869 |
+
# Stage B failed β commit Stage A only
|
| 870 |
+
st.tail_nr = True
|
| 871 |
+
jalaa_note = ' (JALAA-adj)' if st.jalaa else ''
|
| 872 |
+
_L(st, f' [S6-tailNR] β 1-stage nr={nr}{jalaa_note} nf={nf:.0f}dB '
|
| 873 |
+
f'[anlmdn failed β Stage A only]')
|
| 874 |
+
return out_a
|
| 875 |
+
|
| 876 |
+
# ββ Sibilant SNR guard (RL-16 spirit) βββββββββββββββββββββββββββββββββ
|
| 877 |
+
post_s = _decode(out_b)
|
| 878 |
+
if post_s is not None:
|
| 879 |
+
sib_orig = _band_energy(samples, 3500, 8000)
|
| 880 |
+
sib_post = _band_energy(post_s, 3500, 8000)
|
| 881 |
+
sib_drop = sib_post - sib_orig
|
| 882 |
+
if sib_drop < -2.0:
|
| 883 |
+
_L(st, f' [S6-tailNR] sibilant drop {sib_drop:+.1f}dB β '
|
| 884 |
+
f'revert Stage B, keep Stage A')
|
| 885 |
+
_cleanup(out_b)
|
| 886 |
+
st.tail_nr = True
|
| 887 |
+
_L(st, f' [S6-tailNR] β nr={nr} nf={nf:.0f}dB [Stage A only]')
|
| 888 |
+
return out_a
|
| 889 |
+
|
| 890 |
+
# ββ Stage C: v4 β gentle anlmdn second pass for reverb tail residual ββββ
|
| 891 |
+
out_c = _tmp('s6c', st)
|
| 892 |
+
rc3, _, _ = _run(['ffmpeg', '-y', '-i', out_b,
|
| 893 |
+
'-af', f'anlmdn=s=5:p=3:r=10:m=1',
|
| 894 |
+
'-acodec', WAV_CODEC, '-ar', str(SR), '-ac', '2',
|
| 895 |
+
'-loglevel', 'error', out_c])
|
| 896 |
+
if rc3 or not os.path.exists(out_c):
|
| 897 |
+
pass # keep Stage B
|
| 898 |
+
else:
|
| 899 |
+
post_c = _decode(out_c)
|
| 900 |
+
if post_c is not None:
|
| 901 |
+
sib_c = _band_energy(post_c, 3500, 8000)
|
| 902 |
+
sib_drop_c = sib_c - _band_energy(samples, 3500, 8000)
|
| 903 |
+
if sib_drop_c >= -2.5:
|
| 904 |
+
_cleanup(out_b); out_b = out_c
|
| 905 |
+
else:
|
| 906 |
+
_cleanup(out_c)
|
| 907 |
+
|
| 908 |
+
_cleanup(out_a)
|
| 909 |
+
st.tail_nr = True
|
| 910 |
+
jalaa_note = ' (JALAA-adj)' if st.jalaa else ''
|
| 911 |
+
_L(st, f' [S6-tailNR] β 3-stage nr={nr}{jalaa_note} nf={nf:.0f}dB '
|
| 912 |
+
f'patch={patch} rt60={rt60:.1f}s')
|
| 913 |
+
return out_b
|
| 914 |
+
|
| 915 |
+
|
| 916 |
+
# βββ Stage 6.5: Wind noise removal (v4) βββββββββββββββββββββββββββββββββββββ
|
| 917 |
+
def _windnr(wav, samples, rt60, st):
|
| 918 |
+
"""
|
| 919 |
+
Targets wind noise: broadband low-frequency energy (30β400Hz)
|
| 920 |
+
that DF3 doesn't clean because it looks like speech sub-harmonics.
|
| 921 |
+
|
| 922 |
+
Strategy:
|
| 923 |
+
A) Hard HPF at 60Hz to kill sub-rumble
|
| 924 |
+
B) Spectral gate on 60β300Hz band: estimate wind energy from
|
| 925 |
+
speech-inactive frames, subtract with 6dB headroom
|
| 926 |
+
C) Gentle de-essing inversion below 400Hz (anlmdn lightweight)
|
| 927 |
+
D) Guard: if low-band energy drops > 8dB β revert (protect bass vowels)
|
| 928 |
+
"""
|
| 929 |
+
if samples is None or not NUMPY_OK:
|
| 930 |
+
_L(st, ' [S6.5-WIND] no samples β skip'); return wav
|
| 931 |
+
|
| 932 |
+
# Measure wind energy spectrally β find steady LF floor even during speech
|
| 933 |
+
# Wind = energy in 60-300Hz that doesn't modulate with speech (stays constant)
|
| 934 |
+
fn = int(0.100 * SR)
|
| 935 |
+
n = len(samples) // fn
|
| 936 |
+
overall_db = _rmsdb(samples)
|
| 937 |
+
|
| 938 |
+
# Low-band energy per frame (60β300Hz via FFT)
|
| 939 |
+
lo_energy_db = []
|
| 940 |
+
for i in range(n):
|
| 941 |
+
frame = samples[i*fn:(i+1)*fn]
|
| 942 |
+
spec = np.abs(np.fft.rfft(frame, n=fn)) / fn # normalize by N
|
| 943 |
+
freqs = np.fft.rfftfreq(fn, d=1.0/SR)
|
| 944 |
+
lo_mask = (freqs >= 60) & (freqs <= 300)
|
| 945 |
+
lo_rms = float(np.sqrt(np.mean(spec[lo_mask]**2) + 1e-20))
|
| 946 |
+
lo_energy_db.append(20 * np.log10(lo_rms + 1e-10))
|
| 947 |
+
|
| 948 |
+
lo_energy_db = np.array(lo_energy_db)
|
| 949 |
+
# Wind floor = the bottom 20th percentile of LF energy across all frames
|
| 950 |
+
# Wind is the *minimum* steady LF that persists regardless of speech activity
|
| 951 |
+
wind_floor_db = float(np.percentile(lo_energy_db, 20))
|
| 952 |
+
|
| 953 |
+
# Only apply if wind floor is detectable (above -62dBFS in LF band)
|
| 954 |
+
if wind_floor_db < -62.0:
|
| 955 |
+
_L(st, f' [S6.5-WIND] LF floor={wind_floor_db:.1f}dBFS β inaudible, skip'); return wav
|
| 956 |
+
|
| 957 |
+
# Baseline for guards must be the wav INPUT (already DF3/tailNR processed),
|
| 958 |
+
# NOT s_orig β comparing against original would fire on DF3's own changes.
|
| 959 |
+
wav_pre = _decode(wav)
|
| 960 |
+
if wav_pre is None:
|
| 961 |
+
_L(st, ' [S6.5-WIND] decode failed β skip'); return wav
|
| 962 |
+
|
| 963 |
+
lo_before = _band_energy(wav_pre, 60, 200) # wind zone: 60-200Hz
|
| 964 |
+
mid_before = _band_energy(wav_pre, 250, 900) # vowel zone: protect formants
|
| 965 |
+
|
| 966 |
+
# Wind noise in mosque/outdoor recordings sits below 200Hz.
|
| 967 |
+
# afftdn nt=w is too broad (hits vowel formants) β use HPF + low-shelf instead.
|
| 968 |
+
# Stage A: HPF at 80Hz (2-pole) β kills sub-rumble below speech
|
| 969 |
+
tmp_a = _tmp('s65a', st)
|
| 970 |
+
rc, _, _ = _run(['ffmpeg', '-y', '-i', wav,
|
| 971 |
+
'-af', 'highpass=f=80:poles=2',
|
| 972 |
+
'-acodec', WAV_CODEC, '-ar', str(SR), '-ac', '2',
|
| 973 |
+
'-loglevel', 'error', tmp_a])
|
| 974 |
+
if rc or not os.path.exists(tmp_a):
|
| 975 |
+
_L(st, ' [S6.5-WIND] HPF failed β skip'); return wav
|
| 976 |
+
|
| 977 |
+
# Stage B: low-shelf EQ targeting 80-200Hz wind band.
|
| 978 |
+
# Depth scales with severity: heavy wind β up to -8dB shelf; faint β -3dB.
|
| 979 |
+
# shelf at 200Hz, so everything above is unaffected.
|
| 980 |
+
shelf_db = -8.0 if wind_floor_db > -35 else (-5.0 if wind_floor_db > -45 else -3.0)
|
| 981 |
+
tmp_b = _tmp('s65b', st)
|
| 982 |
+
rc2, _, _ = _run(['ffmpeg', '-y', '-i', tmp_a,
|
| 983 |
+
'-af', (f'equalizer=f=100:width_type=o:width=1.0:g={shelf_db:.0f},'
|
| 984 |
+
f'equalizer=f=180:width_type=o:width=0.8:g={shelf_db*0.5:.0f}'),
|
| 985 |
+
'-acodec', WAV_CODEC, '-ar', str(SR), '-ac', '2',
|
| 986 |
+
'-loglevel', 'error', tmp_b])
|
| 987 |
+
if rc2 or not os.path.exists(tmp_b):
|
| 988 |
+
_L(st, ' [S6.5-WIND] shelf EQ failed β keep HPF only')
|
| 989 |
+
result = tmp_a
|
| 990 |
+
else:
|
| 991 |
+
# Stage C: very gentle anlmdn for residual wind texture (s=2, conservative)
|
| 992 |
+
tmp_c = _tmp('s65c', st)
|
| 993 |
+
rc3, _, _ = _run(['ffmpeg', '-y', '-i', tmp_b,
|
| 994 |
+
'-af', 'anlmdn=s=2:p=2:r=6:m=1',
|
| 995 |
+
'-acodec', WAV_CODEC, '-ar', str(SR), '-ac', '2',
|
| 996 |
+
'-loglevel', 'error', tmp_c])
|
| 997 |
+
result = tmp_c if (rc3 == 0 and os.path.exists(tmp_c)) else tmp_b
|
| 998 |
+
|
| 999 |
+
# Dual guard:
|
| 1000 |
+
# Wind zone (60-200Hz): allow up to -15dB β this IS the wind band
|
| 1001 |
+
# Vowel zone (250-900Hz): max -2dB β protect speech formants tightly
|
| 1002 |
+
post_s = _decode(result)
|
| 1003 |
+
if post_s is not None:
|
| 1004 |
+
lo_after = _band_energy(post_s, 60, 200)
|
| 1005 |
+
mid_after = _band_energy(post_s, 250, 900)
|
| 1006 |
+
if lo_before > 1e-15:
|
| 1007 |
+
lo_drop = 10 * np.log10(lo_after / (lo_before + 1e-20) + 1e-20)
|
| 1008 |
+
if lo_drop < -15.0:
|
| 1009 |
+
for t in [tmp_a, tmp_b, tmp_c if 'tmp_c' in dir() else None]:
|
| 1010 |
+
if t: _cleanup(t)
|
| 1011 |
+
st.guard_reverts += 1
|
| 1012 |
+
_L(st, f' [S6.5-WIND] wind-zone over-removal {lo_drop:+.1f}dB β REVERT')
|
| 1013 |
+
return wav
|
| 1014 |
+
if mid_before > 1e-15:
|
| 1015 |
+
mid_drop = 10 * np.log10(mid_after / (mid_before + 1e-20) + 1e-20)
|
| 1016 |
+
if mid_drop < -2.0:
|
| 1017 |
+
for t in [tmp_a, tmp_b, tmp_c if 'tmp_c' in dir() else None]:
|
| 1018 |
+
if t: _cleanup(t)
|
| 1019 |
+
st.guard_reverts += 1
|
| 1020 |
+
_L(st, f' [S6.5-WIND] vowel band drop {mid_drop:+.1f}dB β REVERT')
|
| 1021 |
+
return wav
|
| 1022 |
+
_L(st, f' [S6.5-WIND] guards β wind={lo_drop:+.1f}dB vowel={mid_drop:+.1f}dB')
|
| 1023 |
+
|
| 1024 |
+
if result not in (tmp_a,):
|
| 1025 |
+
_cleanup(tmp_a)
|
| 1026 |
+
if 'tmp_b' in dir() and result not in (tmp_b,):
|
| 1027 |
+
_cleanup(tmp_b)
|
| 1028 |
+
_L(st, f' [S6.5-WIND] β floor={wind_floor_db:.1f}dBFS shelf={shelf_db:.0f}dB @100-180Hz')
|
| 1029 |
+
return result
|
| 1030 |
+
|
| 1031 |
+
|
| 1032 |
+
# βββ Stage 7: Arabic phoneme guards (Β§35/Β§52/Β§143/Β§152) ββββββββββββββββββββββ
|
| 1033 |
+
def _arabic_guards(orig_s, proc_wav, st):
|
| 1034 |
+
"""
|
| 1035 |
+
Seven guards verifying Tajweed-critical features survived processing.
|
| 1036 |
+
WARN-only by design β reverb is worse than mild phoneme loss.
|
| 1037 |
+
Results stored in st.guard_pass / st.guard_warn (structured). [I6]
|
| 1038 |
+
[B3] _band_energy() now samples across full file.
|
| 1039 |
+
[B4] G4 Ra-trill scans full audio in overlapping 1s windows.
|
| 1040 |
+
"""
|
| 1041 |
+
if not NUMPY_OK or orig_s is None:
|
| 1042 |
+
return proc_wav
|
| 1043 |
+
proc_s = _decode(proc_wav)
|
| 1044 |
+
if proc_s is None:
|
| 1045 |
+
return proc_wav
|
| 1046 |
+
n = min(len(orig_s), len(proc_s))
|
| 1047 |
+
o = orig_s[:n]; p = proc_s[:n]
|
| 1048 |
+
|
| 1049 |
+
def chk(name, cond, detail):
|
| 1050 |
+
entry = f'{name}: {detail}'
|
| 1051 |
+
if cond:
|
| 1052 |
+
st.guard_pass.append(entry); _L(st, f' [S7-PASS] {entry}')
|
| 1053 |
+
else:
|
| 1054 |
+
st.guard_warn.append(entry); _L(st, f' [S7-WARN] β {entry}')
|
| 1055 |
+
|
| 1056 |
+
# G1 Ghunnah 250-300 Hz (Β§152.3)
|
| 1057 |
+
go = _band_energy(o, 250, 300); gp = _band_energy(p, 250, 300)
|
| 1058 |
+
if go > 1e-15:
|
| 1059 |
+
d = 10 * np.log10(gp / go + 1e-20)
|
| 1060 |
+
chk('G1-Ghunnah', d >= -3.0, f'{d:+.1f}dB {"β" if d>=-3 else "β nasal murmur lost"}')
|
| 1061 |
+
|
| 1062 |
+
# G2 Ikhfa 250-400 Hz (Β§52.5)
|
| 1063 |
+
io = _band_energy(o, 250, 400); ip = _band_energy(p, 250, 400)
|
| 1064 |
+
if io > 1e-15:
|
| 1065 |
+
d = 10 * np.log10(ip / io + 1e-20)
|
| 1066 |
+
chk('G2-Ikhfa', d >= -4.0, f'{d:+.1f}dB {"β" if d>=-4 else "β ikhfa nasalisation lost"}')
|
| 1067 |
+
|
| 1068 |
+
# G3 Qalqalah burst (Β§52.7, Β§143 Class 2)
|
| 1069 |
+
sil_n = int(0.020 * SR); bst_n = int(0.030 * SR)
|
| 1070 |
+
total = viol = 0
|
| 1071 |
+
for i in range(0, n - sil_n - bst_n, sil_n):
|
| 1072 |
+
sr_ = float(np.sqrt(np.mean(o[i:i + sil_n] ** 2)) + 1e-10)
|
| 1073 |
+
br_ = float(np.sqrt(np.mean(o[i + sil_n:i + sil_n + bst_n] ** 2)) + 1e-10)
|
| 1074 |
+
if sr_ < 0.005 and br_ > sr_ * 5:
|
| 1075 |
+
total += 1
|
| 1076 |
+
bp = float(np.sqrt(np.mean(p[i + sil_n:i + sil_n + bst_n] ** 2)) + 1e-10)
|
| 1077 |
+
if 20 * np.log10(bp / br_ + 1e-10) < -6.0: viol += 1
|
| 1078 |
+
if total > 0:
|
| 1079 |
+
pct = viol / total * 100
|
| 1080 |
+
chk('G3-Qalqalah', pct <= 20,
|
| 1081 |
+
f'{total} bursts {pct:.0f}% violated {"β" if pct<=20 else "β echo burst attenuated"}')
|
| 1082 |
+
|
| 1083 |
+
# G4 Ra trill AM 25-35 Hz β FULL AUDIO scan in overlapping 1s windows [B4]
|
| 1084 |
+
win = SR; hop = SR // 2
|
| 1085 |
+
am_ratios = []
|
| 1086 |
+
for pos in range(0, n - win, hop):
|
| 1087 |
+
ef_o = np.abs(np.fft.rfft(np.abs(o[pos:pos + win]), n=win))
|
| 1088 |
+
ef_p = np.abs(np.fft.rfft(np.abs(p[pos:pos + win]), n=win))
|
| 1089 |
+
am_o = float(np.mean(ef_o[25:36])); am_p = float(np.mean(ef_p[25:36]))
|
| 1090 |
+
if am_o > 1e-8:
|
| 1091 |
+
am_ratios.append(am_p / am_o)
|
| 1092 |
+
if am_ratios:
|
| 1093 |
+
r = float(np.median(am_ratios))
|
| 1094 |
+
chk('G4-Ra-trill', r >= 0.70,
|
| 1095 |
+
f'AM ratio={r:.2f} (median over {len(am_ratios)} windows) '
|
| 1096 |
+
f'{"β" if r>=0.70 else "β Ψ± trill may be smeared"}')
|
| 1097 |
+
|
| 1098 |
+
# G5 Safir 5.5-12 kHz β Ψ΅ Ψ³ Ψ² (Β§152.3)
|
| 1099 |
+
so = _band_energy(o, 5500, 12000); sp = _band_energy(p, 5500, 12000)
|
| 1100 |
+
if so > 1e-15:
|
| 1101 |
+
d = 10 * np.log10(sp / so + 1e-20)
|
| 1102 |
+
chk('G5-Safir', d >= -5.0,
|
| 1103 |
+
f'{d:+.1f}dB {"β" if d>=-5 else "β Ψ΅ Ψ³ Ψ² may be dull"}')
|
| 1104 |
+
|
| 1105 |
+
# G6 Tafasshi 3-8 kHz β Ψ΄ (Β§152.3)
|
| 1106 |
+
to = _band_energy(o, 3000, 8000); tp = _band_energy(p, 3000, 8000)
|
| 1107 |
+
if to > 1e-15:
|
| 1108 |
+
d = 10 * np.log10(tp / to + 1e-20)
|
| 1109 |
+
chk('G6-Tafasshi', d >= -4.0,
|
| 1110 |
+
f'{d:+.1f}dB {"β" if d>=-4 else "β Ψ΄ may lose spread"}')
|
| 1111 |
+
|
| 1112 |
+
# G7 Izhar silence count (Β§52.5.1)
|
| 1113 |
+
def _sil_count(s):
|
| 1114 |
+
fn_ = int(0.010 * SR)
|
| 1115 |
+
db = np.array([float(20 * np.log10(np.sqrt(np.mean(s[i:i + fn_] ** 2)) + 1e-10))
|
| 1116 |
+
for i in range(0, len(s) - fn_, fn_)])
|
| 1117 |
+
med = float(np.median(db)); c = 0; in_s = False; sl = 0
|
| 1118 |
+
for v in db:
|
| 1119 |
+
if v < med - 18: in_s = True; sl += 1
|
| 1120 |
+
else:
|
| 1121 |
+
if in_s and 2 <= sl <= 8: c += 1
|
| 1122 |
+
in_s = False; sl = 0
|
| 1123 |
+
return c
|
| 1124 |
+
sc_o = _sil_count(o); sc_p = _sil_count(p)
|
| 1125 |
+
if sc_o > 0:
|
| 1126 |
+
r = sc_p / sc_o
|
| 1127 |
+
chk('G7-Izhar', r >= 0.70,
|
| 1128 |
+
f'silences {sc_o}β{sc_p} ({r:.0%}) {"β" if r>=0.70 else "β words may run together"}')
|
| 1129 |
+
|
| 1130 |
+
total_g = len(st.guard_pass) + len(st.guard_warn)
|
| 1131 |
+
if st.guard_warn:
|
| 1132 |
+
_L(st, f' [S7] {len(st.guard_warn)}/{total_g} warnings β check output for Tajweed artifacts')
|
| 1133 |
+
else:
|
| 1134 |
+
_L(st, f' [S7] All {total_g} guards passed β')
|
| 1135 |
+
return proc_wav
|
| 1136 |
+
|
| 1137 |
+
|
| 1138 |
+
# βββ Main βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1139 |
+
def process(input_path, output_path, source_tier='TIER_UNKNOWN',
|
| 1140 |
+
mujawwad_conf=0.0, force_rt60=0.0, verbose=True, aggressive=False):
|
| 1141 |
+
"""
|
| 1142 |
+
Ψ§ΩΨ΅ΩΨ§Ψ‘ v3 β main entry point.
|
| 1143 |
+
Returns SafaaState with full diagnostics.
|
| 1144 |
+
All temp files are tracked and cleaned up on exit. [I8]
|
| 1145 |
+
"""
|
| 1146 |
+
st = SafaaState(input_path=input_path, source_tier=source_tier,
|
| 1147 |
+
mujawwad_conf=mujawwad_conf)
|
| 1148 |
+
_L(st, f'\n{"β"*60}')
|
| 1149 |
+
_L(st, f' Ψ§ΩΨ΅ΩΨ§Ψ‘ {__version__} β Ψ₯Ψ²Ψ§ΩΨ© Ψ§ΩΨ΅Ψ―Ω ΩΨ§ΩΨ±ΩΩΩΨ±Ψ¨')
|
| 1150 |
+
_L(st, f' Input : {Path(input_path).name}')
|
| 1151 |
+
_L(st, f' Tier : {source_tier} Mujawwad: {mujawwad_conf:.2f}')
|
| 1152 |
+
_L(st, f'{"β"*60}')
|
| 1153 |
+
if aggressive:
|
| 1154 |
+
_L(st, ' [AGGRESSIVE] DF3 attenuation caps + post-filter coverage widened '
|
| 1155 |
+
'(Mujawwad ceiling unchanged β protected by design)')
|
| 1156 |
+
|
| 1157 |
+
s_orig = _decode(input_path)
|
| 1158 |
+
if s_orig is None:
|
| 1159 |
+
_L(st, ' ERROR: decode failed'); return st
|
| 1160 |
+
|
| 1161 |
+
try:
|
| 1162 |
+
cur = input_path
|
| 1163 |
+
|
| 1164 |
+
# S1: RT60 + DRR
|
| 1165 |
+
rt60 = force_rt60 if force_rt60 > 0 else _rt60(s_orig)
|
| 1166 |
+
st.rt60_initial = rt60; st.drr_before = _drr(s_orig)
|
| 1167 |
+
_L(st, f' [S1] RT60={rt60:.2f}s DRR={st.drr_before:.1f}dB')
|
| 1168 |
+
|
| 1169 |
+
if rt60 < RT60_MIN:
|
| 1170 |
+
_L(st, f' [S1] RT60 < {RT60_MIN}s β no processing needed')
|
| 1171 |
+
_enc_stereo(input_path, output_path); return st
|
| 1172 |
+
|
| 1173 |
+
# S2 Sub-band LF EQ
|
| 1174 |
+
cur = _lf_eq(cur, s_orig, rt60, st)
|
| 1175 |
+
# S3 WPE
|
| 1176 |
+
cur = _wpe(cur, rt60, st)
|
| 1177 |
+
# S4 DF3 (parallel)
|
| 1178 |
+
_s4 = _decode(cur); s4 = _s4 if _s4 is not None else s_orig
|
| 1179 |
+
cur = _df3(cur, s4, rt60, st, aggressive=aggressive)
|
| 1180 |
+
# S5 JALAA (DRR-weighted, corrected late window)
|
| 1181 |
+
_s5 = _decode(cur); s5 = _s5 if _s5 is not None else s_orig
|
| 1182 |
+
cur = _jalaa(cur, s5, rt60, st.drr_before, st)
|
| 1183 |
+
# S6 Tail NR (JALAA-aware)
|
| 1184 |
+
_s6 = _decode(cur); s6 = _s6 if _s6 is not None else s_orig
|
| 1185 |
+
cur = _tailnr(cur, s6, rt60, st)
|
| 1186 |
+
# S6.5 Wind noise removal β v4 addition
|
| 1187 |
+
cur = _windnr(cur, s_orig, rt60, st)
|
| 1188 |
+
# S7 Arabic guards
|
| 1189 |
+
cur = _arabic_guards(s_orig, cur, st)
|
| 1190 |
+
|
| 1191 |
+
# Final stereo encode + S8a dynamic normalizer + S8b volume boost
|
| 1192 |
+
# S8a: dynaudnorm final level evenness (v5: DF3 now self-smooth; dynaudnorm is a safety net)
|
| 1193 |
+
# f=500ms window (long=smooth), m=10 max gain cap (20dB safety),
|
| 1194 |
+
# p=0.92 peak target, r=0.0 (peak mode, not RMS β preserves Tajweed transients)
|
| 1195 |
+
# S8b: Aggressive mode = 4x boost (7.40) vs standard (1.85); limiter tightened
|
| 1196 |
+
_s8_vol = 7.40 if aggressive else 1.85
|
| 1197 |
+
_s8_lim = 0.94 if aggressive else 0.89
|
| 1198 |
+
_s8_norm = 'dynaudnorm=f=500:g=31:p=0.92:m=10:r=0.0:b=1,'
|
| 1199 |
+
_s8_af = (_s8_norm +
|
| 1200 |
+
f'volume={_s8_vol},'
|
| 1201 |
+
'equalizer=f=2000:width_type=o:width=1.0:g=1.5,'
|
| 1202 |
+
'equalizer=f=300:width_type=o:width=1.0:g=-1.0,'
|
| 1203 |
+
f'alimiter=level_in=1:level_out=1:limit={_s8_lim}:attack=5:release=50')
|
| 1204 |
+
_s8_mode = 'AGGRESSIVE 4x' if aggressive else 'standard'
|
| 1205 |
+
_L(st, f' [S8a] dynaudnorm f=500ms m=10 p=0.92 β level evenness pass')
|
| 1206 |
+
_L(st, f' [S8b] volume boost={_s8_vol:.2f} ({_s8_mode})')
|
| 1207 |
+
rc, _, err = _run(['ffmpeg', '-y', '-i', cur,
|
| 1208 |
+
'-af', _s8_af,
|
| 1209 |
+
'-acodec', WAV_CODEC, '-ar', str(SR), '-ac', '2',
|
| 1210 |
+
'-loglevel', 'error', output_path])
|
| 1211 |
+
if rc:
|
| 1212 |
+
_L(st, f' ERROR: final encode: {err[:80]}'); return st
|
| 1213 |
+
|
| 1214 |
+
sf_ = _decode(output_path)
|
| 1215 |
+
if sf_ is not None: st.drr_after = _drr(sf_)
|
| 1216 |
+
|
| 1217 |
+
_L(st, f'\n{"β"*60}')
|
| 1218 |
+
_L(st, f' Ψ§ΩΨ΅ΩΨ§Ψ‘ {__version__} β')
|
| 1219 |
+
_L(st, f' RT60 : {st.rt60_initial:.2f}s')
|
| 1220 |
+
_L(st, f' DRR : {st.drr_before:.1f} β {st.drr_after:.1f} dB '
|
| 1221 |
+
f'(Ξ{st.drr_after - st.drr_before:+.1f})')
|
| 1222 |
+
_L(st, f' LF={st.lf_eq} WPE={st.wpe} DF3={st.df3} JALAA={st.jalaa} tailNR={st.tail_nr}')
|
| 1223 |
+
_L(st, f' Reverts:{st.guard_reverts} Warns:{len(st.guard_warn)}/{len(st.guard_pass)+len(st.guard_warn)}')
|
| 1224 |
+
_L(st, f'{"β"*60}\n')
|
| 1225 |
+
return st
|
| 1226 |
+
|
| 1227 |
+
finally:
|
| 1228 |
+
_cleanup_all(st) # [I8] always runs
|
| 1229 |
+
|
| 1230 |
+
|
| 1231 |
+
# βββ CLI ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1232 |
+
if __name__ == '__main__':
|
| 1233 |
+
import argparse, json
|
| 1234 |
+
ap = argparse.ArgumentParser(description=f'Ψ§ΩΨ΅ΩΨ§Ψ‘ {__version__} β Dereverberation Engine')
|
| 1235 |
+
ap.add_argument('input')
|
| 1236 |
+
ap.add_argument('output')
|
| 1237 |
+
ap.add_argument('--tier', default='TIER_UNKNOWN')
|
| 1238 |
+
ap.add_argument('--mujawwad', type=float, default=0.0)
|
| 1239 |
+
ap.add_argument('--rt60', type=float, default=0.0, help='Force RT60 (0=auto)')
|
| 1240 |
+
ap.add_argument('--aggressive', action='store_true',
|
| 1241 |
+
help='4x volume boost (7.40) + wider DF3 caps vs standard (1.85)')
|
| 1242 |
+
a = ap.parse_args()
|
| 1243 |
+
st = process(a.input, a.output,
|
| 1244 |
+
source_tier=a.tier, mujawwad_conf=a.mujawwad, force_rt60=a.rt60,
|
| 1245 |
+
aggressive=a.aggressive)
|
| 1246 |
+
print('\n[REPORT]')
|
| 1247 |
+
print(json.dumps({
|
| 1248 |
+
'version': __version__,
|
| 1249 |
+
'rt60': st.rt60_initial,
|
| 1250 |
+
'drr_before': round(st.drr_before, 2),
|
| 1251 |
+
'drr_after': round(st.drr_after, 2),
|
| 1252 |
+
'drr_gain': round(st.drr_after - st.drr_before, 2),
|
| 1253 |
+
'stages': {
|
| 1254 |
+
'lf_eq': st.lf_eq,
|
| 1255 |
+
'wpe': st.wpe,
|
| 1256 |
+
'df3': st.df3,
|
| 1257 |
+
'jalaa': st.jalaa,
|
| 1258 |
+
'tail_nr': st.tail_nr,
|
| 1259 |
+
},
|
| 1260 |
+
'guard_reverts': st.guard_reverts,
|
| 1261 |
+
'guard_pass': st.guard_pass,
|
| 1262 |
+
'guard_warn': st.guard_warn,
|
| 1263 |
+
}, indent=2, ensure_ascii=False))
|