Skip to content

fix: Validate audio duration before speaker embedding (#4572) - #4627

Merged
beastoin merged 3 commits into
mainfrom
fix/diarizer-short-audio-validation-4572
Feb 6, 2026
Merged

beastoin merged 3 commits into
mainfrom
fix/diarizer-short-audio-validation-4572

Conversation

@beastoin

@beastoin beastoin commented Feb 5, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • Add 3-layer audio duration validation to prevent pyannote wespeaker fbank AssertionError on short audio clips (~25ms, 400 samples)
  • Server (diarizer/embedding.py): Validates via torchaudio.info() before inference, returns HTTP 422 with structured error instead of 500
  • Client (utils/stt/speaker_embedding.py): Validates WAV duration via wave module before API call, raises ValueError
  • Producer (routers/transcribe.py): Checks extracted duration after ring buffer clamping, skips short clips before encoding

Root Cause

In realtime speaker identification, audio ring buffer clamping (extract_start = max(buffer_start_ts, ...)) can shrink the extraction range to near-zero duration. The existing guard only checks extract_end > extract_start (any positive duration passes), allowing ~25ms clips through to the diarizer where they crash the wespeaker fbank model.

Configuration

Minimum threshold defaults to 0.5s, configurable via MIN_EMBEDDING_AUDIO_DURATION env var (shared across client and server).

Test Plan

  • 12 new unit tests (test_short_audio_embedding.py) covering:
    • WAV duration parsing (multiple sample rates, empty/garbage/truncated bytes)
    • Boundary tests (exactly at threshold passes, just below rejects)
    • Short audio clips raise ValueError (the 25ms crash case)
    • Threshold default value (0.5s)
  • All 57 existing speaker tests pass (no regressions)
  • Full backend/test.sh passes (212 tests, 0 failures)

Risks / Edge Cases

  • wave module only works for WAV format; non-WAV uploads to diarizer validated by torchaudio.info() fallback
  • Threshold applies to both v1 and v2 embedding endpoints on server side (v1 could also crash on short audio)

Closes #4572

by AI for @beastoin

…izer crash (#4572)

Short audio clips (~25ms) crash the pyannote wespeaker fbank model with
AssertionError (100 errors/hour in prod). Add 3-layer defense:

- Server (diarizer): validate duration via torchaudio.info(), return 422
- Client (speaker_embedding): validate WAV duration before API call
- Producer (transcribe): check extracted duration after buffer clamping

Minimum threshold: 0.5s (configurable via MIN_EMBEDDING_AUDIO_DURATION env var).

Closes #4572

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces validation for audio duration to prevent crashes on short clips when generating speaker embeddings. The changes are applied on the server, client, and producer levels. My review focuses on ensuring the validation is consistently and correctly applied. I've identified a critical issue where the validation is missing from one of the server endpoints, and another high-severity issue regarding an inconsistent threshold being used in the producer logic. The new unit tests are well-written and provide good coverage for the changes.

Comment thread backend/diarizer/embedding.py Outdated
Comment on lines +82 to +96
# Validate audio duration before inference (issue #4572)
try:
info = torchaudio.info(file_path)
duration = info.num_frames / info.sample_rate if info.sample_rate > 0 else 0.0
except Exception:
duration = 0.0
if duration < MIN_EMBEDDING_AUDIO_DURATION:
raise HTTPException(
status_code=422,
detail={
"error": "audio_too_short",
"min_duration": MIN_EMBEDDING_AUDIO_DURATION,
"actual_duration": round(duration, 3),
},
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

The duration validation has been added to embedding_endpoint_v2, but it's missing from the v1 embedding_endpoint. As noted in the PR description, the v1 endpoint is also vulnerable to crashing on short audio clips. This leaves a known crash path open.

To fix this and avoid code duplication, I recommend extracting the validation logic into a private helper function and calling it from both embedding_endpoint and embedding_endpoint_v2 after the file is saved.

Example helper function:

def _validate_audio_duration(file_path: str):
    """Validate audio duration is above the minimum threshold."""
    try:
        info = torchaudio.info(file_path)
        duration = info.num_frames / info.sample_rate if info.sample_rate > 0 else 0.0
    except Exception:
        duration = 0.0
    if duration < MIN_EMBEDDING_AUDIO_DURATION:
        raise HTTPException(
            status_code=422,
            detail={
                "error": "audio_too_short",
                "min_duration": MIN_EMBEDDING_AUDIO_DURATION,
                "actual_duration": round(duration, 3),
            },
        )

Comment on lines +1392 to +1398
if extracted_duration < SPEAKER_ID_MIN_AUDIO:
print(
f"Speaker ID: extracted audio too short ({extracted_duration:.2f}s < {SPEAKER_ID_MIN_AUDIO}s) after buffer clamping",
uid,
session_id,
)
return

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

This check uses SPEAKER_ID_MIN_AUDIO (hardcoded to 2.0s), which is inconsistent with the MIN_EMBEDDING_AUDIO_DURATION (configurable, defaults to 0.5s) used elsewhere for this fix. Using the 2.0s threshold is overly restrictive and may reject valid clips (between 0.5s and 2.0s) that would not cause a crash.

Please use MIN_EMBEDDING_AUDIO_DURATION for this check to align with the client-side and diarizer-side validation. You'll need to add MIN_EMBEDDING_AUDIO_DURATION to your import from utils.stt.speaker_embedding.

Suggested change
if extracted_duration < SPEAKER_ID_MIN_AUDIO:
print(
f"Speaker ID: extracted audio too short ({extracted_duration:.2f}s < {SPEAKER_ID_MIN_AUDIO}s) after buffer clamping",
uid,
session_id,
)
return
if extracted_duration < MIN_EMBEDDING_AUDIO_DURATION:
print(
f"Speaker ID: extracted audio too short ({extracted_duration:.2f}s < {MIN_EMBEDDING_AUDIO_DURATION}s) after buffer clamping",
uid,
session_id,
)
return

@beastoin

beastoin commented Feb 6, 2026

Copy link
Copy Markdown
Collaborator Author

⚡ P0 blocker — this fixes #4572 (Diarizer AssertionError on short audio clips). PR is mergeable and ready. Requesting review to unblock.

@beastoin

beastoin commented Feb 6, 2026

Copy link
Copy Markdown
Collaborator Author

Which steps can increase the extra costs for CPU, memory, and I/O, and how would you solve this? Please note that these are all real-time APIs, and the extra cost must be considered carefully.

)

Address CTO cost concern: torchaudio.info() opened files twice (extra I/O
on every real-time request). Replaced with stdlib wave.open() which only
reads the WAV header (~44 bytes). Also added validation to v1 endpoint
via shared _validate_audio_duration helper.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@beastoin

beastoin commented Feb 6, 2026

Copy link
Copy Markdown
Collaborator Author

Cost analysis for each validation step

Step File What it does CPU Memory I/O Extra cost
1 speaker_embedding.py _get_wav_duration() — stdlib wave.open() on in-memory bytes ~0 ~0 None (bytes already in memory) Negligible
2 embedding.py torchaudio.info(file_path) → now wave.open(file_path) ~0 ~0 44-byte header read (was: full file re-open via torchaudio) Fixed — replaced torchaudio with stdlib wave
3 transcribe.py extract_end - extract_start float comparison ~0 ~0 None (pure arithmetic on existing values) Zero

What changed in this push

  • Removed torchaudio import from embedding.py — replaced with stdlib wave (header-only read, ~44 bytes vs torchaudio reopening the entire file)
  • Added validation to v1 endpoint too — shared _validate_audio_duration() helper used by both v1 and v2 (addresses Gemini review feedback)
  • No new dependencies — wave is Python stdlib

Why the cost is minimal

All three checks run before the expensive GPU inference call. For short/invalid audio, we reject early and save the full inference cost. The only file I/O added is a 44-byte WAV header read via stdlib wave.open(), which is orders of magnitude cheaper than the pyannote inference that follows.


by AI for @beastoin

@beastoin

beastoin commented Feb 6, 2026

Copy link
Copy Markdown
Collaborator Author

Required fixes before merge:

  • backend/diarizer/embedding.py:15 The new WAV-only duration check will reject non-WAV uploads (docstring says "wav, mp3, etc."); either restrict the endpoint to WAV and update docs/error, or use a format-agnostic duration reader to avoid 422s for mp3/etc.
  • backend/tests/unit/test_short_audio_embedding.py:91 Move the in-function import requests to module top-level to comply with the no in-function imports rule.

Please push a follow-up commit when ready.


by AI for @beastoin

…-level (#4572)

- _get_wav_duration_from_file → _get_audio_duration_from_file: tries
  stdlib wave first (fast, header-only), falls back to torchaudio.info()
  for mp3/flac/ogg. Prevents false 422 rejections for non-WAV uploads.
- Move in-function `import requests` to module top-level in test file.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@beastoin

beastoin commented Feb 6, 2026

Copy link
Copy Markdown
Collaborator Author

Follow-up commit pushed (d91b087), addressing both review items:

1. Non-WAV format support (embedding.py)

  • Renamed _get_wav_duration_from_file → _get_audio_duration_from_file
  • Tries stdlib wave.open() first (fast, header-only read for WAV)
  • Falls back to torchaudio.info() for non-WAV formats (mp3, flac, ogg, etc.)
  • torchaudio is already a transitive dependency via pyannote.audio, no new deps added
  • WAV files see zero perf regression (same fast path); non-WAV files get correct duration instead of false 422

2. Import moved to top-level (test_short_audio_embedding.py)

  • import requests moved from inside test_boundary_at_threshold_passes_validation to module-level imports

All 12 tests pass.

@beastoin

beastoin commented Feb 6, 2026

Copy link
Copy Markdown
Collaborator Author

Required fixes before merge:

  • None found in the follow-up; the non-WAV duration handling and top-level import fix look good.

Tests: bash backend/test.sh — pass (1 warning: Pydantic @validator deprecation in models/memories.py).

Ready to merge when you are.


by AI for @beastoin

@beastoin
beastoin merged commit d3a20a4 into main Feb 6, 2026
1 check passed
@beastoin
beastoin deleted the fix/diarizer-short-audio-validation-4572 branch February 6, 2026 04:21
@beastoin

beastoin commented Feb 6, 2026

Copy link
Copy Markdown
Collaborator Author

lgtm

ellaaicare pushed a commit to ellaaicare/omi that referenced this pull request Apr 12, 2026
…4572) (BasedHardware#4627)

* fix: Validate audio duration before speaker embedding to prevent diarizer crash (BasedHardware#4572)

Short audio clips (~25ms) crash the pyannote wespeaker fbank model with
AssertionError (100 errors/hour in prod). Add 3-layer defense:

- Server (diarizer): validate duration via torchaudio.info(), return 422
- Client (speaker_embedding): validate WAV duration before API call
- Producer (transcribe): check extracted duration after buffer clamping

Minimum threshold: 0.5s (configurable via MIN_EMBEDDING_AUDIO_DURATION env var).

Closes BasedHardware#4572

* perf: replace torchaudio.info with stdlib wave for duration check (BasedHardware#4572)

Address CTO cost concern: torchaudio.info() opened files twice (extra I/O
on every real-time request). Replaced with stdlib wave.open() which only
reads the WAV header (~44 bytes). Also added validation to v1 endpoint
via shared _validate_audio_duration helper.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix: support non-WAV audio in duration validation, move import to top-level (BasedHardware#4572)

- _get_wav_duration_from_file → _get_audio_duration_from_file: tries
  stdlib wave first (fast, header-only), falls back to torchaudio.info()
  for mp3/flac/ogg. Prevents false 422 rejections for non-WAV uploads.
- Move in-function `import requests` to module top-level in test file.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

---------

Co-authored-by: Claude Opus 4.6 <[email protected]>
Glucksberg pushed a commit to Glucksberg/omi-local that referenced this pull request Apr 28, 2026
…4572) (BasedHardware#4627)

* fix: Validate audio duration before speaker embedding to prevent diarizer crash (BasedHardware#4572)

Short audio clips (~25ms) crash the pyannote wespeaker fbank model with
AssertionError (100 errors/hour in prod). Add 3-layer defense:

- Server (diarizer): validate duration via torchaudio.info(), return 422
- Client (speaker_embedding): validate WAV duration before API call
- Producer (transcribe): check extracted duration after buffer clamping

Minimum threshold: 0.5s (configurable via MIN_EMBEDDING_AUDIO_DURATION env var).

Closes BasedHardware#4572

* perf: replace torchaudio.info with stdlib wave for duration check (BasedHardware#4572)

Address CTO cost concern: torchaudio.info() opened files twice (extra I/O
on every real-time request). Replaced with stdlib wave.open() which only
reads the WAV header (~44 bytes). Also added validation to v1 endpoint
via shared _validate_audio_duration helper.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix: support non-WAV audio in duration validation, move import to top-level (BasedHardware#4572)

- _get_wav_duration_from_file → _get_audio_duration_from_file: tries
  stdlib wave first (fast, header-only), falls back to torchaudio.info()
  for mp3/flac/ogg. Prevents false 422 rejections for non-WAV uploads.
- Move in-function `import requests` to module top-level in test file.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

---------

Co-authored-by: Claude Opus 4.6 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Diarizer AssertionError: window size validation fails for short audio clips

1 participant