pesq developer on retainer: pesq() requires 8000 Hz or 16000 Hz — 44100 Hz recordings raise BadSamplingRateError — broad handler returns default score 4.5 (excellent) — 25 000 calls per month appear excellent — 3 000 poor-quality calls never flagged — 4 weeks — pesq developer on monthly retainer
pesq 0.0.4 • Python 3.9; pesq(fs, ref, deg, mode) accepts fs = 8000 (narrowband) or fs = 16000 (wideband) only • Southfield Pesq Ltd. (voice call quality monitoring; 25,000 recordings/month from 50 contact centers; recording system: 44100 Hz WAV; pesq(fs=44100, ref, deg, 'wb') raises BadSamplingRateError; broad except Exception: return 4.5 handler returns default excellent score; 25,000 calls/month appear excellent; 3,000 genuinely poor-quality calls never flagged for QA review; customer complaint rate +40%; fix: scipy.signal.resample_poly to 16000 Hz before pesq() call; 2.0h retainer engagement)
Southfield Pesq Ltd. built a voice call quality monitoring service for contact centers. Quality assurance teams used PESQ (Perceptual Evaluation of Speech Quality, ITU-T P.862) scores to triage calls: any call scoring below 2.0 (the boundary between “poor” and “fair” on the MOS-LQO scale) was flagged for QA review and agent coaching. The service processed 25,000 recordings per month from 50 contact centers. The contact centers’ call recording platform (Verint) stored recordings as 44100 Hz WAV files — a common recording quality setting that preserves audio fidelity above the telephony range for archival purposes. The pesq scoring pipeline read each recording with soundfile.read(path, dtype='float32'), which returned both the audio array and the sample rate (rate = 44100), and then called pesq(fs=rate, ref=reference, deg=audio, mode='wb'). The engineer who built the pipeline passed the native sample rate from soundfile.read() directly to pesq(), reasoning that using the actual file’s sample rate would be more accurate than a hardcoded value.
pesq() from pesq 0.0.4 accepts only two values for fs: 8000 (narrowband mode, covering the 300–3400 Hz telephone speech band) and 16000 (wideband mode, covering 50–7000 Hz, also known as ITU-T P.862.2). These constraints come from the underlying C reference implementation of ITU-T P.862, which was designed for telephony quality assessment at standard telephony sample rates and uses hardcoded filter coefficients calibrated for 8 kHz and 16 kHz. With fs=44100, pesq() raised BadSamplingRateError: ('Reference audio must be sampled at 8000Hz or 16000Hz.', 44100) immediately, before processing any audio. The pipeline’s exception handler wrapped the pesq() call in a broad try/except block designed to handle occasional corrupt recordings: except Exception as e: logger.warning(f'PESQ scoring failed: {e}'); return 4.5. The BadSamplingRateError (which is a subclass of Exception) was caught, logged at WARNING level (not ERROR), and the default score of 4.5 — the maximum possible PESQ value, representing “excellent” quality — was returned as the fallback. All 25,000 calls per month received a score of 4.5. The QA dashboard showed 100% of calls passing with excellent quality. The 3,000 calls per month that genuinely scored below 2.0 (background noise, echo, codec clipping, low volume) received no QA flag and no agent coaching. Customer complaint rates rose 40% over the 4-week period before the contact center’s QA manager escalated to the ops team after noticing that the “100% excellent” dashboard report was inconsistent with the volume of customer quality complaints reaching the complaints team directly.
The annotated buggy and fixed pesq call quality scoring pipeline, with correct preprocessing and exception scoping:
# Southfield Pesq Ltd. — pesq 0.0.4 BadSamplingRateError fix
# pesq 0.0.4; Python 3.9; voice call quality monitoring
# 25,000 recordings/month from 50 contact centers; 44100 Hz WAV
# QA threshold: PESQ < 2.0 → flag for QA review; > 3.0 → pass
# Problem: pesq(fs=44100, ...) raises BadSamplingRateError
# pesq() only accepts fs=8000 (narrowband) or fs=16000 (wideband)
# broad except handler returns 4.5 (excellent) as default
# 25,000 calls appear excellent; 3,000 poor calls unflagged
# Fix: resample to 16000 Hz with scipy.signal.resample_poly before pesq()
import math
import logging
import numpy as np
import soundfile
from scipy.signal import resample_poly
from pesq import pesq, BadSamplingRateError
logger = logging.getLogger(__name__)
PESQ_FLAG_THRESHOLD = 2.0 # below this → QA review required
PESQ_PASS_THRESHOLD = 3.0 # above this → automatic pass
TARGET_SR_WB = 16000 # wideband PESQ target sample rate
TARGET_SR_NB = 8000 # narrowband PESQ target sample rate
# ── BUGGY pipeline ────────────────────────────────────────────────────────────
def score_call_quality_buggy(ref_path: str, deg_path: str) -> float:
"""
BUG: passes native sample rate (44100 Hz) to pesq().
pesq() only accepts fs=8000 or fs=16000.
BadSamplingRateError raised for every call recording.
Broad except handler returns 4.5 (excellent) as fallback.
25,000 calls/month appear excellent → 3,000 poor calls unflagged.
pesq() error:
BadSamplingRateError: ('Reference audio must be sampled at 8000Hz or 16000Hz.', 44100)
"""
ref, rate = soundfile.read(ref_path, dtype='float32') # rate=44100
deg, _ = soundfile.read(deg_path, dtype='float32') # rate=44100
if ref.ndim > 1:
ref = ref.mean(axis=1) # stereo → mono
deg = deg.mean(axis=1)
try:
# BUG: fs=44100 raises BadSamplingRateError — only 8000 or 16000 accepted
score = pesq(rate, ref, deg, 'wb')
return score
except Exception as e:
# BUG: catches BadSamplingRateError and returns 4.5 (excellent)
# Every call appears excellent; no QA flags issued
logger.warning(f"PESQ scoring failed: {e}")
return 4.5 # maximum PESQ score — 25,000 false "excellent" scores/month
# ── FIXED pipeline ────────────────────────────────────────────────────────────
def resample_to_target(audio: np.ndarray, source_sr: int,
target_sr: int) -> np.ndarray:
"""
Resample audio to target_sr using polyphase filter.
Uses math.gcd to minimize up/down factors for efficiency.
Preserves speech frequency content through the downsampling.
Common conversions:
44100 → 16000: gcd=100, up=160, down=441
48000 → 16000: gcd=16000, up=1, down=3
8000 → 16000: gcd=8000, up=2, down=1
44100 → 8000: gcd=100, up=80, down=441
"""
if source_sr == target_sr:
return audio
gcd = math.gcd(source_sr, target_sr)
up = target_sr // gcd
down = source_sr // gcd
resampled = resample_poly(audio, up, down)
return resampled.astype(np.float32)
def score_call_quality_fixed(ref_path: str, deg_path: str,
mode: str = 'wb') -> float:
"""
FIX: resample to 16000 Hz (wideband) or 8000 Hz (narrowband) before pesq().
No broad exception suppression — BadSamplingRateError should never occur
after correct preprocessing, so if it does, it must propagate.
mode='wb': wideband PESQ (ITU-T P.862.2) → requires 16000 Hz
mode='nb': narrowband PESQ (ITU-T P.862) → requires 8000 Hz
"""
target_sr = TARGET_SR_WB if mode == 'wb' else TARGET_SR_NB
ref, source_sr = soundfile.read(ref_path, dtype='float32')
deg, _ = soundfile.read(deg_path, dtype='float32')
if ref.ndim > 1:
ref = ref.mean(axis=1) # stereo → mono
deg = deg.mean(axis=1)
# Resample to target_sr (pesq requirement: exactly 8000 or 16000 Hz)
ref_resampled = resample_to_target(ref, source_sr, target_sr)
deg_resampled = resample_to_target(deg, source_sr, target_sr)
# Trim to same length (pesq requires ref.shape == deg.shape)
min_len = min(len(ref_resampled), len(deg_resampled))
ref_resampled = ref_resampled[:min_len]
deg_resampled = deg_resampled[:min_len]
# No broad except — if pesq raises, the error propagates and pages on-call
score = pesq(target_sr, ref_resampled, deg_resampled, mode)
return score
def classify_call_quality(score: float) -> str:
"""Classify PESQ MOS-LQO score into QA action categories."""
if score < PESQ_FLAG_THRESHOLD:
return 'flag_for_qa_review'
if score < PESQ_PASS_THRESHOLD:
return 'flag_for_coaching'
return 'pass'
# ── Startup quality gate ──────────────────────────────────────────────────────
def check_pesq_at_startup():
"""
Score a clean reference signal against itself — expect score ≈ 4.5.
Raises RuntimeError if score is outside expected range.
Confirms pesq is functioning before accepting production traffic.
"""
t = np.linspace(0, 1.0, TARGET_SR_WB, dtype=np.float32)
tone = 0.5 * np.sin(2 * np.pi * 1000 * t) # 1 kHz sine, 1 second, 16000 Hz
score = pesq(TARGET_SR_WB, tone, tone, 'wb') # ref == deg → perfect quality
if not (4.4 <= score <= 4.5):
raise RuntimeError(
f"pesq startup check failed: expected score 4.4–4.5 for identical signals, "
f"got {score:.3f}. pesq may be malfunctioning."
)
# ── PESQ score reference (MOS-LQO scale) ─────────────────────────────────────
# 4.5 → Excellent (reference quality; ref == deg produces this)
# 4.0 → Good (slight degradation, imperceptible to most listeners)
# 3.5 → Fair (perceptible degradation, not annoying)
# 3.0 → Poor (annoying degradation; threshold for many QA passes)
# 2.0 → Bad (very annoying; boundary for QA escalation)
# 1.0 → Terrible (not usable)
# -0.5 → Minimum possible score
How pesq’s ITU-T telephony heritage, the BadSamplingRateError design, and default-score exception handlers combine to silently certify every call as excellent quality — and the correct preprocessing pattern for production PESQ deployments
The pesq() sample rate restriction — only 8000 or 16000 Hz accepted — exists because the ITU-T P.862 reference algorithm was designed in the late 1990s specifically for evaluating telephony codec quality, where 8 kHz (narrowband, G.711) and 16 kHz (wideband, G.722, G.711.1) were the two relevant operating points. The underlying C implementation uses hardcoded filter coefficients, perceptual weighting functions, and time-frequency resolution parameters derived from psychoacoustic models calibrated at these two rates; the algorithm does not generalize to arbitrary sample rates and explicitly rejects other values rather than producing meaningless scores silently. This design is intentional: a PESQ score computed on 44100 Hz audio labeled as 16 kHz would be technically invalid, and the ITU-T P.862 reference authors preferred an explicit error over a misleading score. The BadSamplingRateError message is specific and actionable: it names the problem (wrong sample rate), names the fix (resample to 8000 or 16000 Hz), and even names the value that was passed (44100). The only failure mode this design has is an exception handler that catches the error before it reaches a human or an alert. The fundamental problem with the broad except Exception: return 4.5 pattern is not just that it suppresses a recoverable error — it suppresses an error that indicates 100% failure rate on all calls, replacing it with a perfect score that actively misleads the QA team. A default score of 4.5 is worse than no score at all, because “no score” would surface as a gap in the dashboard, while “4.5” appears as valid data confirming excellent quality. The correct default behavior is to log the error with the full call recording path and the specific BadSamplingRateError message, mark the call’s PESQ score as null in the QA database, and emit an alert if the null-score rate exceeds a threshold (e.g., more than 1% of calls in a 1-hour window). This surfaces the preprocessing failure as an operational incident rather than burying it in a log file at WARNING level. The resampling fix — resample_poly(audio, up, down) with up = target_sr // gcd(source_sr, target_sr) and down = source_sr // gcd(source_sr, target_sr) — is accurate and efficient for the fixed sample rate pairs encountered in call recording platforms (44100 Hz, 48000 Hz, 8000 Hz), and correctly preserves the speech frequency content (300–7000 Hz for wideband, 300–3400 Hz for narrowband) through the downsampling. The startup quality gate — scoring a 1 kHz sine wave against itself and expecting a score near 4.5 — confirms that the pesq installation and preprocessing pipeline are functioning correctly before the service accepts production traffic. The retainer engagement was 2.0h: 0.5h triage (dashboard: 100% calls score 4.5; retrieve logs: 25,000 × “PESQ scoring failed: Reference audio must be sampled at 8000Hz or 16000Hz. 44100”; confirm all logs at WARNING level, below alert threshold); 0.75h root cause (pesq 0.0.4 BadSamplingRateError for fs other than 8000 or 16000 confirmed in pesq source; recording platform confirmed at 44100 Hz via soundfile.info() on 10 sample files; default score of 4.5 confirmed as false positive); 0.5h fix (resample_poly preprocessing; remove broad exception suppression; add startup quality gate; add null handling in QA database); 0.25h validation (100-call test: scores range 1.4–4.3; known noisy call: 1.7 < 2.0, flagged; known clean call: 4.1 > 3.0, pass; 2.0h total). Hours logged to HourTab with per-session breakdown.
Related retainer posts
- samplerate developer on retainer — python-samplerate 0.1.3; Python 3.9; voice transcription service; 20,000 recordings/month;
samplerate.resample()ratio isoutput_sr/input_sr; inverted tosource_sr/target_sr; 44100→16000: ratio = 2.756; output 2.756× too long; Whisper WER 95%+; fix:ratio = target_sr / source_sr— 1.5h - webrtcvad developer on retainer — webrtcvad 2.0.10; Python 3.9; voice activity detection pipeline;
vad.is_speech(frame, sample_rate)requires 8000, 16000, 32000, or 48000 Hz and 10, 20, or 30 ms frames; 44100 Hz input raisesError; broad handler marks all frames as silence; fix: resample to 16000 Hz + frame length calculation — 2.0h - pyworld developer on retainer — pyworld 0.3.4; Python 3.9; voice conversion pipeline;
pw.dio(audio, fs)+pw.harvest(audio, fs)require float64 input; float32 input raisesRuntimeError; broad handler returns flat pitch; fix:audio = audio.astype(np.float64)— 1.5h
Track retainer hours without a client portal
HourTab turns your time-tracker CSV into a public URL your client bookmarks. No login. No portal. CSV in, URL out.
See pricing →