Metadata-Version: 2.4
Name: mashood-neural-snr
Version: 0.1.5
Summary: Blind SNR estimation for speech and voice technology pipelines. Designed for TTS, ASR, voice biometrics, and STS workflows. No clean reference file required.
Home-page: https://github.com/mashoodAwan/mashood-neural-snr
Author: Muhammad Mashood Awan
Author-email: mashoodawan27@gmail.com
License: MIT
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: torch<=2.5.1,>=1.9
Requires-Dist: torchaudio<=2.5.1,>=0.9
Requires-Dist: numpy
Requires-Dist: scipy
Requires-Dist: pandas
Requires-Dist: deepfilternet
Requires-Dist: soundfile
Requires-Dist: tqdm
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: license
Dynamic: license-file
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# mashood-neural-snr 🎙️

[![PyPI version](https://img.shields.io/pypi/v/mashood-neural-snr.svg)](https://pypi.org/project/mashood-neural-snr/)
[![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Downloads](https://static.pepy.tech/badge/mashood-neural-snr)](https://pepy.tech/project/mashood-neural-snr)

**Blind SNR estimation for speech and voice technology pipelines — TTS, ASR, voice biometrics, and STS. No clean reference file required.**

---

## What Is This

`mashood-neural-snr` is a Python package that measures the **Signal-to-Noise Ratio (SNR)** of a voice recording — without needing a separate clean version of the same recording.

It was built specifically for **speech technology workflows** where audio quality is not a nice-to-have but a direct input to model performance. If you are building or maintaining a TTS system, an ASR pipeline, a voice biometrics system, or a speech-to-speech engine — the SNR of your audio data determines the quality of what comes out the other side.

---

## What Is SNR — In the Context of Voice

SNR stands for Signal-to-Noise Ratio. In the context of voice recordings, it measures how dominant the speech signal is over the background noise — expressed in decibels (dB).

Think of it this way:

> You have a voice recording. Inside that recording there are two things: the person's voice (the **signal**) and everything else — traffic, HVAC, keyboard clicks, crowd noise (the **noise**). SNR tells you the ratio of one to the other.

A **high SNR** means the voice is loud and clear relative to the background. A **low SNR** means the noise is competing with or burying the voice.

```
+20 dB  →  Voice is 100× more powerful than noise  →  Clean recording
 +5 dB  →  Voice is only 3× more powerful than noise  →  Noisy recording
  0 dB  →  Voice and noise are equal in power  →  Very poor
-10 dB  →  Noise is 10× more powerful than voice  →  Voice buried
```

In speech technology, SNR is not just a quality metric — **it is a data quality gate.** Recordings below a minimum SNR threshold should not enter your training pipeline, your enrollment database, or your production system.

---

## Why SNR Matters — Per Domain

### Text-to-Speech (TTS) and Voice Cloning

A TTS model learns to synthesize speech by studying the acoustic patterns in your training recordings. If those recordings contain background noise, the model learns the noise too — and reproduces it in synthesis output as artifacts, distortion, or unnatural voice quality.

This is especially critical for voice cloning, where the model is learning the characteristics of a specific speaker. Noisy recordings corrupt the speaker representation at the identity level, not just at the quality level.

**Consequence of ignoring SNR:** Degraded synthesis quality, audible artifacts, failed voice cloning.

### Automatic Speech Recognition (ASR)

ASR models convert voice to text. Background noise introduces acoustic ambiguity — phonemes become harder to distinguish, and the model accumulates errors. This is measured as Word Error Rate (WER). The relationship is direct: lower SNR → higher WER.

For ASR training data, noisy recordings teach the model wrong acoustic-to-phoneme mappings. For inference, noisy input audio causes transcription failures that no amount of model improvement can compensate for if the input quality is fundamentally poor.

**Consequence of ignoring SNR:** Elevated Word Error Rate, transcription failures, poor model generalization.

### Voice Biometrics and Speaker Verification

Voice biometrics systems work by extracting a speaker embedding — a mathematical fingerprint of a person's voice — and comparing it against a stored enrollment embedding. This comparison needs to be stable across different recording conditions.

Background noise distorts the acoustic features that speaker embeddings are built from. A recording with poor SNR produces a distorted embedding that may not match even the correct speaker's enrollment profile, causing false rejections. Conversely, noise patterns that are consistent across recordings can cause false accepts.

**Consequence of ignoring SNR:** Increased false rejection rate (FRR), degraded Equal Error Rate (EER), unreliable biometric authentication.

### Speech-to-Speech (STS)

Speech-to-speech systems — voice translation, voice conversion, real-time dubbing — chain together ASR, processing, and TTS or voice synthesis. Noise at the input compounds through every stage of the pipeline. A transcription error caused by low SNR at the ASR stage propagates forward and cannot be recovered by downstream components.

**Consequence of ignoring SNR:** Compounding errors across pipeline stages, degraded output naturalness and intelligibility.

---

## Why Existing SNR Tools Fail on Real Voice Recordings

Traditional SNR estimation methods — including VAD-based approaches and WADA-SNR — share a fundamental assumption: **noise can only be measured during silence.**

```
Traditional method:  [SPEECH+NOISE]  [SILENCE]  [SPEECH+NOISE]
                                         ↑
                              measure noise here only
```

This works in controlled laboratory recordings. It fails in the real world because:

- **Continuous noise** (traffic, HVAC, air conditioning) produces no silence gaps long enough for stable estimation
- **Noise measured in silence is not noise under speech** — spectral characteristics differ during voiced activity
- **Short clips** (< 5 seconds) may have no silence at all

**The blind estimation problem.** In a real-world recording you never receive two separate files — one clean, one noisy. You receive a single mixed file where speech and noise are already combined. The standard SNR formula requires signal power and noise power to be known independently — but in a real recording you only have their sum. This is called blind SNR estimation, and it is why reference-based tools are useless in production pipelines: there is no clean reference to compare against.

**WADA-SNR** specifically fits a gamma distribution to speech amplitude values. It requires long recordings to converge and degrades on non-stationary or overlapping noise — exactly the conditions present in real-world data collection.

`mashood-neural-snr` does not look for silence at all. It estimates the speech component directly using a neural enhancement model, making the noise derivation independent of silence regions and noise type.

---

## How It Works

The package repurposes **DeepFilterNet3** — a real-time neural speech enhancement model — as the engine of a blind SNR estimator. Here is exactly what happens when you call `snr("recording.wav")`:

### Step 1 — Load and Resample
The WAV file is loaded and resampled to 48 kHz, the fixed sample rate required by DeepFilterNet3.

### Step 2 — Neural Speech Enhancement
DeepFilterNet3 processes the noisy waveform and produces a denoised output. The model was trained specifically to preserve speech and suppress background noise — it applies learned spectral gains and complex filters in the frequency domain to output its best estimate of what the clean speech sounds like.

```
noisy_recording  →  DeepFilterNet3  →  enhanced_speech
```

This enhanced output **is the speech estimate**. The key insight is that a model trained to remove noise gives us a proxy for the clean signal — which we can then use to derive the noise component by subtraction.

### Step 3 — Latency Correction
Neural enhancement introduces a small processing delay. The enhanced signal is time-shifted relative to the original. Cross-correlation finds the exact lag between them and aligns both signals to the same time axis.

### Step 4 — Amplitude Correction
The enhancement model may output at a slightly different amplitude than the original. A least-squares scalar `α` is computed to match the enhanced signal's amplitude to the original — ensuring the subsequent subtraction is numerically clean.

### Step 5 — Noise Extraction and SNR Computation
The scaled, aligned speech estimate is subtracted from the original to isolate the noise residual:

```
noise_estimate  =  original_recording  −  (α × enhanced_speech)
```

SNR is then computed as the power ratio of the speech estimate to the noise estimate:

```
SNR (dB)  =  10 × log₁₀ ( Power(speech_estimate) / Power(noise_estimate) )
```

---

## Requirements & Compatibility

| | |
|---|---|
| Python | >= 3.8 |
| PyTorch | >= 1.9, <= 2.5.1 |
| torchaudio | >= 0.9, <= 2.5.1 |
| Device | CPU and CUDA — auto-detected |
| Google Colab | ✅ Compatible |
| OS | Windows, Linux, macOS |

---

## Installation

```bash
pip install mashood-neural-snr
```

**Using uv:**
```bash
uv pip install mashood-neural-snr
```

**CPU-only torch (smaller download, no CUDA):**
```bash
pip install mashood-neural-snr --index-url https://download.pytorch.org/whl/cpu
```

---

## Usage

### Basic

```python
from mashood_neural_snr import snr

score = snr("recording.wav")
# SNR: 12.43 dB | Device: cpu
```

### Device Control

```python
# Auto-detect — uses CUDA if available, falls back to CPU
score = snr("recording.wav")

# Force CPU
score = snr("recording.wav", device="cpu")

# Force CUDA
score = snr("recording.wav", device="cuda")
```

### Batch Processing

Use `SNREstimator` directly for multiple files. It loads the model once on creation and reuses it across all calls. Using `snr()` in a loop initializes the model on every call, which is significantly slower.

```python
from mashood_neural_snr import SNREstimator

estimator = SNREstimator(device="cuda")  # model loads here, once

files = ["speaker1.wav", "speaker2.wav", "speaker3.wav"]
for f in files:
    score = estimator.estimate(f, show_progress=False)
    print(f"{f}: {score:.2f} dB")
```

### Suppress Progress Bar

```python
score = estimator.estimate("recording.wav", show_progress=False)
```

---

## API Reference

### `snr(file_path, device=None)`

Single-file convenience function. Maintains a module-level `SNREstimator` singleton — the model loads on the first call and is reused on all subsequent calls with the same device.

| Parameter | Type | Default | Description |
|---|---|---|---|
| `file_path` | `str` | required | Path to a `.wav` audio file |
| `device` | `str` | `None` | `'cuda'`, `'cpu'`, or `None` (auto-detect) |

**Returns:** `float` — estimated SNR in decibels (dB)

---

### `SNREstimator(device=None)`

Class-based interface. Recommended for batch processing.

| Parameter | Type | Default | Description |
|---|---|---|---|
| `device` | `str` | `None` | `'cuda'`, `'cpu'`, or `None` (auto-detect) |

**Attributes:**
- `.device` — the resolved device (`torch.device`) in use

#### `.estimate(file_path, show_progress=True)`

| Parameter | Type | Default | Description |
|---|---|---|---|
| `file_path` | `str` | required | Path to a `.wav` audio file |
| `show_progress` | `bool` | `True` | Show per-step tqdm progress bar |

**Returns:** `float` — estimated SNR in decibels (dB)

---

## Supported Audio

| Property | Details |
|---|---|
| Format | `.wav` only |
| Channels | Mono and Stereo (stereo averaged to mono internally) |
| Sample Rate | Any — resampled to 48 kHz internally |
| Minimum Duration | ~3 seconds recommended |
| Signal Type | Speech and voice only |

---

## SNR Thresholds — Per Domain

These thresholds reflect the SNR levels at which each speech technology domain experiences meaningful performance degradation. Use them as data quality gates in your pipeline.

### Text-to-Speech (TTS) and Voice Cloning

| SNR | Recommendation |
|---|---|
| ≥ 35 dB | Ideal — use for voice cloning and high-quality TTS training |
| 25–35 dB | Good — suitable for TTS training with standard preprocessing |
| 20–25 dB | Acceptable — apply enhancement before use |
| < 20 dB | Reject — noise will corrupt synthesis quality |

> LibriTTS, the standard benchmark corpus for TTS research, applies SNR filtering as a core curation criterion. 20 dB is widely treated as the minimum floor for TTS training data.

### Automatic Speech Recognition (ASR)

| SNR | Recommendation |
|---|---|
| ≥ 30 dB | Ideal for training and inference |
| 20–30 dB | Good — acceptable for most ASR systems |
| 10–20 dB | Marginal — enhancement recommended before use |
| < 10 dB | Reject for training; expect elevated WER at inference |

> ASR systems generally require SNR ≥ 30 dB for accurate contextual understanding. Below 10 dB, word error rates rise sharply.

### Voice Biometrics and Speaker Verification

| SNR | Recommendation |
|---|---|
| ≥ 20 dB | Reliable speaker embeddings — use for enrollment and verification |
| 10–20 dB | Acceptable — monitor Equal Error Rate (EER) closely |
| < 10 dB | Reject — noise distorts speaker embeddings, degrades EER |

> **10 dB is the recommended minimum threshold for voice biometrics**, based on empirical study of noise impact on speaker verification performance across Animal, Nature, Environmental, and Object noise categories at controlled SNR levels.

### Speech-to-Speech (STS)

| SNR | Recommendation |
|---|---|
| ≥ 25 dB | Clean input — full pipeline quality preserved |
| 15–25 dB | Acceptable — minor degradation at output |
| < 15 dB | Apply enhancement at input stage before pipeline entry |
| < 10 dB | Reject — errors compound through ASR → synthesis stages |

---

## Benchmark Results

Evaluated on a controlled dataset of **2,560 samples** built from LibriSpeech:

- **Speakers:** 8 LibriSpeech speakers — 4 male, 4 female
- **Duration:** 50 seconds per sample
- **Noise categories:** Animal, Nature, Environmental, Objects
- **Noise sources:** ESC-50, UrbanSound8K, DEMAND
- **SNR levels tested:** −20, −15, −10, −5, +5, +10, +15, +20 dB
- **Mixing:** Power-based SNR mixing — noise scaled to exact target SNR before mixing with clean speech

| True SNR | Mean Predicted | Mean Abs Error | Within ±2 dB |
|---|---|---|---|
| +20 dB | 19.03 dB | 1.46 dB | 78.1% ✅ |
| +15 dB | 14.62 dB | 0.79 dB | 92.2% ✅ |
| +10 dB | 9.84 dB | 0.50 dB | 95.0% ✅ |
| +5 dB | 4.96 dB | 0.35 dB | 99.4% ✅ |
| −5 dB | −4.88 dB | 0.39 dB | 99.7% ✅ |
| −10 dB | −9.44 dB | 0.91 dB | 86.6% ✅ |
| −15 dB | −13.24 dB | 2.37 dB | 60.9% ⚠️ |
| −20 dB | −15.91 dB | 5.11 dB | 30.9% ❌ |

**Overall Mean Absolute Error across the reliable operating range (−10 dB to +20 dB): 0.97 dB**

Sub-1 dB mean error across 7 out of 8 SNR levels covering the full practical range for speech technology applications.

---

## Known Limitations

**Reliable operating range is −10 dB to +20 dB.**
Below −15 dB, the speech signal is physically buried in noise. DeepFilterNet3 cannot reliably suppress noise at this level — the enhancement output becomes unstable, and the residual no longer cleanly represents noise. Recordings in this range should be rejected outright. Do not rely on the estimated score as a quality signal below −15 dB.

**Speech and voice signals only.**
DeepFilterNet3 was trained to preserve speech and suppress everything else. Running it on music, environmental audio, or any non-voice signal will cause the model to treat signal content as noise — producing meaningless SNR estimates.

**WAV format only.**
MP3, FLAC, M4A, and other formats must be converted to WAV before use.

**Minimum recommended duration: ~3 seconds.**
Cross-correlation alignment requires sufficient signal length to find a stable lag peak. Very short clips may produce unreliable alignment and unstable SNR estimates.

**Single-speaker recordings.**
The package has been evaluated on single-speaker recordings only. Multi-speaker or overlapping speech has not been benchmarked.

---

## License

Licensed under the **MIT License**.

You are free to use, copy, modify, merge, publish, distribute, sublicense, and sell copies of this software — including in commercial products — with no restrictions beyond preserving the copyright notice.



Full license terms: [LICENSE](LICENSE)
