AvatarResurrectionChatbot commited on
Commit
d70cd2e
·
verified ·
1 Parent(s): 9d8f4fc

Update vosk_stt.py

Browse files
Files changed (1) hide show
  1. vosk_stt.py +158 -44
vosk_stt.py CHANGED
@@ -1,6 +1,7 @@
1
  """
2
  Vosk Speech-to-Text for HuggingFace Spaces.
3
- Receives audio blobs from the browser, transcribes them server-side.
 
4
  Uses the small English model (~50MB, CPU-only).
5
  """
6
  import os
@@ -10,6 +11,7 @@ import wave
10
  import logging
11
  import subprocess
12
  import tempfile
 
13
 
14
  logger = logging.getLogger(__name__)
15
 
@@ -17,6 +19,11 @@ VOSK_MODEL_PATH = "/app/vosk-model"
17
  _model = None
18
  _initialized = False
19
 
 
 
 
 
 
20
 
21
  def _ts():
22
  return time.strftime("%H:%M:%S", time.gmtime()) + f".{int(time.time()*1000)%1000:03d}"
@@ -38,7 +45,7 @@ def initialize():
38
 
39
  try:
40
  from vosk import Model, SetLogLevel
41
- SetLogLevel(-1) # Suppress Vosk's verbose logging
42
  _model = Model(VOSK_MODEL_PATH)
43
  _initialized = True
44
  logger.info(f"[{_ts()}] [STT] ✓ Vosk ready in {time.time()-t0:.2f}s")
@@ -48,72 +55,179 @@ def initialize():
48
  return False
49
 
50
 
51
- def transcribe_audio(audio_bytes: bytes, content_type: str = "audio/webm") -> str:
52
- """
53
- Transcribe audio bytes to text.
 
54
 
55
- Args:
56
- audio_bytes: Raw audio data from browser MediaRecorder
57
- content_type: MIME type of the audio (audio/webm, audio/ogg, etc.)
58
 
59
- Returns:
60
- Transcribed text string, or empty string on failure
61
- """
62
- if not _initialized or _model is None:
63
- logger.error(f"[{_ts()}] [STT] Not initialized")
64
- return ""
 
 
 
 
 
 
65
 
66
- t0 = time.time()
 
 
 
 
 
 
 
 
 
67
 
68
  try:
69
- from vosk import KaldiRecognizer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
- # Save incoming audio to temp file
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  suffix = ".webm" if "webm" in content_type else ".ogg"
73
  with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp_in:
74
  tmp_in.write(audio_bytes)
75
  tmp_in_path = tmp_in.name
76
 
77
- # Convert to 16kHz mono WAV using ffmpeg
78
- tmp_wav_path = tmp_in_path + ".wav"
79
  cmd = [
80
  "ffmpeg", "-y", "-i", tmp_in_path,
81
- "-ar", "16000", "-ac", "1", "-f", "wav",
82
- tmp_wav_path
83
  ]
84
  result = subprocess.run(cmd, capture_output=True)
 
85
  if result.returncode != 0:
