Spaces:
Paused

tiny_notes / app.py
kalpi314's picture
Update app.py
692ea8a verified
Raw History Blame Contribute Delete
13.2 kB
"""
Live speech-to-text on Apple Silicon, using Whisper on MLX. No torch.
The browser streams short microphone chunks to Gradio, which calls
`transcribe()` with each one. Rather than re-running the model over a
growing buffer, this uses mlx-audio's AlignAtt streaming decoder: each
chunk is turned into a mel spectrogram and fed to a per-session decoder
that emits only the tokens its cross-attention says are already stable.
That choice is worth stating, because the obvious alternative is worse in
a way that isn't obvious until you run it. Re-transcribing a rolling
buffer with `model.generate()` costs more on every chunk as the buffer
grows, and — measured on a 2.8s clip of real speech — reliably appends
hallucinated filler: `"The quick brown fox jumps over the lazy dog. The
The The The The..."`, because Whisper pads to 30s internally and keeps
decoding into the padding. The streaming decoder produced
`"the" -> "quick brown fox" -> "jumps over" -> "the lazy dog."` on the
same audio with no filler at all, at roughly 8x realtime.
"""
import os
import traceback
from concurrent.futures import ThreadPoolExecutor
import gradio as gr
import numpy as np
from mlx_audio.stt import load as load_stt
from mlx_audio.stt.models.whisper import StreamingConfig, StreamingDecoder
from mlx_audio.stt.models.whisper.audio import SAMPLE_RATE, log_mel_spectrogram
from scipy.signal import resample_poly
# `openai/whisper-tiny.en`, not one of the `mlx-community/whisper-*-mlx`
# repos: mlx-audio converts the standard Hugging Face weights to MLX on
# load, and needs the HF processor files (tokenizer, preprocessor config)
# that the pre-converted MLX repos don't ship — loading one of those fails
# with "Processor not found. Make sure the model was loaded with a
# HuggingFace processor."
MODEL_ID = os.environ.get("WHISPER_MODEL", "openai/whisper-tiny.en")
# How often the browser ships a chunk. The decoder accumulates context
# across chunks, so this is a latency/overhead knob, not a quality one.
STREAM_EVERY = float(os.environ.get("WHISPER_STREAM_EVERY", "0.75"))
# Start a fresh decoder before this much audio has gone into the current
# one. **This works around a real bug in mlx-audio's streaming decoder**,
# not a tuning preference. `decode_chunk` computes what to emit as
# `text_tokens[len(self._emitted_tokens):]` — correct only while the
# decoded transcript keeps growing as a prefix of itself. It re-decodes
# the whole accumulated window every chunk, and once that window hits
# Whisper's 30s limit it starts *sliding*: the oldest audio drops off, the
# re-decode covers a different span, and that slice lands in the wrong
# place, re-emitting text that was already shown. Measured on 84s of
# speech: the transcript grew 386 -> 706 -> 1571 -> 5165 characters while
# the same sentence repeated. Rotating before the slide keeps every
# segment inside the regime the decoder is actually correct in.
SEGMENT_SECONDS = float(os.environ.get("WHISPER_SEGMENT_SECONDS", "25"))
# Smallest audio slice worth handing to the mel transform. Its STFT needs
# at least `n_fft` (400) samples and raises "Input is too short" below
# that — and browsers really do deliver very short chunks, especially the
# first one after the mic opens. Short chunks are buffered rather than
# dropped, so no audio is lost to this.
MIN_SAMPLES = 1600 # 0.1s at 16 kHz
# **Every MLX call happens on this one thread.** MLX streams are
# thread-local, and an array created under one thread's stream cannot be
# used from another: doing so raises `RuntimeError: There is no
# Stream(gpu, 0) in current thread.` Gradio runs event handlers in
# anyio's worker pool, which hands out *different* threads over time, so
# a model loaded at import and used straight from a handler fails on
# essentially every chunk.
#
# Neither of the obvious fixes works — measured, not assumed. Wrapping the
# call in `mx.stream(<stream captured on the main thread>)` still raises,
# and so does calling `mx.set_default_device(mx.gpu)` inside the worker:
# the stream cannot be adopted by another thread at all. What does work is
# keeping the work on one consistent thread, which a single-worker
# executor guarantees.
#
# Serializing through it also removes a race worth naming: `stream` and
# `stop_recording` are separate Gradio events, so Gradio's own
# `concurrency_limit=1` on the former never stopped a flush from running
# concurrently with a decode on the same decoder object.
_MLX = ThreadPoolExecutor(max_workers=1, thread_name_prefix="mlx")
def _on_mlx(fn):
"""Run `fn` on the one thread allowed to touch MLX, and return its
result. Exceptions propagate to the caller unchanged."""
return _MLX.submit(fn).result()
print(f"[tiny_voice] loading {MODEL_ID} on MLX…")
model = _on_mlx(lambda: load_stt(MODEL_ID))
N_MELS = getattr(getattr(model, "dims", None), "n_mels", 80)
print(f"[tiny_voice] ready (n_mels={N_MELS})")
# A short run of silence, used only to carry `is_last=True` to the decoder
# when recording stops — see `flush`. Not zero-length: the mel transform
# runs an STFT, which needs at least `n_fft` (400) samples and raises
# "Input is too short" on an empty array. A tenth of a second of silence is
# both long enough and an honest representation of "the utterance ended".
# Plain numpy, deliberately: its mel is computed on the MLX thread like
# every other, so no MLX array is ever created outside that thread.
_FLUSH_AUDIO = np.zeros(int(0.1 * SAMPLE_RATE), dtype=np.float32)
def _to_mono_16k(sr: int, audio: np.ndarray) -> np.ndarray:
"""Browser microphone audio -> mono float32 at Whisper's 16 kHz.
Two conversions, both easy to get subtly wrong:
- **Scale by the dtype's range, not the chunk's peak.** Gradio hands
over int16. Dividing each chunk by its own maximum — the idiom this
demo started with — rescales every chunk independently, so a quiet
chunk gets amplified to full scale and the near-silence between
words reaches the model as loud as speech.
- **Resample with a filter.** `scipy.signal.resample_poly` is
polyphase and anti-aliased. Plain slicing or linear interpolation
from 48 kHz to 16 kHz folds everything above 8 kHz back down into
the speech band as aliasing noise, which degrades transcription in
a way that looks like "the model is bad".
"""
if audio.ndim > 1: # stereo -> mono
audio = audio.mean(axis=1)
if np.issubdtype(audio.dtype, np.integer):
audio = audio.astype(np.float32) / float(np.iinfo(audio.dtype).max)
else:
audio = audio.astype(np.float32)
if sr != SAMPLE_RATE:
audio = resample_poly(audio, SAMPLE_RATE, sr).astype(np.float32)
return audio
def _new_decoder() -> StreamingDecoder:
"""Built on the MLX thread — constructing a decoder allocates MLX
arrays (the SOT token sequence, the logit filters)."""
return _on_mlx(
lambda: StreamingDecoder(model, StreamingConfig(), language="en", task="transcribe")
)
def _new_session() -> dict:
"""One decoder per browser session.
`StreamingDecoder` carries per-conversation state (accumulated mel,
emitted tokens), so a single shared instance would splice two
listeners' speech into one transcript. Gradio's `gr.State` is
per-session, which is exactly the right lifetime.
"""
return {
"decoder": _new_decoder(),
"text": "",
# Audio too short to make a mel frame, carried to the next chunk.
"pending": np.zeros(0, dtype=np.float32),
# How much audio this decoder has consumed, for SEGMENT_SECONDS.
"samples": 0,
}
def _append(session, text: str) -> None:
text = (text or "").strip()
if text:
session["text"] = f"{session['text']} {text}".strip()
def _decode(session, audio: np.ndarray, *, is_last: bool = False) -> None:
"""Feed one slice of 16 kHz audio to this session's decoder.
Failures are logged and swallowed rather than raised. A streaming UI
that dies on a single bad chunk loses the whole transcript and gives
the user a stack trace instead of their words; skipping one chunk
costs a fraction of a second of audio. The traceback still goes to
the log, in full, so nothing is hidden.
"""
decoder = session["decoder"]
def work() -> str:
mel = log_mel_spectrogram(audio, n_mels=N_MELS)
return decoder.decode_chunk(mel, is_last=is_last).text
try:
_append(session, _on_mlx(work))
except Exception: # noqa: BLE001 - one bad chunk must not end the stream
traceback.print_exc()
def _rotate(session) -> None:
"""Flush the current decoder and start a fresh one — see SEGMENT_SECONDS."""
_decode(session, _FLUSH_AUDIO, is_last=True)
session["decoder"] = _new_decoder()
session["samples"] = 0
def transcribe(session, new_chunk):
if new_chunk is None:
return session, (session or {}).get("text", "")
if session is None:
session = _new_session()
sr, audio = new_chunk
audio = _to_mono_16k(sr, audio)
if audio.size == 0:
return session, session["text"]
# Carry anything too short for a mel frame into the next chunk instead
# of dropping it or letting the STFT raise.
audio = np.concatenate([session["pending"], audio])
if audio.size < MIN_SAMPLES:
session["pending"] = audio
return session, session["text"]
session["pending"] = np.zeros(0, dtype=np.float32)
if session["samples"] + audio.size > SEGMENT_SECONDS * SAMPLE_RATE:
_rotate(session)
session["samples"] += audio.size
_decode(session, audio)
return session, session["text"]
def flush(session):
"""Emit whatever the decoder is still holding back, when the mic stops.
AlignAtt deliberately withholds trailing tokens until enough following
audio confirms them, and `is_last=True` is what tells it no more is
coming. A live stream never reaches a "last chunk" on its own, so
without this the final word or two of every utterance is decoded but
never shown — verified: the same clip ends `"…jumps over the"` while
streaming and `"…jumps over the lazy dog."` once flushed.
"""
if session is None:
return session, ""
if session["pending"].size >= MIN_SAMPLES:
_decode(session, session["pending"])
session["pending"] = np.zeros(0, dtype=np.float32)
_decode(session, _FLUSH_AUDIO, is_last=True)
return session, session["text"]
def clear_transcript():
return _new_session(), ""
# Targets Gradio's own semantic class (`.record-button`) plus a plain
# `#mic button` fallback, so the styling survives a Gradio upgrade even if
# that class is renamed — the svelte-hashed classes in the same markup
# (`svelte-doy9oc`) are regenerated per build and would not.
CSS = """
#mic { max-width: 460px; margin: 0 auto; }
#mic .record-button, #mic button {
width: 100%;
min-height: 96px;
font-size: 1.35rem;
font-weight: 600;
border-radius: 16px;
}
#transcript textarea {
font-size: 1.1rem;
line-height: 1.6;
}
"""
with gr.Blocks(title="Live Whisper (MLX)") as demo:
# Injected as a <style> block rather than passed as `launch(css=...)`.
# Gradio 6 moved `css` off `Blocks` (where it is now silently swallowed
# by **kwargs) onto `launch()`/`mount_gradio_app()` — so styling passed
# the documented way is dropped by *any* host that mounts the Blocks
# itself instead of calling `launch()`. A <style> node is part of the
# Blocks, so it survives however this app is served.
gr.HTML(f"<style>{CSS}</style>")
gr.Markdown(
f"""
# 🎙️ Live Speech-to-Text on MLX
Streaming transcription with **{MODEL_ID}** on
[MLX](https://github.com/ml-explore/mlx) — no PyTorch.
"""
)
# The recorder *is* the button: Gradio's streaming Audio renders a
# single control that reads "Record" and turns into "Stop" while
# recording. `show_recording_waveform=False` drops the waveform that
# would otherwise sit next to it, and `container=False` removes the
# component's border/padding, leaving the button itself to be styled.
audio_in = gr.Audio(
sources=["microphone"],
streaming=True,
show_label=False,
container=False,
waveform_options=gr.WaveformOptions(show_recording_waveform=False),
elem_id="mic",
)
output_text = gr.Textbox(
label="Transcript",
lines=14,
autoscroll=True,
elem_id="transcript",
)
state = gr.State(None)
clear_btn = gr.Button("Clear transcript", variant="secondary", size="sm")
audio_in.stream(
fn=transcribe,
inputs=[state, audio_in],
outputs=[state, output_text],
stream_every=STREAM_EVERY,
concurrency_limit=1,
)
# Flush the decoder's withheld tail when the user stops the mic, so the
# last word of an utterance actually appears.
audio_in.stop_recording(fn=flush, inputs=[state], outputs=[state, output_text])
clear_btn.click(fn=clear_transcript, inputs=None, outputs=[state, output_text])
if __name__ == "__main__":
demo.launch()