Spaces:
Paused

kalpi314 commited on
Commit
692ea8a
·
verified ·
1 Parent(s): 63cd28a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +167 -25
app.py CHANGED
@@ -19,6 +19,8 @@ same audio with no filler at all, at roughly 8x realtime.
19
  """
20
 
21
  import os
 
 
22
 
23
  import gradio as gr
24
  import numpy as np
@@ -39,8 +41,57 @@ MODEL_ID = os.environ.get("WHISPER_MODEL", "openai/whisper-tiny.en")
39
  # across chunks, so this is a latency/overhead knob, not a quality one.
40
  STREAM_EVERY = float(os.environ.get("WHISPER_STREAM_EVERY", "0.75"))
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  print(f"[tiny_voice] loading {MODEL_ID} on MLX…")
43
- model = load_stt(MODEL_ID)
44
  N_MELS = getattr(getattr(model, "dims", None), "n_mels", 80)
45
  print(f"[tiny_voice] ready (n_mels={N_MELS})")
46
 
@@ -49,9 +100,9 @@ print(f"[tiny_voice] ready (n_mels={N_MELS})")
49
  # runs an STFT, which needs at least `n_fft` (400) samples and raises
50
  # "Input is too short" on an empty array. A tenth of a second of silence is
51
  # both long enough and an honest representation of "the utterance ended".
52
- _FLUSH_MEL = log_mel_spectrogram(
53
- np.zeros(int(0.1 * SAMPLE_RATE), dtype=np.float32), n_mels=N_MELS
54
- )
55
 
56
 
57
  def _to_mono_16k(sr: int, audio: np.ndarray) -> np.ndarray:
@@ -82,6 +133,14 @@ def _to_mono_16k(sr: int, audio: np.ndarray) -> np.ndarray:
82
  return audio
83
 
84
 
 
 
 
 
 
 
 
 
85
  def _new_session() -> dict:
86
  """One decoder per browser session.
87
 
@@ -91,11 +150,49 @@ def _new_session() -> dict:
91
  per-session, which is exactly the right lifetime.
92
  """
93
  return {
94
- "decoder": StreamingDecoder(model, StreamingConfig(), language="en", task="transcribe"),
95
  "text": "",
 
 
 
 
96
  }
97
 
98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  def transcribe(session, new_chunk):
100
  if new_chunk is None:
101
  return session, (session or {}).get("text", "")
@@ -107,14 +204,19 @@ def transcribe(session, new_chunk):
107
  if audio.size == 0:
108
  return session, session["text"]
109
 
110
- mel = log_mel_spectrogram(audio, n_mels=N_MELS)
111
- result = session["decoder"].decode_chunk(mel)
 
 
 
 
 
 
 
 
112
 
113
- # `decode_chunk` returns only what became stable in this chunk, so the
114
- # transcript is accumulated here rather than replaced.
115
- emitted = (result.text or "").strip()
116
- if emitted:
117
- session["text"] = f"{session['text']} {emitted}".strip()
118
  return session, session["text"]
119
 
120
 
@@ -130,10 +232,10 @@ def flush(session):
130
  """
131
  if session is None:
132
  return session, ""
133
- tail = session["decoder"].decode_chunk(_FLUSH_MEL, is_last=True)
134
- emitted = (tail.text or "").strip()
135
- if emitted:
136
- session["text"] = f"{session['text']} {emitted}".strip()
137
  return session, session["text"]
138
 
139
 
@@ -141,31 +243,71 @@ def clear_transcript():
141
  return _new_session(), ""
142
 
143
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  with gr.Blocks(title="Live Whisper (MLX)") as demo:
 
 
 
 
 
 
 
 
145
  gr.Markdown(
146
  f"""
147
  # 🎙️ Live Speech-to-Text on MLX
148
- Streaming transcription with **{MODEL_ID}** running on
149
  [MLX](https://github.com/ml-explore/mlx) — no PyTorch.
150
- Click the microphone and start talking; text appears as words settle.
151
  """
152
  )
