Debian Codegraph @

fon/SpeechRecognizer.cpp

raw symbols SCIP
1 /* SpeechRecognizer.cpp
2 *
3 * Copyright (C) 2025,2026 Anastasia Shchupak
4 *
5 * This code is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or (at
8 * your option) any later version.
9 *
10 * This code is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 * See the GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this work. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 #include "SpeechRecognizer.h"
20 #include "Sound.h"
21 #include "whisper.h"
22 #include "diarize.h"
23 #include "melder.h"
24 #include "ggml-memory-pool.h"
25 #include "ggml-silero-vad-model-data.h"
26 #include "Preferences.h"
27
28 #include "oo_DESTROY.h"
29 #include "SpeechRecognizer_def.h"
30 #include "oo_COPY.h"
31 #include "SpeechRecognizer_def.h"
32 #include "oo_EQUAL.h"
33 #include "SpeechRecognizer_def.h"
34 #include "oo_CAN_WRITE_AS_ENCODING.h"
35 #include "SpeechRecognizer_def.h"
36 #include "oo_WRITE_TEXT.h"
37 #include "SpeechRecognizer_def.h"
38 #include "oo_WRITE_BINARY.h"
39 #include "SpeechRecognizer_def.h"
40 #include "oo_READ_TEXT.h"
41 #include "SpeechRecognizer_def.h"
42 #include "oo_READ_BINARY.h"
43 #include "SpeechRecognizer_def.h"
44 #include "oo_DESCRIPTION.h"
45 #include "SpeechRecognizer_def.h"
46
47 autoWhisperContext :: ~autoWhisperContext () {
48 //TRACE
49 trace (U"Destroying whisper context at ", Melder_pointer (ptr));
50 if (ptr)
51 whisper_free (ptr);
52 trace (U"Number of allocations in the memory pool is ", theGgmlMemoryPool. n_allocations());
53 trace (U"Total memory in bytes is ", theGgmlMemoryPool. sizeInBytes());
54 }
55 autoWhisperContext& autoWhisperContext :: operator= (autoWhisperContext&& other) noexcept {
56 if (this != & other) {
57 whisper_free (ptr);
58 ptr = other.ptr;
59 other.ptr = nullptr;
60 }
61 return *this;
62 }
63
64 autoWhisperVadContext :: ~autoWhisperVadContext () {
65 //TRACE
66 trace (U"Destroying Silero-VAD context at ", Melder_pointer (ptr));
67 whisper_vad_free (ptr);
68 trace (U"Number of allocations in the memory pool is ", theGgmlMemoryPool. n_allocations());
69 trace (U"Total memory in bytes is ", theGgmlMemoryPool. sizeInBytes());
70 }
71 autoWhisperVadContext& autoWhisperVadContext :: operator= (autoWhisperVadContext&& other) noexcept {
72 if (this != & other) {
73 whisper_vad_free (ptr);
74 ptr = other.ptr;
75 other.ptr = nullptr;
76 }
77 return *this;
78 }
79
80 autoWhisperVadSegments :: ~autoWhisperVadSegments () {
81 //TRACE
82 trace (U"Destroying Silero-VAD segments at ", Melder_pointer (ptr));
83 whisper_vad_free_segments (ptr);
84 }
85 autoWhisperVadSegments& autoWhisperVadSegments :: operator= (autoWhisperVadSegments&& other) noexcept {
86 if (this != & other) {
87 whisper_vad_free_segments (ptr);
88 ptr = other.ptr;
89 other.ptr = nullptr;
90 }
91 return *this;
92 }
93
94 autoDiarizeContext :: ~autoDiarizeContext () {
95 //TRACE
96 trace (U"Destroying diarize context at ", Melder_pointer (ptr));
97 diarize_free (ptr);
98 trace (U"Number of allocations in the memory pool is ", theGgmlMemoryPool. n_allocations());
99 trace (U"Total memory in bytes is ", theGgmlMemoryPool. sizeInBytes());
100 }
101 autoDiarizeContext& autoDiarizeContext :: operator= (autoDiarizeContext&& other) noexcept {
102 if (this != & other) {
103 diarize_free (ptr);
104 ptr = other.ptr;
105 other.ptr = nullptr;
106 }
107 return *this;
108 }
109
110 Thing_implement (SpeechRecognizer, Daata, 0);
111
112 void structSpeechRecognizer :: v1_info () {
113 SpeechRecognizer_Parent :: v1_info ();
114 MelderInfo_writeLine (U"Model: ", our d_modelName.get());
115 MelderInfo_writeLine (U"Language: ", our d_languageName.get());
116 }
117
118 static void whisper_log_silent (ggml_log_level level, const char *text, void *user_data) {
119 (void) level;
120 (void) text;
121 (void) user_data;
122 }
123
124 static void supressGgmlLogging () {
125 if (Melder_debug == 2001)
126 whisper_log_set (nullptr, nullptr);
127 else
128 whisper_log_set (whisper_log_silent, nullptr);
129 }
130
131 static conststring32 theWhisperModelsFolder ();
132
133 autoSpeechRecognizer SpeechRecognizer_create (const conststring32 modelName, const conststring32 languageName) {
134 try {
135 autoSpeechRecognizer me = Thing_new (SpeechRecognizer);
136 my d_modelName = Melder_dup (modelName);
137 my d_languageName = Melder_dup (languageName);
138
139 /*
140 Check if selected model and language are compatible.
141 */
142 if (str32str (modelName, U".en.bin")) {
143 Melder_require (str32str (languageName, U"Autodetect") || str32str (languageName, U"English"),
144 U"Model ", modelName, U" cannot be used for ", languageName, U" transcription. "
145 U"Either select a multilingual model (the model name does not include .en) "
146 U"or select \"Autodetect language\"/\"English\" from the language list."
147 );
148 }
149
150 /*
151 Create Whisper context.
152 */
153 whisper_context_params contextParams = whisper_context_default_params ();
154 contextParams. use_gpu = false;
155 contextParams. flash_attn = false; // needs to be false to use DTW!!!
156
157 /*
158 Enable DTW (Dynamic Time Warping algorithm used for more precise token boundaries).
159 */
160 Melder_assert (! contextParams. flash_attn);
161 contextParams. dtw_token_timestamps = true;
162 if (str32str (modelName, U"tiny.en"))
163 contextParams. dtw_aheads_preset = WHISPER_AHEADS_TINY_EN;
164 else if (str32str (modelName, U"tiny"))
165 contextParams. dtw_aheads_preset = WHISPER_AHEADS_TINY;
166 else if (str32str (modelName, U"base.en"))
167 contextParams. dtw_aheads_preset = WHISPER_AHEADS_BASE_EN;
168 else if (str32str (modelName, U"base"))
169 contextParams. dtw_aheads_preset = WHISPER_AHEADS_BASE;
170 else if (str32str (modelName, U"small.en"))
171 contextParams. dtw_aheads_preset = WHISPER_AHEADS_SMALL_EN;
172 else if (str32str (modelName, U"small"))
173 contextParams. dtw_aheads_preset = WHISPER_AHEADS_SMALL;
174 else if (str32str (modelName, U"medium.en"))
175 contextParams. dtw_aheads_preset = WHISPER_AHEADS_MEDIUM_EN;
176 else if (str32str (modelName, U"medium"))
177 contextParams. dtw_aheads_preset = WHISPER_AHEADS_MEDIUM;
178 else if (str32str (modelName, U"large-v3-turbo") || str32str (modelName, U"turbo"))
179 contextParams. dtw_aheads_preset = WHISPER_AHEADS_LARGE_V3_TURBO;
180 else if (str32str (modelName, U"large-v3"))
181 contextParams. dtw_aheads_preset = WHISPER_AHEADS_LARGE_V3;
182 else if (str32str (modelName, U"large-v2"))
183 contextParams. dtw_aheads_preset = WHISPER_AHEADS_LARGE_V2;
184 else if (str32str (modelName, U"large-v1") || str32str (modelName, U"large"))
185 contextParams. dtw_aheads_preset = WHISPER_AHEADS_LARGE_V1;
186 else
187 contextParams. dtw_aheads_preset = WHISPER_AHEADS_N_TOP_MOST;
188
189 const conststring32 modelPath = Melder_cat (theWhisperModelsFolder(), U"/", modelName);
190 const conststring8 utf8ModelPath = Melder_peek32to8 (modelPath);
191
192 /*
193 Initialise Whisper model.
194 */
195 supressGgmlLogging ();
196 whisper_context *ctx = whisper_init_from_file_with_params (utf8ModelPath, contextParams);
197 if (! ctx)
198 Melder_throw (U"Cannot create Whisper context from: ", modelPath, U". Model file not found?");
199
200 my whisperContext = autoWhisperContext (ctx);
201 theLivingSpeechRecognizers. insert (me.get());
202 return me;
203 } catch (MelderError) {
204 theGgmlMemoryPool. clear();
205 Melder_throw (U"SpeechRecognizer not created.");
206 }
207 }
208
209 static autovector <float> resampleForWhisper (constSound sound) {
210 /*
211 Resample the sound to 16kHz if needed.
212 */
213 autoSound resampled = Sound_resample (sound, 16000.0, 50);
214 sound = resampled.get();
215
216 /*
217 Convert the sound to float32 for Whisper.
218 */
219 autovector <float> samples32 = newvectorzero <float> (sound -> nx);;
220 for (integer i = 1; i <= sound -> nx; i ++)
221 samples32 [i] = static_cast <float> (sound -> z [1] [i]);
222
223 return samples32;
224 }
225
226 static void SpeechRecognizer_runWhisper (constSpeechRecognizer me, constSound sound, const bool useVad,
227 const double speechProbabilityThreshold, const double minNonSpeechDuration, const double minSpeechDuration, const double speechPad) {
228 //TRACE
229 /*
230 Prepare sound for Whispercpp.
231 */
232 autovector <float> samples32 = resampleForWhisper (sound);
233
234 /*
235 Default maximum number of threads for transcription is half the number of logical processors. This is because:
236 1. hyperthreaded CPUs: half = physical cores, optimal for SIMD kernels.
237 2. hybrid P+E core CPUs: half is "mostly P-cores"; using all the cores can cause a 100x slowdown.
238 3. homogeneous non-hyperthreaded CPUs: half is below optimal, but not disastrous as in case 2.
239 The user can override this in Praat preferences.
240 */
241 integer n_threads = SpeechRecognizer_getMaxNumberOfThreadsForTranscription ();
242 if (n_threads <= 0)
243 n_threads = TranscriptionDefaults::n_threads;
244
245 /*
246 Set Whisper parameters.
247 */
248 whisper_sampling_strategy samplingStrategy =
249 Melder_debug == 2002 ? WHISPER_SAMPLING_GREEDY : WHISPER_SAMPLING_BEAM_SEARCH;
250 trace (U"Sampling strategy = ", samplingStrategy == WHISPER_SAMPLING_GREEDY ? U"greedy" : U"beam search");
251 whisper_full_params params = whisper_full_default_params (samplingStrategy);
252 params. token_timestamps = true; // must be true to use t0 and t1 (non-DTW) token timestamps
253 params. n_threads = static_cast<int32_t> (n_threads);
254
255 if (useVad) {
256 params. vad = true; // enable Silero VAD (Voice Activity Detection used to chop away the silences)
257 params. vad_model_data = ggml_silero_bin; // set up either params.vad_model_data or params.vad_model_path
258 params. vad_model_data_size = ggml_silero_bin_len;
259 params. vad_params = whisper_vad_default_params();
260 params. vad_params. threshold = static_cast <float> (speechProbabilityThreshold);
261 params. vad_params. min_speech_duration_ms = static_cast <int> (minSpeechDuration * 1000.0);
262 params. vad_params. min_silence_duration_ms = static_cast <int> (minNonSpeechDuration * 1000.0);
263 params. vad_params. speech_pad_ms = static_cast <int> (speechPad * 1000.0);
264 params. vad_params. samples_overlap = 0.1f; // this is the default, but brought here to remember that it is configurable
265 }
266 if (whisper_is_multilingual (my whisperContext.get ())) {
267 if (my d_languageName && ! str32str (my d_languageName.get(), U"Autodetect")) {
268 autostring32 name = Melder_dup (my d_languageName.get());
269 name [0] = Melder_toLowerCase (name [0]); // e.g. "Dutch" -> "dutch"
270 params.language = whisper_lang_str (whisper_lang_id (Melder_peek32to8 (name.get())));
271 } else {
272 params.language = "auto";
273 }
274 }
275
276 /*
277 Run Whisper.
278 */
279 supressGgmlLogging ();
280 try {
281 if (whisper_full (my whisperContext.get(), params, samples32. asArgumentToFunctionThatExpectsZeroBasedArray(),
282 static_cast <int> (samples32.size)) != 0)
283 Melder_throw (U"Whisper failed to process audio");
284 whisper_print_timings(my whisperContext.get());
285 } catch (MelderError) {
286 theGgmlMemoryPool. clear();
287 Melder_throw (U"Whisper run out of memory. SpeechRecognizer objects are no longer usable and must be recreated.");
288 }
289 }
290
291 static bool endsWithTerminalPunctuation(const conststring32 token) {
292 if (! token || token [0] == U'\0')
293 return false;
294
295 const integer lengthOfToken = Melder_length (token);
296 const char32 lastChar = token [lengthOfToken - 1];
297 return lastChar == U'.' || lastChar == U'!' || lastChar == U'?' ||
298 lastChar == U'。' || lastChar == U'!' || lastChar == U'?';
299 }
300
301 static bool isPurePunctuation(const conststring32 token) {
302 if (! token || token [0] == U'\0')
303 return false;
304
305 const integer lengthOfToken = Melder_length (token);
306 for (integer i = 0; i < lengthOfToken; i ++)
307 if (Melder_isAlphanumeric (token [i]))
308 return false;
309 return true;
310 }
311
312 WhisperTranscription SpeechRecognizer_recognize (constSpeechRecognizer me, constSound sound, const bool useVad,
313 const double speechProbabilityThreshold, const double minNonSpeechDuration, const double minSpeechDuration, const double speechPad) {
314 try {
315 TRACE
316 Melder_require (my whisperContext.get(),
317 U"This SpeechRecognizer object is not usable anymore as it ran out of memory. ",
318 U"Please remove it and create a new one."
319 );
320 trace (U"Sound xmin = ", sound -> xmin, U", sound xmax = ", sound -> xmax);
321
322 /*
323 Run Whisper and control for blank audio.
324 */
325 SpeechRecognizer_runWhisper (me, sound, useVad, speechProbabilityThreshold, minNonSpeechDuration, minSpeechDuration, speechPad);
326 const int numberOfSegments = whisper_full_n_segments (my whisperContext.get());
327 if (! numberOfSegments) {
328 WhisperTranscription transcription;
329 transcription. fullTranscription. text = Melder_dup (U"[BLANK_AUDIO]");
330 transcription. fullTranscription. tmin = sound -> xmin;
331 transcription. fullTranscription. tmax = sound -> xmax;
332 transcription. words = newvectorzero <SpeechSegment> (1);
333 transcription. words [1]. text = Melder_dup (U"BLANKAUDIO");
334 transcription. words [1]. tmin = sound -> xmin;
335 transcription. words [1]. tmax = sound -> xmax;
336 transcription. sentences = newvectorzero <SpeechSegment> (1);
337 transcription. sentences [1]. text = Melder_dup (U"[BLANK_AUDIO]");
338 transcription. sentences [1]. tmin = sound -> xmin;
339 transcription. sentences [1]. tmax = sound -> xmax;
340 return transcription;
341 }
342
343 const int numberOfVadSegments = whisper_full_n_vad_segments (my whisperContext.get());
344 struct VadSegment {
345 double origStart;
346 double origEnd;
347 double vadStart;
348 double vadEnd;
349 };
350 autovector <VadSegment> vadSegments = newvectorzero <VadSegment> (numberOfVadSegments);
351 for (integer i = 1; i <= numberOfVadSegments; i ++) {
352 vadSegments [i]. origStart = std::min (
353 static_cast <double> (whisper_full_get_vad_segment_orig_start (my whisperContext.get(), i - 1)) / 100.0,
354 sound -> xmax
355 );
356 vadSegments [i]. origEnd = std::min (
357 static_cast <double> (whisper_full_get_vad_segment_orig_end (my whisperContext.get(), i - 1)) / 100.0,
358 sound -> xmax
359 );
360 vadSegments [i]. vadStart =
361 static_cast <double> (whisper_full_get_vad_segment_vad_start (my whisperContext.get(), i - 1)) / 100.0;
362 vadSegments [i]. vadEnd =
363 static_cast <double> (whisper_full_get_vad_segment_vad_end (my whisperContext.get(), i - 1)) / 100.0;
364 trace (U"VAD segment ", i, U", orig_start = ", vadSegments [i]. origStart, U", orig_end = ", vadSegments [i]. origEnd,
365 U", vad_start = ", vadSegments [i]. vadStart, U", vad_end = ", vadSegments [i]. vadEnd);
366 }
367
368 /*
369 Lambda for VAD time to real time conversion.
370 */
371 auto vadToRealTime = [& vadSegments, useVad] (double vadTime) {
372 if (! useVad || ! vadSegments.size)
373 return vadTime; // no VAD: VAD time is the real time
374
375 /* mutable scan */ integer k = 1;
376 while (k < vadSegments.size && vadSegments [k + 1]. vadStart <= vadTime)
377 k ++;
378 return vadTime + vadSegments [k]. origStart - vadSegments [k]. vadStart;
379 };
380
381 /*
382 Lambda for finding the end of the VAD segment (in VAD time) that contains vadTime.
383 Note that vadSegments [k]. vadEnd is not used. This is because whisper.cpp pads each VAD segment
384 with 0.1 seconds of context on the right side, and vadEnd points to the end of that padding.
385 Whisper.cpp additionally adds 0.1 seconds of zeroes after each padded VAD segment,
386 resulting in 0.2 seconds of "non-speech" between VAD segments.
387 A vadTime in these 0.2 seconds after a VAD segment is also considered belonging to this segment.
388 */
389 auto vadSegmentEnd = [& vadSegments] (double vadTime) {
390 Melder_assert (vadTime >= vadSegments [1]. vadStart);
391 /* mutable scan */ integer k = 1;
392 while (k < vadSegments.size && vadSegments [k + 1]. vadStart <= vadTime)
393 k ++;
394 return vadSegments [k]. vadStart + (vadSegments [k]. origEnd - vadSegments [k]. origStart);
395 };
396
397 /*
398 Collect all the tokens into a flat list, repairing incomplete UTF8 tokens.
399 */
400 struct RawToken {
401 autostring32 text; // leading space intact
402 double tmax;
403 integer whisperSegment;
404 };
405 autovector <RawToken> rawTokens = newvectorzero <RawToken> (0);
406
407 /* mutable accumulate */ std::string partialTokenText; // here we will accumulate whisper token texts until it is a proper UTF8 string
408 const whisper_token firstSpecialTokenId = whisper_token_eot (my whisperContext.get()); // see struct whisper_vocab in whisper.cpp
409
410 for (integer i = 0; i < numberOfSegments; i ++) {
411 /* mutable flag for tracing */ bool isFirstPartialTokenInSegment = true;
412 for (integer j = 0; j < whisper_full_n_tokens (my whisperContext.get(), static_cast<int> (i)); j ++) {
413 const whisper_token_data tokenData = whisper_full_get_token_data (
414 my whisperContext.get(), static_cast<int> (i), static_cast<int> (j));
415 if (tokenData. id >= firstSpecialTokenId) {
416 trace (U"Skipping special token: ", tokenData. id);
417 continue; // skip special tokens
418 }
419
420 /*
421 Clamp the tail of the previous segment.
422 */
423 if (isFirstPartialTokenInSegment) {
424 if (rawTokens.size >= 1) {
425 /* mutable search */ integer lastPreserved = rawTokens.size;
426 /*
427 Find last segment's tokens to keep before clamping by the beginning of the current Whisper segment.
428 */
429 const integer previousSegment = rawTokens [rawTokens.size]. whisperSegment;
430 /* mutable, may be lowered */ double border = std::min (tokenData. t0 / 100.0, tokenData. t_dtw / 100.0);
431 while (lastPreserved >= 1 && rawTokens [lastPreserved]. whisperSegment == previousSegment
432 && rawTokens [lastPreserved]. tmax > border)
433 lastPreserved --;
434 /*
435 Also apply Inter-VAD segment clamping: the tail of the previous Whisper segment must stay
436 in the VAD segment where the preserved part of the tail ends.
437 */
438 if (useVad && vadSegments.size >= 1 && lastPreserved >= 1 && lastPreserved < rawTokens.size) {
439 const double ceiling = vadSegmentEnd (rawTokens [lastPreserved]. tmax);
440 if (ceiling < border) {
441 border = ceiling;
442 while (lastPreserved >= 1 && rawTokens [lastPreserved]. whisperSegment == previousSegment
443 && rawTokens [lastPreserved]. tmax > border)
444 lastPreserved --;
445 }
446 }
447 if (lastPreserved < rawTokens.size) // there is something to clamp
448 trace (U"Clamping ", rawTokens.size - lastPreserved, U" tail token(s) of segment ", previousSegment, U" to ", vadToRealTime (border));
449 for (integer m = lastPreserved + 1; m <= rawTokens.size; m ++)
450 rawTokens [m]. tmax = border; // actual clamping
451 }
452 trace (U"Segment ", i, U" first-token t0 = ", vadToRealTime (tokenData. t0 / 100.0),
453 U", segment_t0 = ", whisper_full_get_segment_t0 (my whisperContext.get(), i) / 100.0,
454 U", segment_t1 = ", whisper_full_get_segment_t1 (my whisperContext.get(), i) / 100.0
455 );
456 isFirstPartialTokenInSegment = false;
457 }
458
459 partialTokenText += whisper_full_get_token_text (my whisperContext.get(), i, j);
460 const double currentTokenTmax = tokenData. t_dtw / 100.0;
461
462 if (! Melder_str8IsValidUtf8 (partialTokenText.c_str()))
463 continue; // continue accumulating token texts until partialTokenText is a proper UTF8 string
464
465 /*
466 Now partialTokenText is valid UTF8.
467 */
468 RawToken *rawToken = rawTokens. append();
469 rawToken -> text = Melder_8to32_e (partialTokenText.c_str());
470 rawToken -> tmax = currentTokenTmax;
471 rawToken -> whisperSegment = i;
472 partialTokenText. clear();
473
474 trace (U"Segment ", i, U"; original token in it ", j, U": text = \"", rawToken -> text.get(),
475 U"\", t_dtw = ", vadToRealTime (currentTokenTmax),
476 U"\", t0 = ", vadToRealTime (tokenData. t0 / 100.0),
477 U"\", t1 = ", vadToRealTime (tokenData. t1 / 100.0)
478 );
479 }
480 }
481
482 /*
483 Group Whisper tokens into words.
484 */
485 struct WhisperToken {
486 autostring32 text;
487 double tmax;
488 };
489
490 struct WhisperWord {
491 autovector <WhisperToken> whisperTokens = newvectorzero <WhisperToken> (0);
492 autostring32 textWithPunctuation;
493 double tmax;
494 };
495
496 autovector <WhisperWord> whisperWords = newvectorzero <WhisperWord> (0);
497 for (integer i = 1; i <= rawTokens.size; i ++) {
498 RawToken& rawToken = rawTokens [i];
499
500 /*
501 Create a new WhisperWord if
502 - the current token starts with a space or if autovector <WhisperWord> whisperWords is still empty
503 - and the previous word is not a standalone "-".
504 Otherwise, append the current token to the existing word.
505 */
506 const bool isNewWord = rawToken. text.get() [0] == U' ';
507 const bool isLastWordDash = whisperWords.size >= 1 &&
508 Melder_length (whisperWords [whisperWords.size]. textWithPunctuation.get()) == 1 &&
509 whisperWords [whisperWords.size]. textWithPunctuation.get() [0] == U'-';
510
511 WhisperWord *word;
512 if ((isNewWord || whisperWords.size == 0) && ! isLastWordDash)
513 word = whisperWords. append();
514 else
515 word = &whisperWords [whisperWords.size];
516 WhisperToken *token = word -> whisperTokens.append();
517
518 token -> text = Melder_dup (rawToken. text.get() + (isNewWord ? 1 : 0));
519 word -> textWithPunctuation = Melder_dup (Melder_cat (word -> textWithPunctuation.get(), token -> text.get()));
520 token -> tmax = rawToken. tmax;
521 if (word -> whisperTokens.size >= 2 && isPurePunctuation (token -> text.get())
522 && token -> text.get() [0] != U')' && token -> text.get() [0] != U']')
523 word -> tmax = (word -> tmax + token -> tmax) / 2;
524 else
525 word -> tmax = token -> tmax;
526 }
527
528 /*
529 Resolve zero-length words. There might be runs of consecutive words sharing the same tmax (they can be results
530 of clamping or just poor DTW). Distribute them equally over the time from the preceding word's tmax till their tmax,
531 so that there are no zero-length words anymore.
532 */
533 /* mutable scan */ integer iword = 1;
534 while (iword <= whisperWords.size) {
535 /* mutable scan */ integer k = iword + 1;
536 while (k <= whisperWords.size && whisperWords [k]. tmax == whisperWords [iword]. tmax)
537 k ++;
538 const integer n = k - iword;
539 if (n >= 2) {
540 const double prevTmax = ( iword > 1 ? whisperWords [iword - 1]. tmax : 0.0 );
541 const double interval = (whisperWords [iword]. tmax - prevTmax) / n;
542 for (integer l = 1; l < n; l ++)
543 whisperWords [iword + l - 1]. tmax = prevTmax + interval * l;
544 }
545 iword = k;
546 }
547
548 /*
549 Build the list of word intervals (including silences) with VAD-adjustments if VAD is in use.
550 */
551 struct WordInterval {
552 autostring32 textWithPunctuation;
553 double tmax;
554 };
555 autovector <WordInterval> wordIntervals;
556
557 if (! useVad || ! numberOfVadSegments) {
558 /*
559 VAD is not used or no VAD segments detected: no VAD adjustments needed.
560 */
561 wordIntervals = newvectorzero <WordInterval> (whisperWords.size);
562 for (integer i = 1; i <= whisperWords.size; i ++) {
563 wordIntervals [i]. textWithPunctuation = whisperWords [i]. textWithPunctuation.move();
564 wordIntervals [i]. tmax = whisperWords [i]. tmax;
565 }
566 } else {
567 /*
568 VAD is used and at least one VAD segment detected: translate timestamps back to original time
569 and insert silence tokens between consecutive VAD segments.
570 */
571 wordIntervals = newvectorzero <WordInterval> (0);
572
573 /*
574 Lambda to append a silent interval with the given tmax to wordIntervals.
575 */
576 auto appendSilence = [& wordIntervals] (double tmax) {
577 WordInterval *silence;
578 if (wordIntervals.size >= 1 && wordIntervals [wordIntervals.size]. textWithPunctuation [0] == U'\0') {
579 silence = &wordIntervals [wordIntervals.size];
580 silence -> tmax = tmax; // extend the last silence to the end of this one
581 } else {
582 silence = wordIntervals. append();
583 silence -> textWithPunctuation = Melder_dup (U"");
584 silence -> tmax = tmax;
585 }
586 trace (U"Silence ", wordIntervals.size, U": text = ", silence -> textWithPunctuation.get(), U", tmax = ", silence -> tmax);
587 };
588
589 /*
590 Lambda to append a word to wordIntervals, with the given tmax, which is translated from VAD to original timestamps.
591 Note: this might move the text member out of word, leaving it empty.
592 */
593 auto appendWord = [& wordIntervals, & vadSegments, & appendSilence] (WhisperWord& word, integer vadSegment) {
594 Melder_assert (word. tmax >= vadSegments [vadSegment]. vadStart);
595 const double tmax = std::min (
596 word. tmax - vadSegments [vadSegment]. vadStart + vadSegments [vadSegment]. origStart, // original tmax
597 vadSegments [vadSegment]. origEnd
598 ); // clamp to the size of VAD interval
599
600 const conststring32 text = word. textWithPunctuation.get();
601 if (text [0] == U'\0' || text [0] == U'(' || text [0] == U'[')
602 appendSilence (tmax); // insert (append) silence if the word is empty or is non-speech (e.g., "(laughs)")
603 else {
604 WordInterval *wordInterval = wordIntervals. append();
605 wordInterval -> textWithPunctuation = word. textWithPunctuation.move();
606 wordInterval -> tmax = tmax;
607 trace (U"Word interval ", wordIntervals.size, U": text = ", wordInterval -> textWithPunctuation.get(), U", tmax = ", wordInterval -> tmax);
608 }
609 };
610
611 /*
612 First, append a silence token in case speech does not start directly from the beginning of the sound.
613 */
614 if (vadSegments [1]. origStart > sound -> xmin)
615 appendSilence (vadSegments [1]. origStart);
616
617 /*
618 Then iterate over the list of words, inserting silences between VAD segments.
619 */
620 /* mutable increment */ integer currentVadSegment = 1;
621 for (integer i = 1; i <= whisperWords.size; i ++) {
622 WhisperWord& word = whisperWords [i];
623 const integer numberOfTokensInWord = word. whisperTokens.size;
624 const conststring32 lastToken = word. whisperTokens [numberOfTokensInWord]. text.get();
625 /* mutable scan */ integer firstContentToken = 1;
626 while (firstContentToken < numberOfTokensInWord && isPurePunctuation (word. whisperTokens [firstContentToken]. text.get()))
627 firstContentToken ++;
628 const double firstContentTokenTmax = word. whisperTokens [firstContentToken]. tmax; // first token that is not a pure punctuation
629
630 const bool landsInCurrentVadSegment = ( currentVadSegment == numberOfVadSegments ||
631 firstContentTokenTmax < vadSegments [currentVadSegment + 1]. vadStart && Melder_isPunctuationOrSymbol (lastToken [0]) );
632
633 if (! landsInCurrentVadSegment)
634 while (currentVadSegment < numberOfVadSegments && word. tmax > vadSegments [currentVadSegment + 1]. vadStart) {
635 appendSilence (vadSegments [currentVadSegment + 1]. origStart); // insert silence between current and next VAD segments;
636 currentVadSegment ++;
637 }
638 appendWord (word, currentVadSegment);
639 }
640
641 /*
642 Insert trailing silence.
643 */
644 if (wordIntervals.size > 0 && wordIntervals [wordIntervals.size]. tmax < sound -> xmax)
645 appendSilence (sound -> xmax);
646 }
647
648 /*
649 Build word and sentence intervals from the flat token list.
650 */
651 autoMelderString sentenceText;
652 autoMelderString fullText;
653 autovector <SpeechSegment> words = newvectorzero <SpeechSegment> (0);
654 autovector <SpeechSegment> sentences = newvectorzero <SpeechSegment> (0);
655
656 /* mutable per-sentence */ double sentenceTmin = sound -> xmin; // (re)set at each sentence start, default assignment is just a guard
657 /* mutable per-token */ double previousWordTmax = sound -> xmin; // default for the first token
658
659 for (integer i = 1; i <= wordIntervals.size; i ++) {
660 const double wordTmin = previousWordTmax;
661 const double wordTmax = wordIntervals [i]. tmax;
662 previousWordTmax = wordTmax;
663
664 const conststring32 wordTextWithPunctuation = wordIntervals [i]. textWithPunctuation.get();
665 const bool isEmptyWord = wordTextWithPunctuation [0] == U'\0';
666
667 /*
668 Remove all leading and trailing punctuation except ' ('cause, speakers').
669 */
670 /* mutable adjust */ conststring32 clean = wordTextWithPunctuation;
671 while (*clean != U'\0' && ! Melder_isAlphanumeric (*clean) && *clean != U'\'')
672 ++ clean; // move beyond leading punctuation
673 /* mutable adjust */ integer cleanLength = Melder_length (clean);
674 while (cleanLength > 0 && ! Melder_isAlphanumeric (clean [cleanLength - 1]) && clean [cleanLength - 1] != U'\'')
675 -- cleanLength; // exclude trailing punctuation
676 autostring32 wordTextWithoutPunctuation = Melder_ndup (clean, cleanLength);
677
678 /*
679 Add word text to the sentence and to the full transcription text (only for non-silent words to not multiply spaces).
680 */
681 if (! isEmptyWord) {
682 MelderString_append (& sentenceText, sentenceText.length > 0 ? U" " : U"", wordTextWithPunctuation);
683 MelderString_append (& fullText, fullText.length > 0 ? U" " : U"", wordTextWithPunctuation);
684 }
685
686 /*
687 Add a word segment or append a zero-length word to the last word segment.
688 */
689 Melder_assert (wordTmax >= wordTmin);
690 if (wordTmax > wordTmin) { // not a zero-length word
691 SpeechSegment *word = words. append();
692 word -> text = wordTextWithoutPunctuation.move();
693 word -> tmin = wordTmin;
694 word -> tmax = wordTmax;
695 trace (U"Word ", words.size, U": \"", word -> text.get(), U"\" [ ", word -> tmin, U" - ", word -> tmax, U" ]");
696 } else if (wordTextWithoutPunctuation [0] != U'\0' && words.size > 0) { // zero-length word: add its text to previous one
697 SpeechSegment& lastWord = words [words.size];
698 lastWord.text = Melder_dup (Melder_cat (lastWord.text.get(), U" ", wordTextWithoutPunctuation.get()));
699 trace (U"Word ", words.size, U": \"", lastWord.text.get(), U"\" [ ", lastWord. tmin, U" - ", lastWord. tmax, U" ] (appended zero-length)");
700 }
701
702 /*
703 Finalize sentence segment
704 1. if the sentence is complete (ends with terminal punctuation);
705 2. if the current word is the last word of the whole sound;
706 3. if the current word does not contain text (non-speech interval).
707 */
708 if (endsWithTerminalPunctuation (wordTextWithPunctuation) || i == wordIntervals.size || (isEmptyWord && sentenceText.length == 0)) {
709 if (wordTmax > sentenceTmin) {
710 SpeechSegment *sentence = sentences. append();
711 sentence -> text = Melder_dup (sentenceText.string ? sentenceText.string : U"");
712 sentence -> tmin = sentenceTmin;
713 sentence -> tmax = wordTmax;
714 trace (U"Sentence: ", sentences.size, U": \"", sentence -> text.get(), U"\" [ ", sentence -> tmin, U" - ", sentence -> tmax, U" ]");
715 MelderString_empty (& sentenceText);
716 sentenceTmin = wordTmax;
717 } else if (sentences.size > 0) {
718 if (sentenceText.length > 0) {
719 SpeechSegment& lastSentence = sentences [sentences.size];
720 lastSentence.text = Melder_dup (Melder_cat (lastSentence.text.get(), U" ", sentenceText.string));
721 }
722 MelderString_empty (& sentenceText);
723 }
724 }
725 }
726
727 WhisperTranscription transcription;
728 transcription. fullTranscription. text = Melder_dup (fullText.string ? fullText.string : U"");
729 transcription. fullTranscription. tmin = sound -> xmin;
730 transcription. fullTranscription. tmax = sound -> xmax;
731 transcription. words = words.move();
732 transcription. sentences = sentences.move();
733
734 trace (U"Full transcription:",
735 U" [ ", transcription. fullTranscription. tmin, U" - ",
736 transcription. fullTranscription. tmax, U" ]", transcription. fullTranscription. text.get()
737 );
738
739 return transcription;
740
741 } catch (MelderError) {
742 Melder_throw (U"Sound not transcribed.");
743 }
744 }
745
746 autovector <SpeechSegment> doSileroVad (constSound sound, const double speechProbabilityThreshold, const double minNonSpeechDuration,
747 const double minSpeechDuration, const double speechPad, const conststring32 nonSpeechLabel, const conststring32 speechLabel
748 ) {
749 //TRACE
750 trace (U"Sound xmin = ", sound -> xmin, U", sound xmax = ", sound -> xmax);
751 supressGgmlLogging ();
752
753 /*
754 Remember original sound -> xmin and sound -> xmax before resampling; and resample.
755 */
756 const double soundStart = sound -> xmin;
757 const double soundEnd = sound -> xmax;
758 autovector <float> samples32 = resampleForWhisper (sound);
759
760 try {
761 /*
762 Initialize VAD context.
763 */
764 whisper_vad_context_params vad_ctx_params = whisper_vad_default_context_params ();
765 autoWhisperVadContext vad_ctx = whisper_vad_init_from_memory_with_params (ggml_silero_bin, ggml_silero_bin_len, vad_ctx_params);
766 if (! vad_ctx.get())
767 Melder_throw (U"Failed to initialize VAD context.");
768
769 /*
770 Set VAD parameters and run Silero VAD.
771 */
772 whisper_vad_params vad_params = whisper_vad_default_params ();
773 vad_params. threshold = static_cast <float> (speechProbabilityThreshold);
774 vad_params. min_speech_duration_ms = static_cast <int> (minSpeechDuration * 1000.0);
775 vad_params. min_silence_duration_ms = static_cast <int> (minNonSpeechDuration * 1000.0);
776 vad_params. speech_pad_ms = static_cast <int> (speechPad * 1000.0);
777 autoWhisperVadSegments vad_segments = whisper_vad_segments_from_samples (vad_ctx.get(), vad_params,
778 samples32.asArgumentToFunctionThatExpectsZeroBasedArray(), static_cast <int> (samples32.size));
779 if (! vad_segments.get())
780 Melder_throw (U"Failed to obtain VAD segments.");
781
782 /*
783 Collect all VAD segments and wrap them with "non-voice" intervals.
784 */
785 const int numberOfVadSegments = whisper_vad_segments_n_segments (vad_segments.get());
786 autovector <SpeechSegment> allIntervals = newvectorzero <SpeechSegment> (0);
787
788 for (int i = 0; i < numberOfVadSegments; i ++) {
789 const double t0 = whisper_vad_segments_get_segment_t0 (vad_segments.get(), i) / 100.0;
790 const double t1 = whisper_vad_segments_get_segment_t1 (vad_segments.get(), i) / 100.0;
791
792 /*
793 Insert a non-voice interval before the first voice interval or between two voice intervals.
794 */
795 const double previousEnd = (i == 0) ? soundStart : whisper_vad_segments_get_segment_t1 (vad_segments.get(), i - 1) / 100.0;
796 if (t0 > previousEnd) {
797 SpeechSegment *nonVoiceInterval = allIntervals. append ();
798 nonVoiceInterval -> text = Melder_dup (nonSpeechLabel);
799 nonVoiceInterval -> tmin = previousEnd;
800 nonVoiceInterval -> tmax = t0;
801 trace (U"Non-voice: t0 = ", allIntervals [allIntervals.size]. tmin, U", t1 = ", allIntervals [allIntervals.size]. tmax);
802 }
803 /*
804 Insert the voice interval.
805 */
806 SpeechSegment *voiceInterval = allIntervals. append();
807 voiceInterval -> text = Melder_dup (speechLabel);
808 voiceInterval -> tmin = t0;
809 voiceInterval -> tmax = t1;
810 trace (U"VAD segment ", i + 1, U": t0 = ", allIntervals [allIntervals.size]. tmin, U", t1 = ", allIntervals [allIntervals.size]. tmax);
811
812 /*
813 After the last voice interval, add non-voice if there is remaining audio.
814 */
815 if (i == numberOfVadSegments - 1 && t1 < soundEnd) {
816 SpeechSegment *nonVoiceInterval = allIntervals. append ();
817 nonVoiceInterval -> text = Melder_dup (nonSpeechLabel);
818 nonVoiceInterval -> tmin = t1;
819 nonVoiceInterval -> tmax = soundEnd;
820 trace (U"Non-voice: t0 = ", allIntervals [allIntervals.size]. tmin, U", t1 = ", allIntervals [allIntervals.size]. tmax);
821 }
822 }
823
824 /*
825 If no voice activity detected at all, then entire sound is non-voice.
826 */
827 if (! numberOfVadSegments) {
828 SpeechSegment *nonVoice = allIntervals. append ();
829 nonVoice -> text = Melder_dup (nonSpeechLabel);
830 nonVoice -> tmin = soundStart;
831 nonVoice -> tmax = soundEnd;
832 }
833
834 return allIntervals;
835 } catch (MelderError) {
836 theGgmlMemoryPool. clear(); // this runs after destructors of local objects, therefore it must be safe!
837 Melder_throw (U"Voice Activity not detected for sound.");
838 }
839 }
840
841 extern unsigned char model_ggml_segmentation_data[];
842 extern unsigned int model_ggml_segmentation_length;
843 extern unsigned char model_ggml_embedding_data[];
844 extern unsigned int model_ggml_embedding_length;
845
846 autovector <autovector <SpeechSegment>> doDiarization (constSound sound,
847 const integer maxNumSpeakers, const bool allowSpeakersOverlap,
848 const double clusterThreshold, const double segmentationStep,
849 const conststring32 nonSpeechLabel, const conststring32 speechLabel
850 ) {
851 //TRACE
852 autovector <float> samples32 = resampleForWhisper (sound);
853 try {
854 /*
855 Default maximum number of threads for diarization is half the number of logical processors. This is because:
856 1. hyperthreaded CPUs: half = physical cores, optimal for SIMD kernels.
857 2. hybrid P+E core CPUs: not tested yet; chosen by analogy with transcription.
858 3. homogeneous non-hyperthreaded CPUs: not tested yet; half is likely below optimal but the slowdown is probably
859 smaller than the slowdown in case 1.
860 The user can override this in Praat preferences.
861 */
862 integer n_threads = SpeechRecognizer_getMaxNumberOfThreadsForDiarization ();
863 if (n_threads <= 0)
864 n_threads = DiarizationDefaults::n_threads;
865
866 supressGgmlLogging ();
867 autoDiarizeContext diarizeContext = diarize_init_from_memory (
868 model_ggml_segmentation_data, model_ggml_segmentation_length,
869 model_ggml_embedding_data, model_ggml_embedding_length
870 );
871 diarize_full_params diarizeParams = diarize_default_params ();
872 diarizeParams. n_threads = static_cast<int> (n_threads);
873 diarizeParams. max_speakers = static_cast <int> (maxNumSpeakers);
874 diarizeParams. max_simultaneous_speakers = allowSpeakersOverlap ? 2 : 1;
875 diarizeParams. cluster_threshold = static_cast <float> (clusterThreshold);
876 diarizeParams. seg_step_ratio = static_cast <float> (segmentationStep);
877 diarize_full (diarizeContext.get(), diarizeParams,samples32.asArgumentToFunctionThatExpectsZeroBasedArray(),
878 static_cast <int> (samples32.size));
879 const unsigned int numberOfSegments = diarize_full_n_segments (diarizeContext.get());
880 const int numberOfSpeakers = diarize_full_n_speakers(diarizeContext.get());
881
882 trace(U"Speakers:", numberOfSpeakers, U", Segments: ", numberOfSegments);
883
884 autovector <autovector <SpeechSegment>> speakers = newvectorzero <autovector <SpeechSegment>> (numberOfSpeakers);
885 /*
886 Collect segments for each speaker.
887 */
888 for (int i = 1; i <= numberOfSpeakers; i ++) {
889 /* mutable increment */ double currentIntervalStart = sound -> xmin;
890
891 for (int segment = 0; segment < numberOfSegments; segment ++) {
892 if (diarize_full_get_segment_speaker (diarizeContext.get(), segment) + 1 != i) // this segment is from a different speaker
893 continue;
894
895 const double tmin = diarize_full_get_segment_t0 (diarizeContext.get(), segment);
896 const double tmax = diarize_full_get_segment_t1 (diarizeContext.get(), segment);
897
898 if (tmin > currentIntervalStart) {
899 SpeechSegment *gap = speakers [i]. append();
900 gap -> text = Melder_dup (nonSpeechLabel);
901 gap -> tmin = currentIntervalStart;
902 gap -> tmax = tmin;
903 }
904
905 SpeechSegment *speakerSegment = speakers [i]. append();
906 speakerSegment -> text = Melder_dup (speechLabel);
907 speakerSegment -> tmin = tmin;
908 speakerSegment -> tmax = tmax;
909
910 trace (U"Diarization: [ ", speakerSegment -> tmin, U" - ", speakerSegment -> tmax, U" ] \"",
911 speakerSegment -> text.get(), U"\"");
912
913 currentIntervalStart = tmax;
914 }
915
916 if (currentIntervalStart < sound -> xmax) {
917 SpeechSegment *gap = speakers [i].append();
918 gap -> text = Melder_dup (nonSpeechLabel);
919 gap -> tmin = currentIntervalStart;
920 gap -> tmax = sound -> xmax;
921 }
922 }
923
924 return speakers;
925
926 } catch (MelderError) {
927 theGgmlMemoryPool. clear();
928 Melder_throw (U"Diarization failed.");
929 }
930 }
931
932 static conststring32 theWhisperModelsFolder () {
933 static autostring32 whisperModelFolderPath;
934 if (! whisperModelFolderPath) {
935 try {
936 structMelderFolder modelsFolder { };
937 MelderFolder_getSubfolder (Melder_preferencesFolder (), U"models", & modelsFolder);
938 if (! MelderFolder_exists (& modelsFolder))
939 MelderFolder_create (& modelsFolder);
940 structMelderFolder whispercppFolder { };
941 MelderFolder_getSubfolder (& modelsFolder, U"whispercpp", & whispercppFolder);
942 if (! MelderFolder_exists (& whispercppFolder))
943 MelderFolder_create (& whispercppFolder);
944 whisperModelFolderPath = Melder_dup (MelderFolder_peekPath (& whispercppFolder));
945 if (Melder_debug == 2001)
946 Melder_casual (U"Whispercpp model folder path: ", whisperModelFolderPath.get());
947 } catch (MelderError) {
948 Melder_clearError ();
949 }
950 }
951 return whisperModelFolderPath.get();
952 }
953
954 constSTRVEC theCurrentSpeechRecognizerModelNames () {
955 static autoSTRVEC whisperModelNames;
956 try {
957 whisperModelNames = fileNames_STRVEC (Melder_cat (theWhisperModelsFolder (), U"/*.bin"));
958 } catch (MelderError) {
959 Melder_clearError ();
960 }
961 return whisperModelNames.get();
962 }
963
964 constSTRVEC theSpeechRecognizerLanguageNames () {
965 static autoSTRVEC sortedWhisperLanguageNames;
966 if (! sortedWhisperLanguageNames) {
967 autoSTRVEC unsorted;
968 try {
969 const uint8 numberOfLanguages = whisper_lang_max_id ();
970 for (uint8 i = 0; i < numberOfLanguages; i ++) {
971 autostring32 languageName = Melder_8to32_e (whisper_lang_str_full (i));
972
973 /*
974 Capitalize the first letter, e.g. "dutch" -> "Dutch".
975 */
976 if (languageName [0] != U'\0')
977 languageName [0] = Melder_toUpperCase (languageName [0]);
978
979 unsorted. append (languageName.get());
980 }
981 autoSTRVEC sorted = sort_STRVEC (unsorted.get());
982
983 /*
984 Create a list to return (with autodetect option).
985 */
986 sortedWhisperLanguageNames. append (U"Autodetect language");
987 for (integer i = 1; i <= sorted.size; i ++)
988 sortedWhisperLanguageNames. append (sorted [i].get());
989
990 } catch (MelderError) {
991 unsorted. reset();
992 sortedWhisperLanguageNames. reset();
993 Melder_clearError ();
994 }
995 }
996 return sortedWhisperLanguageNames.get();
997 }
998
999 /*
1000 Preferences.
1001 */
1002 static struct {
1003 integer maxNumberOfThreadsForTranscription = 0; // "0" signals automatic (MelderThread_getNumberOfProcessors () / 2)
1004 integer maxNumberOfThreadsForDiarization = 0; // "0" signals automatic (MelderThread_getNumberOfProcessors () / 2)
1005 } preferences;
1006
1007 void SpeechRecognizer_preferences () {
1008 Preferences_addInteger (U"SpeechRecognizer.maxNumberOfThreadsForTranscription",
1009 & preferences. maxNumberOfThreadsForTranscription, 0);
1010 Preferences_addInteger (U"SpeechRecognizer.maxNumberOfThreadsForDiarization",
1011 & preferences. maxNumberOfThreadsForDiarization, 0);
1012 }
1013
1014 void SpeechRecognizer_setMaxNumberOfThreadsForTranscription (integer numberOfThreads) {
1015 preferences. maxNumberOfThreadsForTranscription = numberOfThreads;
1016 }
1017 void SpeechRecognizer_setMaxNumberOfThreadsForDiarization (integer numberOfThreads) {
1018 preferences. maxNumberOfThreadsForDiarization = numberOfThreads;
1019 }
1020
1021 integer SpeechRecognizer_getMaxNumberOfThreadsForTranscription () {
1022 return preferences. maxNumberOfThreadsForTranscription;
1023 }
1024 integer SpeechRecognizer_getMaxNumberOfThreadsForDiarization () {
1025 return preferences. maxNumberOfThreadsForDiarization;
1026 }
1027
1028 /* End of file SpeechRecognizer.cpp */