86
- logger.error(f"[{_ts()}] [STT] ffmpeg conversion failed: {result.stderr.decode()[:200]}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  return ""
88
 
89
- # Read WAV and transcribe
90
  rec = KaldiRecognizer(_model, 16000)
91
- rec.SetWords(False)
92
 
93
- with wave.open(tmp_wav_path, "rb") as wf:
94
- while True:
95
- data = wf.readframes(4000)
96
- if len(data) == 0:
97
- break
98
- rec.AcceptWaveform(data)
99
 
100
- # Get final result
101
  final = json.loads(rec.FinalResult())
102
  text = final.get("text", "").strip()
103
 
104
- elapsed = time.time() - t0
105
- logger.info(f"[{_ts()}] [STT] Transcribed in {elapsed:.2f}s: \"{text[:80]}\"")
106
-
107
  return text
108
 
109
  except Exception as e:
110
- logger.error(f"[{_ts()}] [STT] Transcription error: {e}", exc_info=True)
111
- return ""
112
-
113
- finally:
114
- # Cleanup temp files
115
- for p in [tmp_in_path, tmp_wav_path]:
116
- try:
117
- os.unlink(p)
118
- except Exception:
119
- pass
 
1
  """
2
  Vosk Speech-to-Text for HuggingFace Spaces.
3
+ Supports both one-shot transcription and streaming sessions.
4
+ Streaming: browser sends audio chunks every ~500ms, server returns partial text.
5
  Uses the small English model (~50MB, CPU-only).
6
  """
7
  import os
 
11
  import logging
12
  import subprocess
13
  import tempfile
14
+ import threading
15
 
16
  logger = logging.getLogger(__name__)
17
 
 
19
  _model = None
20
  _initialized = False
21
 
22
+ # Streaming sessions: session_id -> {recognizer, last_active, text}
23
+ _sessions = {}
24
+ _sessions_lock = threading.Lock()
25
+ SESSION_TIMEOUT = 120 # seconds
26
+
27
 
28
  def _ts():
29
  return time.strftime("%H:%M:%S", time.gmtime()) + f".{int(time.time()*1000)%1000:03d}"
 
45
 
46
  try:
47
  from vosk import Model, SetLogLevel
48
+ SetLogLevel(-1)
49
  _model = Model(VOSK_MODEL_PATH)
50
  _initialized = True
51
  logger.info(f"[{_ts()}] [STT] ✓ Vosk ready in {time.time()-t0:.2f}s")
 
55
  return False
56
 
57
 
58
+ def create_session(session_id: str):
59
+ """Create a new streaming recognition session."""
60
+ if not _initialized or _model is None:
61
+ return False
62
 
63
+ from vosk import KaldiRecognizer
 
 
64
 
65
+ with _sessions_lock:
66
+ _sessions[session_id] = {
67
+ "recognizer": KaldiRecognizer(_model, 16000),
68
+ "last_active": time.time(),
69
+ "partial": "",
70
+ "finals": [],
71
+ }
72
+ # Cleanup old sessions
73
+ _cleanup_sessions()
74
+
75
+ logger.info(f"[{_ts()}] [STT] Session created: {session_id}")
76
+ return True
77
 
78
+
79
+ def feed_audio_chunk(session_id: str, audio_bytes: bytes, content_type: str = "audio/webm") -> dict:
80
+ """
81
+ Feed an audio chunk to a streaming session.
82
+ Returns: {"partial": str, "text": str} where text is accumulated finals + current partial
83
+ """
84
+ with _sessions_lock:
85
+ session = _sessions.get(session_id)
86
+ if not session:
87
+ return {"partial": "", "text": "", "error": "session not found"}
88
 
89
  try:
90
+ # Convert chunk to 16kHz mono PCM
91
+ pcm_data = _convert_to_pcm(audio_bytes, content_type)
92
+ if not pcm_data:
93
+ return {"partial": session["partial"], "text": _get_full_text(session)}
94
+
95
+ rec = session["recognizer"]
96
+ session["last_active"] = time.time()
97
+
98
+ # Feed to recognizer in small frames
99
+ offset = 0
100
+ while offset < len(pcm_data):
101
+ chunk = pcm_data[offset:offset + 8000]
102
+ offset += 8000
103
+
104
+ if rec.AcceptWaveform(chunk):
105
+ # Got a final result for this segment
106
+ result = json.loads(rec.Result())
107
+ final_text = result.get("text", "").strip()
108
+ if final_text:
109
+ session["finals"].append(final_text)
110
+
111
+ # Get current partial
112
+ partial_result = json.loads(rec.PartialResult())
113
+ session["partial"] = partial_result.get("partial", "")
114
+
115
+ full_text = _get_full_text(session)
116
+ return {"partial": session["partial"], "text": full_text}
117
+
118
+ except Exception as e:
119
+ logger.error(f"[{_ts()}] [STT] Feed error: {e}")
120
+ return {"partial": "", "text": _get_full_text(session), "error": str(e)}
121
+
122
+
123
+ def finish_session(session_id: str) -> str:
124
+ """Finalize a session — get the last remaining text and clean up."""
125
+ with _sessions_lock:
126
+ session = _sessions.get(session_id)
127
+ if not session:
128
+ return ""
129
+
130
+ rec = session["recognizer"]
131
+
132
+ # Get final result
133
+ final = json.loads(rec.FinalResult())
134
+ final_text = final.get("text", "").strip()
135
+ if final_text:
136
+ session["finals"].append(final_text)
137
+
138
+ full_text = _get_full_text(session)
139
+
140
+ # Clean up
141
+ with _sessions_lock:
142
+ _sessions.pop(session_id, None)
143
 
144
+ logger.info(f"[{_ts()}] [STT] Session finished: {session_id} → \"{full_text[:80]}\"")
145
+ return full_text
146
+
147
+
148
+ def _get_full_text(session) -> str:
149
+ """Combine all final segments + current partial."""
150
+ parts = session["finals"][:]
151
+ if session["partial"]:
152
+ parts.append(session["partial"])
153
+ return " ".join(parts)
154
+
155
+
156
+ def _convert_to_pcm(audio_bytes: bytes, content_type: str) -> bytes:
157
+ """Convert audio blob to raw 16kHz mono 16-bit PCM using ffmpeg."""
158
+ try:
159
  suffix = ".webm" if "webm" in content_type else ".ogg"
160
  with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp_in:
161
  tmp_in.write(audio_bytes)
162
  tmp_in_path = tmp_in.name
163
 
164
+ tmp_pcm_path = tmp_in_path + ".pcm"
 
165
  cmd = [
166
  "ffmpeg", "-y", "-i", tmp_in_path,
167
+ "-ar", "16000", "-ac", "1", "-f", "s16le",
168
+ tmp_pcm_path
169
  ]
170
  result = subprocess.run(cmd, capture_output=True)
171
+
172
  if result.returncode != 0:
173
+ return None
174
+
175
+ with open(tmp_pcm_path, "rb") as f:
176
+ pcm_data = f.read()
177
+
178
+ return pcm_data
179
+
180
+ except Exception:
181
+ return None
182
+
183
+ finally:
184
+ for p in [tmp_in_path, tmp_pcm_path]:
185
+ try:
186
+ os.unlink(p)
187
+ except Exception:
188
+ pass
189
+
190
+
191
+ def _cleanup_sessions():
192
+ """Remove expired sessions (call while holding lock)."""
193
+ now = time.time()
194
+ expired = [k for k, v in _sessions.items() if now - v["last_active"] > SESSION_TIMEOUT]
195
+ for k in expired:
196
+ del _sessions[k]
197
+ if expired:
198
+ logger.info(f"[{_ts()}] [STT] Cleaned up {len(expired)} expired sessions")
199
+
200
+
201
+ # ---- One-shot transcription (backward compat) ----
202
+
203
+ def transcribe_audio(audio_bytes: bytes, content_type: str = "audio/webm") -> str:
204
+ """One-shot transcribe (non-streaming). Used as fallback."""
205
+ if not _initialized or _model is None:
206
+ return ""
207
+
208
+ t0 = time.time()
209
+
210
+ try:
211
+ from vosk import KaldiRecognizer
212
+
213
+ pcm_data = _convert_to_pcm(audio_bytes, content_type)
214
+ if not pcm_data:
215
  return ""
216
 
 
217
  rec = KaldiRecognizer(_model, 16000)
 
218
 
219
+ offset = 0
220
+ while offset < len(pcm_data):
221
+ chunk = pcm_data[offset:offset + 8000]
222
+ offset += 8000
223
+ rec.AcceptWaveform(chunk)
 
224
 
 
225
  final = json.loads(rec.FinalResult())
226
  text = final.get("text", "").strip()
227
 
228
+ logger.info(f"[{_ts()}] [STT] Transcribed in {time.time()-t0:.2f}s: \"{text[:80]}\"")
 
 
229
  return text
230
 
231
  except Exception as e:
232
+ logger.error(f"[{_ts()}] [STT] Error: {e}", exc_info=True)
233
+ return ""