Xenobd/whisper.cpp
0
1// Real-time speech recognition of input from a microphone2//3// A very quick-n-dirty implementation serving mainly as a proof of concept.4//5#include "common-sdl.h"6#include "common.h"7#include "common-whisper.h"8#include "whisper.h"9 10#include <chrono>11#include <cstdio>12#include <fstream>13#include <string>14#include <thread>15#include <vector>16 17// command-line parameters18struct whisper_params {19 int32_t n_threads = std::min(4, (int32_t) std::thread::hardware_concurrency());20 int32_t step_ms = 3000;21 int32_t length_ms = 10000;22 int32_t keep_ms = 200;23 int32_t capture_id = -1;24 int32_t max_tokens = 32;25 int32_t audio_ctx = 0;26 int32_t beam_size = -1;27 28 float vad_thold = 0.6f;29 float freq_thold = 100.0f;30 31 bool translate = false;32 bool no_fallback = false;33 bool print_special = false;34 bool no_context = true;35 bool no_timestamps = false;36 bool tinydiarize = false;37 bool save_audio = false; // save audio to wav file38 bool use_gpu = true;39 bool flash_attn = false;40 41 std::string language = "en";42 std::string model = "models/ggml-base.en.bin";43 std::string fname_out;44};45 46void whisper_print_usage(int argc, char ** argv, const whisper_params & params);47 48static bool whisper_params_parse(int argc, char ** argv, whisper_params & params) {49 for (int i = 1; i < argc; i++) {50 std::string arg = argv[i];51 52 if (arg == "-h" || arg == "--help") {53 whisper_print_usage(argc, argv, params);54 exit(0);55 }56 else if (arg == "-t" || arg == "--threads") { params.n_threads = std::stoi(argv[++i]); }57 else if ( arg == "--step") { params.step_ms = std::stoi(argv[++i]); }58 else if ( arg == "--length") { params.length_ms = std::stoi(argv[++i]); }59 else if ( arg == "--keep") { params.keep_ms = std::stoi(argv[++i]); }60 else if (arg == "-c" || arg == "--capture") { params.capture_id = std::stoi(argv[++i]); }61 else if (arg == "-mt" || arg == "--max-tokens") { params.max_tokens = std::stoi(argv[++i]); }62 else if (arg == "-ac" || arg == "--audio-ctx") { params.audio_ctx = std::stoi(argv[++i]); }63 else if (arg == "-bs" || arg == "--beam-size") { params.beam_size = std::stoi(argv[++i]); }64 else if (arg == "-vth" || arg == "--vad-thold") { params.vad_thold = std::stof(argv[++i]); }65 else if (arg == "-fth" || arg == "--freq-thold") { params.freq_thold = std::stof(argv[++i]); }66 else if (arg == "-tr" || arg == "--translate") { params.translate = true; }67 else if (arg == "-nf" || arg == "--no-fallback") { params.no_fallback = true; }68 else if (arg == "-ps" || arg == "--print-special") { params.print_special = true; }69 else if (arg == "-kc" || arg == "--keep-context") { params.no_context = false; }70 else if (arg == "-l" || arg == "--language") { params.language = argv[++i]; }71 else if (arg == "-m" || arg == "--model") { params.model = argv[++i]; }72 else if (arg == "-f" || arg == "--file") { params.fname_out = argv[++i]; }73 else if (arg == "-tdrz" || arg == "--tinydiarize") { params.tinydiarize = true; }74 else if (arg == "-sa" || arg == "--save-audio") { params.save_audio = true; }75 else if (arg == "-ng" || arg == "--no-gpu") { params.use_gpu = false; }76 else if (arg == "-fa" || arg == "--flash-attn") { params.flash_attn = true; }77 78 else {79 fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());80 whisper_print_usage(argc, argv, params);81 exit(0);82 }83 }84 85 return true;86}87 88void whisper_print_usage(int /*argc*/, char ** argv, const whisper_params & params) {89 fprintf(stderr, "\n");90 fprintf(stderr, "usage: %s [options]\n", argv[0]);91 fprintf(stderr, "\n");92 fprintf(stderr, "options:\n");93 fprintf(stderr, " -h, --help [default] show this help message and exit\n");94 fprintf(stderr, " -t N, --threads N [%-7d] number of threads to use during computation\n", params.n_threads);95 fprintf(stderr, " --step N [%-7d] audio step size in milliseconds\n", params.step_ms);96 fprintf(stderr, " --length N [%-7d] audio length in milliseconds\n", params.length_ms);97 fprintf(stderr, " --keep N [%-7d] audio to keep from previous step in ms\n", params.keep_ms);98 fprintf(stderr, " -c ID, --capture ID [%-7d] capture device ID\n", params.capture_id);99 fprintf(stderr, " -mt N, --max-tokens N [%-7d] maximum number of tokens per audio chunk\n", params.max_tokens);100 fprintf(stderr, " -ac N, --audio-ctx N [%-7d] audio context size (0 - all)\n", params.audio_ctx);101 fprintf(stderr, " -bs N, --beam-size N [%-7d] beam size for beam search\n", params.beam_size);102 fprintf(stderr, " -vth N, --vad-thold N [%-7.2f] voice activity detection threshold\n", params.vad_thold);103 fprintf(stderr, " -fth N, --freq-thold N [%-7.2f] high-pass frequency cutoff\n", params.freq_thold);104 fprintf(stderr, " -tr, --translate [%-7s] translate from source language to english\n", params.translate ? "true" : "false");105 fprintf(stderr, " -nf, --no-fallback [%-7s] do not use temperature fallback while decoding\n", params.no_fallback ? "true" : "false");106 fprintf(stderr, " -ps, --print-special [%-7s] print special tokens\n", params.print_special ? "true" : "false");107 fprintf(stderr, " -kc, --keep-context [%-7s] keep context between audio chunks\n", params.no_context ? "false" : "true");108 fprintf(stderr, " -l LANG, --language LANG [%-7s] spoken language\n", params.language.c_str());109 fprintf(stderr, " -m FNAME, --model FNAME [%-7s] model path\n", params.model.c_str());110 fprintf(stderr, " -f FNAME, --file FNAME [%-7s] text output file name\n", params.fname_out.c_str());111 fprintf(stderr, " -tdrz, --tinydiarize [%-7s] enable tinydiarize (requires a tdrz model)\n", params.tinydiarize ? "true" : "false");112 fprintf(stderr, " -sa, --save-audio [%-7s] save the recorded audio to a file\n", params.save_audio ? "true" : "false");113 fprintf(stderr, " -ng, --no-gpu [%-7s] disable GPU inference\n", params.use_gpu ? "false" : "true");114 fprintf(stderr, " -fa, --flash-attn [%-7s] flash attention during inference\n", params.flash_attn ? "true" : "false");115 fprintf(stderr, "\n");116}117 118int main(int argc, char ** argv) {119 ggml_backend_load_all();120 121 whisper_params params;122 123 if (whisper_params_parse(argc, argv, params) == false) {124 return 1;125 }126 127 params.keep_ms = std::min(params.keep_ms, params.step_ms);128 params.length_ms = std::max(params.length_ms, params.step_ms);129 130 const int n_samples_step = (1e-3*params.step_ms )*WHISPER_SAMPLE_RATE;131 const int n_samples_len = (1e-3*params.length_ms)*WHISPER_SAMPLE_RATE;132 const int n_samples_keep = (1e-3*params.keep_ms )*WHISPER_SAMPLE_RATE;133 const int n_samples_30s = (1e-3*30000.0 )*WHISPER_SAMPLE_RATE;134 135 const bool use_vad = n_samples_step <= 0; // sliding window mode uses VAD136 137 const int n_new_line = !use_vad ? std::max(1, params.length_ms / params.step_ms - 1) : 1; // number of steps to print new line138 139 params.no_timestamps = !use_vad;140 params.no_context |= use_vad;141 params.max_tokens = 0;142 143 // init audio144 145 audio_async audio(params.length_ms);146 if (!audio.init(params.capture_id, WHISPER_SAMPLE_RATE)) {147 fprintf(stderr, "%s: audio.init() failed!\n", __func__);148 return 1;149 }150 151 audio.resume();152 153 // whisper init154 if (params.language != "auto" && whisper_lang_id(params.language.c_str()) == -1){155 fprintf(stderr, "error: unknown language '%s'\n", params.language.c_str());156 whisper_print_usage(argc, argv, params);157 exit(0);158 }159 160 struct whisper_context_params cparams = whisper_context_default_params();161 162 cparams.use_gpu = params.use_gpu;163 cparams.flash_attn = params.flash_attn;164 165 struct whisper_context * ctx = whisper_init_from_file_with_params(params.model.c_str(), cparams);166 if (ctx == nullptr) {167 fprintf(stderr, "error: failed to initialize whisper context\n");168 return 2;169 }170 171 std::vector<float> pcmf32 (n_samples_30s, 0.0f);172 std::vector<float> pcmf32_old;173 std::vector<float> pcmf32_new(n_samples_30s, 0.0f);174 175 std::vector<whisper_token> prompt_tokens;176 177 // print some info about the processing178 {179 fprintf(stderr, "\n");180 if (!whisper_is_multilingual(ctx)) {181 if (params.language != "en" || params.translate) {182 params.language = "en";183 params.translate = false;184 fprintf(stderr, "%s: WARNING: model is not multilingual, ignoring language and translation options\n", __func__);185 }186 }187 fprintf(stderr, "%s: processing %d samples (step = %.1f sec / len = %.1f sec / keep = %.1f sec), %d threads, lang = %s, task = %s, timestamps = %d ...\n",188 __func__,189 n_samples_step,190 float(n_samples_step)/WHISPER_SAMPLE_RATE,191 float(n_samples_len )/WHISPER_SAMPLE_RATE,192 float(n_samples_keep)/WHISPER_SAMPLE_RATE,193 params.n_threads,194 params.language.c_str(),195 params.translate ? "translate" : "transcribe",196 params.no_timestamps ? 0 : 1);197 198 if (!use_vad) {199 fprintf(stderr, "%s: n_new_line = %d, no_context = %d\n", __func__, n_new_line, params.no_context);200 } else {201 fprintf(stderr, "%s: using VAD, will transcribe on speech activity\n", __func__);202 }203 204 fprintf(stderr, "\n");205 }206 207 int n_iter = 0;208 209 bool is_running = true;210 211 std::ofstream fout;212 if (params.fname_out.length() > 0) {213 fout.open(params.fname_out);214 if (!fout.is_open()) {215 fprintf(stderr, "%s: failed to open output file '%s'!\n", __func__, params.fname_out.c_str());216 return 1;217 }218 }219 220 wav_writer wavWriter;221 // save wav file222 if (params.save_audio) {223 // Get current date/time for filename224 time_t now = time(0);225 char buffer[80];226 strftime(buffer, sizeof(buffer), "%Y%m%d%H%M%S", localtime(&now));227 std::string filename = std::string(buffer) + ".wav";228 229 wavWriter.open(filename, WHISPER_SAMPLE_RATE, 16, 1);230 }231 printf("[Start speaking]\n");232 fflush(stdout);233 234 auto t_last = std::chrono::high_resolution_clock::now();235 const auto t_start = t_last;236 237 // main audio loop238 while (is_running) {239 if (params.save_audio) {240 wavWriter.write(pcmf32_new.data(), pcmf32_new.size());241 }242 // handle Ctrl + C243 is_running = sdl_poll_events();244 245 if (!is_running) {246 break;247 }248 249 // process new audio250 251 if (!use_vad) {252 while (true) {253 // handle Ctrl + C254 is_running = sdl_poll_events();255 if (!is_running) {256 break;257 }258 audio.get(params.step_ms, pcmf32_new);259 260 if ((int) pcmf32_new.size() > 2*n_samples_step) {261 fprintf(stderr, "\n\n%s: WARNING: cannot process audio fast enough, dropping audio ...\n\n", __func__);262 audio.clear();263 continue;264 }265 266 if ((int) pcmf32_new.size() >= n_samples_step) {267 audio.clear();268 break;269 }270 271 std::this_thread::sleep_for(std::chrono::milliseconds(1));272 }273 274 const int n_samples_new = pcmf32_new.size();275 276 // take up to params.length_ms audio from previous iteration277 const int n_samples_take = std::min((int) pcmf32_old.size(), std::max(0, n_samples_keep + n_samples_len - n_samples_new));278 279 //printf("processing: take = %d, new = %d, old = %d\n", n_samples_take, n_samples_new, (int) pcmf32_old.size());280 281 pcmf32.resize(n_samples_new + n_samples_take);282 283 for (int i = 0; i < n_samples_take; i++) {284 pcmf32[i] = pcmf32_old[pcmf32_old.size() - n_samples_take + i];285 }286 287 memcpy(pcmf32.data() + n_samples_take, pcmf32_new.data(), n_samples_new*sizeof(float));288 289 pcmf32_old = pcmf32;290 } else {291 const auto t_now = std::chrono::high_resolution_clock::now();292 const auto t_diff = std::chrono::duration_cast<std::chrono::milliseconds>(t_now - t_last).count();293 294 if (t_diff < 2000) {295 std::this_thread::sleep_for(std::chrono::milliseconds(100));296 297 continue;298 }299 300 audio.get(2000, pcmf32_new);301 302 if (::vad_simple(pcmf32_new, WHISPER_SAMPLE_RATE, 1000, params.vad_thold, params.freq_thold, false)) {303 audio.get(params.length_ms, pcmf32);304 } else {305 std::this_thread::sleep_for(std::chrono::milliseconds(100));306 307 continue;308 }309 310 t_last = t_now;311 }312 313 // run the inference314 {315 whisper_full_params wparams = whisper_full_default_params(params.beam_size > 1 ? WHISPER_SAMPLING_BEAM_SEARCH : WHISPER_SAMPLING_GREEDY);316 317 wparams.print_progress = false;318 wparams.print_special = params.print_special;319 wparams.print_realtime = false;320 wparams.print_timestamps = !params.no_timestamps;321 wparams.translate = params.translate;322 wparams.single_segment = !use_vad;323 wparams.max_tokens = params.max_tokens;324 wparams.language = params.language.c_str();325 wparams.n_threads = params.n_threads;326 wparams.beam_search.beam_size = params.beam_size;327 328 wparams.audio_ctx = params.audio_ctx;329 330 wparams.tdrz_enable = params.tinydiarize; // [TDRZ]331 332 // disable temperature fallback333 //wparams.temperature_inc = -1.0f;334 wparams.temperature_inc = params.no_fallback ? 0.0f : wparams.temperature_inc;335 336 wparams.prompt_tokens = params.no_context ? nullptr : prompt_tokens.data();337 wparams.prompt_n_tokens = params.no_context ? 0 : prompt_tokens.size();338 339 if (whisper_full(ctx, wparams, pcmf32.data(), pcmf32.size()) != 0) {340 fprintf(stderr, "%s: failed to process audio\n", argv[0]);341 return 6;342 }343 344 // print result;345 {346 if (!use_vad) {347 printf("\33[2K\r");348 349 // print long empty line to clear the previous line350 printf("%s", std::string(100, ' ').c_str());351 352 printf("\33[2K\r");353 } else {354 const int64_t t1 = (t_last - t_start).count()/1000000;355 const int64_t t0 = std::max(0.0, t1 - pcmf32.size()*1000.0/WHISPER_SAMPLE_RATE);356 357 printf("\n");358 printf("### Transcription %d START | t0 = %d ms | t1 = %d ms\n", n_iter, (int) t0, (int) t1);359 printf("\n");360 }361 362 const int n_segments = whisper_full_n_segments(ctx);363 for (int i = 0; i < n_segments; ++i) {364 const char * text = whisper_full_get_segment_text(ctx, i);365 366 if (params.no_timestamps) {367 printf("%s", text);368 fflush(stdout);369 370 if (params.fname_out.length() > 0) {371 fout << text;372 }373 } else {374 const int64_t t0 = whisper_full_get_segment_t0(ctx, i);375 const int64_t t1 = whisper_full_get_segment_t1(ctx, i);376 377 std::string output = "[" + to_timestamp(t0, false) + " --> " + to_timestamp(t1, false) + "] " + text;378 379 if (whisper_full_get_segment_speaker_turn_next(ctx, i)) {380 output += " [SPEAKER_TURN]";381 }382 383 output += "\n";384 385 printf("%s", output.c_str());386 fflush(stdout);387 388 if (params.fname_out.length() > 0) {389 fout << output;390 }391 }392 }393 394 if (params.fname_out.length() > 0) {395 fout << std::endl;396 }397 398 if (use_vad) {399 printf("\n");400 printf("### Transcription %d END\n", n_iter);401 }402 }403 404 ++n_iter;405 406 if (!use_vad && (n_iter % n_new_line) == 0) {407 printf("\n");408 409 // keep part of the audio for next iteration to try to mitigate word boundary issues410 pcmf32_old = std::vector<float>(pcmf32.end() - n_samples_keep, pcmf32.end());411 412 // Add tokens of the last full length segment as the prompt413 if (!params.no_context) {414 prompt_tokens.clear();415 416 const int n_segments = whisper_full_n_segments(ctx);417 for (int i = 0; i < n_segments; ++i) {418 const int token_count = whisper_full_n_tokens(ctx, i);419 for (int j = 0; j < token_count; ++j) {420 prompt_tokens.push_back(whisper_full_get_token_id(ctx, i, j));421 }422 }423 }424 }425 fflush(stdout);426 }427 }428 429 audio.pause();430 431 whisper_print_timings(ctx);432 whisper_free(ctx);433 434 return 0;435}436 