fcabla Claude Opus 4.8 (1M context) commited on
Commit
db257d4
·
1 Parent(s): b752726

ASR: remove temporary [asr-debug] instrumentation (mic bug resolved)

Browse files

Root cause was Brave-on-Android's Web Audio tampering breaking Gradio's
client-side recorder re-encode (confirmed: Chrome records fine, upload always
worked). No app/model change needed for that. Strip the ASR_DEBUG-gated logging
now that it's diagnosed.

Kept: format="wav" (m4a/mp3 uploads), editable=False (skip the fragile trim
re-encode), soundfile->librosa loader, silence guard, single-language decode,
fast scipy resample, peak-normalization.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

Files changed (1) hide show
  1. game/asr.py +10 -30
game/asr.py CHANGED
@@ -10,7 +10,6 @@ function returns an empty string and logs the exact error — it NEVER fabricate
10
  """
11
  from __future__ import annotations
12
 
13
- import os
14
  import threading
15
 
16
  COHERE_ASR_ID = "CohereLabs/cohere-transcribe-03-2026"
@@ -55,17 +54,15 @@ def preload():
55
  @_gpu
56
  def transcribe(audio: "str | tuple[int, np.ndarray] | None", language: str = "en") -> str:
57
  """gr.Audio filepath (or legacy (sr, array) tuple) -> witness text in the
58
- chosen language ('en'/'es').
59
- Decodes in the witness's language; only retries the other language if that
60
- pass is empty. Empty string on any failure (never fabricated text)."""
61
  import numpy as np
62
 
63
  if audio is None:
64
  return ""
65
- dbg = os.getenv("ASR_DEBUG") == "1"
66
- # gr.Audio(type="filepath") -> read as float, exactly like the working self-test.
67
- # The old type="numpy" path delivered int16 already truncated to +/-1, which
68
- # destroyed the waveform before we ever saw it. A tuple is still accepted (legacy).
69
  if isinstance(audio, str):
70
  try:
71
  import soundfile as sf
@@ -76,22 +73,16 @@ def transcribe(audio: "str | tuple[int, np.ndarray] | None", language: str = "en
76
  wav = np.asarray(wav, dtype=np.float32)
77
  print(f"[asr] soundfile failed ({type(e_sf).__name__}: {e_sf}); "
78
  f"used librosa/ffmpeg", flush=True)
79
- src = f"path={audio!r}"
80
  else:
81
  sr, wav = audio
82
  wav = np.asarray(wav, dtype=np.float32)
83
  if np.abs(wav).max() > 1.5: # legacy int16-ranged numpy input
84
  wav = wav / 32768.0
85
- src = "tuple"
86
  wav = np.asarray(wav, dtype=np.float32)
87
  if wav.ndim > 1:
88
  wav = wav.mean(axis=1)
89
- if dbg:
90
- print(f"[asr-debug] IN {src} sr={sr} shape={wav.shape} "
91
- f"min={float(wav.min()):.4f} max={float(wav.max()):.4f} "
92
- f"rms={float(np.sqrt((wav ** 2).mean())):.5f} lang_arg={language!r}", flush=True)
93
- # Silence guard: a silent/near-silent clip (e.g. a mic that captured nothing)
94
- # must NOT be fed to the model — it answers confident hallucinations. Return "".
95
  peak = float(np.abs(wav).max()) if wav.size else 0.0
96
  if len(wav) < sr // 2 or peak < 1e-3:
97
  print(f"[asr] no usable audio (samples={len(wav)}, peak={peak:.5f}) -> empty", flush=True)
@@ -101,26 +92,17 @@ def transcribe(audio: "str | tuple[int, np.ndarray] | None", language: str = "en
101
  try:
102
  import torch
103
  proc, mdl = _load()
104
- if sr != 16000:
105
- try: # fast polyphase resample (librosa's default was ~13s on mic clips)
106
  from scipy.signal import resample_poly
107
  wav = resample_poly(wav, 16000, sr).astype(np.float32)
108
- rs = "scipy"
109
  except Exception:
110
  try:
111
  import librosa
112
  wav = librosa.resample(np.ascontiguousarray(wav), orig_sr=sr, target_sr=16000)
113
- rs = "librosa"
114
- except Exception as _re:
115
  idx = np.linspace(0, len(wav) - 1, int(len(wav) * 16000 / sr))
116
  wav = wav[np.floor(idx).astype(int)]
117
- rs = f"decimate({type(_re).__name__})"
118
- else:
119
- rs = "none(already16k)"
120
- if dbg:
121
- print(f"[asr-debug] FEED via={rs} len={len(wav)} dur={len(wav)/16000:.2f}s "
122
- f"peak={float(np.abs(wav).max()):.4f} "
123
- f"rms={float(np.sqrt((wav ** 2).mean())):.5f} lang={lang}", flush=True)
124
  # `language` is a REQUIRED processor arg: it builds the decoder prompt.
125
  inputs = proc(wav, language=lang, sampling_rate=16000, return_tensors="pt")
126
  inputs = {k: (v.to(mdl.device, dtype=mdl.dtype) if v.dtype.is_floating_point
@@ -128,8 +110,6 @@ def transcribe(audio: "str | tuple[int, np.ndarray] | None", language: str = "en
128
  with torch.no_grad():
129
  ids = mdl.generate(**inputs, max_new_tokens=120)
130
  text = proc.batch_decode(ids, skip_special_tokens=True)[0].strip()
131
- if dbg:
132
- print(f"[asr-debug] decoded({lang}): {text!r}", flush=True)
133
  print(f"[asr] {lang}: {text[:90]!r}", flush=True)
134
  return text
135
  except Exception as e:
 
10
  """
