Spaces:
Paused
Paused
NarratifAI deploy commited on
Commit ·
a690be2
1
Parent(s): 65b8f9a
Deploy asr_system 4f6c67f
Browse files- src/audio_processor/enhance.py +175 -0
- src/transcription/engine.py +36 -2
src/audio_processor/enhance.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Speech clean-up before transcription and speaker detection.
|
| 2 |
+
|
| 3 |
+
Levels
|
| 4 |
+
off the audio as converted (16 kHz mono, peak-normalised)
|
| 5 |
+
light DC offset removed, low rumble cut (80 Hz high-pass), speech brought to
|
| 6 |
+
a steady level so quiet and loud voices sit closer together, peaks
|
| 7 |
+
limited instead of clipped
|
| 8 |
+
full light, plus noise reduction when the recording measures as noisy
|
| 9 |
+
|
| 10 |
+
The noise reduction is deliberately gentle (a floor on how much any part of the
|
| 11 |
+
spectrum is turned down, gains smoothed across time and frequency): heavy
|
| 12 |
+
denoising leaves artefacts that make Whisper drop or invent words.
|
| 13 |
+
|
| 14 |
+
Everything is numpy/scipy so it runs the same on Modal and the HF Space.
|
| 15 |
+
"""
|
| 16 |
+
import warnings
|
| 17 |
+
from dataclasses import dataclass, asdict
|
| 18 |
+
from typing import Dict, Tuple
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
from scipy import signal
|
| 22 |
+
from scipy.ndimage import uniform_filter1d
|
| 23 |
+
|
| 24 |
+
LEVELS = ("off", "light", "full")
|
| 25 |
+
|
| 26 |
+
TARGET_SPEECH_DBFS = -20.0 # level speech is brought to
|
| 27 |
+
MAX_BOOST_DB = 12.0 # quietest speakers are lifted at most this much
|
| 28 |
+
MAX_CUT_DB = 6.0 # loudest speakers are lowered at most this much
|
| 29 |
+
LIMIT_AT = 0.89 # about -1 dBFS; above this peaks are softened
|
| 30 |
+
DENOISE_BELOW_SNR_DB = 25.0 # cleaner recordings are left alone
|
| 31 |
+
DENOISE_FLOOR_DB = -12.0 # never turn any time-frequency cell down more than this
|
| 32 |
+
DENOISE_OVERSUBTRACT = 1.5
|
| 33 |
+
# The 15th percentile of a noise band's power sits at about 0.16 of its mean
|
| 34 |
+
# (power of random noise is exponentially distributed): scale it back up.
|
| 35 |
+
NOISE_BIAS = 1 / 0.1625
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@dataclass
|
| 39 |
+
class EnhanceReport:
|
| 40 |
+
level: str
|
| 41 |
+
snr_db: float
|
| 42 |
+
noise_floor_dbfs: float
|
| 43 |
+
speech_dbfs: float
|
| 44 |
+
denoised: bool
|
| 45 |
+
boost_db_max: float
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _frame_db(x: np.ndarray, sr: int, frame_s: float = 0.02) -> np.ndarray:
|
| 49 |
+
n = max(1, int(sr * frame_s))
|
| 50 |
+
usable = len(x) // n * n
|
| 51 |
+
if usable == 0:
|
| 52 |
+
return np.array([-120.0])
|
| 53 |
+
frames = x[:usable].reshape(-1, n)
|
| 54 |
+
rms = np.sqrt(np.mean(frames ** 2, axis=1) + 1e-12)
|
| 55 |
+
return 20 * np.log10(rms + 1e-12)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def measure(x: np.ndarray, sr: int) -> Tuple[float, float, float]:
|
| 59 |
+
"""(snr_db, noise_floor_dbfs, speech_dbfs) from the spread of 20 ms frame levels."""
|
| 60 |
+
db = _frame_db(x, sr)
|
| 61 |
+
db = db[db > -100]
|
| 62 |
+
if db.size < 10:
|
| 63 |
+
return 0.0, -100.0, -100.0
|
| 64 |
+
noise = float(np.percentile(db, 10))
|
| 65 |
+
speech = float(np.percentile(db, 90))
|
| 66 |
+
return speech - noise, noise, speech
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _highpass(x: np.ndarray, sr: int, hz: float = 80.0) -> np.ndarray:
|
| 70 |
+
sos = signal.butter(2, hz, btype="highpass", fs=sr, output="sos")
|
| 71 |
+
return signal.sosfilt(sos, x).astype(np.float32)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _denoise(x: np.ndarray, sr: int) -> np.ndarray:
|
| 75 |
+
"""Spectral gating against a slowly moving noise estimate (non-stationary:
|
| 76 |
+
a fan that starts or a generator in the next room is followed)."""
|
| 77 |
+
n_fft, hop = 512, 128
|
| 78 |
+
_, _, Z = signal.stft(x, fs=sr, nperseg=n_fft, noverlap=n_fft - hop, boundary="zeros", padded=True)
|
| 79 |
+
power = np.abs(Z) ** 2
|
| 80 |
+
frames_per_s = sr / hop
|
| 81 |
+
# Noise estimate per frequency: a low percentile over ~3 s blocks, then
|
| 82 |
+
# interpolated across time, so speech pauses anywhere nearby define the floor.
|
| 83 |
+
block = max(8, int(3.0 * frames_per_s))
|
| 84 |
+
n_frames = power.shape[1]
|
| 85 |
+
centres, floors = [], []
|
| 86 |
+
for start in range(0, n_frames, block // 2):
|
| 87 |
+
seg = power[:, start:start + block]
|
| 88 |
+
if seg.shape[1] < 4:
|
| 89 |
+
continue
|
| 90 |
+
centres.append(start + seg.shape[1] / 2)
|
| 91 |
+
floors.append(np.percentile(seg, 15, axis=1) * NOISE_BIAS)
|
| 92 |
+
if not floors:
|
| 93 |
+
return x
|
| 94 |
+
floors = np.stack(floors, axis=1)
|
| 95 |
+
if floors.shape[1] == 1:
|
| 96 |
+
noise = np.repeat(floors, n_frames, axis=1)
|
| 97 |
+
else:
|
| 98 |
+
idx = np.arange(n_frames)
|
| 99 |
+
noise = np.vstack([np.interp(idx, centres, floors[k]) for k in range(floors.shape[0])])
|
| 100 |
+
gain = 1.0 - DENOISE_OVERSUBTRACT * noise / (power + 1e-12)
|
| 101 |
+
floor = 10 ** (DENOISE_FLOOR_DB / 20)
|
| 102 |
+
gain = np.clip(gain, floor ** 2, 1.0) ** 0.5
|
| 103 |
+
# Smooth gains over ~3 bins and ~40 ms to avoid "musical" artefacts.
|
| 104 |
+
gain = uniform_filter1d(gain, size=3, axis=0)
|
| 105 |
+
gain = uniform_filter1d(gain, size=max(3, int(0.04 * frames_per_s)), axis=1)
|
| 106 |
+
_, y = signal.istft(Z * gain, fs=sr, nperseg=n_fft, noverlap=n_fft - hop, boundary=True)
|
| 107 |
+
return y[: len(x)].astype(np.float32)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def _level(x: np.ndarray, sr: int, noise_dbfs: float) -> Tuple[np.ndarray, float]:
|
| 111 |
+
"""Slow gain riding so each stretch of speech sits near TARGET_SPEECH_DBFS.
|
| 112 |
+
Gain is decided from speech frames only and held through pauses, so
|
| 113 |
+
background noise between sentences is not pumped up."""
|
| 114 |
+
frame_s = 0.02
|
| 115 |
+
db = _frame_db(x, sr, frame_s)
|
| 116 |
+
speechy = db > noise_dbfs + 6
|
| 117 |
+
if speechy.sum() < 10:
|
| 118 |
+
return x, 0.0
|
| 119 |
+
# Speech level over ~1.5 s, carried across pauses.
|
| 120 |
+
level = np.where(speechy, db, np.nan)
|
| 121 |
+
win = int(1.5 / frame_s)
|
| 122 |
+
pad = np.pad(level, (win // 2, win - win // 2 - 1), constant_values=np.nan)
|
| 123 |
+
windows = np.lib.stride_tricks.sliding_window_view(pad, win)
|
| 124 |
+
with np.errstate(all="ignore"), warnings.catch_warnings():
|
| 125 |
+
warnings.simplefilter("ignore", RuntimeWarning)
|
| 126 |
+
local = np.nanpercentile(windows, 75, axis=1)
|
| 127 |
+
known = ~np.isnan(local)
|
| 128 |
+
idx = np.arange(len(local))
|
| 129 |
+
local = np.interp(idx, idx[known], local[known])
|
| 130 |
+
gain_db = np.clip(TARGET_SPEECH_DBFS - local, -MAX_CUT_DB, MAX_BOOST_DB)
|
| 131 |
+
gain_db = uniform_filter1d(gain_db, size=int(0.5 / frame_s))
|
| 132 |
+
n = int(sr * frame_s)
|
| 133 |
+
curve = np.interp(np.arange(len(x)), np.arange(len(gain_db)) * n + n / 2, gain_db)
|
| 134 |
+
return (x * 10 ** (curve / 20)).astype(np.float32), float(gain_db.max())
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def _limit(x: np.ndarray) -> np.ndarray:
|
| 138 |
+
"""Soft-knee limiter: untouched below LIMIT_AT, smoothly squeezed above."""
|
| 139 |
+
a = np.abs(x)
|
| 140 |
+
over = a > LIMIT_AT
|
| 141 |
+
if not over.any():
|
| 142 |
+
return x
|
| 143 |
+
head = 1.0 - LIMIT_AT
|
| 144 |
+
y = x.copy()
|
| 145 |
+
y[over] = np.sign(x[over]) * (LIMIT_AT + head * np.tanh((a[over] - LIMIT_AT) / head))
|
| 146 |
+
return y
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def enhance(x: np.ndarray, sr: int, level: str = "light") -> Tuple[np.ndarray, EnhanceReport]:
|
| 150 |
+
"""Return the cleaned-up audio (same length and sample rate) and what was done."""
|
| 151 |
+
x = np.asarray(x, dtype=np.float32)
|
| 152 |
+
if x.ndim > 1:
|
| 153 |
+
x = x.mean(axis=1 if x.shape[1] < x.shape[0] else 0)
|
| 154 |
+
snr, noise, speech = measure(x, sr)
|
| 155 |
+
if level not in LEVELS:
|
| 156 |
+
raise ValueError(f"Unknown enhancement level {level!r}; use one of {LEVELS}")
|
| 157 |
+
if level == "off" or x.size < sr // 2:
|
| 158 |
+
return x, EnhanceReport("off", round(snr, 1), round(noise, 1), round(speech, 1), False, 0.0)
|
| 159 |
+
y = x - float(np.mean(x))
|
| 160 |
+
y = _highpass(y, sr)
|
| 161 |
+
# Measured again once DC offset and rumble are gone: they inflate the noise
|
| 162 |
+
# floor, which would hide quiet speakers from the levelling below.
|
| 163 |
+
snr, noise, speech = measure(y, sr)
|
| 164 |
+
denoised = False
|
| 165 |
+
if level == "full" and snr < DENOISE_BELOW_SNR_DB:
|
| 166 |
+
y = _denoise(y, sr)
|
| 167 |
+
denoised = True
|
| 168 |
+
_, noise, _ = measure(y, sr)
|
| 169 |
+
y, boost = _level(y, sr, noise)
|
| 170 |
+
y = _limit(y)
|
| 171 |
+
return y, EnhanceReport(level, round(snr, 1), round(noise, 1), round(speech, 1), denoised, round(boost, 1))
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def report_dict(r: EnhanceReport) -> Dict:
|
| 175 |
+
return asdict(r)
|
src/transcription/engine.py
CHANGED
|
@@ -15,6 +15,7 @@ import soundfile as sf
|
|
| 15 |
|
| 16 |
from ..audio_processor.validator import AudioValidator
|
| 17 |
from ..audio_processor.converter import AudioConverter
|
|
|
|
| 18 |
from ..audio_processor.chunker import AudioChunker
|
| 19 |
from ..models.registry import ModelRegistry
|
| 20 |
from ..models.asr_pipeline import ASRPipeline, TranscriptionResult
|
|
@@ -153,6 +154,37 @@ class TranscriptionEngine:
|
|
| 153 |
# as a single block (no app-level overlap, no context between chunks).
|
| 154 |
actual_duration = len(audio) / sr
|
| 155 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
requested = [l for l in (kwargs.pop("languages", None) or ([kwargs["language"]] if kwargs.get("language") else [])) if l]
|
| 157 |
job_model = self.current_model_key
|
| 158 |
self._plan_windows = None
|
|
@@ -163,7 +195,7 @@ class TranscriptionEngine:
|
|
| 163 |
speaker_turns = None
|
| 164 |
if diarize and self.diarization.is_available():
|
| 165 |
try:
|
| 166 |
-
speaker_turns = self.diarization.diarize(str(
|
| 167 |
except Exception as e:
|
| 168 |
logger.warning(f"Diarization failed: {e}. Returning transcript without speakers.")
|
| 169 |
self._turn_cuts = turn_cuts(speaker_turns) if speaker_turns else []
|
|
@@ -215,7 +247,7 @@ class TranscriptionEngine:
|
|
| 215 |
try:
|
| 216 |
result.segments = self.diarization.align_speakers(result.segments, speaker_turns)
|
| 217 |
result.segments = self.diarization.refine_speakers(
|
| 218 |
-
str(
|
| 219 |
except Exception as e:
|
| 220 |
logger.warning(f"Speaker labelling failed: {e}. Returning transcript without speakers.")
|
| 221 |
elif not self.diarization.is_available():
|
|
@@ -230,6 +262,8 @@ class TranscriptionEngine:
|
|
| 230 |
|
| 231 |
finally:
|
| 232 |
Path(processed_path).unlink(missing_ok=True)
|
|
|
|
|
|
|
| 233 |
|
| 234 |
return result
|
| 235 |
|
|
|
|
| 15 |
|
| 16 |
from ..audio_processor.validator import AudioValidator
|
| 17 |
from ..audio_processor.converter import AudioConverter
|
| 18 |
+
from ..audio_processor.enhance import enhance, report_dict
|
| 19 |
from ..audio_processor.chunker import AudioChunker
|
| 20 |
from ..models.registry import ModelRegistry
|
| 21 |
from ..models.asr_pipeline import ASRPipeline, TranscriptionResult
|
|
|
|
| 154 |
# as a single block (no app-level overlap, no context between chunks).
|
| 155 |
actual_duration = len(audio) / sr
|
| 156 |
|
| 157 |
+
# Clean-up levels (off / light / full), set separately for the words and
|
| 158 |
+
# for speaker detection: each benefits from different treatment. A
|
| 159 |
+
# failed clean-up never fails the job; the converted audio is used.
|
| 160 |
+
# Defaults from an evaluation on AMI meetings (headset, room mic, added
|
| 161 |
+
# noise; Whisper small and large-v3) and FLEURS Yoruba (clean, noisy):
|
| 162 |
+
# "light" lowered word errors in every condition; "full" noise reduction
|
| 163 |
+
# helped English a little more but hurt the Yoruba model, and neither
|
| 164 |
+
# changed how well speakers were told apart.
|
| 165 |
+
asr_level = kwargs.pop("enhance_asr", None) or os.getenv("AUDIO_ENHANCE_ASR", "light")
|
| 166 |
+
diar_level = kwargs.pop("enhance_diarization", None) or os.getenv("AUDIO_ENHANCE_DIARIZATION", "off")
|
| 167 |
+
diar_path = processed_path
|
| 168 |
+
self.last_enhance = {}
|
| 169 |
+
try:
|
| 170 |
+
raw = audio
|
| 171 |
+
if asr_level != "off":
|
| 172 |
+
audio, rep = enhance(raw, sr, asr_level)
|
| 173 |
+
self.last_enhance["asr"] = report_dict(rep)
|
| 174 |
+
if diar_level != "off":
|
| 175 |
+
if diar_level == asr_level:
|
| 176 |
+
diar_audio = audio
|
| 177 |
+
else:
|
| 178 |
+
diar_audio, rep = enhance(raw, sr, diar_level)
|
| 179 |
+
self.last_enhance["diarization"] = report_dict(rep)
|
| 180 |
+
diar_path = str(Path(processed_path).with_name(Path(processed_path).stem + "_diar.wav"))
|
| 181 |
+
sf.write(diar_path, diar_audio, sr)
|
| 182 |
+
if self.last_enhance:
|
| 183 |
+
logger.info(f"Audio clean-up: {self.last_enhance}")
|
| 184 |
+
except Exception as e:
|
| 185 |
+
logger.warning(f"Audio clean-up skipped: {type(e).__name__}: {e}")
|
| 186 |
+
audio, diar_path = raw, processed_path
|
| 187 |
+
|
| 188 |
requested = [l for l in (kwargs.pop("languages", None) or ([kwargs["language"]] if kwargs.get("language") else [])) if l]
|
| 189 |
job_model = self.current_model_key
|
| 190 |
self._plan_windows = None
|
|
|
|
| 195 |
speaker_turns = None
|
| 196 |
if diarize and self.diarization.is_available():
|
| 197 |
try:
|
| 198 |
+
speaker_turns = self.diarization.diarize(str(diar_path), num_speakers=num_speakers)
|
| 199 |
except Exception as e:
|
| 200 |
logger.warning(f"Diarization failed: {e}. Returning transcript without speakers.")
|
| 201 |
self._turn_cuts = turn_cuts(speaker_turns) if speaker_turns else []
|
|
|
|
| 247 |
try:
|
| 248 |
result.segments = self.diarization.align_speakers(result.segments, speaker_turns)
|
| 249 |
result.segments = self.diarization.refine_speakers(
|
| 250 |
+
str(diar_path), result.segments, num_speakers=num_speakers)
|
| 251 |
except Exception as e:
|
| 252 |
logger.warning(f"Speaker labelling failed: {e}. Returning transcript without speakers.")
|
| 253 |
elif not self.diarization.is_available():
|
|
|
|
| 262 |
|
| 263 |
finally:
|
| 264 |
Path(processed_path).unlink(missing_ok=True)
|
| 265 |
+
if diar_path != processed_path:
|
| 266 |
+
Path(diar_path).unlink(missing_ok=True)
|
| 267 |
|
| 268 |
return result
|
| 269 |
|