pyogg developer on retainer: PyOgg.VorbisFile() returns int16 in [−32 768, 32 767] — developer casts .astype(np.float32) without dividing by 32 768 — emotion model predicts 100% neutral — 20 000 Ogg Vorbis call recordings per month — 3 weeks — pyogg developer on monthly retainer

PyOgg 0.6.14a1 • Python 3.9 • PyTorch 1.12; np.frombuffer(vf.buffer, dtype=np.int16).astype(np.float32) produces values in [−32 768.0, 32 767.0] not [−1.0, 1.0]; • Southfield Pyogg Ltd. (speech emotion recognition API; 20,000 Ogg Vorbis call recordings/month from 150 enterprise call centers; BiLSTM 4-class model: angry/happy/neutral/sad; batchnorm running_var=0.09 trained on [−1.0, 1.0]; inference input 32 768× too large; all hidden states saturate; ‘neutral’ always wins softmax; confidence 0.76–0.81; 3 weeks; fix: / 32768.0; 1.5h retainer engagement)

Southfield Pyogg Ltd. built a speech emotion recognition API that classified customer sentiment in call recordings for 150 enterprise call center clients, processing 20,000 Ogg Vorbis recordings per month. Each recording was decoded using PyOgg 0.6.14a1 and passed to a 4-class BiLSTM model (angry, happy, neutral, sad) trained internally on a labelled call center dataset. The engineering team chose PyOgg specifically to handle Ogg Vorbis files delivered by the clients’ VoIP platforms — Ogg Vorbis is a patent-free format widely used by telephony infrastructure — because adding libsndfile with Ogg Vorbis support required additional packaging effort on their container builds, while PyOgg provided Ogg Vorbis support through a minimal ctypes wrapper. The model had been trained using soundfile.read(path, dtype='float32'), which automatically normalises 16-bit PCM audio to float32 in [−1.0, 1.0]. When the team rewrote the inference pipeline to use PyOgg, they translated the loading code to np.frombuffer(vf.buffer, dtype=np.int16).astype(np.float32) without adding the / 32768.0 normalisation step.

PyOgg.VorbisFile(path).buffer exposes the decoded PCM data as a ctypes array of bytes. np.frombuffer(vf.buffer, dtype=np.int16) reinterprets these bytes as a 1-D int16 array; the values remain in [−32 768, 32 767] — the integer encoding of 16-bit signed PCM. .astype(np.float32) widens the dtype from int16 to float32 without any numeric rescaling: 32 767 becomes 32 767.0, −16 384 becomes −16 384.0. The model’s first layer was torch.nn.BatchNorm1d, trained with running_mean = 0.0 and running_var = 0.09 (computed over audio in [−1.0, 1.0]). In inference mode, BatchNorm1d computes output = (input − running_mean) / sqrt(running_var + eps) × γ + β. With an input value of 16 000.0: (16000.0 − 0.0) / sqrt(0.09 + 1e-5) ≈ 53 333 enters the subsequent BiLSTM gate activations. The tanh activation used in LSTM gates saturates to ±1.0 for inputs beyond approximately ±4; every gate for every timestep across all 20,000 recordings was pinned at ±1.0 regardless of emotional content. The BiLSTM produced an identical constant hidden-state sequence for every recording. The final linear classification layer received these constant hidden states and produced logits determined solely by its bias terms. ‘Neutral’ was the most frequent label in the training corpus (call center QA datasets tend toward neutral-dominant distributions); the linear layer accumulated the highest bias for class 2 (neutral), which won the softmax for every prediction. Confidence scores were 0.76–0.81 — a plausible range for an emotion classifier, not the 0.99+ that would trigger a sanity check. The issue ran for 3 weeks before a QA analyst at one enterprise client noticed their emotion distribution dashboard showed 100% neutral for a week containing a documented service outage with elevated customer frustration. Manual review of 10 flagged recordings confirmed obvious expressions of anger labeled neutral by the API.

