nnresample developer on retainer: nnresample.resample() requires a 1-D array — stereo float32 input raises ValueError in upfirdn — broad handler returns original audio at wrong sample rate — librosa processes 44100 Hz audio labeled as 22050 Hz — 30 000 segments per month indexed with wrong temporal features — 2 weeks — nnresample developer on monthly retainer

nnresample 0.0.3 • Python 3.9; nnresample.resample(x, up, down) requires a 1-D float64 array • Northfield Nnresample Ltd. (podcast audio search indexing; 30,000 segments/month from 500 studios; source: 44100 Hz stereo WAV (shape (n_samples, 2)); nnresample.resample(audio, 1, 2) raises ValueError in upfirdn; broad handler returns original 44100 Hz audio unchanged; librosa MFCC at double frame rate; 30,000 segments indexed with wrong temporal features; audio search returns 0 matches for 95% of queries; fix: audio.mean(axis=1).astype(np.float64) before nnresample.resample(); 1.5h retainer engagement)

Northfield Nnresample Ltd. built a podcast audio search indexing service. Podcast studios uploaded stereo WAV files at 44100 Hz; the pipeline resampled each file to 22050 Hz mono and extracted MFCC features using librosa, which were indexed by a FAISS similarity search engine to power episode discovery. The resampling step used nnresample 0.0.3, chosen for its neural-network-designed anti-aliasing FIR filters which provide better spectral accuracy than naive polyphase resampling at the 2:1 downsampling ratio. Files were loaded with soundfile.read(path, dtype='float32'), which returns a 2-D float32 array of shape (n_samples, 2) for stereo WAV files. The pipeline called nnresample.resample(audio, up=1, down=2) directly on this 2-D array, then passed the result to librosa for MFCC extraction. The engineer who wrote the pipeline assumed nnresample would handle the channel dimension the way librosa does — by processing along the last axis — because both libraries accept numpy arrays and both are common in audio ML pipelines.

nnresample.resample(x, up, down) from nnresample 0.0.3 passes x directly to scipy.signal.upfirdn(h, x, up=up, down=down), where h is the neural-network-designed anti-aliasing filter. scipy.signal.upfirdn requires x to be a 1-D array; for a 2-D input of shape (n_samples, 2), it raises ValueError: Invalid rank of array: upfirdn requires a 1-D input array. This error is raised immediately, before any resampling computation occurs. The pipeline wrapped the nnresample.resample() call in a broad try/except block designed to handle occasional corrupt audio files: except Exception as e: logger.warning(f'Resampling failed: {e}'); return audio. The ValueError from upfirdn was caught, logged at WARNING level (below the alert threshold), and the original audio array was returned as the fallback — still at 44100 Hz, still float32, still shape (n_samples, 2). The returned array looked valid: a numpy float32 array with amplitude values in [-1.0, 1.0]. The caller extracted the left channel with resampled[:, 0] (which worked on the original shape) and passed it to librosa.feature.mfcc(y=audio_44k, sr=22050). librosa computed MFCCs using its default hop_length=512; at the labeled sample rate of 22050 Hz this represents 23.2 ms per frame, but the actual audio was at 44100 Hz, so each frame covered only 11.6 ms. A 30-second clip at 44100 Hz produced 2,580 MFCC frames instead of the expected 1,290. The mel filter bank was also miscalibrated: its frequency bins were computed for 22050 Hz audio but applied to a signal at 44100 Hz, mapping energy from the 0–22050 Hz range into mel bins designed for the 0–11025 Hz range. All 30,000 segments per month were indexed with these double-density, frequency-shifted MFCC features. The FAISS index was internally consistent — segments with similar content clustered together — but was completely incompatible with the reference corpus, which had been correctly resampled. Similarity queries against the reference corpus returned 0 matches for 95% of queries. Studio customers reported that episode search had stopped working two weeks after a Docker image upgrade that had changed the scipy version and therefore the upfirdn error message format.

The annotated buggy and fixed nnresample audio indexing pipeline, with correct array preparation and output length validation:

