Files
VoiceStudio/backend/services/transcript_diarization.py
Palash Debnath 87fe27d5a0 fix: translation provider errors, agent failure causes, M4A diarization (rewrites of #4356, #4357, #4337) (#4371)
* fix(translate): show the paid provider's own reason when it rejects a request

raise_for_status() discarded the provider's error body, so a wrong-provider,
expired or over-quota key surfaced as a bare "403 Forbidden for url ...".
Translator.translate() now raises TranslationProviderError naming the
provider and status, quoting the provider's message (DeepL message,
Microsoft/Google error.message, capped and with the key redacted), plus a
next step for 401/403, DeepL's 456 quota, 429 and 5xx.

Independent rewrite inspired by #4357 by @tng7576650-commits.

* fix(transcribe): decode uploads libsndfile cannot read before speaker diarization

Accurate transcription with speaker labels passed the raw upload to the
diarization pipeline. Transcription decodes through ffmpeg, but pyannote
reads through soundfile/torchaudio and the native Sortformer reads WAV, so
an M4A/AAC upload transcribed fine and then lost its speaker labels
(DIARIZATION_FAILED). diarize_segments() now hands both backends a
temporary WAV decoded with the shared load_audio() fallback chain when
libsndfile cannot open the file, and removes it afterwards.

Independent rewrite inspired by #4337 by @Error404-page.

* fix(dub): agent translation failures name their cause instead of an exit code

- agentProviderFailure() also reads the CLI's stderr: diagnostic lines that
  report an expired login or 401/403, a 429 or usage limit, or an
  unsupported model become AgentAuthenticationError / AgentRateLimitError /
  AgentModelError with a next step (never the raw provider text). Lines that
  are not diagnostics, such as translated dialogue, are ignored.
- An unknown non-zero exit appends the last diagnostic stderr line,
  scrubbed and capped at 240 characters.
- A second run while one is active is AgentBusyError and says which docks
  can hold the runner; the LLM bridge still answers it as a retryable 429.

Independent rewrite inspired by #4356 by @tng7576650-commits.

* docs(changelog): #4371 rewrites

* fix: review findings on #4371

- Translation: a JSON string error body is the provider's explanation.
- Agent stderr: 'not logged in', 'login expired' and 'usage limit reached'
  lines count as diagnostics; stderr only classifies a failure when the CLI
  exited non-zero, so a logged-and-retried 429 no longer rejects a good run.
- Diarization: a request cancelled while an upload is decoded never starts
  the native child.
- Test fixture keys are built at runtime so the secret scan stays clean.

* chore(security): ignore the synthetic translation-test fixture gitleaks saw in #4371's first commit

* fix(translate): redact the effective key in a provider error at any length (#4371)

* fix(translate): redact the key before collapsing whitespace in provider errors (#4371)
2026-11-23 13:00:25 +05:30

118 lines
4.6 KiB
Python

"""Speaker labels for file transcription (`POST /transcribe`, accurate mode).
Reuses the dub pipeline's diarization loader and overlap assignment so both
features pick the same backend (pyannote or native Sortformer) and label
speakers the same way ("Speaker 1", "Speaker 2", …).
"""
from __future__ import annotations
import contextlib
import logging
import os
import tempfile
from typing import Iterator, Optional
logger = logging.getLogger("omnivoice.transcribe")
MAX_SPEAKER_HINT = 20
def parse_speaker_hint(value: Optional[str]) -> Optional[int]:
"""Multipart `num_speakers`: a positive int up to ``MAX_SPEAKER_HINT``, else None."""
try:
count = int((value or "").strip())
except ValueError:
return None
return count if 1 <= count <= MAX_SPEAKER_HINT else None
@contextlib.contextmanager
def _diarizable_audio(audio_path: str) -> Iterator[str]:
"""A path both diarization backends can open.
pyannote reads through soundfile/torchaudio and the native Sortformer reads
WAV, so an upload libsndfile cannot open (M4A/AAC, some MP3/WebM builds) is
decoded once with the shared decoder (torchaudio, soundfile, then the
ffmpeg CLI) into a temporary WAV that is removed afterwards. A file
libsndfile already reads is passed through untouched.
"""
import soundfile as sf
try:
readable = not os.path.isfile(audio_path) or bool(sf.info(audio_path))
except Exception:
readable = False
if readable:
yield audio_path
return
from services.audio_io import load_audio
waveform, sample_rate = load_audio(audio_path)
handle, wav_path = tempfile.mkstemp(prefix="diarize-", suffix=".wav")
os.close(handle)
try:
sf.write(wav_path, waveform.numpy().T, sample_rate, subtype="PCM_16")
yield wav_path
finally:
with contextlib.suppress(OSError):
os.remove(wav_path)
def diarize_segments(
audio_path: str,
segments: list[dict],
num_speakers: Optional[int] = None,
) -> tuple[list[Optional[str]], Optional[str]]:
"""Label each ASR segment with a speaker.
Returns ``(labels, error)``: one label per input segment (``None`` where
the segment has no usable timing or no speaker turn overlaps it) and an
error code when diarization could not run. It never raises, so a missing
or broken diarization model degrades to a plain transcript.
"""
labels: list[Optional[str]] = [None] * len(segments)
timed = [
(i, {"start": float(s["start"]), "end": float(s["end"])})
for i, s in enumerate(segments)
if isinstance(s.get("start"), (int, float)) and isinstance(s.get("end"), (int, float))
]
if not timed:
return labels, None
try:
from services.model_manager import get_diarization_pipeline
from services.segmentation import assign_speakers_from_diarization
pipeline, error = get_diarization_pipeline(return_error=True)
if pipeline is None:
return labels, error or "LOAD_FAILED"
from services.diarization_native import NativeSortformer
# Sortformer detects up to four speakers and rejects an exact count.
hint = None if isinstance(pipeline, NativeSortformer) else num_speakers
if isinstance(pipeline, NativeSortformer):
# Its child process is the only part that can be stopped. When the
# request is abandoned (timeout or client gone) the guard sets this
# scope's cancellation; passing it through lets the child exit
# instead of holding the GPU pool until its own deadline.
from services.inference_cancellation import current_cancellation
scope = current_cancellation()
with _diarizable_audio(audio_path) as source:
# Decoding can take a while; a request abandoned meanwhile must
# not start the native child at all.
if scope and scope.cancelled.is_set():
return [None] * len(segments), "DIARIZATION_FAILED"
diarization = pipeline(
source, cancel_check=scope.cancelled.is_set if scope else None
)
else:
with _diarizable_audio(audio_path) as source:
diarization = pipeline(source, num_speakers=hint) if hint else pipeline(source)
assigned = assign_speakers_from_diarization([d for _, d in timed], diarization)
for (index, _), item in zip(timed, assigned):
labels[index] = item.get("speaker_id")
except Exception:
logger.exception("Transcript diarization failed")
return [None] * len(segments), "DIARIZATION_FAILED"
return labels, None