跳到正文
DEV Community· Jack M·· 4 小時前AI 評分68

如何測試 Whisper 在靜音時的幻覺,同時避免漏掉低聲語音

How to Test Whisper Hallucinations on Silence Without Losing Quiet Speech

AI 導讀

文章示範如何為 Whisper 建立靜音與低聲語音的成對回歸測試,確認靜音不產生口述文字,同時保留真實説出的收尾短句。靜音樣本的 WER 分母為零,因此應另計輸出文字的靜音樣本數及插入詞總數,並獨立統計短語完整識別率。測試應沿用部署中的音訊處理流程,保存分段時間、逐字稿及候選版本輸出,以定位問題出現的階段。

正文

A meeting ends with two people still connected. One mutes the mic. The other closes a laptop. The caption file adds “Thank you for watching.” Now put those same words in a recording where someone actually says them. What should your transcription pipeline do with each file?

That pair makes a useful Whisper regression test. One recording should produce an empty transcript. The other should retain the closing words, even when the speaker is quiet. A phrase filter can pass the first test and fail the second. So can a change to the voice activity detector. Here’s how to build the pair, score both outcomes in Python, and trace a failed release check back to the stage that changed.

Define the expected transcript for silence

Start with the file users receive. For a verbatim spoken-word transcript, an interval with no speech should contribute zero words. A caption product might also emit a cue such as “[music].” Decide whether that cue belongs in a separate sound-event field. Write the contract down before you normalize text. Removing everything inside brackets could hide a fabricated utterance if the application wraps speaker text in brackets too.

There is evidence for testing pauses explicitly. In Careless Whisper, researchers examined invented phrases in transcriptions and found that speakers with longer non-vocal stretches faced greater risk in their study. Their population, model and recording conditions matter. Their result gives you a reason to include pauses in a test set. Your own error rate still depends on what you record and how you process it. Read the original study.

Use human listening to establish the expected result. A voice activity detector (VAD) is one of the components under test. Letting it label the reference audio creates a circular check. If it misses a whispered word, your test can reward the pipeline for dropping that word. Give unclear clips an “uncertain” label and send them for review. Keep them out of pass/fail counts until someone resolves the ambiguity.

Build a small audio set with opposing outcomes

A first suite can fit in a folder. Make it from recordings you have permission to retain and replay. Record in the format your app accepts, including a sample that passes through its normal upload codec. Keep the original bytes, a content hash, and the expected transcript together. The hash helps catch an accidental fixture replacement that leaves the filename and test output looking familiar.

Fixture What to put in the recording What to check
Digital silence A valid audio file with zero-valued samples The request succeeds with zero spoken words
Room tone An open microphone near a fan Background sound produces zero words
Quiet closing A person softly says “thank you for watching” All four words survive in order
Pause and restart Two short sentences around a long pause Both survive, with no words inside the gap
Noisy ending A speaker stops, then moves a chair The transcript ends with the speaker’s final word

Change one property at a time when you make variants. If a clean phrase passes but its low-volume copy fails, keep their duration, codec and wording identical. If both are clean WAV files while your users upload compressed calls, add a second matched pair that follows the upload path. Label the pairs. A failure isolated to one codec gives you a much shorter debugging session than a folder of unrelated failing files.

Preserve a few genuinely awkward cases. For example, record a speaker pausing before saying a short final “no.” A clipped negative can reverse the meaning of the whole sentence. Test the specific word at the end even if you also calculate word error rate across the full clip. A mostly correct transcript can still give the reader the opposite answer.

Score empty references and quiet speech separately

Word error rate divides edits by the number of reference words. On a silent clip that denominator is zero. Libraries can define special handling for this case. For a release review, show the numerator directly. Count silent clips that emitted at least one spoken word, and report the total number of inserted words. Three clips with one extra word each imply a different review task from one clip containing a whole invented paragraph.

For the positive control, count exact recoveries of a short known phrase. Keep this strict for a deliberately tiny fixture. State your text normalization policy so a punctuation change cannot move the score by accident. In the example below, case and punctuation do not matter. Word order and repeated words do. The tokenizer is deliberately scoped to these English fixtures. Supply a language-appropriate tokenizer if you extend the suite.

import re

def words(text):
    return re.findall(r"[a-z]+(?:'[a-z]+)?", text.lower())

def score(rows):
    silent = invented = added = spoken = recovered = 0
    for expected, actual in rows:
        ref, hyp = words(expected), words(actual)
        if ref:
            spoken += 1
            recovered += int(ref == hyp)
        else:
            silent += 1
            invented += int(bool(hyp))
            added += len(hyp)
    return {
        "silent_failed": (invented, silent),
        "words_on_silence": added,
        "phrase_recovered": (recovered, spoken),
    }

# Synthetic transcripts for a unit test of the scorer.
rows = [("", ""), ("", "Thank you."), ("Thank you.", "thank you")]
assert score(rows) == {
    "silent_failed": (1, 2),
    "words_on_silence": 2,
    "phrase_recovered": (1, 1),
}

For a real run, replace the synthetic outputs with strings returned by your app. Join fixture IDs to completed requests before calling the scorer. A timeout, missing upload or crashed worker should fail the run as an execution error. Converting any of those to an empty string gives the system a perfect result on the silent row. Also check that both groups have at least one completed case before you interpret the counts.

Keep the mixed clips in a separate timestamp check. A whole-file word comparison can tell you that a word appeared twice. It cannot tell you which copy landed inside the pause. Annotate the quiet interval by listening, leave a documented margin around speech boundaries, and inspect segments that overlap it. If a segment straddles the edge and only segment-level times are available, replay it. Coarse timing alone cannot establish when an individual word was spoken.

Run the same audio through the deployed path