# Northfield Nnresample Ltd. — nnresample 0.0.3 1-D array requirement fix
# nnresample 0.0.3; Python 3.9; scipy 1.7.3
# podcast audio search indexing; 30,000 segments/month from 500 studios
# source: 44100 Hz stereo WAV; target: 22050 Hz mono for librosa MFCC
# Problem: nnresample.resample() requires 1-D array
#          stereo (n_samples, 2) causes upfirdn ValueError
#          broad handler returns original 44100 Hz audio as fallback
#          librosa processes 44100 Hz audio labeled 22050 Hz
#          MFCCs at double frame rate — similarity search useless
# Fix: mean(axis=1) + astype(float64) before nnresample.resample()

import math
import logging
import numpy as np
import soundfile
import librosa
import nnresample

logger = logging.getLogger(__name__)

SOURCE_SR = 44100
TARGET_SR = 22050
UP   = TARGET_SR // math.gcd(SOURCE_SR, TARGET_SR)   # = 1
DOWN = SOURCE_SR // math.gcd(SOURCE_SR, TARGET_SR)   # = 2


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

def extract_mfcc_buggy(path: str) -> np.ndarray:
    """
    BUG: passes stereo (n_samples, 2) float32 array to nnresample.resample().
    upfirdn raises ValueError: 'Invalid rank of array'.
    Broad handler returns original 44100 Hz audio as fallback.
    librosa.feature.mfcc called with sr=22050 on 44100 Hz audio.
    MFCCs at 2x expected frame rate; wrong frequency bins.
    30,000 segments indexed wrong; similarity search returns 0 matches.
    """
    audio, sr = soundfile.read(path, dtype='float32')
    # audio.shape = (n_samples, 2) for stereo files — upfirdn will fail
    try:
        # BUG: audio is 2-D — upfirdn raises ValueError
        resampled = nnresample.resample(audio, UP, DOWN)
    except Exception as e:
        # BUG: returns original 44100 Hz audio — looks valid, is wrong
        logger.warning(f"Resampling failed: {e}")
        resampled = audio   # still 44100 Hz, still (n_samples, 2)
    mono = resampled[:, 0] if resampled.ndim > 1 else resampled
    # BUG: sr=22050 but mono is at 44100 Hz — double frame rate
    mfccs = librosa.feature.mfcc(y=mono, sr=TARGET_SR, n_mfcc=20)
    return mfccs.T   # (n_frames, 20) — but n_frames is 2x expected


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

def to_mono_float64(audio: np.ndarray) -> np.ndarray:
    """
    Convert audio to 1-D float64 mono array for nnresample.
    Handles (n_samples,), (n_samples, n_channels), (n_channels, n_samples).
    """
    if audio.ndim == 1:
        return audio.astype(np.float64)
    # channels-last: (n_samples, n_channels)
    if audio.shape[0] > audio.shape[1]:
        return audio.mean(axis=1).astype(np.float64)
    # channels-first: (n_channels, n_samples)
    return audio.mean(axis=0).astype(np.float64)


def extract_mfcc_fixed(path: str) -> np.ndarray:
    """
    FIX: convert to 1-D float64 mono before nnresample.resample().
    No broad exception suppression — ValueError should not occur after
    correct preparation; if it does, it must propagate to surface the bug.
    Output length validation catches any future handler fallbacks.
    """
    audio, sr = soundfile.read(path, dtype='float64')
    if sr != SOURCE_SR:
        raise ValueError(
            f"Unexpected source sample rate {sr} Hz in {path}; "
            f"expected {SOURCE_SR} Hz. Update resampling constants."
        )

    mono = to_mono_float64(audio)   # 1-D float64, (n_samples,)

    # No broad except — ValueError from upfirdn must not be suppressed
    resampled = nnresample.resample(mono, UP, DOWN)   # returns float64

    # Output length validation — catches fallbacks returning wrong-length audio
    expected_len = round(len(mono) * UP / DOWN)
    if abs(len(resampled) - expected_len) > 2:
        raise RuntimeError(
            f"nnresample output length {len(resampled)} != expected "
            f"{expected_len} for {path}. Possible handler fallback returning "
            f"original audio (len={len(mono)}) instead of resampled output."
        )

    resampled_f32 = resampled.astype(np.float32)
    mfccs = librosa.feature.mfcc(
        y=resampled_f32,
        sr=TARGET_SR,       # 22050 Hz — matches actual resampled rate
        n_mfcc=20,
        hop_length=512,
        n_fft=2048,
    )
    return mfccs.T   # (n_frames, 20) — correct temporal scale


