Spaces:
Sleeping
Sleeping
Upload whisper_online module and demo.wav
Browse files- .gitattributes +1 -0
- demo.wav +3 -0
- whisper_online.py +740 -0
.gitattributes
CHANGED
@@ -32,3 +32,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
32 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
33 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
34 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
32 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
33 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
34 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
35 |
+
demo.wav filter=lfs diff=lfs merge=lfs -text
|
demo.wav
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:c9eb3ce675366cb216fa8f4033842e913b65df0d1897b14ec2f78ea54fedcb5a
|
3 |
+
size 1474638
|
whisper_online.py
ADDED
@@ -0,0 +1,740 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
import sys
|
3 |
+
import numpy as np
|
4 |
+
import librosa
|
5 |
+
from functools import lru_cache
|
6 |
+
import time
|
7 |
+
import logging
|
8 |
+
|
9 |
+
|
10 |
+
import io
|
11 |
+
import soundfile as sf
|
12 |
+
import math
|
13 |
+
|
14 |
+
logger = logging.getLogger(__name__)
|
15 |
+
|
16 |
+
@lru_cache
|
17 |
+
def load_audio(fname):
|
18 |
+
a, _ = librosa.load(fname, sr=16000, dtype=np.float32)
|
19 |
+
return a
|
20 |
+
|
21 |
+
def load_audio_chunk(fname, beg, end):
|
22 |
+
audio = load_audio(fname)
|
23 |
+
beg_s = int(beg*16000)
|
24 |
+
end_s = int(end*16000)
|
25 |
+
return audio[beg_s:end_s]
|
26 |
+
|
27 |
+
|
28 |
+
# Whisper backend
|
29 |
+
|
30 |
+
class ASRBase:
|
31 |
+
|
32 |
+
sep = " " # join transcribe words with this character (" " for whisper_timestamped,
|
33 |
+
# "" for faster-whisper because it emits the spaces when neeeded)
|
34 |
+
|
35 |
+
def __init__(self, lan, modelsize=None, cache_dir=None, model_dir=None, logfile=sys.stderr):
|
36 |
+
self.logfile = logfile
|
37 |
+
|
38 |
+
self.transcribe_kargs = {}
|
39 |
+
if lan == "auto":
|
40 |
+
self.original_language = None
|
41 |
+
else:
|
42 |
+
self.original_language = lan
|
43 |
+
|
44 |
+
print("Loading Whisper model for", lan, "...")
|
45 |
+
self.model = self.load_model(modelsize, cache_dir, model_dir)
|
46 |
+
print("Loaded Whisper model.")
|
47 |
+
|
48 |
+
|
49 |
+
def load_model(self, modelsize, cache_dir):
|
50 |
+
raise NotImplemented("must be implemented in the child class")
|
51 |
+
|
52 |
+
def transcribe(self, audio, init_prompt=""):
|
53 |
+
raise NotImplemented("must be implemented in the child class")
|
54 |
+
|
55 |
+
def use_vad(self):
|
56 |
+
raise NotImplemented("must be implemented in the child class")
|
57 |
+
|
58 |
+
|
59 |
+
class WhisperTimestampedASR(ASRBase):
|
60 |
+
"""Uses whisper_timestamped library as the backend. Initially, we tested the code on this backend. It worked, but slower than faster-whisper.
|
61 |
+
On the other hand, the installation for GPU could be easier.
|
62 |
+
"""
|
63 |
+
|
64 |
+
sep = " "
|
65 |
+
|
66 |
+
def load_model(self, modelsize=None, cache_dir=None, model_dir=None):
|
67 |
+
import whisper
|
68 |
+
import whisper_timestamped
|
69 |
+
from whisper_timestamped import transcribe_timestamped
|
70 |
+
self.transcribe_timestamped = transcribe_timestamped
|
71 |
+
if model_dir is not None:
|
72 |
+
logger.debug("ignoring model_dir, not implemented")
|
73 |
+
return whisper.load_model(modelsize, download_root=cache_dir)
|
74 |
+
|
75 |
+
def transcribe(self, audio, init_prompt=""):
|
76 |
+
result = self.transcribe_timestamped(self.model,
|
77 |
+
audio, language=self.original_language,
|
78 |
+
initial_prompt=init_prompt, verbose=None,
|
79 |
+
condition_on_previous_text=True, **self.transcribe_kargs)
|
80 |
+
return result
|
81 |
+
|
82 |
+
def ts_words(self,r):
|
83 |
+
# return: transcribe result object to [(beg,end,"word1"), ...]
|
84 |
+
o = []
|
85 |
+
for s in r["segments"]:
|
86 |
+
for w in s["words"]:
|
87 |
+
t = (w["start"],w["end"],w["text"])
|
88 |
+
o.append(t)
|
89 |
+
return o
|
90 |
+
|
91 |
+
def segments_end_ts(self, res):
|
92 |
+
return [s["end"] for s in res["segments"]]
|
93 |
+
|
94 |
+
def use_vad(self):
|
95 |
+
self.transcribe_kargs["vad"] = True
|
96 |
+
|
97 |
+
def set_translate_task(self):
|
98 |
+
self.transcribe_kargs["task"] = "translate"
|
99 |
+
|
100 |
+
|
101 |
+
|
102 |
+
|
103 |
+
class FasterWhisperASR(ASRBase):
|
104 |
+
"""Uses faster-whisper library as the backend. Works much faster, appx 4-times (in offline mode). For GPU, it requires installation with a specific CUDNN version.
|
105 |
+
"""
|
106 |
+
|
107 |
+
sep = ""
|
108 |
+
|
109 |
+
def load_model(self, modelsize=None, cache_dir=None, model_dir=None):
|
110 |
+
from faster_whisper import WhisperModel
|
111 |
+
# logging.getLogger("faster_whisper").setLevel(logger.level)
|
112 |
+
if model_dir is not None:
|
113 |
+
logger.debug(f"Loading whisper model from model_dir {model_dir}. modelsize and cache_dir parameters are not used.")
|
114 |
+
model_size_or_path = model_dir
|
115 |
+
elif modelsize is not None:
|
116 |
+
model_size_or_path = modelsize
|
117 |
+
else:
|
118 |
+
raise ValueError("modelsize or model_dir parameter must be set")
|
119 |
+
|
120 |
+
|
121 |
+
# this worked fast and reliably on NVIDIA L40
|
122 |
+
model = WhisperModel(model_size_or_path, device="cuda", compute_type="float16", download_root=cache_dir)
|
123 |
+
|
124 |
+
# or run on GPU with INT8
|
125 |
+
# tested: the transcripts were different, probably worse than with FP16, and it was slightly (appx 20%) slower
|
126 |
+
#model = WhisperModel(model_size, device="cuda", compute_type="int8_float16")
|
127 |
+
|
128 |
+
# or run on CPU with INT8
|
129 |
+
# tested: works, but slow, appx 10-times than cuda FP16
|
130 |
+
# model = WhisperModel(modelsize, device="cpu", compute_type="int8") #, download_root="faster-disk-cache-dir/")
|
131 |
+
return model
|
132 |
+
|
133 |
+
def transcribe(self, audio, init_prompt=""):
|
134 |
+
|
135 |
+
# tested: beam_size=5 is faster and better than 1 (on one 200 second document from En ESIC, min chunk 0.01)
|
136 |
+
segments, info = self.model.transcribe(audio, language=self.original_language, initial_prompt=init_prompt, beam_size=5, word_timestamps=True, condition_on_previous_text=True, **self.transcribe_kargs)
|
137 |
+
#print(info) # info contains language detection result
|
138 |
+
|
139 |
+
return list(segments)
|
140 |
+
|
141 |
+
def ts_words(self, segments):
|
142 |
+
o = []
|
143 |
+
for segment in segments:
|
144 |
+
for word in segment.words:
|
145 |
+
# not stripping the spaces -- should not be merged with them!
|
146 |
+
w = word.word
|
147 |
+
t = (word.start, word.end, w)
|
148 |
+
o.append(t)
|
149 |
+
return o
|
150 |
+
|
151 |
+
def segments_end_ts(self, res):
|
152 |
+
return [s.end for s in res]
|
153 |
+
|
154 |
+
def use_vad(self):
|
155 |
+
self.transcribe_kargs["vad_filter"] = True
|
156 |
+
|
157 |
+
def set_translate_task(self):
|
158 |
+
self.transcribe_kargs["task"] = "translate"
|
159 |
+
|
160 |
+
|
161 |
+
class OpenaiApiASR(ASRBase):
|
162 |
+
"""Uses OpenAI's Whisper API for audio transcription."""
|
163 |
+
|
164 |
+
def __init__(self, lan=None, temperature=0, logfile=sys.stderr):
|
165 |
+
self.logfile = logfile
|
166 |
+
|
167 |
+
self.modelname = "whisper-1"
|
168 |
+
self.original_language = None if lan == "auto" else lan # ISO-639-1 language code
|
169 |
+
self.response_format = "verbose_json"
|
170 |
+
self.temperature = temperature
|
171 |
+
|
172 |
+
self.load_model()
|
173 |
+
|
174 |
+
self.use_vad_opt = False
|
175 |
+
|
176 |
+
# reset the task in set_translate_task
|
177 |
+
self.task = "transcribe"
|
178 |
+
|
179 |
+
def load_model(self, *args, **kwargs):
|
180 |
+
from openai import OpenAI
|
181 |
+
self.client = OpenAI()
|
182 |
+
|
183 |
+
self.transcribed_seconds = 0 # for logging how many seconds were processed by API, to know the cost
|
184 |
+
|
185 |
+
|
186 |
+
def ts_words(self, segments):
|
187 |
+
no_speech_segments = []
|
188 |
+
if self.use_vad_opt:
|
189 |
+
for segment in segments.segments:
|
190 |
+
# TODO: threshold can be set from outside
|
191 |
+
if segment["no_speech_prob"] > 0.8:
|
192 |
+
no_speech_segments.append((segment.get("start"), segment.get("end")))
|
193 |
+
|
194 |
+
o = []
|
195 |
+
for word in segments.words:
|
196 |
+
start = word.get("start")
|
197 |
+
end = word.get("end")
|
198 |
+
if any(s[0] <= start <= s[1] for s in no_speech_segments):
|
199 |
+
# print("Skipping word", word.get("word"), "because it's in a no-speech segment")
|
200 |
+
continue
|
201 |
+
o.append((start, end, word.get("word")))
|
202 |
+
return o
|
203 |
+
|
204 |
+
|
205 |
+
def segments_end_ts(self, res):
|
206 |
+
return [s["end"] for s in res.words]
|
207 |
+
|
208 |
+
def transcribe(self, audio_data, prompt=None, *args, **kwargs):
|
209 |
+
# Write the audio data to a buffer
|
210 |
+
buffer = io.BytesIO()
|
211 |
+
buffer.name = "temp.wav"
|
212 |
+
sf.write(buffer, audio_data, samplerate=16000, format='WAV', subtype='PCM_16')
|
213 |
+
buffer.seek(0) # Reset buffer's position to the beginning
|
214 |
+
|
215 |
+
self.transcribed_seconds += math.ceil(len(audio_data)/16000) # it rounds up to the whole seconds
|
216 |
+
|
217 |
+
params = {
|
218 |
+
"model": self.modelname,
|
219 |
+
"file": buffer,
|
220 |
+
"response_format": self.response_format,
|
221 |
+
"temperature": self.temperature,
|
222 |
+
"timestamp_granularities": ["word", "segment"]
|
223 |
+
}
|
224 |
+
if self.task != "translate" and self.original_language:
|
225 |
+
params["language"] = self.original_language
|
226 |
+
if prompt:
|
227 |
+
params["prompt"] = prompt
|
228 |
+
|
229 |
+
if self.task == "translate":
|
230 |
+
proc = self.client.audio.translations
|
231 |
+
else:
|
232 |
+
proc = self.client.audio.transcriptions
|
233 |
+
|
234 |
+
# Process transcription/translation
|
235 |
+
transcript = proc.create(**params)
|
236 |
+
logger.debug(f"OpenAI API processed accumulated {self.transcribed_seconds} seconds")
|
237 |
+
|
238 |
+
return transcript
|
239 |
+
|
240 |
+
def use_vad(self):
|
241 |
+
self.use_vad_opt = True
|
242 |
+
|
243 |
+
def set_translate_task(self):
|
244 |
+
self.task = "translate"
|
245 |
+
|
246 |
+
|
247 |
+
|
248 |
+
|
249 |
+
class HypothesisBuffer:
|
250 |
+
|
251 |
+
def __init__(self, logfile=sys.stderr):
|
252 |
+
self.commited_in_buffer = []
|
253 |
+
self.buffer = []
|
254 |
+
self.new = []
|
255 |
+
|
256 |
+
self.last_commited_time = 0
|
257 |
+
self.last_commited_word = None
|
258 |
+
|
259 |
+
self.logfile = logfile
|
260 |
+
|
261 |
+
def insert(self, new, offset):
|
262 |
+
# compare self.commited_in_buffer and new. It inserts only the words in new that extend the commited_in_buffer, it means they are roughly behind last_commited_time and new in content
|
263 |
+
# the new tail is added to self.new
|
264 |
+
|
265 |
+
new = [(a+offset,b+offset,t) for a,b,t in new]
|
266 |
+
self.new = [(a,b,t) for a,b,t in new if a > self.last_commited_time-0.1]
|
267 |
+
|
268 |
+
if len(self.new) >= 1:
|
269 |
+
a,b,t = self.new[0]
|
270 |
+
if abs(a - self.last_commited_time) < 1:
|
271 |
+
if self.commited_in_buffer:
|
272 |
+
# it's going to search for 1, 2, ..., 5 consecutive words (n-grams) that are identical in commited and new. If they are, they're dropped.
|
273 |
+
cn = len(self.commited_in_buffer)
|
274 |
+
nn = len(self.new)
|
275 |
+
for i in range(1,min(min(cn,nn),5)+1): # 5 is the maximum
|
276 |
+
c = " ".join([self.commited_in_buffer[-j][2] for j in range(1,i+1)][::-1])
|
277 |
+
tail = " ".join(self.new[j-1][2] for j in range(1,i+1))
|
278 |
+
if c == tail:
|
279 |
+
words = []
|
280 |
+
for j in range(i):
|
281 |
+
words.append(repr(self.new.pop(0)))
|
282 |
+
words_msg = " ".join(words)
|
283 |
+
logger.debug(f"removing last {i} words: {words_msg}")
|
284 |
+
break
|
285 |
+
|
286 |
+
def flush(self):
|
287 |
+
# returns commited chunk = the longest common prefix of 2 last inserts.
|
288 |
+
|
289 |
+
commit = []
|
290 |
+
while self.new:
|
291 |
+
na, nb, nt = self.new[0]
|
292 |
+
|
293 |
+
if len(self.buffer) == 0:
|
294 |
+
break
|
295 |
+
|
296 |
+
if nt == self.buffer[0][2]:
|
297 |
+
commit.append((na,nb,nt))
|
298 |
+
self.last_commited_word = nt
|
299 |
+
self.last_commited_time = nb
|
300 |
+
self.buffer.pop(0)
|
301 |
+
self.new.pop(0)
|
302 |
+
else:
|
303 |
+
break
|
304 |
+
self.buffer = self.new
|
305 |
+
self.new = []
|
306 |
+
self.commited_in_buffer.extend(commit)
|
307 |
+
return commit
|
308 |
+
|
309 |
+
def pop_commited(self, time):
|
310 |
+
while self.commited_in_buffer and self.commited_in_buffer[0][1] <= time:
|
311 |
+
self.commited_in_buffer.pop(0)
|
312 |
+
|
313 |
+
def complete(self):
|
314 |
+
return self.buffer
|
315 |
+
|
316 |
+
class OnlineASRProcessor:
|
317 |
+
|
318 |
+
SAMPLING_RATE = 16000
|
319 |
+
|
320 |
+
def __init__(self, asr, tokenizer=None, buffer_trimming=("segment", 15), logfile=sys.stderr):
|
321 |
+
"""asr: WhisperASR object
|
322 |
+
tokenizer: sentence tokenizer object for the target language. Must have a method *split* that behaves like the one of MosesTokenizer. It can be None, if "segment" buffer trimming option is used, then tokenizer is not used at all.
|
323 |
+
("segment", 15)
|
324 |
+
buffer_trimming: a pair of (option, seconds), where option is either "sentence" or "segment", and seconds is a number. Buffer is trimmed if it is longer than "seconds" threshold. Default is the most recommended option.
|
325 |
+
logfile: where to store the log.
|
326 |
+
"""
|
327 |
+
self.asr = asr
|
328 |
+
self.tokenizer = tokenizer
|
329 |
+
self.logfile = logfile
|
330 |
+
|
331 |
+
self.init()
|
332 |
+
|
333 |
+
self.buffer_trimming_way, self.buffer_trimming_sec = buffer_trimming
|
334 |
+
|
335 |
+
def init(self):
|
336 |
+
"""run this when starting or restarting processing"""
|
337 |
+
self.audio_buffer = np.array([],dtype=np.float32)
|
338 |
+
self.buffer_time_offset = 0
|
339 |
+
|
340 |
+
self.transcript_buffer = HypothesisBuffer(logfile=self.logfile)
|
341 |
+
self.commited = []
|
342 |
+
|
343 |
+
def insert_audio_chunk(self, audio):
|
344 |
+
self.audio_buffer = np.append(self.audio_buffer, audio)
|
345 |
+
|
346 |
+
def prompt(self):
|
347 |
+
"""Returns a tuple: (prompt, context), where "prompt" is a 200-character suffix of commited text that is inside of the scrolled away part of audio buffer.
|
348 |
+
"context" is the commited text that is inside the audio buffer. It is transcribed again and skipped. It is returned only for debugging and logging reasons.
|
349 |
+
"""
|
350 |
+
k = max(0,len(self.commited)-1)
|
351 |
+
while k > 0 and self.commited[k-1][1] > self.buffer_time_offset:
|
352 |
+
k -= 1
|
353 |
+
|
354 |
+
p = self.commited[:k]
|
355 |
+
p = [t for _,_,t in p]
|
356 |
+
prompt = []
|
357 |
+
l = 0
|
358 |
+
while p and l < 200: # 200 characters prompt size
|
359 |
+
x = p.pop(-1)
|
360 |
+
l += len(x)+1
|
361 |
+
prompt.append(x)
|
362 |
+
non_prompt = self.commited[k:]
|
363 |
+
return self.asr.sep.join(prompt[::-1]), self.asr.sep.join(t for _,_,t in non_prompt)
|
364 |
+
|
365 |
+
def process_iter(self):
|
366 |
+
"""Runs on the current audio buffer.
|
367 |
+
Returns: a tuple (beg_timestamp, end_timestamp, "text"), or (None, None, "").
|
368 |
+
The non-emty text is confirmed (committed) partial transcript.
|
369 |
+
"""
|
370 |
+
|
371 |
+
prompt, non_prompt = self.prompt()
|
372 |
+
logger.debug(f"PROMPT: {prompt}")
|
373 |
+
logger.debug(f"CONTEXT: {non_prompt}")
|
374 |
+
logger.debug(f"transcribing {len(self.audio_buffer)/self.SAMPLING_RATE:2.2f} seconds from {self.buffer_time_offset:2.2f}")
|
375 |
+
res = self.asr.transcribe(self.audio_buffer, init_prompt=prompt)
|
376 |
+
|
377 |
+
# transform to [(beg,end,"word1"), ...]
|
378 |
+
tsw = self.asr.ts_words(res)
|
379 |
+
|
380 |
+
self.transcript_buffer.insert(tsw, self.buffer_time_offset)
|
381 |
+
o = self.transcript_buffer.flush()
|
382 |
+
self.commited.extend(o)
|
383 |
+
completed = self.to_flush(o)
|
384 |
+
logger.debug(f">>>>COMPLETE NOW: {completed}")
|
385 |
+
the_rest = self.to_flush(self.transcript_buffer.complete())
|
386 |
+
logger.debug(f"INCOMPLETE: {the_rest}")
|
387 |
+
|
388 |
+
# there is a newly confirmed text
|
389 |
+
|
390 |
+
if o and self.buffer_trimming_way == "sentence": # trim the completed sentences
|
391 |
+
if len(self.audio_buffer)/self.SAMPLING_RATE > self.buffer_trimming_sec: # longer than this
|
392 |
+
self.chunk_completed_sentence()
|
393 |
+
|
394 |
+
|
395 |
+
if self.buffer_trimming_way == "segment":
|
396 |
+
s = self.buffer_trimming_sec # trim the completed segments longer than s,
|
397 |
+
else:
|
398 |
+
s = 30 # if the audio buffer is longer than 30s, trim it
|
399 |
+
|
400 |
+
if len(self.audio_buffer)/self.SAMPLING_RATE > s:
|
401 |
+
self.chunk_completed_segment(res)
|
402 |
+
|
403 |
+
# alternative: on any word
|
404 |
+
#l = self.buffer_time_offset + len(self.audio_buffer)/self.SAMPLING_RATE - 10
|
405 |
+
# let's find commited word that is less
|
406 |
+
#k = len(self.commited)-1
|
407 |
+
#while k>0 and self.commited[k][1] > l:
|
408 |
+
# k -= 1
|
409 |
+
#t = self.commited[k][1]
|
410 |
+
logger.debug("chunking segment")
|
411 |
+
#self.chunk_at(t)
|
412 |
+
|
413 |
+
logger.debug(f"len of buffer now: {len(self.audio_buffer)/self.SAMPLING_RATE:2.2f}")
|
414 |
+
return self.to_flush(o)
|
415 |
+
|
416 |
+
def chunk_completed_sentence(self):
|
417 |
+
if self.commited == []: return
|
418 |
+
logger.debug(self.commited)
|
419 |
+
sents = self.words_to_sentences(self.commited)
|
420 |
+
for s in sents:
|
421 |
+
logger.debug(f"\t\tSENT: {s}")
|
422 |
+
if len(sents) < 2:
|
423 |
+
return
|
424 |
+
while len(sents) > 2:
|
425 |
+
sents.pop(0)
|
426 |
+
# we will continue with audio processing at this timestamp
|
427 |
+
chunk_at = sents[-2][1]
|
428 |
+
|
429 |
+
logger.debug(f"--- sentence chunked at {chunk_at:2.2f}")
|
430 |
+
self.chunk_at(chunk_at)
|
431 |
+
|
432 |
+
def chunk_completed_segment(self, res):
|
433 |
+
if self.commited == []: return
|
434 |
+
|
435 |
+
ends = self.asr.segments_end_ts(res)
|
436 |
+
|
437 |
+
t = self.commited[-1][1]
|
438 |
+
|
439 |
+
if len(ends) > 1:
|
440 |
+
|
441 |
+
e = ends[-2]+self.buffer_time_offset
|
442 |
+
while len(ends) > 2 and e > t:
|
443 |
+
ends.pop(-1)
|
444 |
+
e = ends[-2]+self.buffer_time_offset
|
445 |
+
if e <= t:
|
446 |
+
logger.debug(f"--- segment chunked at {e:2.2f}")
|
447 |
+
self.chunk_at(e)
|
448 |
+
else:
|
449 |
+
logger.debug(f"--- last segment not within commited area")
|
450 |
+
else:
|
451 |
+
logger.debug(f"--- not enough segments to chunk")
|
452 |
+
|
453 |
+
|
454 |
+
|
455 |
+
|
456 |
+
|
457 |
+
def chunk_at(self, time):
|
458 |
+
"""trims the hypothesis and audio buffer at "time"
|
459 |
+
"""
|
460 |
+
self.transcript_buffer.pop_commited(time)
|
461 |
+
cut_seconds = time - self.buffer_time_offset
|
462 |
+
self.audio_buffer = self.audio_buffer[int(cut_seconds*self.SAMPLING_RATE):]
|
463 |
+
self.buffer_time_offset = time
|
464 |
+
|
465 |
+
def words_to_sentences(self, words):
|
466 |
+
"""Uses self.tokenizer for sentence segmentation of words.
|
467 |
+
Returns: [(beg,end,"sentence 1"),...]
|
468 |
+
"""
|
469 |
+
|
470 |
+
cwords = [w for w in words]
|
471 |
+
t = " ".join(o[2] for o in cwords)
|
472 |
+
s = self.tokenizer.split(t)
|
473 |
+
out = []
|
474 |
+
while s:
|
475 |
+
beg = None
|
476 |
+
end = None
|
477 |
+
sent = s.pop(0).strip()
|
478 |
+
fsent = sent
|
479 |
+
while cwords:
|
480 |
+
b,e,w = cwords.pop(0)
|
481 |
+
w = w.strip()
|
482 |
+
if beg is None and sent.startswith(w):
|
483 |
+
beg = b
|
484 |
+
elif end is None and sent == w:
|
485 |
+
end = e
|
486 |
+
out.append((beg,end,fsent))
|
487 |
+
break
|
488 |
+
sent = sent[len(w):].strip()
|
489 |
+
return out
|
490 |
+
|
491 |
+
def finish(self):
|
492 |
+
"""Flush the incomplete text when the whole processing ends.
|
493 |
+
Returns: the same format as self.process_iter()
|
494 |
+
"""
|
495 |
+
o = self.transcript_buffer.complete()
|
496 |
+
f = self.to_flush(o)
|
497 |
+
logger.debug("last, noncommited: {f}")
|
498 |
+
return f
|
499 |
+
|
500 |
+
|
501 |
+
def to_flush(self, sents, sep=None, offset=0, ):
|
502 |
+
# concatenates the timestamped words or sentences into one sequence that is flushed in one line
|
503 |
+
# sents: [(beg1, end1, "sentence1"), ...] or [] if empty
|
504 |
+
# return: (beg1,end-of-last-sentence,"concatenation of sentences") or (None, None, "") if empty
|
505 |
+
if sep is None:
|
506 |
+
sep = self.asr.sep
|
507 |
+
t = sep.join(s[2] for s in sents)
|
508 |
+
if len(sents) == 0:
|
509 |
+
b = None
|
510 |
+
e = None
|
511 |
+
else:
|
512 |
+
b = offset + sents[0][0]
|
513 |
+
e = offset + sents[-1][1]
|
514 |
+
return (b,e,t)
|
515 |
+
|
516 |
+
WHISPER_LANG_CODES = "af,am,ar,as,az,ba,be,bg,bn,bo,br,bs,ca,cs,cy,da,de,el,en,es,et,eu,fa,fi,fo,fr,gl,gu,ha,haw,he,hi,hr,ht,hu,hy,id,is,it,ja,jw,ka,kk,km,kn,ko,la,lb,ln,lo,lt,lv,mg,mi,mk,ml,mn,mr,ms,mt,my,ne,nl,nn,no,oc,pa,pl,ps,pt,ro,ru,sa,sd,si,sk,sl,sn,so,sq,sr,su,sv,sw,ta,te,tg,th,tk,tl,tr,tt,uk,ur,uz,vi,yi,yo,zh".split(",")
|
517 |
+
|
518 |
+
def create_tokenizer(lan):
|
519 |
+
"""returns an object that has split function that works like the one of MosesTokenizer"""
|
520 |
+
|
521 |
+
assert lan in WHISPER_LANG_CODES, "language must be Whisper's supported lang code: " + " ".join(WHISPER_LANG_CODES)
|
522 |
+
|
523 |
+
if lan == "uk":
|
524 |
+
import tokenize_uk
|
525 |
+
class UkrainianTokenizer:
|
526 |
+
def split(self, text):
|
527 |
+
return tokenize_uk.tokenize_sents(text)
|
528 |
+
return UkrainianTokenizer()
|
529 |
+
|
530 |
+
# supported by fast-mosestokenizer
|
531 |
+
if lan in "as bn ca cs de el en es et fi fr ga gu hi hu is it kn lt lv ml mni mr nl or pa pl pt ro ru sk sl sv ta te yue zh".split():
|
532 |
+
from mosestokenizer import MosesTokenizer
|
533 |
+
return MosesTokenizer(lan)
|
534 |
+
|
535 |
+
# the following languages are in Whisper, but not in wtpsplit:
|
536 |
+
if lan in "as ba bo br bs fo haw hr ht jw lb ln lo mi nn oc sa sd sn so su sw tk tl tt".split():
|
537 |
+
logger.debug(f"{lan} code is not supported by wtpsplit. Going to use None lang_code option.")
|
538 |
+
lan = None
|
539 |
+
|
540 |
+
from wtpsplit import WtP
|
541 |
+
# downloads the model from huggingface on the first use
|
542 |
+
wtp = WtP("wtp-canine-s-12l-no-adapters")
|
543 |
+
class WtPtok:
|
544 |
+
def split(self, sent):
|
545 |
+
return wtp.split(sent, lang_code=lan)
|
546 |
+
return WtPtok()
|
547 |
+
|
548 |
+
|
549 |
+
def add_shared_args(parser):
|
550 |
+
"""shared args for simulation (this entry point) and server
|
551 |
+
parser: argparse.ArgumentParser object
|
552 |
+
"""
|
553 |
+
parser.add_argument('--min-chunk-size', type=float, default=1.0, help='Minimum audio chunk size in seconds. It waits up to this time to do processing. If the processing takes shorter time, it waits, otherwise it processes the whole segment that was received by this time.')
|
554 |
+
parser.add_argument('--model', type=str, default='large-v2', choices="tiny.en,tiny,base.en,base,small.en,small,medium.en,medium,large-v1,large-v2,large-v3,large".split(","),help="Name size of the Whisper model to use (default: large-v2). The model is automatically downloaded from the model hub if not present in model cache dir.")
|
555 |
+
parser.add_argument('--model_cache_dir', type=str, default=None, help="Overriding the default model cache dir where models downloaded from the hub are saved")
|
556 |
+
parser.add_argument('--model_dir', type=str, default=None, help="Dir where Whisper model.bin and other files are saved. This option overrides --model and --model_cache_dir parameter.")
|
557 |
+
parser.add_argument('--lan', '--language', type=str, default='auto', help="Source language code, e.g. en,de,cs, or 'auto' for language detection.")
|
558 |
+
parser.add_argument('--task', type=str, default='transcribe', choices=["transcribe","translate"],help="Transcribe or translate.")
|
559 |
+
parser.add_argument('--backend', type=str, default="faster-whisper", choices=["faster-whisper", "whisper_timestamped", "openai-api"],help='Load only this backend for Whisper processing.')
|
560 |
+
parser.add_argument('--vad', action="store_true", default=False, help='Use VAD = voice activity detection, with the default parameters.')
|
561 |
+
parser.add_argument('--buffer_trimming', type=str, default="segment", choices=["sentence", "segment"],help='Buffer trimming strategy -- trim completed sentences marked with punctuation mark and detected by sentence segmenter, or the completed segments returned by Whisper. Sentence segmenter must be installed for "sentence" option.')
|
562 |
+
parser.add_argument('--buffer_trimming_sec', type=float, default=15, help='Buffer trimming length threshold in seconds. If buffer length is longer, trimming sentence/segment is triggered.')
|
563 |
+
parser.add_argument("-l", "--log-level", dest="log_level", choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], help="Set the log level", default='DEBUG')
|
564 |
+
|
565 |
+
def asr_factory(args, logfile=sys.stderr):
|
566 |
+
"""
|
567 |
+
Creates and configures an ASR and ASR Online instance based on the specified backend and arguments.
|
568 |
+
"""
|
569 |
+
backend = args.backend
|
570 |
+
if backend == "openai-api":
|
571 |
+
logger.debug("Using OpenAI API.")
|
572 |
+
asr = OpenaiApiASR(lan=args.lan)
|
573 |
+
else:
|
574 |
+
if backend == "faster-whisper":
|
575 |
+
asr_cls = FasterWhisperASR
|
576 |
+
else:
|
577 |
+
asr_cls = WhisperTimestampedASR
|
578 |
+
|
579 |
+
# Only for FasterWhisperASR and WhisperTimestampedASR
|
580 |
+
size = args.model
|
581 |
+
t = time.time()
|
582 |
+
logger.info(f"Loading Whisper {size} model for {args.lan}...")
|
583 |
+
asr = asr_cls(modelsize=size, lan=args.lan, cache_dir=args.model_cache_dir, model_dir=args.model_dir)
|
584 |
+
e = time.time()
|
585 |
+
logger.info(f"done. It took {round(e-t,2)} seconds.")
|
586 |
+
|
587 |
+
# Apply common configurations
|
588 |
+
if getattr(args, 'vad', False): # Checks if VAD argument is present and True
|
589 |
+
logger.info("Setting VAD filter")
|
590 |
+
asr.use_vad()
|
591 |
+
|
592 |
+
language = args.lan
|
593 |
+
if args.task == "translate":
|
594 |
+
asr.set_translate_task()
|
595 |
+
tgt_language = "en" # Whisper translates into English
|
596 |
+
else:
|
597 |
+
tgt_language = language # Whisper transcribes in this language
|
598 |
+
|
599 |
+
# Create the tokenizer
|
600 |
+
if args.buffer_trimming == "sentence":
|
601 |
+
tokenizer = create_tokenizer(tgt_language)
|
602 |
+
else:
|
603 |
+
tokenizer = None
|
604 |
+
|
605 |
+
# Create the OnlineASRProcessor
|
606 |
+
online = OnlineASRProcessor(asr,tokenizer,logfile=logfile,buffer_trimming=(args.buffer_trimming, args.buffer_trimming_sec))
|
607 |
+
|
608 |
+
return asr, online
|
609 |
+
|
610 |
+
def set_logging(args,logger,other="_server"):
|
611 |
+
logging.basicConfig(#format='%(name)s
|
612 |
+
format='%(levelname)s\t%(message)s')
|
613 |
+
logger.setLevel(args.log_level)
|
614 |
+
logging.getLogger("whisper_online"+other).setLevel(args.log_level)
|
615 |
+
# logging.getLogger("whisper_online_server").setLevel(args.log_level)
|
616 |
+
|
617 |
+
|
618 |
+
|
619 |
+
if __name__ == "__main__":
|
620 |
+
|
621 |
+
import argparse
|
622 |
+
parser = argparse.ArgumentParser()
|
623 |
+
parser.add_argument('audio_path', type=str, help="Filename of 16kHz mono channel wav, on which live streaming is simulated.")
|
624 |
+
add_shared_args(parser)
|
625 |
+
parser.add_argument('--start_at', type=float, default=0.0, help='Start processing audio at this time.')
|
626 |
+
parser.add_argument('--offline', action="store_true", default=False, help='Offline mode.')
|
627 |
+
parser.add_argument('--comp_unaware', action="store_true", default=False, help='Computationally unaware simulation.')
|
628 |
+
|
629 |
+
args = parser.parse_args()
|
630 |
+
|
631 |
+
# reset to store stderr to different file stream, e.g. open(os.devnull,"w")
|
632 |
+
logfile = sys.stderr
|
633 |
+
|
634 |
+
if args.offline and args.comp_unaware:
|
635 |
+
logger.error("No or one option from --offline and --comp_unaware are available, not both. Exiting.")
|
636 |
+
sys.exit(1)
|
637 |
+
|
638 |
+
# if args.log_level:
|
639 |
+
# logging.basicConfig(format='whisper-%(levelname)s:%(name)s: %(message)s',
|
640 |
+
# level=getattr(logging, args.log_level))
|
641 |
+
|
642 |
+
set_logging(args,logger)
|
643 |
+
|
644 |
+
audio_path = args.audio_path
|
645 |
+
|
646 |
+
SAMPLING_RATE = 16000
|
647 |
+
duration = len(load_audio(audio_path))/SAMPLING_RATE
|
648 |
+
logger.info("Audio duration is: %2.2f seconds" % duration)
|
649 |
+
|
650 |
+
asr, online = asr_factory(args, logfile=logfile)
|
651 |
+
min_chunk = args.min_chunk_size
|
652 |
+
|
653 |
+
# load the audio into the LRU cache before we start the timer
|
654 |
+
a = load_audio_chunk(audio_path,0,1)
|
655 |
+
|
656 |
+
# warm up the ASR because the very first transcribe takes much more time than the other
|
657 |
+
asr.transcribe(a)
|
658 |
+
|
659 |
+
beg = args.start_at
|
660 |
+
start = time.time()-beg
|
661 |
+
|
662 |
+
def output_transcript(o, now=None):
|
663 |
+
# output format in stdout is like:
|
664 |
+
# 4186.3606 0 1720 Takhle to je
|
665 |
+
# - the first three words are:
|
666 |
+
# - emission time from beginning of processing, in milliseconds
|
667 |
+
# - beg and end timestamp of the text segment, as estimated by Whisper model. The timestamps are not accurate, but they're useful anyway
|
668 |
+
# - the next words: segment transcript
|
669 |
+
if now is None:
|
670 |
+
now = time.time()-start
|
671 |
+
if o[0] is not None:
|
672 |
+
print("%1.4f %1.0f %1.0f %s" % (now*1000, o[0]*1000,o[1]*1000,o[2]),file=logfile,flush=True)
|
673 |
+
print("%1.4f %1.0f %1.0f %s" % (now*1000, o[0]*1000,o[1]*1000,o[2]),flush=True)
|
674 |
+
else:
|
675 |
+
# No text, so no output
|
676 |
+
pass
|
677 |
+
|
678 |
+
if args.offline: ## offline mode processing (for testing/debugging)
|
679 |
+
a = load_audio(audio_path)
|
680 |
+
online.insert_audio_chunk(a)
|
681 |
+
try:
|
682 |
+
o = online.process_iter()
|
683 |
+
except AssertionError as e:
|
684 |
+
log.error(f"assertion error: {repr(e)}")
|
685 |
+
else:
|
686 |
+
output_transcript(o)
|
687 |
+
now = None
|
688 |
+
elif args.comp_unaware: # computational unaware mode
|
689 |
+
end = beg + min_chunk
|
690 |
+
while True:
|
691 |
+
a = load_audio_chunk(audio_path,beg,end)
|
692 |
+
online.insert_audio_chunk(a)
|
693 |
+
try:
|
694 |
+
o = online.process_iter()
|
695 |
+
except AssertionError as e:
|
696 |
+
logger.error(f"assertion error: {repr(e)}")
|
697 |
+
pass
|
698 |
+
else:
|
699 |
+
output_transcript(o, now=end)
|
700 |
+
|
701 |
+
logger.debug(f"## last processed {end:.2f}s")
|
702 |
+
|
703 |
+
if end >= duration:
|
704 |
+
break
|
705 |
+
|
706 |
+
beg = end
|
707 |
+
|
708 |
+
if end + min_chunk > duration:
|
709 |
+
end = duration
|
710 |
+
else:
|
711 |
+
end += min_chunk
|
712 |
+
now = duration
|
713 |
+
|
714 |
+
else: # online = simultaneous mode
|
715 |
+
end = 0
|
716 |
+
while True:
|
717 |
+
now = time.time() - start
|
718 |
+
if now < end+min_chunk:
|
719 |
+
time.sleep(min_chunk+end-now)
|
720 |
+
end = time.time() - start
|
721 |
+
a = load_audio_chunk(audio_path,beg,end)
|
722 |
+
beg = end
|
723 |
+
online.insert_audio_chunk(a)
|
724 |
+
|
725 |
+
try:
|
726 |
+
o = online.process_iter()
|
727 |
+
except AssertionError as e:
|
728 |
+
logger.error(f"assertion error: {e}")
|
729 |
+
pass
|
730 |
+
else:
|
731 |
+
output_transcript(o)
|
732 |
+
now = time.time() - start
|
733 |
+
logger.debug(f"## last processed {end:.2f} s, now is {now:.2f}, the latency is {now-end:.2f}")
|
734 |
+
|
735 |
+
if end >= duration:
|
736 |
+
break
|
737 |
+
now = None
|
738 |
+
|
739 |
+
o = online.finish()
|
740 |
+
output_transcript(o, now=now)
|