Suppose you use faster-whisper. Its transcription method returns a segment generator. Iterate over it inside your test so decoding completes and errors surface before you save results. Pass the same model revision, language selection and beam settings that your service uses. This minimal adapter illustrates a fixed English experiment. For multilingual traffic, add fixtures that exercise the actual language-selection path. See the faster-whisper transcription and VAD examples.

def transcribe_clip(model, path, use_vad):
    segments, info = model.transcribe(
        str(path), language="en", beam_size=5, vad_filter=use_vad
    )
    spans = [(s.start, s.end, s.text.strip()) for s in segments]
    return " ".join(text for _, _, text in spans), spans

Run the baseline and candidate on the same fixture manifest. Save raw segment output and the final transcript returned to the caller. If your service has a separate caption exporter, exercise that too. A decoder can return an empty list while an exporter keeps the previous caption on screen. From the viewer’s seat that is still a wrong subtitle. Fixing the decoder would leave this bug intact.

For hosted transcription APIs you can use exactly the same expected text and scorer. Record the model identifier the API exposes and any options the service accepts. Leave unobservable fields blank. A useful report might say that a candidate lost the last word after the upload path changed. It takes a controlled comparison or more evidence to attribute that loss to the provider’s model.

Find where the unwanted words first appear

Take a failed room-tone clip and listen to the decoded input. An exported file can contain a distant voice on one stereo channel that a laptop speaker barely reproduces. Check both channels before treating this as a model error. If the input truly contains no speech, inspect the spans admitted by your detector, the recognizer output and the final rendered captions in that order.

First observation Next comparison
Detector admits chair noise Replay the same noise and a soft spoken ending across candidate detector settings
Recognizer invents words only after a spoken segment Compare decoding the same gap alone and after the original lead-in
Recognizer returns no words but captions show text Inspect cue end times, empty-result handling and export state
Stronger filtering removes the quiet closing Check the retained waveform and its boundaries before changing the decoder

The second row matters for long recordings. Cutting a problematic interval out of a meeting also removes its history. If the isolated clip passes, preserve a short lead-in and replay the pair in the original order. Where your decoder exposes conditioning on previous text, compare both settings with everything else fixed. Record any change to the real words around the pause. Developers have described this exact difficulty when investigating Whisper on recordings without speech. Whisper maintainer repository discussion.

Choose a release gate that exposes the trade-off

Imagine a caption service tests ten non-speech clips and ten matched quiet phrases. Its baseline inserts words into two silent clips and recovers all ten phrases. A candidate detector suppresses every silent clip and recovers eight phrases. These illustrative counts show why the choice matters. Combining the two columns into a single accuracy score would give both systems eighteen successes and hide which users encounter a failure.

Look at the two newly missing phrases before shipping. If both occur after a pause, replay the waveform the recognizer actually received. A boundary setting might be trimming the onset of speech. If the waveform contains the entire phrase, inspect what the recognizer and postprocessor emitted. Keep a copy of the baseline result beside the candidate so the reviewer can hear the same moment and compare both outcomes.

For a small, curated release suite, make the gate concrete. Require the named room-tone regression to pass, preserve every previously passing critical spoken control, and require a human decision on each newly failing fixture. Report counts by category with denominators. Keep a separate holdout set for periodic checks. Tuning a detector until it recognizes five recordings perfectly tells you very little about the next microphone a customer connects.

Public benchmarks can expand coverage once the small suite works. The Scicom dataset separates voice-free audio from cases where a person actually speaks a phrase associated with hallucination. Read the configuration descriptions and licensing before you import a slice. Keep your service-specific codec and export fixtures as a separate group in the report so a large public dataset cannot drown out a local regression. Dataset card and evaluation splits.

Hand the failure to the person who can fix it

For a support-captioning tool, the most helpful issue title might be “Quiet closing word disappears after upload.” Attach a small table with the original WAV result, the decoded upload result and the final caption text. If the WAV passes on both releases while the uploaded version fails only on the candidate, the person maintaining the upload path has a concrete starting point. They can replay the conversion locally and inspect the exact bytes handed to recognition.

Keep one incident fixture frozen after the fix. Put its expected outcome under review just as you would a change to an API contract. Otherwise a future developer updating snapshots may accept an invented sentence because the new output looks grammatical. Playing the disputed interval usually takes less effort than debating whether the sentence sounds plausible.

FAQ

Can I filter out “thank you for watching” after transcription?

A viewer might actually have said it. Include a real recording of the phrase before adding a suppression rule. If the product flags suspect text for review, preserve the audio interval and the original decoder output so the reviewer can check what was said. A global phrase deletion loses that distinction.

How much silence should a Whisper test contain?

Choose durations around boundaries your own pipeline uses. Include a pause inside one decode window and a gap that crosses a chunk boundary. Add the length of a typical muted ending from your product if you have permission to use that information. Record durations alongside the results so the next engineer can reproduce the failure.

Does passing a file full of zeros prove VAD works?

It proves one path handled that file. A fan, keyboard or chair movement can produce a very different input even when nobody speaks. Include at least one recording from an open microphone and one quiet spoken control captured on that same device. Listen for distant speech before labeling the first file empty.

Should live voice agents use this suite too?

Use it for transcript fidelity, then test conversational timing separately. A system may transcribe a long pause correctly and still interrupt someone who is about to continue. For that second problem, replay pauses and interruptions through the full dialogue loop. Voice agent turn-taking and interruption tests.

What should I save when a regression fails?

Save the fixture ID and hash, configuration, software versions, segment timestamps, raw words and visible caption for that fixture. Include an executable replay command and identify the first stage where baseline and candidate disagree. For customer reports, follow the product’s retention and consent rules. A short, consented reenactment that reproduces the fault can become a permanent test without retaining the original call.

來源:DEV Community · dev.to