The annotated buggy and fixed PyOgg int16 normalisation pipeline, with stereo handling and amplitude validation:

# Southfield Pyogg Ltd. — PyOgg 0.6.14a1 int16 normalisation fix
# PyOgg 0.6.14a1; Python 3.9; PyTorch 1.12
# Speech emotion recognition API; 20,000 Ogg Vorbis call recordings/month
# from 150 enterprise call centers; BiLSTM 4-class: angry/happy/neutral/sad
#
# Problem: PyOgg.VorbisFile().buffer contains int16 PCM in [-32768, 32767]
#          .astype(np.float32) widens dtype — values become [-32768.0, 32767.0]
#          model expects [-1.0, 1.0]; BatchNorm1d running_var=0.09 (trained on [-1.0,1.0])
#          (16000.0 - 0.0) / sqrt(0.09) = 53333 → BiLSTM tanh saturates to ±1.0
#          hidden states constant; 'neutral' (highest bias) wins softmax always
# Fix:     audio_int16.astype(np.float32) / 32768.0 → [-1.0, 0.99997]

import logging
import numpy as np
import pyogg
import torch

logger = logging.getLogger(__name__)

EMOTION_CLASSES = ['angry', 'happy', 'neutral', 'sad']
MODEL_SAMPLE_RATE = 16000  # Hz — model trained on 16 kHz mono float32 audio


# ── BUGGY pipeline ────────────────────────────────────────────────────────────

def classify_emotion_buggy(ogg_path: str, model: torch.nn.Module) -> str:
    """
    BUG: int16 PCM cast to float32 without /32768.0 normalisation.
    .astype(np.float32) keeps values in [-32768.0, 32767.0].
    BatchNorm1d amplifies 32768x scale error; BiLSTM gates saturate;
    all hidden states become constant; 'neutral' always wins softmax.
    """
    vf = pyogg.VorbisFile(ogg_path)
    audio_int16 = np.frombuffer(vf.buffer, dtype=np.int16)
    audio = audio_int16.astype(np.float32)   # BUG: no / 32768.0
    # audio.max() = 32767.0 — model expects 1.0

    with torch.no_grad():
        tensor = torch.from_numpy(audio).unsqueeze(0)  # (1, n_samples)
        logits = model(tensor)
    return EMOTION_CLASSES[logits.argmax(dim=-1).item()]


# ── FIXED pipeline ────────────────────────────────────────────────────────────

def classify_emotion_fixed(ogg_path: str, model: torch.nn.Module) -> str:
    """
    FIX: normalise int16 PCM to float32 in [-1.0, 0.99997] by /32768.0.
    int16 range: [-32768, 32767]; divide by 2^15 = 32768.
    32767 / 32768 = 0.99997 — not 1.0 (asymmetric); this matches soundfile
    normalisation convention and is correct for 16-bit signed PCM.
    Also downmix stereo (interleaved L/R) to mono via reshape + mean.
    """
    vf = pyogg.VorbisFile(ogg_path)
    audio_int16 = np.frombuffer(vf.buffer, dtype=np.int16)

    # normalise int16 PCM to float32 in [-1.0, 0.99997]
    audio = audio_int16.astype(np.float32) / 32768.0

    # stereo → mono: interleaved (L0, R0, L1, R1, ...) → average channels
    if vf.channels == 2:
        audio = audio.reshape(-1, 2).mean(axis=1)
    elif vf.channels != 1:
        raise ValueError(
            f"Unexpected channel count: {vf.channels}. "
            "PyOgg.VorbisFile supports mono (1) and stereo (2)."
        )

    # amplitude validation: post-normalisation audio must be in [-1.0, 1.0]
    max_abs = float(np.abs(audio).max())
    if max_abs > 1.0:
        logger.error(
            f"Post-normalisation amplitude {max_abs:.4f} > 1.0. "
            "Check dtype: PyOgg.VorbisFile() returns int16; must divide by 32768.0. "
            f"Path: {ogg_path}"
        )
        raise ValueError(
            f"Audio amplitude {max_abs:.4f} out of [-1.0, 1.0] range after normalisation. "
            "Missing / 32768.0 in int16 → float32 conversion."
        )

    with torch.no_grad():
        tensor = torch.from_numpy(audio).unsqueeze(0)  # (1, n_samples)
        logits = model(tensor)

    predicted_class = EMOTION_CLASSES[logits.argmax(dim=-1).item()]
    confidence = float(torch.softmax(logits, dim=-1).max())

    # sanity gate: uniform high confidence across all calls → possible saturation
    if confidence > 0.98:
        logger.warning(
            f"Emotion confidence {confidence:.3f} > 0.98 for {ogg_path}. "
            "If all predictions share the same class with high confidence, "
            "check audio.max() before normalisation — should be ~32767, not ~1.0."
        )

    return predicted_class