153
 
154
- with gr.Row():
155
- audio_in = gr.Audio(sources=["microphone"], streaming=True, label="Microphone")
156
- output_text = gr.Textbox(label="Transcript", lines=8, autoscroll=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
 
158
  state = gr.State(None)
159
- clear_btn = gr.Button("Clear transcript")
160
 
161
  audio_in.stream(
162
  fn=transcribe,
163
  inputs=[state, audio_in],
164
  outputs=[state, output_text],
165
  stream_every=STREAM_EVERY,
166
- # One decode at a time per session: without this a slow chunk and
167
- # the next one overlap, and two calls mutate the same decoder's
168
- # accumulated state concurrently.
169
  concurrency_limit=1,
170
  )
171
  # Flush the decoder's withheld tail when the user stops the mic, so the
 
19
  """
20
 
21
  import os
22
+ import traceback
23
+ from concurrent.futures import ThreadPoolExecutor
24
 
25
  import gradio as gr
26
  import numpy as np
 
41
  # across chunks, so this is a latency/overhead knob, not a quality one.
42
  STREAM_EVERY = float(os.environ.get("WHISPER_STREAM_EVERY", "0.75"))
43
 
44
+ # Start a fresh decoder before this much audio has gone into the current
45
+ # one. **This works around a real bug in mlx-audio's streaming decoder**,
46
+ # not a tuning preference. `decode_chunk` computes what to emit as
47
+ # `text_tokens[len(self._emitted_tokens):]` — correct only while the
48
+ # decoded transcript keeps growing as a prefix of itself. It re-decodes
49
+ # the whole accumulated window every chunk, and once that window hits
50
+ # Whisper's 30s limit it starts *sliding*: the oldest audio drops off, the
51
+ # re-decode covers a different span, and that slice lands in the wrong
52
+ # place, re-emitting text that was already shown. Measured on 84s of
53
+ # speech: the transcript grew 386 -> 706 -> 1571 -> 5165 characters while
54
+ # the same sentence repeated. Rotating before the slide keeps every
55
+ # segment inside the regime the decoder is actually correct in.
56
+ SEGMENT_SECONDS = float(os.environ.get("WHISPER_SEGMENT_SECONDS", "25"))
57
+
58
+ # Smallest audio slice worth handing to the mel transform. Its STFT needs
59
+ # at least `n_fft` (400) samples and raises "Input is too short" below
60
+ # that — and browsers really do deliver very short chunks, especially the
61
+ # first one after the mic opens. Short chunks are buffered rather than
62
+ # dropped, so no audio is lost to this.
63
+ MIN_SAMPLES = 1600 # 0.1s at 16 kHz
64
+
65
+ # **Every MLX call happens on this one thread.** MLX streams are
66
+ # thread-local, and an array created under one thread's stream cannot be
67
+ # used from another: doing so raises `RuntimeError: There is no
68
+ # Stream(gpu, 0) in current thread.` Gradio runs event handlers in
69
+ # anyio's worker pool, which hands out *different* threads over time, so
70
+ # a model loaded at import and used straight from a handler fails on
71
+ # essentially every chunk.
72
+ #
73
+ # Neither of the obvious fixes works — measured, not assumed. Wrapping the
74
+ # call in `mx.stream(<stream captured on the main thread>)` still raises,
75
+ # and so does calling `mx.set_default_device(mx.gpu)` inside the worker:
76
+ # the stream cannot be adopted by another thread at all. What does work is
77
+ # keeping the work on one consistent thread, which a single-worker
78
+ # executor guarantees.
79
+ #
80
+ # Serializing through it also removes a race worth naming: `stream` and
81
+ # `stop_recording` are separate Gradio events, so Gradio's own
82
+ # `concurrency_limit=1` on the former never stopped a flush from running
83
+ # concurrently with a decode on the same decoder object.
84
+ _MLX = ThreadPoolExecutor(max_workers=1, thread_name_prefix="mlx")
85
+
86
+
87
+ def _on_mlx(fn):
88
+ """Run `fn` on the one thread allowed to touch MLX, and return its
89
+ result. Exceptions propagate to the caller unchanged."""
90
+ return _MLX.submit(fn).result()
91
+
92
+
93
  print(f"[tiny_voice] loading {MODEL_ID} on MLX…")
94
+ model = _on_mlx(lambda: load_stt(MODEL_ID))
95
  N_MELS = getattr(getattr(model, "dims", None), "n_mels", 80)
96
  print(f"[tiny_voice] ready (n_mels={N_MELS})")
97
 
 
100
  # runs an STFT, which needs at least `n_fft` (400) samples and raises
101
  # "Input is too short" on an empty array. A tenth of a second of silence is
102
  # both long enough and an honest representation of "the utterance ended".
103
+ # Plain numpy, deliberately: its mel is computed on the MLX thread like
104
+ # every other, so no MLX array is ever created outside that thread.
105
+ _FLUSH_AUDIO = np.zeros(int(0.1 * SAMPLE_RATE), dtype=np.float32)
106
 
107
 
108
  def _to_mono_16k(sr: int, audio: np.ndarray) -> np.ndarray:
 
133
  return audio
134
 
135
 
136
+ def _new_decoder() -> StreamingDecoder:
137
+ """Built on the MLX thread — constructing a decoder allocates MLX
138
+ arrays (the SOT token sequence, the logit filters)."""
139
+ return _on_mlx(
140
+ lambda: StreamingDecoder(model, StreamingConfig(), language="en", task="transcribe")
141
+ )
142
+
143
+
144
  def _new_session() -> dict:
145
  """One decoder per browser session.
146
 
 
150
  per-session, which is exactly the right lifetime.
151
  """
152
  return {
153
+ "decoder": _new_decoder(),
154
  "text": "",
155
+ # Audio too short to make a mel frame, carried to the next chunk.
156
+ "pending": np.zeros(0, dtype=np.float32),
157
+ # How much audio this decoder has consumed, for SEGMENT_SECONDS.
158
+ "samples": 0,
159
  }
160
 
161
 
162
+ def _append(session, text: str) -> None:
163
+ text = (text or "").strip()
164
+ if text:
165
+ session["text"] = f"{session['text']} {text}".strip()
166
+
167
+
168
+ def _decode(session, audio: np.ndarray, *, is_last: bool = False) -> None:
169
+ """Feed one slice of 16 kHz audio to this session's decoder.
170
+
171
+ Failures are logged and swallowed rather than raised. A streaming UI
172
+ that dies on a single bad chunk loses the whole transcript and gives
173
+ the user a stack trace instead of their words; skipping one chunk
174
+ costs a fraction of a second of audio. The traceback still goes to
175
+ the log, in full, so nothing is hidden.
176
+ """
177
+ decoder = session["decoder"]
178
+
179
+ def work() -> str:
180
+ mel = log_mel_spectrogram(audio, n_mels=N_MELS)
181
+ return decoder.decode_chunk(mel, is_last=is_last).text
182
+
183
+ try:
184
+ _append(session, _on_mlx(work))
185
+ except Exception: # noqa: BLE001 - one bad chunk must not end the stream
186
+ traceback.print_exc()
187
+
188
+
189
+ def _rotate(session) -> None:
190
+ """Flush the current decoder and start a fresh one — see SEGMENT_SECONDS."""
191
+ _decode(session, _FLUSH_AUDIO, is_last=True)
192
+ session["decoder"] = _new_decoder()
193
+ session["samples"] = 0
194
+
195
+
196
  def transcribe(session, new_chunk):
197
  if new_chunk is None:
198
  return session, (session or {}).get("text", "")
 
204
  if audio.size == 0:
205
  return session, session["text"]
206
 
207
+ # Carry anything too short for a mel frame into the next chunk instead
208
+ # of dropping it or letting the STFT raise.
209
+ audio = np.concatenate([session["pending"], audio])
210
+ if audio.size < MIN_SAMPLES:
211
+ session["pending"] = audio
212
+ return session, session["text"]
213
+ session["pending"] = np.zeros(0, dtype=np.float32)
214
+
215
+ if session["samples"] + audio.size > SEGMENT_SECONDS * SAMPLE_RATE:
216
+ _rotate(session)
217
 
218
+ session["samples"] += audio.size
219
+ _decode(session, audio)
 
 
 
220
  return session, session["text"]
221
 
222
 
 
232
  """
233
  if session is None:
234
  return session, ""
235
+ if session["pending"].size >= MIN_SAMPLES:
236
+ _decode(session, session["pending"])
237
+ session["pending"] = np.zeros(0, dtype=np.float32)
238
+ _decode(session, _FLUSH_AUDIO, is_last=True)
239
  return session, session["text"]
240
 
241
 
 
243
  return _new_session(), ""
244
 
245
 
246
+ # Targets Gradio's own semantic class (`.record-button`) plus a plain
247
+ # `#mic button` fallback, so the styling survives a Gradio upgrade even if
248
+ # that class is renamed — the svelte-hashed classes in the same markup
249
+ # (`svelte-doy9oc`) are regenerated per build and would not.
250
+ CSS = """
251
+ #mic { max-width: 460px; margin: 0 auto; }
252
+ #mic .record-button, #mic button {
253
+ width: 100%;
254
+ min-height: 96px;
255
+ font-size: 1.35rem;
256
+ font-weight: 600;
257
+ border-radius: 16px;
258
+ }
259
+ #transcript textarea {
260
+ font-size: 1.1rem;
261
+ line-height: 1.6;
262
+ }
263
+ """
264
+
265
  with gr.Blocks(title="Live Whisper (MLX)") as demo:
266
+ # Injected as a <style> block rather than passed as `launch(css=...)`.
267
+ # Gradio 6 moved `css` off `Blocks` (where it is now silently swallowed
268
+ # by **kwargs) onto `launch()`/`mount_gradio_app()` — so styling passed
269
+ # the documented way is dropped by *any* host that mounts the Blocks
270
+ # itself instead of calling `launch()`. A <style> node is part of the
271
+ # Blocks, so it survives however this app is served.
272
+ gr.HTML(f"<style>{CSS}</style>")
273
+
274
  gr.Markdown(
275
  f"""
276
  # 🎙️ Live Speech-to-Text on MLX
277
+ Streaming transcription with **{MODEL_ID}** on
278
  [MLX](https://github.com/ml-explore/mlx) — no PyTorch.
 
279
  """
280
  )
281
 
282
+ # The recorder *is* the button: Gradio's streaming Audio renders a
283
+ # single control that reads "Record" and turns into "Stop" while
284
+ # recording. `show_recording_waveform=False` drops the waveform that
285
+ # would otherwise sit next to it, and `container=False` removes the
286
+ # component's border/padding, leaving the button itself to be styled.
287
+ audio_in = gr.Audio(
288
+ sources=["microphone"],
289
+ streaming=True,
290
+ show_label=False,
291
+ container=False,
292
+ waveform_options=gr.WaveformOptions(show_recording_waveform=False),
293
+ elem_id="mic",
294
+ )
295
+
296
+ output_text = gr.Textbox(
297
+ label="Transcript",
298
+ lines=14,
299
+ autoscroll=True,
300
+ elem_id="transcript",
301
+ )
302
 
303
  state = gr.State(None)
304
+ clear_btn = gr.Button("Clear transcript", variant="secondary", size="sm")
305
 
306
  audio_in.stream(
307
  fn=transcribe,
308
  inputs=[state, audio_in],
309
  outputs=[state, output_text],
310
  stream_every=STREAM_EVERY,
 
 
 
311
  concurrency_limit=1,
312
  )
313
  # Flush the decoder's withheld tail when the user stops the mic, so the