juanluisrto commited on
Commit
26674e7
·
1 Parent(s): 0f7ebaa

faster-whisper test

Browse files
Files changed (3) hide show
  1. app.py +34 -0
  2. requirements.txt +1 -0
  3. whisper_online.py +408 -0
app.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+
4
+
5
+ from whisper_online import *
6
+
7
+ asr = FasterWhisperASR("es", "large-v3") # loads and wraps Whisper model
8
+ # set options:
9
+ # asr.set_translate_task() # it will translate from lan into English
10
+ asr.use_vad() # set using VAD
11
+
12
+ online = OnlineASRProcessor(asr) # create processing object with default buffer trimming option
13
+ online.init()
14
+
15
+
16
+ def transcribe(transcription, new_chunk):
17
+ sr, y = new_chunk
18
+ y = y.astype(np.float32)
19
+ y /= np.max(np.abs(y))
20
+
21
+ online.insert_audio_chunk(y)
22
+ text = online.process_iter()
23
+
24
+ return transcription + text
25
+
26
+
27
+ demo = gr.Interface(
28
+ transcribe,
29
+ ["state", gr.Audio(sources=["microphone"], streaming=True)],
30
+ ["state", "text"],
31
+ live=True,
32
+ )
33
+
34
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ faster-whisper
whisper_online.py ADDED
@@ -0,0 +1,408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
8
+
9
+
10
+ @lru_cache
11
+ def load_audio(fname):
12
+ a, _ = librosa.load(fname, sr=16000)
13
+ return a
14
+
15
+ def load_audio_chunk(fname, beg, end):
16
+ audio = load_audio(fname)
17
+ beg_s = int(beg*16000)
18
+ end_s = int(end*16000)
19
+ return audio[beg_s:end_s]
20
+
21
+
22
+ # Whisper backend
23
+
24
+ class ASRBase:
25
+
26
+ sep = " " # join transcribe words with this character (" " for whisper_timestamped,
27
+ # "" for faster-whisper because it emits the spaces when neeeded)
28
+
29
+ def __init__(self, lan, modelsize=None, cache_dir=None, model_dir=None, logfile=sys.stderr):
30
+ self.logfile = logfile
31
+
32
+ self.transcribe_kargs = {}
33
+ if lan == "auto":
34
+ self.original_language = None
35
+ else:
36
+ self.original_language = lan
37
+
38
+ self.model = self.load_model(modelsize, cache_dir, model_dir)
39
+
40
+
41
+ def load_model(self, modelsize, cache_dir):
42
+ raise NotImplemented("must be implemented in the child class")
43
+
44
+ def transcribe(self, audio, init_prompt=""):
45
+ raise NotImplemented("must be implemented in the child class")
46
+
47
+ def use_vad(self):
48
+ raise NotImplemented("must be implemented in the child class")
49
+
50
+
51
+
52
+ class FasterWhisperASR(ASRBase):
53
+ """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.
54
+ """
55
+
56
+ sep = ""
57
+
58
+ def load_model(self, modelsize=None, cache_dir=None, model_dir=None):
59
+ from faster_whisper import WhisperModel
60
+ if model_dir is not None:
61
+ print(f"Loading whisper model from model_dir {model_dir}. modelsize and cache_dir parameters are not used.",file=self.logfile)
62
+ model_size_or_path = model_dir
63
+ elif modelsize is not None:
64
+ model_size_or_path = modelsize
65
+ else:
66
+ raise ValueError("modelsize or model_dir parameter must be set")
67
+
68
+
69
+ # this worked fast and reliably on NVIDIA L40
70
+ model = WhisperModel(model_size_or_path, device="cuda", compute_type="float16", download_root=cache_dir)
71
+
72
+ # or run on GPU with INT8
73
+ # tested: the transcripts were different, probably worse than with FP16, and it was slightly (appx 20%) slower
74
+ #model = WhisperModel(model_size, device="cuda", compute_type="int8_float16")
75
+
76
+ # or run on CPU with INT8
77
+ # tested: works, but slow, appx 10-times than cuda FP16
78
+ # model = WhisperModel(modelsize, device="cpu", compute_type="int8") #, download_root="faster-disk-cache-dir/")
79
+ return model
80
+
81
+ def transcribe(self, audio, init_prompt=""):
82
+
83
+ # tested: beam_size=5 is faster and better than 1 (on one 200 second document from En ESIC, min chunk 0.01)
84
+ 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)
85
+ #print(info) # info contains language detection result
86
+
87
+ return list(segments)
88
+
89
+ def ts_words(self, segments):
90
+ o = []
91
+ for segment in segments:
92
+ for word in segment.words:
93
+ # not stripping the spaces -- should not be merged with them!
94
+ w = word.word
95
+ t = (word.start, word.end, w)
96
+ o.append(t)
97
+ return o
98
+
99
+ def segments_end_ts(self, res):
100
+ return [s.end for s in res]
101
+
102
+ def use_vad(self):
103
+ self.transcribe_kargs["vad_filter"] = True
104
+
105
+ def set_translate_task(self):
106
+ self.transcribe_kargs["task"] = "translate"
107
+
108
+
109
+
110
+ class HypothesisBuffer:
111
+
112
+ def __init__(self, logfile=sys.stderr):
113
+ self.commited_in_buffer = []
114
+ self.buffer = []
115
+ self.new = []
116
+
117
+ self.last_commited_time = 0
118
+ self.last_commited_word = None
119
+
120
+ self.logfile = logfile
121
+
122
+ def insert(self, new, offset):
123
+ # 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
124
+ # the new tail is added to self.new
125
+
126
+ new = [(a+offset,b+offset,t) for a,b,t in new]
127
+ self.new = [(a,b,t) for a,b,t in new if a > self.last_commited_time-0.1]
128
+
129
+ if len(self.new) >= 1:
130
+ a,b,t = self.new[0]
131
+ if abs(a - self.last_commited_time) < 1:
132
+ if self.commited_in_buffer:
133
+ # 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.
134
+ cn = len(self.commited_in_buffer)
135
+ nn = len(self.new)
136
+ for i in range(1,min(min(cn,nn),5)+1): # 5 is the maximum
137
+ c = " ".join([self.commited_in_buffer[-j][2] for j in range(1,i+1)][::-1])
138
+ tail = " ".join(self.new[j-1][2] for j in range(1,i+1))
139
+ if c == tail:
140
+ print("removing last",i,"words:",file=self.logfile)
141
+ for j in range(i):
142
+ print("\t",self.new.pop(0),file=self.logfile)
143
+ break
144
+
145
+ def flush(self):
146
+ # returns commited chunk = the longest common prefix of 2 last inserts.
147
+
148
+ commit = []
149
+ while self.new:
150
+ na, nb, nt = self.new[0]
151
+
152
+ if len(self.buffer) == 0:
153
+ break
154
+
155
+ if nt == self.buffer[0][2]:
156
+ commit.append((na,nb,nt))
157
+ self.last_commited_word = nt
158
+ self.last_commited_time = nb
159
+ self.buffer.pop(0)
160
+ self.new.pop(0)
161
+ else:
162
+ break
163
+ self.buffer = self.new
164
+ self.new = []
165
+ self.commited_in_buffer.extend(commit)
166
+ return commit
167
+
168
+ def pop_commited(self, time):
169
+ while self.commited_in_buffer and self.commited_in_buffer[0][1] <= time:
170
+ self.commited_in_buffer.pop(0)
171
+
172
+ def complete(self):
173
+ return self.buffer
174
+
175
+ class OnlineASRProcessor:
176
+
177
+ SAMPLING_RATE = 16000
178
+
179
+ def __init__(self, asr, tokenizer=None, buffer_trimming=("segment", 15), logfile=sys.stderr):
180
+ """asr: WhisperASR object
181
+ 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.
182
+ ("segment", 15)
183
+ 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.
184
+ logfile: where to store the log.
185
+ """
186
+ self.asr = asr
187
+ self.tokenizer = tokenizer
188
+ self.logfile = logfile
189
+
190
+ self.init()
191
+
192
+ self.buffer_trimming_way, self.buffer_trimming_sec = buffer_trimming
193
+
194
+ def init(self):
195
+ """run this when starting or restarting processing"""
196
+ self.audio_buffer = np.array([],dtype=np.float32)
197
+ self.buffer_time_offset = 0
198
+
199
+ self.transcript_buffer = HypothesisBuffer(logfile=self.logfile)
200
+ self.commited = []
201
+ self.last_chunked_at = 0
202
+
203
+ self.silence_iters = 0
204
+
205
+ def insert_audio_chunk(self, audio):
206
+ self.audio_buffer = np.append(self.audio_buffer, audio)
207
+
208
+ def prompt(self):
209
+ """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.
210
+ "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.
211
+ """
212
+ k = max(0,len(self.commited)-1)
213
+ while k > 0 and self.commited[k-1][1] > self.last_chunked_at:
214
+ k -= 1
215
+
216
+ p = self.commited[:k]
217
+ p = [t for _,_,t in p]
218
+ prompt = []
219
+ l = 0
220
+ while p and l < 200: # 200 characters prompt size
221
+ x = p.pop(-1)
222
+ l += len(x)+1
223
+ prompt.append(x)
224
+ non_prompt = self.commited[k:]
225
+ return self.asr.sep.join(prompt[::-1]), self.asr.sep.join(t for _,_,t in non_prompt)
226
+
227
+ def process_iter(self):
228
+ """Runs on the current audio buffer.
229
+ Returns: a tuple (beg_timestamp, end_timestamp, "text"), or (None, None, "").
230
+ The non-emty text is confirmed (committed) partial transcript.
231
+ """
232
+
233
+ prompt, non_prompt = self.prompt()
234
+ print("PROMPT:", prompt, file=self.logfile)
235
+ print("CONTEXT:", non_prompt, file=self.logfile)
236
+ print(f"transcribing {len(self.audio_buffer)/self.SAMPLING_RATE:2.2f} seconds from {self.buffer_time_offset:2.2f}",file=self.logfile)
237
+ res = self.asr.transcribe(self.audio_buffer, init_prompt=prompt)
238
+
239
+ # transform to [(beg,end,"word1"), ...]
240
+ tsw = self.asr.ts_words(res)
241
+
242
+ self.transcript_buffer.insert(tsw, self.buffer_time_offset)
243
+ o = self.transcript_buffer.flush()
244
+ self.commited.extend(o)
245
+ print(">>>>COMPLETE NOW:",self.to_flush(o),file=self.logfile,flush=True)
246
+ print("INCOMPLETE:",self.to_flush(self.transcript_buffer.complete()),file=self.logfile,flush=True)
247
+
248
+ # there is a newly confirmed text
249
+
250
+ if o and self.buffer_trimming_way == "sentence": # trim the completed sentences
251
+ if len(self.audio_buffer)/self.SAMPLING_RATE > self.buffer_trimming_sec: # longer than this
252
+ self.chunk_completed_sentence()
253
+
254
+
255
+ if self.buffer_trimming_way == "segment":
256
+ s = self.buffer_trimming_sec # trim the completed segments longer than s,
257
+ else:
258
+ s = 30 # if the audio buffer is longer than 30s, trim it
259
+
260
+ if len(self.audio_buffer)/self.SAMPLING_RATE > s:
261
+ self.chunk_completed_segment(res)
262
+
263
+ # alternative: on any word
264
+ #l = self.buffer_time_offset + len(self.audio_buffer)/self.SAMPLING_RATE - 10
265
+ # let's find commited word that is less
266
+ #k = len(self.commited)-1
267
+ #while k>0 and self.commited[k][1] > l:
268
+ # k -= 1
269
+ #t = self.commited[k][1]
270
+ print(f"chunking segment",file=self.logfile)
271
+ #self.chunk_at(t)
272
+
273
+ print(f"len of buffer now: {len(self.audio_buffer)/self.SAMPLING_RATE:2.2f}",file=self.logfile)
274
+ return self.to_flush(o)
275
+
276
+ def chunk_completed_sentence(self):
277
+ if self.commited == []: return
278
+ print(self.commited,file=self.logfile)
279
+ sents = self.words_to_sentences(self.commited)
280
+ for s in sents:
281
+ print("\t\tSENT:",s,file=self.logfile)
282
+ if len(sents) < 2:
283
+ return
284
+ while len(sents) > 2:
285
+ sents.pop(0)
286
+ # we will continue with audio processing at this timestamp
287
+ chunk_at = sents[-2][1]
288
+
289
+ print(f"--- sentence chunked at {chunk_at:2.2f}",file=self.logfile)
290
+ self.chunk_at(chunk_at)
291
+
292
+ def chunk_completed_segment(self, res):
293
+ if self.commited == []: return
294
+
295
+ ends = self.asr.segments_end_ts(res)
296
+
297
+ t = self.commited[-1][1]
298
+
299
+ if len(ends) > 1:
300
+
301
+ e = ends[-2]+self.buffer_time_offset
302
+ while len(ends) > 2 and e > t:
303
+ ends.pop(-1)
304
+ e = ends[-2]+self.buffer_time_offset
305
+ if e <= t:
306
+ print(f"--- segment chunked at {e:2.2f}",file=self.logfile)
307
+ self.chunk_at(e)
308
+ else:
309
+ print(f"--- last segment not within commited area",file=self.logfile)
310
+ else:
311
+ print(f"--- not enough segments to chunk",file=self.logfile)
312
+
313
+
314
+
315
+
316
+
317
+ def chunk_at(self, time):
318
+ """trims the hypothesis and audio buffer at "time"
319
+ """
320
+ self.transcript_buffer.pop_commited(time)
321
+ cut_seconds = time - self.buffer_time_offset
322
+ self.audio_buffer = self.audio_buffer[int(cut_seconds*self.SAMPLING_RATE):]
323
+ self.buffer_time_offset = time
324
+ self.last_chunked_at = time
325
+
326
+ def words_to_sentences(self, words):
327
+ """Uses self.tokenizer for sentence segmentation of words.
328
+ Returns: [(beg,end,"sentence 1"),...]
329
+ """
330
+
331
+ cwords = [w for w in words]
332
+ t = " ".join(o[2] for o in cwords)
333
+ s = self.tokenizer.split(t)
334
+ out = []
335
+ while s:
336
+ beg = None
337
+ end = None
338
+ sent = s.pop(0).strip()
339
+ fsent = sent
340
+ while cwords:
341
+ b,e,w = cwords.pop(0)
342
+ w = w.strip()
343
+ if beg is None and sent.startswith(w):
344
+ beg = b
345
+ elif end is None and sent == w:
346
+ end = e
347
+ out.append((beg,end,fsent))
348
+ break
349
+ sent = sent[len(w):].strip()
350
+ return out
351
+
352
+ def finish(self):
353
+ """Flush the incomplete text when the whole processing ends.
354
+ Returns: the same format as self.process_iter()
355
+ """
356
+ o = self.transcript_buffer.complete()
357
+ f = self.to_flush(o)
358
+ print("last, noncommited:",f,file=self.logfile)
359
+ return f
360
+
361
+
362
+ def to_flush(self, sents, sep=None, offset=0, ):
363
+ # concatenates the timestamped words or sentences into one sequence that is flushed in one line
364
+ # sents: [(beg1, end1, "sentence1"), ...] or [] if empty
365
+ # return: (beg1,end-of-last-sentence,"concatenation of sentences") or (None, None, "") if empty
366
+ if sep is None:
367
+ sep = self.asr.sep
368
+ t = sep.join(s[2] for s in sents)
369
+ if len(sents) == 0:
370
+ b = None
371
+ e = None
372
+ else:
373
+ b = offset + sents[0][0]
374
+ e = offset + sents[-1][1]
375
+ return (b,e,t)
376
+
377
+ 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(",")
378
+
379
+ def create_tokenizer(lan):
380
+ """returns an object that has split function that works like the one of MosesTokenizer"""
381
+
382
+ assert lan in WHISPER_LANG_CODES, "language must be Whisper's supported lang code: " + " ".join(WHISPER_LANG_CODES)
383
+
384
+ if lan == "uk":
385
+ import tokenize_uk
386
+ class UkrainianTokenizer:
387
+ def split(self, text):
388
+ return tokenize_uk.tokenize_sents(text)
389
+ return UkrainianTokenizer()
390
+
391
+ # supported by fast-mosestokenizer
392
+ 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():
393
+ from mosestokenizer import MosesTokenizer
394
+ return MosesTokenizer(lan)
395
+
396
+ # the following languages are in Whisper, but not in wtpsplit:
397
+ 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():
398
+ print(f"{lan} code is not supported by wtpsplit. Going to use None lang_code option.", file=sys.stderr)
399
+ lan = None
400
+
401
+ from wtpsplit import WtP
402
+ # downloads the model from huggingface on the first use
403
+ wtp = WtP("wtp-canine-s-12l-no-adapters")
404
+ class WtPtok:
405
+ def split(self, sent):
406
+ return wtp.split(sent, lang_code=lan)
407
+ return WtPtok()
408
+