11
  from __future__ import annotations
12
 
 
13
  import threading
14
 
15
  COHERE_ASR_ID = "CohereLabs/cohere-transcribe-03-2026"
 
54
  @_gpu
55
  def transcribe(audio: "str | tuple[int, np.ndarray] | None", language: str = "en") -> str:
56
  """gr.Audio filepath (or legacy (sr, array) tuple) -> witness text in the
57
+ selected language ('en'/'es'). Empty string on any failure, and a silent clip
58
+ returns "" rather than a hallucination — never fabricated text."""
 
59
  import numpy as np
60
 
61
  if audio is None:
62
  return ""
63
+ # Read as float [-1, 1]. soundfile handles wav/flac/ogg; librosa (ffmpeg) covers
64
+ # m4a/mp3/opus uploads. (gr.Audio has format="wav", so recordings arrive as wav.)
65
+ # A legacy (sample_rate, numpy) tuple is still accepted.
 
66
  if isinstance(audio, str):
67
  try:
68
  import soundfile as sf
 
73
  wav = np.asarray(wav, dtype=np.float32)
74
  print(f"[asr] soundfile failed ({type(e_sf).__name__}: {e_sf}); "
75
  f"used librosa/ffmpeg", flush=True)
 
76
  else:
77
  sr, wav = audio
78
  wav = np.asarray(wav, dtype=np.float32)
79
  if np.abs(wav).max() > 1.5: # legacy int16-ranged numpy input
80
  wav = wav / 32768.0
 
81
  wav = np.asarray(wav, dtype=np.float32)
82
  if wav.ndim > 1:
83
  wav = wav.mean(axis=1)
84
+ # Silence guard: a silent/near-silent clip must NOT be fed to the model — it
85
+ # answers confident hallucinations. Return "" instead.
 
 
 
 
86
  peak = float(np.abs(wav).max()) if wav.size else 0.0
87
  if len(wav) < sr // 2 or peak < 1e-3:
88
  print(f"[asr] no usable audio (samples={len(wav)}, peak={peak:.5f}) -> empty", flush=True)
 
92
  try:
93
  import torch
94
  proc, mdl = _load()
95
+ if sr != 16000: # fast polyphase resample (librosa's default was ~13s on mic clips)
96
+ try:
97
  from scipy.signal import resample_poly
98
  wav = resample_poly(wav, 16000, sr).astype(np.float32)
 
99
  except Exception:
100
  try:
101
  import librosa
102
  wav = librosa.resample(np.ascontiguousarray(wav), orig_sr=sr, target_sr=16000)
103
+ except Exception:
 
104
  idx = np.linspace(0, len(wav) - 1, int(len(wav) * 16000 / sr))
105
  wav = wav[np.floor(idx).astype(int)]
 
 
 
 
 
 
 
106
  # `language` is a REQUIRED processor arg: it builds the decoder prompt.
107
  inputs = proc(wav, language=lang, sampling_rate=16000, return_tensors="pt")
108
  inputs = {k: (v.to(mdl.device, dtype=mdl.dtype) if v.dtype.is_floating_point
 
110
  with torch.no_grad():
111
  ids = mdl.generate(**inputs, max_new_tokens=120)
112
  text = proc.batch_decode(ids, skip_special_tokens=True)[0].strip()
 
 
113
  print(f"[asr] {lang}: {text[:90]!r}", flush=True)
114
  return text
115
  except Exception as e: