main.cpp 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  1. #include "common.h"
  2. #include "whisper.h"
  3. #include <cmath>
  4. #include <fstream>
  5. #include <cstdio>
  6. #include <string>
  7. #include <thread>
  8. #include <vector>
  9. #include <cstring>
  10. #if defined(_MSC_VER)
  11. #pragma warning(disable: 4244 4267) // possible loss of data
  12. #endif
  13. // Terminal color map. 10 colors grouped in ranges [0.0, 0.1, ..., 0.9]
  14. // Lowest is red, middle is yellow, highest is green.
  15. const std::vector<std::string> k_colors = {
  16. "\033[38;5;196m", "\033[38;5;202m", "\033[38;5;208m", "\033[38;5;214m", "\033[38;5;220m",
  17. "\033[38;5;226m", "\033[38;5;190m", "\033[38;5;154m", "\033[38;5;118m", "\033[38;5;82m",
  18. };
  19. // 500 -> 00:05.000
  20. // 6000 -> 01:00.000
  21. std::string to_timestamp(int64_t t, bool comma = false) {
  22. int64_t msec = t * 10;
  23. int64_t hr = msec / (1000 * 60 * 60);
  24. msec = msec - hr * (1000 * 60 * 60);
  25. int64_t min = msec / (1000 * 60);
  26. msec = msec - min * (1000 * 60);
  27. int64_t sec = msec / 1000;
  28. msec = msec - sec * 1000;
  29. char buf[32];
  30. snprintf(buf, sizeof(buf), "%02d:%02d:%02d%s%03d", (int) hr, (int) min, (int) sec, comma ? "," : ".", (int) msec);
  31. return std::string(buf);
  32. }
  33. int timestamp_to_sample(int64_t t, int n_samples) {
  34. return std::max(0, std::min((int) n_samples - 1, (int) ((t*WHISPER_SAMPLE_RATE)/100)));
  35. }
  36. // helper function to replace substrings
  37. void replace_all(std::string & s, const std::string & search, const std::string & replace) {
  38. for (size_t pos = 0; ; pos += replace.length()) {
  39. pos = s.find(search, pos);
  40. if (pos == std::string::npos) break;
  41. s.erase(pos, search.length());
  42. s.insert(pos, replace);
  43. }
  44. }
  45. // command-line parameters
  46. struct whisper_params {
  47. int32_t n_threads = std::min(4, (int32_t) std::thread::hardware_concurrency());
  48. int32_t n_processors = 1;
  49. int32_t offset_t_ms = 0;
  50. int32_t offset_n = 0;
  51. int32_t duration_ms = 0;
  52. int32_t progress_step = 5;
  53. int32_t max_context = -1;
  54. int32_t max_len = 0;
  55. int32_t best_of = 2;
  56. int32_t beam_size = -1;
  57. float word_thold = 0.01f;
  58. float entropy_thold = 2.40f;
  59. float logprob_thold = -1.00f;
  60. bool speed_up = false;
  61. bool debug_mode = false;
  62. bool translate = false;
  63. bool detect_language = false;
  64. bool diarize = false;
  65. bool tinydiarize = false;
  66. bool split_on_word = false;
  67. bool no_fallback = false;
  68. bool output_txt = false;
  69. bool output_vtt = false;
  70. bool output_srt = false;
  71. bool output_wts = false;
  72. bool output_csv = false;
  73. bool output_jsn = false;
  74. bool output_lrc = false;
  75. bool print_special = false;
  76. bool print_colors = false;
  77. bool print_progress = false;
  78. bool no_timestamps = false;
  79. bool log_score = false;
  80. std::string language = "en";
  81. std::string prompt;
  82. std::string font_path = "/System/Library/Fonts/Supplemental/Courier New Bold.ttf";
  83. std::string model = "models/ggml-base.en.bin";
  84. // [TDRZ] speaker turn string
  85. std::string tdrz_speaker_turn = " [SPEAKER_TURN]"; // TODO: set from command line
  86. std::string openvino_encode_device = "CPU";
  87. std::vector<std::string> fname_inp = {};
  88. std::vector<std::string> fname_out = {};
  89. };
  90. void whisper_print_usage(int argc, char ** argv, const whisper_params & params);
  91. bool whisper_params_parse(int argc, char ** argv, whisper_params & params) {
  92. for (int i = 1; i < argc; i++) {
  93. std::string arg = argv[i];
  94. if (arg == "-"){
  95. params.fname_inp.push_back(arg);
  96. continue;
  97. }
  98. if (arg[0] != '-') {
  99. params.fname_inp.push_back(arg);
  100. continue;
  101. }
  102. if (arg == "-h" || arg == "--help") {
  103. whisper_print_usage(argc, argv, params);
  104. exit(0);
  105. }
  106. else if (arg == "-t" || arg == "--threads") { params.n_threads = std::stoi(argv[++i]); }
  107. else if (arg == "-p" || arg == "--processors") { params.n_processors = std::stoi(argv[++i]); }
  108. else if (arg == "-ot" || arg == "--offset-t") { params.offset_t_ms = std::stoi(argv[++i]); }
  109. else if (arg == "-on" || arg == "--offset-n") { params.offset_n = std::stoi(argv[++i]); }
  110. else if (arg == "-d" || arg == "--duration") { params.duration_ms = std::stoi(argv[++i]); }
  111. else if (arg == "-mc" || arg == "--max-context") { params.max_context = std::stoi(argv[++i]); }
  112. else if (arg == "-ml" || arg == "--max-len") { params.max_len = std::stoi(argv[++i]); }
  113. else if (arg == "-bo" || arg == "--best-of") { params.best_of = std::stoi(argv[++i]); }
  114. else if (arg == "-bs" || arg == "--beam-size") { params.beam_size = std::stoi(argv[++i]); }
  115. else if (arg == "-wt" || arg == "--word-thold") { params.word_thold = std::stof(argv[++i]); }
  116. else if (arg == "-et" || arg == "--entropy-thold") { params.entropy_thold = std::stof(argv[++i]); }
  117. else if (arg == "-lpt" || arg == "--logprob-thold") { params.logprob_thold = std::stof(argv[++i]); }
  118. // else if (arg == "-su" || arg == "--speed-up") { params.speed_up = true; }
  119. else if (arg == "-debug"|| arg == "--debug-mode") { params.debug_mode = true; }
  120. else if (arg == "-tr" || arg == "--translate") { params.translate = true; }
  121. else if (arg == "-di" || arg == "--diarize") { params.diarize = true; }
  122. else if (arg == "-tdrz" || arg == "--tinydiarize") { params.tinydiarize = true; }
  123. else if (arg == "-sow" || arg == "--split-on-word") { params.split_on_word = true; }
  124. else if (arg == "-nf" || arg == "--no-fallback") { params.no_fallback = true; }
  125. else if (arg == "-otxt" || arg == "--output-txt") { params.output_txt = true; }
  126. else if (arg == "-ovtt" || arg == "--output-vtt") { params.output_vtt = true; }
  127. else if (arg == "-osrt" || arg == "--output-srt") { params.output_srt = true; }
  128. else if (arg == "-owts" || arg == "--output-words") { params.output_wts = true; }
  129. else if (arg == "-olrc" || arg == "--output-lrc") { params.output_lrc = true; }
  130. else if (arg == "-fp" || arg == "--font-path") { params.font_path = argv[++i]; }
  131. else if (arg == "-ocsv" || arg == "--output-csv") { params.output_csv = true; }
  132. else if (arg == "-oj" || arg == "--output-json") { params.output_jsn = true; }
  133. else if (arg == "-of" || arg == "--output-file") { params.fname_out.emplace_back(argv[++i]); }
  134. else if (arg == "-ps" || arg == "--print-special") { params.print_special = true; }
  135. else if (arg == "-pc" || arg == "--print-colors") { params.print_colors = true; }
  136. else if (arg == "-pp" || arg == "--print-progress") { params.print_progress = true; }
  137. else if (arg == "-nt" || arg == "--no-timestamps") { params.no_timestamps = true; }
  138. else if (arg == "-l" || arg == "--language") { params.language = argv[++i]; }
  139. else if (arg == "-dl" || arg == "--detect-language") { params.detect_language = true; }
  140. else if ( arg == "--prompt") { params.prompt = argv[++i]; }
  141. else if (arg == "-m" || arg == "--model") { params.model = argv[++i]; }
  142. else if (arg == "-f" || arg == "--file") { params.fname_inp.emplace_back(argv[++i]); }
  143. else if (arg == "-oved" || arg == "--ov-e-device") { params.openvino_encode_device = argv[++i]; }
  144. else if (arg == "-ls" || arg == "--log-score") { params.log_score = true; }
  145. else {
  146. fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
  147. whisper_print_usage(argc, argv, params);
  148. exit(0);
  149. }
  150. }
  151. return true;
  152. }
  153. void whisper_print_usage(int /*argc*/, char ** argv, const whisper_params & params) {
  154. fprintf(stderr, "\n");
  155. fprintf(stderr, "usage: %s [options] file0.wav file1.wav ...\n", argv[0]);
  156. fprintf(stderr, "\n");
  157. fprintf(stderr, "options:\n");
  158. fprintf(stderr, " -h, --help [default] show this help message and exit\n");
  159. fprintf(stderr, " -t N, --threads N [%-7d] number of threads to use during computation\n", params.n_threads);
  160. fprintf(stderr, " -p N, --processors N [%-7d] number of processors to use during computation\n", params.n_processors);
  161. fprintf(stderr, " -ot N, --offset-t N [%-7d] time offset in milliseconds\n", params.offset_t_ms);
  162. fprintf(stderr, " -on N, --offset-n N [%-7d] segment index offset\n", params.offset_n);
  163. fprintf(stderr, " -d N, --duration N [%-7d] duration of audio to process in milliseconds\n", params.duration_ms);
  164. fprintf(stderr, " -mc N, --max-context N [%-7d] maximum number of text context tokens to store\n", params.max_context);
  165. fprintf(stderr, " -ml N, --max-len N [%-7d] maximum segment length in characters\n", params.max_len);
  166. fprintf(stderr, " -sow, --split-on-word [%-7s] split on word rather than on token\n", params.split_on_word ? "true" : "false");
  167. fprintf(stderr, " -bo N, --best-of N [%-7d] number of best candidates to keep\n", params.best_of);
  168. fprintf(stderr, " -bs N, --beam-size N [%-7d] beam size for beam search\n", params.beam_size);
  169. fprintf(stderr, " -wt N, --word-thold N [%-7.2f] word timestamp probability threshold\n", params.word_thold);
  170. fprintf(stderr, " -et N, --entropy-thold N [%-7.2f] entropy threshold for decoder fail\n", params.entropy_thold);
  171. fprintf(stderr, " -lpt N, --logprob-thold N [%-7.2f] log probability threshold for decoder fail\n", params.logprob_thold);
  172. // fprintf(stderr, " -su, --speed-up [%-7s] speed up audio by x2 (reduced accuracy)\n", params.speed_up ? "true" : "false");
  173. fprintf(stderr, " -debug, --debug-mode [%-7s] enable debug mode (eg. dump log_mel)\n", params.debug_mode ? "true" : "false");
  174. fprintf(stderr, " -tr, --translate [%-7s] translate from source language to english\n", params.translate ? "true" : "false");
  175. fprintf(stderr, " -di, --diarize [%-7s] stereo audio diarization\n", params.diarize ? "true" : "false");
  176. fprintf(stderr, " -tdrz, --tinydiarize [%-7s] enable tinydiarize (requires a tdrz model)\n", params.tinydiarize ? "true" : "false");
  177. fprintf(stderr, " -nf, --no-fallback [%-7s] do not use temperature fallback while decoding\n", params.no_fallback ? "true" : "false");
  178. fprintf(stderr, " -otxt, --output-txt [%-7s] output result in a text file\n", params.output_txt ? "true" : "false");
  179. fprintf(stderr, " -ovtt, --output-vtt [%-7s] output result in a vtt file\n", params.output_vtt ? "true" : "false");
  180. fprintf(stderr, " -osrt, --output-srt [%-7s] output result in a srt file\n", params.output_srt ? "true" : "false");
  181. fprintf(stderr, " -olrc, --output-lrc [%-7s] output result in a lrc file\n", params.output_lrc ? "true" : "false");
  182. fprintf(stderr, " -owts, --output-words [%-7s] output script for generating karaoke video\n", params.output_wts ? "true" : "false");
  183. fprintf(stderr, " -fp, --font-path [%-7s] path to a monospace font for karaoke video\n", params.font_path.c_str());
  184. fprintf(stderr, " -ocsv, --output-csv [%-7s] output result in a CSV file\n", params.output_csv ? "true" : "false");
  185. fprintf(stderr, " -oj, --output-json [%-7s] output result in a JSON file\n", params.output_jsn ? "true" : "false");
  186. fprintf(stderr, " -of FNAME, --output-file FNAME [%-7s] output file path (without file extension)\n", "");
  187. fprintf(stderr, " -ps, --print-special [%-7s] print special tokens\n", params.print_special ? "true" : "false");
  188. fprintf(stderr, " -pc, --print-colors [%-7s] print colors\n", params.print_colors ? "true" : "false");
  189. fprintf(stderr, " -pp, --print-progress [%-7s] print progress\n", params.print_progress ? "true" : "false");
  190. fprintf(stderr, " -nt, --no-timestamps [%-7s] do not print timestamps\n", params.no_timestamps ? "true" : "false");
  191. fprintf(stderr, " -l LANG, --language LANG [%-7s] spoken language ('auto' for auto-detect)\n", params.language.c_str());
  192. fprintf(stderr, " -dl, --detect-language [%-7s] exit after automatically detecting language\n", params.detect_language ? "true" : "false");
  193. fprintf(stderr, " --prompt PROMPT [%-7s] initial prompt\n", params.prompt.c_str());
  194. fprintf(stderr, " -m FNAME, --model FNAME [%-7s] model path\n", params.model.c_str());
  195. fprintf(stderr, " -f FNAME, --file FNAME [%-7s] input WAV file path\n", "");
  196. fprintf(stderr, " -oved D, --ov-e-device DNAME [%-7s] the OpenVINO device used for encode inference\n", params.openvino_encode_device.c_str());
  197. fprintf(stderr, " -ls, --log-score [%-7s] log best decoder scores of tokens\n", params.log_score?"true":"false");
  198. fprintf(stderr, "\n");
  199. }
  200. struct whisper_print_user_data {
  201. const whisper_params * params;
  202. const std::vector<std::vector<float>> * pcmf32s;
  203. int progress_prev;
  204. };
  205. std::string estimate_diarization_speaker(std::vector<std::vector<float>> pcmf32s, int64_t t0, int64_t t1, bool id_only = false) {
  206. std::string speaker = "";
  207. const int64_t n_samples = pcmf32s[0].size();
  208. const int64_t is0 = timestamp_to_sample(t0, n_samples);
  209. const int64_t is1 = timestamp_to_sample(t1, n_samples);
  210. double energy0 = 0.0f;
  211. double energy1 = 0.0f;
  212. for (int64_t j = is0; j < is1; j++) {
  213. energy0 += fabs(pcmf32s[0][j]);
  214. energy1 += fabs(pcmf32s[1][j]);
  215. }
  216. if (energy0 > 1.1*energy1) {
  217. speaker = "0";
  218. } else if (energy1 > 1.1*energy0) {
  219. speaker = "1";
  220. } else {
  221. speaker = "?";
  222. }
  223. //printf("is0 = %lld, is1 = %lld, energy0 = %f, energy1 = %f, speaker = %s\n", is0, is1, energy0, energy1, speaker.c_str());
  224. if (!id_only) {
  225. speaker.insert(0, "(speaker ");
  226. speaker.append(")");
  227. }
  228. return speaker;
  229. }
  230. void whisper_print_progress_callback(struct whisper_context * /*ctx*/, struct whisper_state * /*state*/, int progress, void * user_data) {
  231. int progress_step = ((whisper_print_user_data *) user_data)->params->progress_step;
  232. int * progress_prev = &(((whisper_print_user_data *) user_data)->progress_prev);
  233. if (progress >= *progress_prev + progress_step) {
  234. *progress_prev += progress_step;
  235. fprintf(stderr, "%s: progress = %3d%%\n", __func__, progress);
  236. }
  237. }
  238. void whisper_print_segment_callback(struct whisper_context * ctx, struct whisper_state * /*state*/, int n_new, void * user_data) {
  239. const auto & params = *((whisper_print_user_data *) user_data)->params;
  240. const auto & pcmf32s = *((whisper_print_user_data *) user_data)->pcmf32s;
  241. const int n_segments = whisper_full_n_segments(ctx);
  242. std::string speaker = "";
  243. int64_t t0 = 0;
  244. int64_t t1 = 0;
  245. // print the last n_new segments
  246. const int s0 = n_segments - n_new;
  247. if (s0 == 0) {
  248. printf("\n");
  249. }
  250. for (int i = s0; i < n_segments; i++) {
  251. if (!params.no_timestamps || params.diarize) {
  252. t0 = whisper_full_get_segment_t0(ctx, i);
  253. t1 = whisper_full_get_segment_t1(ctx, i);
  254. }
  255. if (!params.no_timestamps) {
  256. printf("[%s --> %s] ", to_timestamp(t0).c_str(), to_timestamp(t1).c_str());
  257. }
  258. if (params.diarize && pcmf32s.size() == 2) {
  259. speaker = estimate_diarization_speaker(pcmf32s, t0, t1);
  260. }
  261. if (params.print_colors) {
  262. for (int j = 0; j < whisper_full_n_tokens(ctx, i); ++j) {
  263. if (params.print_special == false) {
  264. const whisper_token id = whisper_full_get_token_id(ctx, i, j);
  265. if (id >= whisper_token_eot(ctx)) {
  266. continue;
  267. }
  268. }
  269. const char * text = whisper_full_get_token_text(ctx, i, j);
  270. const float p = whisper_full_get_token_p (ctx, i, j);
  271. const int col = std::max(0, std::min((int) k_colors.size() - 1, (int) (std::pow(p, 3)*float(k_colors.size()))));
  272. printf("%s%s%s%s", speaker.c_str(), k_colors[col].c_str(), text, "\033[0m");
  273. }
  274. } else {
  275. const char * text = whisper_full_get_segment_text(ctx, i);
  276. printf("%s%s", speaker.c_str(), text);
  277. }
  278. if (params.tinydiarize) {
  279. if (whisper_full_get_segment_speaker_turn_next(ctx, i)) {
  280. printf("%s", params.tdrz_speaker_turn.c_str());
  281. }
  282. }
  283. // with timestamps or speakers: each segment on new line
  284. if (!params.no_timestamps || params.diarize) {
  285. printf("\n");
  286. }
  287. fflush(stdout);
  288. }
  289. }
  290. bool output_txt(struct whisper_context * ctx, const char * fname, const whisper_params & params, std::vector<std::vector<float>> pcmf32s) {
  291. std::ofstream fout(fname);
  292. if (!fout.is_open()) {
  293. fprintf(stderr, "%s: failed to open '%s' for writing\n", __func__, fname);
  294. return false;
  295. }
  296. fprintf(stderr, "%s: saving output to '%s'\n", __func__, fname);
  297. const int n_segments = whisper_full_n_segments(ctx);
  298. for (int i = 0; i < n_segments; ++i) {
  299. const char * text = whisper_full_get_segment_text(ctx, i);
  300. std::string speaker = "";
  301. if (params.diarize && pcmf32s.size() == 2)
  302. {
  303. const int64_t t0 = whisper_full_get_segment_t0(ctx, i);
  304. const int64_t t1 = whisper_full_get_segment_t1(ctx, i);
  305. speaker = estimate_diarization_speaker(pcmf32s, t0, t1);
  306. }
  307. fout << speaker << text << "\n";
  308. }
  309. return true;
  310. }
  311. bool output_vtt(struct whisper_context * ctx, const char * fname, const whisper_params & params, std::vector<std::vector<float>> pcmf32s) {
  312. std::ofstream fout(fname);
  313. if (!fout.is_open()) {
  314. fprintf(stderr, "%s: failed to open '%s' for writing\n", __func__, fname);
  315. return false;
  316. }
  317. fprintf(stderr, "%s: saving output to '%s'\n", __func__, fname);
  318. fout << "WEBVTT\n\n";
  319. const int n_segments = whisper_full_n_segments(ctx);
  320. for (int i = 0; i < n_segments; ++i) {
  321. const char * text = whisper_full_get_segment_text(ctx, i);
  322. const int64_t t0 = whisper_full_get_segment_t0(ctx, i);
  323. const int64_t t1 = whisper_full_get_segment_t1(ctx, i);
  324. std::string speaker = "";
  325. if (params.diarize && pcmf32s.size() == 2)
  326. {
  327. speaker = estimate_diarization_speaker(pcmf32s, t0, t1, true);
  328. speaker.insert(0, "<v Speaker");
  329. speaker.append(">");
  330. }
  331. fout << to_timestamp(t0) << " --> " << to_timestamp(t1) << "\n";
  332. fout << speaker << text << "\n\n";
  333. }
  334. return true;
  335. }
  336. bool output_srt(struct whisper_context * ctx, const char * fname, const whisper_params & params, std::vector<std::vector<float>> pcmf32s) {
  337. std::ofstream fout(fname);
  338. if (!fout.is_open()) {
  339. fprintf(stderr, "%s: failed to open '%s' for writing\n", __func__, fname);
  340. return false;
  341. }
  342. fprintf(stderr, "%s: saving output to '%s'\n", __func__, fname);
  343. const int n_segments = whisper_full_n_segments(ctx);
  344. for (int i = 0; i < n_segments; ++i) {
  345. const char * text = whisper_full_get_segment_text(ctx, i);
  346. const int64_t t0 = whisper_full_get_segment_t0(ctx, i);
  347. const int64_t t1 = whisper_full_get_segment_t1(ctx, i);
  348. std::string speaker = "";
  349. if (params.diarize && pcmf32s.size() == 2)
  350. {
  351. speaker = estimate_diarization_speaker(pcmf32s, t0, t1);
  352. }
  353. fout << i + 1 + params.offset_n << "\n";
  354. fout << to_timestamp(t0, true) << " --> " << to_timestamp(t1, true) << "\n";
  355. fout << speaker << text << "\n\n";
  356. }
  357. return true;
  358. }
  359. char *escape_double_quotes_and_backslashes(const char *str) {
  360. if (str == NULL) {
  361. return NULL;
  362. }
  363. size_t escaped_length = strlen(str) + 1;
  364. for (size_t i = 0; str[i] != '\0'; i++) {
  365. if (str[i] == '"' || str[i] == '\\') {
  366. escaped_length++;
  367. }
  368. }
  369. char *escaped = (char *)calloc(escaped_length, 1); // pre-zeroed
  370. if (escaped == NULL) {
  371. return NULL;
  372. }
  373. size_t pos = 0;
  374. for (size_t i = 0; str[i] != '\0'; i++) {
  375. if (str[i] == '"' || str[i] == '\\') {
  376. escaped[pos++] = '\\';
  377. }
  378. escaped[pos++] = str[i];
  379. }
  380. // no need to set zero due to calloc() being used prior
  381. return escaped;
  382. }
  383. bool output_csv(struct whisper_context * ctx, const char * fname, const whisper_params & params, std::vector<std::vector<float>> pcmf32s) {
  384. std::ofstream fout(fname);
  385. if (!fout.is_open()) {
  386. fprintf(stderr, "%s: failed to open '%s' for writing\n", __func__, fname);
  387. return false;
  388. }
  389. fprintf(stderr, "%s: saving output to '%s'\n", __func__, fname);
  390. const int n_segments = whisper_full_n_segments(ctx);
  391. fout << "start,end,";
  392. if (params.diarize && pcmf32s.size() == 2)
  393. {
  394. fout << "speaker,";
  395. }
  396. fout << "text\n";
  397. for (int i = 0; i < n_segments; ++i) {
  398. const char * text = whisper_full_get_segment_text(ctx, i);
  399. const int64_t t0 = whisper_full_get_segment_t0(ctx, i);
  400. const int64_t t1 = whisper_full_get_segment_t1(ctx, i);
  401. char * text_escaped = escape_double_quotes_and_backslashes(text);
  402. //need to multiply times returned from whisper_full_get_segment_t{0,1}() by 10 to get milliseconds.
  403. fout << 10 * t0 << "," << 10 * t1 << ",";
  404. if (params.diarize && pcmf32s.size() == 2)
  405. {
  406. fout << estimate_diarization_speaker(pcmf32s, t0, t1, true) << ",";
  407. }
  408. fout << "\"" << text_escaped << "\"\n";
  409. }
  410. return true;
  411. }
  412. bool output_score(struct whisper_context * ctx, const char * fname, const whisper_params & /*params*/, std::vector<std::vector<float>> /*pcmf32s*/) {
  413. std::ofstream fout(fname);
  414. fprintf(stderr, "%s: saving output to '%s'\n", __func__, fname);
  415. const int n_segments = whisper_full_n_segments(ctx);
  416. // fprintf(stderr,"segments: %d\n",n_segments);
  417. for (int i = 0; i < n_segments; ++i) {
  418. const int n_tokens = whisper_full_n_tokens(ctx, i);
  419. // fprintf(stderr,"tokens: %d\n",n_tokens);
  420. for (int j = 0; j < n_tokens; j++) {
  421. auto token = whisper_full_get_token_text(ctx, i, j);
  422. auto probability = whisper_full_get_token_p(ctx, i, j);
  423. fout << token << '\t' << probability << std::endl;
  424. // fprintf(stderr,"token: %s %f\n",token,probability);
  425. }
  426. }
  427. return true;
  428. }
  429. bool output_json(struct whisper_context * ctx, const char * fname, const whisper_params & params, std::vector<std::vector<float>> pcmf32s) {
  430. std::ofstream fout(fname);
  431. int indent = 0;
  432. auto doindent = [&]() {
  433. for (int i = 0; i < indent; i++) fout << "\t";
  434. };
  435. auto start_arr = [&](const char *name) {
  436. doindent();
  437. fout << "\"" << name << "\": [\n";
  438. indent++;
  439. };
  440. auto end_arr = [&](bool end) {
  441. indent--;
  442. doindent();
  443. fout << (end ? "]\n" : "},\n");
  444. };
  445. auto start_obj = [&](const char *name) {
  446. doindent();
  447. if (name) {
  448. fout << "\"" << name << "\": {\n";
  449. } else {
  450. fout << "{\n";
  451. }
  452. indent++;
  453. };
  454. auto end_obj = [&](bool end) {
  455. indent--;
  456. doindent();
  457. fout << (end ? "}\n" : "},\n");
  458. };
  459. auto start_value = [&](const char *name) {
  460. doindent();
  461. fout << "\"" << name << "\": ";
  462. };
  463. auto value_s = [&](const char *name, const char *val, bool end) {
  464. start_value(name);
  465. char * val_escaped = escape_double_quotes_and_backslashes(val);
  466. fout << "\"" << val_escaped << (end ? "\"\n" : "\",\n");
  467. free(val_escaped);
  468. };
  469. auto end_value = [&](bool end) {
  470. fout << (end ? "\n" : ",\n");
  471. };
  472. auto value_i = [&](const char *name, const int64_t val, bool end) {
  473. start_value(name);
  474. fout << val;
  475. end_value(end);
  476. };
  477. auto value_b = [&](const char *name, const bool val, bool end) {
  478. start_value(name);
  479. fout << (val ? "true" : "false");
  480. end_value(end);
  481. };
  482. if (!fout.is_open()) {
  483. fprintf(stderr, "%s: failed to open '%s' for writing\n", __func__, fname);
  484. return false;
  485. }
  486. fprintf(stderr, "%s: saving output to '%s'\n", __func__, fname);
  487. start_obj(nullptr);
  488. value_s("systeminfo", whisper_print_system_info(), false);
  489. start_obj("model");
  490. value_s("type", whisper_model_type_readable(ctx), false);
  491. value_b("multilingual", whisper_is_multilingual(ctx), false);
  492. value_i("vocab", whisper_model_n_vocab(ctx), false);
  493. start_obj("audio");
  494. value_i("ctx", whisper_model_n_audio_ctx(ctx), false);
  495. value_i("state", whisper_model_n_audio_state(ctx), false);
  496. value_i("head", whisper_model_n_audio_head(ctx), false);
  497. value_i("layer", whisper_model_n_audio_layer(ctx), true);
  498. end_obj(false);
  499. start_obj("text");
  500. value_i("ctx", whisper_model_n_text_ctx(ctx), false);
  501. value_i("state", whisper_model_n_text_state(ctx), false);
  502. value_i("head", whisper_model_n_text_head(ctx), false);
  503. value_i("layer", whisper_model_n_text_layer(ctx), true);
  504. end_obj(false);
  505. value_i("mels", whisper_model_n_mels(ctx), false);
  506. value_i("ftype", whisper_model_ftype(ctx), true);
  507. end_obj(false);
  508. start_obj("params");
  509. value_s("model", params.model.c_str(), false);
  510. value_s("language", params.language.c_str(), false);
  511. value_b("translate", params.translate, true);
  512. end_obj(false);
  513. start_obj("result");
  514. value_s("language", whisper_lang_str(whisper_full_lang_id(ctx)), true);
  515. end_obj(false);
  516. start_arr("transcription");
  517. const int n_segments = whisper_full_n_segments(ctx);
  518. for (int i = 0; i < n_segments; ++i) {
  519. const char * text = whisper_full_get_segment_text(ctx, i);
  520. const int64_t t0 = whisper_full_get_segment_t0(ctx, i);
  521. const int64_t t1 = whisper_full_get_segment_t1(ctx, i);
  522. start_obj(nullptr);
  523. start_obj("timestamps");
  524. value_s("from", to_timestamp(t0, true).c_str(), false);
  525. value_s("to", to_timestamp(t1, true).c_str(), true);
  526. end_obj(false);
  527. start_obj("offsets");
  528. value_i("from", t0 * 10, false);
  529. value_i("to", t1 * 10, true);
  530. end_obj(false);
  531. value_s("text", text, !params.diarize && !params.tinydiarize);
  532. if (params.diarize && pcmf32s.size() == 2) {
  533. value_s("speaker", estimate_diarization_speaker(pcmf32s, t0, t1, true).c_str(), true);
  534. }
  535. if (params.tinydiarize) {
  536. value_b("speaker_turn_next", whisper_full_get_segment_speaker_turn_next(ctx, i), true);
  537. }
  538. end_obj(i == (n_segments - 1));
  539. }
  540. end_arr(true);
  541. end_obj(true);
  542. return true;
  543. }
  544. // karaoke video generation
  545. // outputs a bash script that uses ffmpeg to generate a video with the subtitles
  546. // TODO: font parameter adjustments
  547. bool output_wts(struct whisper_context * ctx, const char * fname, const char * fname_inp, const whisper_params & params, float t_sec, std::vector<std::vector<float>> pcmf32s) {
  548. std::ofstream fout(fname);
  549. fprintf(stderr, "%s: saving output to '%s'\n", __func__, fname);
  550. static const char * font = params.font_path.c_str();
  551. std::ifstream fin(font);
  552. if (!fin.is_open()) {
  553. fprintf(stderr, "%s: font not found at '%s', please specify a monospace font with -fp\n", __func__, font);
  554. return false;
  555. }
  556. fout << "#!/bin/bash" << "\n";
  557. fout << "\n";
  558. fout << "ffmpeg -i " << fname_inp << " -f lavfi -i color=size=1200x120:duration=" << t_sec << ":rate=25:color=black -vf \"";
  559. for (int i = 0; i < whisper_full_n_segments(ctx); i++) {
  560. const int64_t t0 = whisper_full_get_segment_t0(ctx, i);
  561. const int64_t t1 = whisper_full_get_segment_t1(ctx, i);
  562. const int n = whisper_full_n_tokens(ctx, i);
  563. std::vector<whisper_token_data> tokens(n);
  564. for (int j = 0; j < n; ++j) {
  565. tokens[j] = whisper_full_get_token_data(ctx, i, j);
  566. }
  567. if (i > 0) {
  568. fout << ",";
  569. }
  570. // background text
  571. fout << "drawtext=fontfile='" << font << "':fontsize=24:fontcolor=gray:x=(w-text_w)/2:y=h/2:text='':enable='between(t," << t0/100.0 << "," << t0/100.0 << ")'";
  572. bool is_first = true;
  573. std::string speaker = "";
  574. if (params.diarize && pcmf32s.size() == 2) {
  575. speaker = estimate_diarization_speaker(pcmf32s, t0, t1);
  576. }
  577. for (int j = 0; j < n; ++j) {
  578. const auto & token = tokens[j];
  579. if (tokens[j].id >= whisper_token_eot(ctx)) {
  580. continue;
  581. }
  582. std::string txt_bg = "";
  583. std::string txt_fg = ""; // highlight token
  584. std::string txt_ul = ""; // underline
  585. if (params.diarize && pcmf32s.size() == 2) {
  586. txt_bg = speaker;
  587. txt_fg = speaker;
  588. txt_ul = "\\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ ";
  589. }
  590. txt_bg.append("> ");
  591. txt_fg.append("> ");
  592. txt_ul.append("\\ \\ ");
  593. {
  594. for (int k = 0; k < n; ++k) {
  595. const auto & token2 = tokens[k];
  596. if (tokens[k].id >= whisper_token_eot(ctx)) {
  597. continue;
  598. }
  599. const std::string txt = whisper_token_to_str(ctx, token2.id);
  600. txt_bg += txt;
  601. if (k == j) {
  602. for (int l = 0; l < (int) txt.size(); ++l) {
  603. txt_fg += txt[l];
  604. txt_ul += "_";
  605. }
  606. txt_fg += "|";
  607. } else {
  608. for (int l = 0; l < (int) txt.size(); ++l) {
  609. txt_fg += "\\ ";
  610. txt_ul += "\\ ";
  611. }
  612. }
  613. }
  614. ::replace_all(txt_bg, "'", "\u2019");
  615. ::replace_all(txt_bg, "\"", "\\\"");
  616. ::replace_all(txt_fg, "'", "\u2019");
  617. ::replace_all(txt_fg, "\"", "\\\"");
  618. }
  619. if (is_first) {
  620. // background text
  621. fout << ",drawtext=fontfile='" << font << "':fontsize=24:fontcolor=gray:x=(w-text_w)/2:y=h/2:text='" << txt_bg << "':enable='between(t," << t0/100.0 << "," << t1/100.0 << ")'";
  622. is_first = false;
  623. }
  624. // foreground text
  625. fout << ",drawtext=fontfile='" << font << "':fontsize=24:fontcolor=lightgreen:x=(w-text_w)/2+8:y=h/2:text='" << txt_fg << "':enable='between(t," << token.t0/100.0 << "," << token.t1/100.0 << ")'";
  626. // underline
  627. fout << ",drawtext=fontfile='" << font << "':fontsize=24:fontcolor=lightgreen:x=(w-text_w)/2+8:y=h/2+16:text='" << txt_ul << "':enable='between(t," << token.t0/100.0 << "," << token.t1/100.0 << ")'";
  628. }
  629. }
  630. fout << "\" -c:v libx264 -pix_fmt yuv420p -y " << fname_inp << ".mp4" << "\n";
  631. fout << "\n\n";
  632. fout << "echo \"Your video has been saved to " << fname_inp << ".mp4\"" << "\n";
  633. fout << "\n";
  634. fout << "echo \" ffplay " << fname_inp << ".mp4\"\n";
  635. fout << "\n";
  636. fout.close();
  637. fprintf(stderr, "%s: run 'source %s' to generate karaoke video\n", __func__, fname);
  638. return true;
  639. }
  640. bool output_lrc(struct whisper_context * ctx, const char * fname, const whisper_params & params, std::vector<std::vector<float>> pcmf32s) {
  641. std::ofstream fout(fname);
  642. if (!fout.is_open()) {
  643. fprintf(stderr, "%s: failed to open '%s' for writing\n", __func__, fname);
  644. return false;
  645. }
  646. fprintf(stderr, "%s: saving output to '%s'\n", __func__, fname);
  647. fout << "[by:whisper.cpp]\n";
  648. const int n_segments = whisper_full_n_segments(ctx);
  649. for (int i = 0; i < n_segments; ++i) {
  650. const char * text = whisper_full_get_segment_text(ctx, i);
  651. const int64_t t = whisper_full_get_segment_t0(ctx, i);
  652. int64_t msec = t * 10;
  653. int64_t min = msec / (1000 * 60);
  654. msec = msec - min * (1000 * 60);
  655. int64_t sec = msec / 1000;
  656. msec = msec - sec * 1000;
  657. char buf[16];
  658. snprintf(buf, sizeof(buf), "%02d:%02d.%02d", (int) min, (int) sec, (int) ( msec / 10));
  659. std::string timestamp_lrc = std::string(buf);
  660. std::string speaker = "";
  661. if (params.diarize && pcmf32s.size() == 2)
  662. {
  663. const int64_t t0 = whisper_full_get_segment_t0(ctx, i);
  664. const int64_t t1 = whisper_full_get_segment_t1(ctx, i);
  665. speaker = estimate_diarization_speaker(pcmf32s, t0, t1);
  666. }
  667. fout << '[' << timestamp_lrc << ']' << speaker << text << "\n";
  668. }
  669. return true;
  670. }
  671. int main(int argc, char ** argv) {
  672. whisper_params params;
  673. if (whisper_params_parse(argc, argv, params) == false) {
  674. whisper_print_usage(argc, argv, params);
  675. return 1;
  676. }
  677. if (params.fname_inp.empty()) {
  678. fprintf(stderr, "error: no input files specified\n");
  679. whisper_print_usage(argc, argv, params);
  680. return 2;
  681. }
  682. if (params.language != "auto" && whisper_lang_id(params.language.c_str()) == -1) {
  683. fprintf(stderr, "error: unknown language '%s'\n", params.language.c_str());
  684. whisper_print_usage(argc, argv, params);
  685. exit(0);
  686. }
  687. if (params.diarize && params.tinydiarize) {
  688. fprintf(stderr, "error: cannot use both --diarize and --tinydiarize\n");
  689. whisper_print_usage(argc, argv, params);
  690. exit(0);
  691. }
  692. // whisper init
  693. struct whisper_context * ctx = whisper_init_from_file(params.model.c_str());
  694. if (ctx == nullptr) {
  695. fprintf(stderr, "error: failed to initialize whisper context\n");
  696. return 3;
  697. }
  698. // initialize openvino encoder. this has no effect on whisper.cpp builds that don't have OpenVINO configured
  699. whisper_ctx_init_openvino_encoder(ctx, nullptr, params.openvino_encode_device.c_str(), nullptr);
  700. for (int f = 0; f < (int) params.fname_inp.size(); ++f) {
  701. const auto fname_inp = params.fname_inp[f];
  702. const auto fname_out = f < (int) params.fname_out.size() && !params.fname_out[f].empty() ? params.fname_out[f] : params.fname_inp[f];
  703. std::vector<float> pcmf32; // mono-channel F32 PCM
  704. std::vector<std::vector<float>> pcmf32s; // stereo-channel F32 PCM
  705. if (!::read_wav(fname_inp, pcmf32, pcmf32s, params.diarize)) {
  706. fprintf(stderr, "error: failed to read WAV file '%s'\n", fname_inp.c_str());
  707. continue;
  708. }
  709. // print system information
  710. {
  711. fprintf(stderr, "\n");
  712. fprintf(stderr, "system_info: n_threads = %d / %d | %s\n",
  713. params.n_threads*params.n_processors, std::thread::hardware_concurrency(), whisper_print_system_info());
  714. }
  715. // print some info about the processing
  716. {
  717. fprintf(stderr, "\n");
  718. if (!whisper_is_multilingual(ctx)) {
  719. if (params.language != "en" || params.translate) {
  720. params.language = "en";
  721. params.translate = false;
  722. fprintf(stderr, "%s: WARNING: model is not multilingual, ignoring language and translation options\n", __func__);
  723. }
  724. }
  725. if (params.detect_language) {
  726. params.language = "auto";
  727. }
  728. fprintf(stderr, "%s: processing '%s' (%d samples, %.1f sec), %d threads, %d processors, lang = %s, task = %s, %stimestamps = %d ...\n",
  729. __func__, fname_inp.c_str(), int(pcmf32.size()), float(pcmf32.size())/WHISPER_SAMPLE_RATE,
  730. params.n_threads, params.n_processors,
  731. params.language.c_str(),
  732. params.translate ? "translate" : "transcribe",
  733. params.tinydiarize ? "tdrz = 1, " : "",
  734. params.no_timestamps ? 0 : 1);
  735. fprintf(stderr, "\n");
  736. }
  737. // run the inference
  738. {
  739. whisper_full_params wparams = whisper_full_default_params(WHISPER_SAMPLING_GREEDY);
  740. wparams.strategy = params.beam_size > 1 ? WHISPER_SAMPLING_BEAM_SEARCH : WHISPER_SAMPLING_GREEDY;
  741. wparams.print_realtime = false;
  742. wparams.print_progress = params.print_progress;
  743. wparams.print_timestamps = !params.no_timestamps;
  744. wparams.print_special = params.print_special;
  745. wparams.translate = params.translate;
  746. wparams.language = params.language.c_str();
  747. wparams.detect_language = params.detect_language;
  748. wparams.n_threads = params.n_threads;
  749. wparams.n_max_text_ctx = params.max_context >= 0 ? params.max_context : wparams.n_max_text_ctx;
  750. wparams.offset_ms = params.offset_t_ms;
  751. wparams.duration_ms = params.duration_ms;
  752. wparams.token_timestamps = params.output_wts || params.max_len > 0;
  753. wparams.thold_pt = params.word_thold;
  754. wparams.max_len = params.output_wts && params.max_len == 0 ? 60 : params.max_len;
  755. wparams.split_on_word = params.split_on_word;
  756. wparams.speed_up = params.speed_up;
  757. wparams.debug_mode = params.debug_mode;
  758. wparams.tdrz_enable = params.tinydiarize; // [TDRZ]
  759. wparams.initial_prompt = params.prompt.c_str();
  760. wparams.greedy.best_of = params.best_of;
  761. wparams.beam_search.beam_size = params.beam_size;
  762. wparams.temperature_inc = params.no_fallback ? 0.0f : wparams.temperature_inc;
  763. wparams.entropy_thold = params.entropy_thold;
  764. wparams.logprob_thold = params.logprob_thold;
  765. whisper_print_user_data user_data = { &params, &pcmf32s, 0 };
  766. // this callback is called on each new segment
  767. if (!wparams.print_realtime) {
  768. wparams.new_segment_callback = whisper_print_segment_callback;
  769. wparams.new_segment_callback_user_data = &user_data;
  770. }
  771. if (wparams.print_progress) {
  772. wparams.progress_callback = whisper_print_progress_callback;
  773. wparams.progress_callback_user_data = &user_data;
  774. }
  775. // example for abort mechanism
  776. // in this example, we do not abort the processing, but we could if the flag is set to true
  777. // the callback is called before every encoder run - if it returns false, the processing is aborted
  778. {
  779. static bool is_aborted = false; // NOTE: this should be atomic to avoid data race
  780. wparams.encoder_begin_callback = [](struct whisper_context * /*ctx*/, struct whisper_state * /*state*/, void * user_data) {
  781. bool is_aborted = *(bool*)user_data;
  782. return !is_aborted;
  783. };
  784. wparams.encoder_begin_callback_user_data = &is_aborted;
  785. }
  786. if (whisper_full_parallel(ctx, wparams, pcmf32.data(), pcmf32.size(), params.n_processors) != 0) {
  787. fprintf(stderr, "%s: failed to process audio\n", argv[0]);
  788. return 10;
  789. }
  790. }
  791. // output stuff
  792. {
  793. printf("\n");
  794. // output to text file
  795. if (params.output_txt) {
  796. const auto fname_txt = fname_out + ".txt";
  797. output_txt(ctx, fname_txt.c_str(), params, pcmf32s);
  798. }
  799. // output to VTT file
  800. if (params.output_vtt) {
  801. const auto fname_vtt = fname_out + ".vtt";
  802. output_vtt(ctx, fname_vtt.c_str(), params, pcmf32s);
  803. }
  804. // output to SRT file
  805. if (params.output_srt) {
  806. const auto fname_srt = fname_out + ".srt";
  807. output_srt(ctx, fname_srt.c_str(), params, pcmf32s);
  808. }
  809. // output to WTS file
  810. if (params.output_wts) {
  811. const auto fname_wts = fname_out + ".wts";
  812. output_wts(ctx, fname_wts.c_str(), fname_inp.c_str(), params, float(pcmf32.size() + 1000)/WHISPER_SAMPLE_RATE, pcmf32s);
  813. }
  814. // output to CSV file
  815. if (params.output_csv) {
  816. const auto fname_csv = fname_out + ".csv";
  817. output_csv(ctx, fname_csv.c_str(), params, pcmf32s);
  818. }
  819. // output to JSON file
  820. if (params.output_jsn) {
  821. const auto fname_jsn = fname_out + ".json";
  822. output_json(ctx, fname_jsn.c_str(), params, pcmf32s);
  823. }
  824. // output to LRC file
  825. if (params.output_lrc) {
  826. const auto fname_lrc = fname_out + ".lrc";
  827. output_lrc(ctx, fname_lrc.c_str(), params, pcmf32s);
  828. }
  829. // output to score file
  830. if (params.log_score) {
  831. const auto fname_score = fname_out + ".score.txt";
  832. output_score(ctx, fname_score.c_str(), params, pcmf32s);
  833. }
  834. }
  835. }
  836. whisper_print_timings(ctx);
  837. whisper_free(ctx);
  838. return 0;
  839. }