# ── Startup validation ────────────────────────────────────────────────────────

def check_nnresample_at_startup():
    """
    Resample a 1-second 44100 Hz tone to 22050 Hz.
    Confirm output length is 22050 ± 2 samples.
    Raises RuntimeError if output length is wrong.
    """
    tone = np.sin(2 * np.pi * 440 * np.linspace(0, 1, SOURCE_SR))
    resampled = nnresample.resample(tone, UP, DOWN)
    if abs(len(resampled) - TARGET_SR) > 2:
        raise RuntimeError(
            f"nnresample startup check failed: resampled 1-second "
            f"{SOURCE_SR} Hz tone, expected {TARGET_SR} samples, "
            f"got {len(resampled)}. nnresample may be malfunctioning."
        )

How nnresample’s scipy.signal.upfirdn dependency, the 1-D array constraint, and default-audio exception handlers combine to silently index 30,000 audio segments per month with wrong temporal features — and the correct mono float64 preparation pattern for production nnresample deployments

The nnresample.resample() 1-D array constraint exists because scipy.signal.upfirdn — the function nnresample delegates to for the actual convolution — processes a single signal at a time and does not broadcast across a channel dimension. Unlike scipy.signal.resample_poly (which accepts N-D arrays and processes along a specified axis) or librosa.resample (which also handles channels), upfirdn is a low-level filtered up-down resampling primitive that expects a 1-D signal as its direct input. nnresample does not add a dimension-handling wrapper; it passes the input array to upfirdn as-is. This design is intentional: nnresample is a thin wrapper around scipy whose value is in the neural-network-designed filter coefficients, not in providing a high-level channel-aware API. The ValueError from upfirdn is unambiguous: “Invalid rank of array: upfirdn requires a 1-D input array” (scipy 1.7.x) names both the problem (wrong rank) and the fix (reduce to 1-D). The only failure mode this design has is an exception handler that catches the ValueError and returns the original audio as if resampling had succeeded. The fundamental problem with the broad except Exception: return audio pattern in a resampling pipeline is that the returned fallback audio — the original 44100 Hz array — is indistinguishable from successfully-resampled audio when inspected as a numpy array: same dtype, same amplitude range, similar length. The caller has no mechanism to detect that resampling failed. The correct fallback behavior is to log the error with the full file path, the input array shape (which will show (n_samples, 2)), and the exception message, and then raise the exception or enqueue the file for manual review — not to return an array that will produce silently wrong features downstream. The mono conversion — audio.mean(axis=1).astype(np.float64) for channels-last stereo — produces a 1-D float64 array that upfirdn accepts; using mean rather than selecting a single channel (e.g., audio[:, 0]) preserves both channels’ content and avoids introducing a 3 dB amplitude difference between mono-mixed and single-channel audio that would create distance discontinuities in the MFCC similarity space. The float64 cast ensures numerical compatibility with nnresample’s internal filter arithmetic across all scipy versions. The output length validation — assert abs(len(resampled) - round(len(input) * UP / DOWN)) <= 2 — catches any future exception handler fallbacks that return the original-length array instead of the correctly-resampled output. The retainer engagement was 1.5h: 0.5h triage (search dashboard: 0% match rate for 95% of queries; retrieve resampling logs: 30,000 × “Resampling failed: Invalid rank of array: upfirdn requires a 1-D input array” at WARNING level; alert threshold not breached; check audio array shapes in logs — (n_samples, 2) confirmed); 0.5h root cause (nnresample 0.0.3 passes input to upfirdn without dimension handling confirmed in nnresample source; soundfile.read() returns (n_samples, 2) for stereo files confirmed; original audio returned as fallback confirmed by adding output-shape logging); 0.25h fix (mean(axis=1) + float64 cast; remove broad exception suppression; output length validation; re-trigger full reindex job); 0.25h validation (100-file test: output lengths within 2 samples of expected; MFCC frames at 1,290 for 30-second clips, confirming 22050 Hz processing; similarity precision on held-out test set 94%; 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 →