All guides

Gradio speech transcription: finish recording, then check the text

Use the Audio numpy contract, reject missing and zero-valued clips, submit completed audio and compare text with the recording.

AINavWritten / Updated Sources checked
On this page

At a glance

Gradio can wrap an existing speech model in a recording page. This task adapts the official Whisper example for full-context transcription. The callback receives a sample rate and array, checks empty input, duration and zero signals, then performs recognition. It delivers code and an audio/text comparison record. It does not implement live streaming or establish accent accuracy. No model was downloaded, microphone opened or page run.

Recording-to-text acceptance

  1. Finish a short clip

    Record a synthetic sentence and stop recording before submitting.

  2. Validate and recognize

    Convert the tuple data to mono float32 and reject empty or zero signals.

  3. Compare audio and text

    Read text and compare every sentence, recording discrepancies.

Finished recording, inference and text inspection are separate checks.

Prepare dependencies and a short sentence

Compatible Gradio, NumPy, Transformers, torch, torchaudio and ffmpeg are required. The official example uses openai/whisper-base.en; this task retains it for an English sentence. Pipeline initialization may acquire model files, so confirm downloads and execution are intended. An example is not a completed installation. Use “The demo starts at noon. Bring two notebooks.” without real information, recording at most 30 seconds. That is this teaching cap, not a universal Gradio limit.

Select numpy input explicitly

Audio type="numpy" returns (int sample rate, numpy.array): mono shape is samples and multichannel shape is samples × channels. type="filepath" instead returns a temporary path. This code selects numpy explicitly; do not treat the tuple as a path. Only microphone is permitted. The model receives sampling_rate and raw, and the result is read through text.

Nearby speech-tutorial prose mentions filepath, while its code and later explanation unpack a tuple. The current Audio contract resolves that wording conflict. Convert and average channels before peak normalization. Reject zero signals first to avoid division by zero.

Save the complete demonstration script

Original full-context demonstration; not run
python
import gradio as gr
import numpy as np
from transformers import pipeline

transcriber = pipeline(
    "automatic-speech-recognition", model="openai/whisper-base.en"
)


def transcribe(audio):
    if audio is None:
        raise ValueError("Record an audio clip first")
    sample_rate, samples = audio
    if not isinstance(sample_rate, int) or sample_rate <= 0:
        raise ValueError("Invalid sample rate")
    waveform = np.asarray(samples, dtype=np.float32)
    if waveform.ndim == 2:
        waveform = waveform.mean(axis=1)
    if waveform.ndim != 1 or waveform.size == 0:
        raise ValueError("Expected a nonempty mono or multichannel clip")
    if not np.isfinite(waveform).all():
        raise ValueError("Non-finite audio samples")
    if waveform.size / sample_rate > 30:
        raise ValueError("This demonstration accepts at most 30 seconds")
    peak = float(np.max(np.abs(waveform)))
    if peak <= 0:
        raise ValueError("The clip contains only zero samples")
    waveform = waveform / peak
    result = transcriber({"sampling_rate": sample_rate, "raw": waveform})
    text = result["text"]
    if not isinstance(text, str) or not text.strip():
        raise ValueError("No usable transcript returned")
    return text


demo = gr.Interface(
    fn=transcribe,
    inputs=gr.Audio(sources=["microphone"], type="numpy"),
    outputs=gr.Textbox(label="Transcript"),
)
demo.launch()

Save as transcribe_demo.py and run python transcribe_demo.py in an existing compatible environment. No streaming=True or live=True is enabled. The 30-second check happens before inference. Input validation and empty-transcript checks raise ValueError. Model-call failures or a missing text field retain their actual exception; inspect runtime diagnostics without assuming every UI setup exposes identical messages.

Stop recording before submitting

Open your own running demo, permit the microphone through actual browser prompts and record the synthetic sentence. Stop recording, then submit the completed clip. A waveform alone does not prove recognition ran. The callback validates the clip before sending its complete waveform to the model. Replay it and compare each sentence, especially noon, two and notebooks. No fabricated observed transcript is provided.

Inspect input, returned text and meaning

Acceptance checks
ObjectRequirementFailure exit
ClipNonempty, within teaching duration and finishedRecord again; do not send invalid input
ArrayValid dimensions, positive sample rate, finite nonzero samplesInspect acquisition and Audio contract
ReturnNonempty string textRetain real error and stop
TranscriptSentences and key words match audioRecord mishearing or omission rather than accept it

A neat transcript can still mishear numbers and nouns. One correct short clip establishes no accuracy for other languages, noise or accents. Broader quality assessment needs representative samples and a metric; this task checks one teaching clip.

Close out missing or failed results

  • Denied microphone, missing clip or zero signal stops acquisition/validation before recognition.
  • Dependency, ffmpeg or model-loading errors retain their cause; empty text is not success.
  • Recognition errors or mismatches retain synthetic audio and its corresponding diagnostics/text record, blocking consumption.
  • At completion, stop recording and exit the demo process you started. An open page alone is not completion.
  • Public sharing needs separate identity, access and file-exposure checks; a local demo does not establish those conditions.

Verification scope

The official full-context/streaming tutorial and current Audio types, sources and recording events were read. Only the full-context branch is implemented in this original adaptation. No dependency, model, microphone, Gradio process or transcript was tested. Streaming state, chunk boundaries, queues, cleanup APIs and performance are outside scope; adding streaming=True cannot establish them.

Article sources

Original editorial content; official descriptions and checking suggestions are distinguished.

  1. Gradio · Official sources
    View details
  2. Gradio · Official sources
    View details