How PyOgg’s raw int16 output, the difference between dtype widening and amplitude normalisation, and the absence of a range error combine to silently corrupt 20 000 emotion classifications — and the correct normalisation for production PyOgg deployments

The core issue is a distinction between two conceptually different operations that look syntactically similar: dtype widening and amplitude normalisation. .astype(np.float32) converts the numeric type of each array element without changing its value: np.int16(32767) becomes np.float32(32767.0). Amplitude normalisation divides by the maximum possible absolute value: np.int16(32767).astype(np.float32) / 32768.0 = 0.99997. The two operations produce identical results only when the integer values are already in [−1, 1] — which is never true for 16-bit PCM audio. The confusion arises because soundfile.read(path, dtype='float32') performs both steps internally: it reads int16 and returns float32 in [−1.0, 1.0], hiding the normalisation from the caller. When switching from soundfile to PyOgg, the developer saw np.frombuffer(vf.buffer, dtype=np.int16) and correctly added .astype(np.float32) for the dtype, but did not know that soundfile had been silently normalising. The error is invisible at runtime because there is no range check on the model’s input layer: torch.nn.BatchNorm1d does not raise for out-of-range inputs in inference mode; it simply applies the stored running statistics, amplifying the scale error rather than flagging it. The BatchNorm1d output for a value of 16 000.0 is 53 333 (see FAQ above), which is orders of magnitude above the LSTM tanh saturation threshold of ±4. The tanh function maps all values above ≈4 to 1.0 and all values below ≈−4 to −1.0; the exact value of 53 333 vs 50 000 makes no difference to the LSTM output. The confidence of 0.76–0.81 (rather than ≈1.0) arises because the linear classification layer has 4 bias terms with different magnitudes; softmax over 4 different saturated-bias logits produces moderate probabilities rather than hard maxima. The detection path is to print audio.max() immediately after loading: a correctly normalised float32 array has max ≈ 0.9; an unnormalised int16-cast array has max = 32 767.0. A single-line assert abs(audio).max() ≤ 1.0 would have caught this immediately. The divisor is 32 768 (not 32 767): using 32 767 makes the maximum positive value exactly 1.0 but makes the minimum negative value −1.0001 (since −32 768 / 32 767 = −1.0000305); the standard convention (and soundfile’s internal implementation) uses 32 768 to produce a symmetric range where the minimum is exactly −1.0 and the maximum is 0.99997. The retainer engagement was 1.5h: 0.5h triage (QA report: 100% neutral distribution; check audio.max() post-load: 32 767.0; confirms missing / 32 768.0); 0.5h root cause (PyOgg returns int16; soundfile training pipeline normalised silently; .astype(float32) is dtype widening not normalisation; batchnorm amplifies 32 768× scale error); 0.5h fix (add / 32 768.0; stereo reshape; amplitude validation gate; re-infer 3-week backlog; 1.5h total). Hours logged to HourTab with per-session breakdown.

Related retainer posts


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 →