calebnwokocha commited on
Commit
6ff554c
·
1 Parent(s): 549deb7

Delete common.cpp

Browse files
Files changed (1) hide show
  1. common.cpp +0 -911
common.cpp DELETED
@@ -1,911 +0,0 @@
1
- #define _USE_MATH_DEFINES // for M_PI
2
-
3
- #include "common.h"
4
-
5
- // third-party utilities
6
- // use your favorite implementations
7
- #define DR_WAV_IMPLEMENTATION
8
- #include "dr_wav.h"
9
-
10
- #include <cmath>
11
- #include <cstring>
12
- #include <fstream>
13
- #include <regex>
14
- #include <locale>
15
- #include <codecvt>
16
- #include <sstream>
17
-
18
- #if defined(_MSC_VER)
19
- #pragma warning(disable: 4244 4267) // possible loss of data
20
- #endif
21
-
22
- #ifdef _WIN32
23
- #include <fcntl.h>
24
- #include <io.h>
25
- #endif
26
-
27
- #ifdef WHISPER_FFMPEG
28
- // as implemented in ffmpeg_trancode.cpp only embedded in common lib if whisper built with ffmpeg support
29
- extern bool ffmpeg_decode_audio(const std::string & ifname, std::vector<uint8_t> & wav_data);
30
- #endif
31
-
32
- // Function to check if the next argument exists
33
- static std::string get_next_arg(int& i, int argc, char** argv, const std::string& flag, gpt_params& params) {
34
- if (i + 1 < argc && argv[i + 1][0] != '-') {
35
- return argv[++i];
36
- } else {
37
- fprintf(stderr, "error: %s requires one argument.\n", flag.c_str());
38
- gpt_print_usage(argc, argv, params);
39
- exit(0);
40
- }
41
- }
42
-
43
- bool gpt_params_parse(int argc, char ** argv, gpt_params & params) {
44
- for (int i = 1; i < argc; i++) {
45
- std::string arg = argv[i];
46
-
47
- if (arg == "-s" || arg == "--seed") {
48
- params.seed = std::stoi(get_next_arg(i, argc, argv, arg, params));
49
- } else if (arg == "-t" || arg == "--threads") {
50
- params.n_threads = std::stoi(get_next_arg(i, argc, argv, arg, params));
51
- } else if (arg == "-p" || arg == "--prompt") {
52
- params.prompt = get_next_arg(i, argc, argv, arg, params);
53
- } else if (arg == "-n" || arg == "--n_predict") {
54
- params.n_predict = std::stoi(get_next_arg(i, argc, argv, arg, params));
55
- } else if (arg == "-np" || arg == "--n_parallel") {
56
- params.n_parallel = std::stoi(get_next_arg(i, argc, argv, arg, params));
57
- } else if (arg == "--top_k") {
58
- params.top_k = std::stoi(get_next_arg(i, argc, argv, arg, params));
59
- } else if (arg == "--top_p") {
60
- params.top_p = std::stof(get_next_arg(i, argc, argv, arg, params));
61
- } else if (arg == "--temp") {
62
- params.temp = std::stof(get_next_arg(i, argc, argv, arg, params));
63
- } else if (arg == "--repeat-last-n") {
64
- params.repeat_last_n = std::stoi(get_next_arg(i, argc, argv, arg, params));
65
- } else if (arg == "--repeat-penalty") {
66
- params.repeat_penalty = std::stof(get_next_arg(i, argc, argv, arg, params));
67
- } else if (arg == "-b" || arg == "--batch_size") {
68
- params.n_batch= std::stoi(get_next_arg(i, argc, argv, arg, params));
69
- } else if (arg == "-c" || arg == "--context") {
70
- params.n_ctx= std::stoi(get_next_arg(i, argc, argv, arg, params));
71
- } else if (arg == "-ngl" || arg == "--gpu-layers" || arg == "--n-gpu-layers") {
72
- params.n_gpu_layers = std::stoi(get_next_arg(i, argc, argv, arg, params));
73
- } else if (arg == "--ignore-eos") {
74
- params.ignore_eos = true;
75
- } else if (arg == "-m" || arg == "--model") {
76
- params.model = get_next_arg(i, argc, argv, arg, params);
77
- } else if (arg == "-i" || arg == "--interactive") {
78
- params.interactive = true;
79
- } else if (arg == "-ip" || arg == "--interactive-port") {
80
- params.interactive = true;
81
- params.interactive_port = std::stoi(get_next_arg(i, argc, argv, arg, params));
82
- } else if (arg == "-h" || arg == "--help") {
83
- gpt_print_usage(argc, argv, params);
84
- exit(0);
85
- } else if (arg == "-f" || arg == "--file") {
86
- get_next_arg(i, argc, argv, arg, params);
87
- std::ifstream file(argv[i]);
88
- if (!file) {
89
- fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
90
- break;
91
- }
92
- std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), back_inserter(params.prompt));
93
- if (params.prompt.back() == '\n') {
94
- params.prompt.pop_back();
95
- }
96
- } else if (arg == "-tt" || arg == "--token_test") {
97
- params.token_test = get_next_arg(i, argc, argv, arg, params);
98
- }
99
- else {
100
- fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
101
- gpt_print_usage(argc, argv, params);
102
- exit(0);
103
- }
104
- }
105
-
106
- return true;
107
- }
108
-
109
- void gpt_print_usage(int /*argc*/, char ** argv, const gpt_params & params) {
110
- fprintf(stderr, "usage: %s [options]\n", argv[0]);
111
- fprintf(stderr, "\n");
112
- fprintf(stderr, "options:\n");
113
- fprintf(stderr, " -h, --help show this help message and exit\n");
114
- fprintf(stderr, " -s SEED, --seed SEED RNG seed (default: -1)\n");
115
- fprintf(stderr, " -t N, --threads N number of threads to use during computation (default: %d)\n", params.n_threads);
116
- fprintf(stderr, " -p PROMPT, --prompt PROMPT\n");
117
- fprintf(stderr, " prompt to start generation with (default: random)\n");
118
- fprintf(stderr, " -f FNAME, --file FNAME\n");
119
- fprintf(stderr, " load prompt from a file\n");
120
- fprintf(stderr, " -tt TOKEN_TEST, --token_test TOKEN_TEST\n");
121
- fprintf(stderr, " test tokenization\n");
122
- fprintf(stderr, " -n N, --n_predict N number of tokens to predict (default: %d)\n", params.n_predict);
123
- fprintf(stderr, " --top_k N top-k sampling (default: %d)\n", params.top_k);
124
- fprintf(stderr, " --top_p N top-p sampling (default: %.1f)\n", params.top_p);
125
- fprintf(stderr, " --temp N temperature (default: %.1f)\n", params.temp);
126
- fprintf(stderr, " --repeat-last-n N last n tokens to consider for penalize (default: %d, 0 = disabled)\n", params.repeat_last_n);
127
- fprintf(stderr, " --repeat-penalty N penalize repeat sequence of tokens (default: %.2f, 1.0 = disabled)\n", (double)params.repeat_penalty);
128
- fprintf(stderr, " -b N, --batch_size N batch size for prompt processing (default: %d)\n", params.n_batch);
129
- fprintf(stderr, " -c N, --context N context / KV cache size (default: %d)\n", params.n_ctx);
130
- fprintf(stderr, " --ignore-eos ignore EOS token during generation\n");
131
- fprintf(stderr, " -ngl N, --gpu-layers N number of layers to offload to GPU on supported models (default: %d)\n", params.n_gpu_layers);
132
- fprintf(stderr, " -m FNAME, --model FNAME\n");
133
- fprintf(stderr, " model path (default: %s)\n", params.model.c_str());
134
- fprintf(stderr, "\n");
135
- }
136
-
137
- std::string gpt_random_prompt(std::mt19937 & rng) {
138
- const int r = rng() % 10;
139
- switch (r) {
140
- case 0: return "So";
141
- case 1: return "Once upon a time";
142
- case 2: return "When";
143
- case 3: return "The";
144
- case 4: return "After";
145
- case 5: return "If";
146
- case 6: return "import";
147
- case 7: return "He";
148
- case 8: return "She";
149
- case 9: return "They";
150
- }
151
-
152
- return "The";
153
- }
154
-
155
- std::string trim(const std::string & s) {
156
- std::regex e("^\\s+|\\s+$");
157
- return std::regex_replace(s, e, "");
158
- }
159
-
160
- std::string replace(const std::string & s, const std::string & from, const std::string & to) {
161
- std::string result = s;
162
- size_t pos = 0;
163
- while ((pos = result.find(from, pos)) != std::string::npos) {
164
- result.replace(pos, from.length(), to);
165
- pos += to.length();
166
- }
167
- return result;
168
- }
169
-
170
- void gpt_vocab::add_special_token(const std::string & token) {
171
- special_tokens.push_back(token);
172
- }
173
-
174
- std::map<std::string, int32_t> json_parse(const std::string & fname) {
175
- std::map<std::string, int32_t> result;
176
-
177
- // read file into string
178
- std::string json;
179
- {
180
- std::ifstream ifs(fname);
181
- if (!ifs) {
182
- fprintf(stderr, "Failed to open %s\n", fname.c_str());
183
- exit(1);
184
- }
185
-
186
- json = std::string((std::istreambuf_iterator<char>(ifs)),
187
- (std::istreambuf_iterator<char>()));
188
- }
189
-
190
- if (json[0] != '{') {
191
- return result;
192
- }
193
-
194
- // parse json
195
- {
196
- bool has_key = false;
197
- bool in_token = false;
198
-
199
- std::string str_key = "";
200
- std::string str_val = "";
201
-
202
- int n = json.size();
203
- for (int i = 1; i < n; ++i) {
204
- if (!in_token) {
205
- if (json[i] == ' ') continue;
206
- if (json[i] == '"') {
207
- in_token = true;
208
- continue;
209
- }
210
- } else {
211
- if (json[i] == '\\' && i+1 < n) {
212
- if (has_key == false) {
213
- str_key += json[i];
214
- } else {
215
- str_val += json[i];
216
- }
217
- ++i;
218
- } else if (json[i] == '"') {
219
- if (has_key == false) {
220
- has_key = true;
221
- ++i;
222
- while (json[i] == ' ') ++i;
223
- ++i; // :
224
- while (json[i] == ' ') ++i;
225
- if (json[i] != '\"') {
226
- while (json[i] != ',' && json[i] != '}') {
227
- str_val += json[i++];
228
- }
229
- has_key = false;
230
- } else {
231
- in_token = true;
232
- continue;
233
- }
234
- } else {
235
- has_key = false;
236
- }
237
-
238
- str_key = ::replace(str_key, "\\u0120", " " ); // \u0120 -> space
239
- str_key = ::replace(str_key, "\\u010a", "\n"); // \u010a -> new line
240
- str_key = ::replace(str_key, "\\\"", "\""); // \\\" -> "
241
-
242
- try {
243
- result[str_key] = std::stoi(str_val);
244
- } catch (...) {
245
- //fprintf(stderr, "%s: ignoring key '%s' with value '%s'\n", fname.c_str(), str_key.c_str(), str_val.c_str());
246
-
247
- }
248
- str_key = "";
249
- str_val = "";
250
- in_token = false;
251
- continue;
252
- }
253
- if (has_key == false) {
254
- str_key += json[i];
255
- } else {
256
- str_val += json[i];
257
- }
258
- }
259
- }
260
- }
261
-
262
- return result;
263
- }
264
-
265
- std::string convert_to_utf8(const std::wstring & input) {
266
- std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
267
- return converter.to_bytes(input);
268
- }
269
-
270
-
271
- std::wstring convert_to_wstring(const std::string & input) {
272
- std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
273
- return converter.from_bytes(input);
274
- }
275
-
276
- void gpt_split_words(std::string str, std::vector<std::string>& words) {
277
- const std::string pattern = R"('s|'t|'re|'ve|'m|'ll|'d| ?[[:alpha:]]+| ?[[:digit:]]+| ?[^\s[:alpha:][:digit:]]+|\s+(?!\S)|\s+)";
278
- const std::regex re(pattern);
279
- std::smatch m;
280
-
281
- while (std::regex_search(str, m, re)) {
282
- for (auto x : m) {
283
- words.push_back(x);
284
- }
285
- str = m.suffix();
286
- }
287
- }
288
-
289
- std::vector<gpt_vocab::id> gpt_tokenize(const gpt_vocab & vocab, const std::string & text) {
290
- std::vector<std::string> words;
291
-
292
- // first split the text into words
293
- {
294
- std::string str = text;
295
-
296
- // Generate the subpattern from the special_tokens vector if it's not empty
297
- if (!vocab.special_tokens.empty()) {
298
- const std::regex escape(R"([\[\\\^\$\.\|\?\*\+\(\)\{\}])");
299
- std::string special_tokens_subpattern;
300
- for (const auto & token : vocab.special_tokens) {
301
- if (!special_tokens_subpattern.empty()) {
302
- special_tokens_subpattern += "|";
303
- }
304
- special_tokens_subpattern += std::regex_replace(token, escape, R"(\$&)");
305
- }
306
-
307
- std::regex re(special_tokens_subpattern);
308
- std::smatch m;
309
- // Split the text by special tokens.
310
- while (std::regex_search(str, m, re)) {
311
- // Split the substrings in-between special tokens into words.
312
- gpt_split_words(m.prefix(), words);
313
- // Add matched special tokens as words.
314
- for (auto x : m) {
315
- words.push_back(x);
316
- }
317
- str = m.suffix();
318
- }
319
- // Remaining text without special tokens will be handled below.
320
- }
321
-
322
- gpt_split_words(str, words);
323
- }
324
-
325
- // find the longest token that forms each word in words:
326
- std::vector<gpt_vocab::id> tokens;
327
- for (const auto & word : words) {
328
- for (int i = 0; i < (int) word.size(); ){
329
- for (int j = word.size() - 1; j >= i; j--){
330
- auto cand = word.substr(i, j-i+1);
331
- auto it = vocab.token_to_id.find(cand);
332
- if (it != vocab.token_to_id.end()){ // word.substr(i, j-i+1) in vocab
333
- tokens.push_back(it->second);
334
- i = j + 1;
335
- break;
336
- }
337
- else if (j == i){ // word.substr(i, 1) has no matching
338
- fprintf(stderr, "%s: unknown token '%s'\n", __func__, word.substr(i, 1).data());
339
- i++;
340
- }
341
- }
342
- }
343
- }
344
-
345
- return tokens;
346
- }
347
-
348
- static std::vector<gpt_vocab::id> parse_tokens_from_string(const std::string& input, char delimiter) {
349
- std::vector<gpt_vocab::id> output;
350
- std::stringstream ss(input);
351
- std::string token;
352
-
353
- while (std::getline(ss, token, delimiter)) {
354
- output.push_back(std::stoi(token));
355
- }
356
-
357
- return output;
358
- }
359
-
360
- static std::map<std::string, std::vector<gpt_vocab::id>> extract_tests_from_file(const std::string & fpath_test){
361
- if (fpath_test.empty()){
362
- fprintf(stderr, "%s : No test file found.\n", __func__);
363
- return std::map<std::string, std::vector<gpt_vocab::id>>();
364
- }
365
-
366
- std::map<std::string, std::vector<gpt_vocab::id>> tests;
367
-
368
- auto fin = std::ifstream(fpath_test, std::ios_base::in);
369
- const char * delimeter = " => ";
370
- const char del_tok = ',';
371
- std::string line;
372
- while (std::getline(fin, line)) {
373
- size_t delimiterPos = line.find(delimeter);
374
- if (delimiterPos != std::string::npos) {
375
- std::string text = line.substr(0, delimiterPos);
376
- std::string s_tokens = line.substr(delimiterPos + std::strlen(delimeter));
377
- tests[text] = parse_tokens_from_string(s_tokens, del_tok);
378
- }
379
- }
380
- return tests;
381
- }
382
-
383
- void test_gpt_tokenizer(gpt_vocab & vocab, const std::string & fpath_test){
384
- std::map<std::string, std::vector<gpt_vocab::id>> tests = extract_tests_from_file(fpath_test);
385
-
386
- size_t n_fails = 0;
387
-
388
- for (const auto & test : tests) {
389
- std::vector<gpt_vocab::id> tokens = gpt_tokenize(vocab, test.first);
390
-
391
- if (tokens != test.second){
392
- n_fails++;
393
-
394
- // print out failure cases
395
- fprintf(stderr, "%s : failed test: '%s'\n", __func__, test.first.c_str());
396
- fprintf(stderr, "%s : tokens in hf: ", __func__);
397
- for (const auto & t : test.second) {
398
- fprintf(stderr, "%s(%d), ", vocab.id_to_token[t].c_str(), t);
399
- }
400
- fprintf(stderr, "\n");
401
- fprintf(stderr, "%s : tokens in ggml: ", __func__);
402
- for (const auto & t : tokens) {
403
- fprintf(stderr, "%s(%d), ", vocab.id_to_token[t].c_str(), t);
404
- }
405
- fprintf(stderr, "\n");
406
- }
407
- }
408
-
409
- fprintf(stderr, "%s : %zu tests failed out of %zu tests.\n", __func__, n_fails, tests.size());
410
- }
411
-
412
- bool gpt_vocab_init(const std::string & fname, gpt_vocab & vocab) {
413
- printf("%s: loading vocab from '%s'\n", __func__, fname.c_str());
414
-
415
- vocab.token_to_id = ::json_parse(fname);
416
-
417
- for (const auto & kv : vocab.token_to_id) {
418
- vocab.id_to_token[kv.second] = kv.first;
419
- }
420
-
421
- printf("%s: vocab size = %d\n", __func__, (int) vocab.token_to_id.size());
422
-
423
- // print the vocabulary
424
- //for (auto kv : vocab.token_to_id) {
425
- // printf("'%s' -> %d\n", kv.first.data(), kv.second);
426
- //}
427
-
428
- return true;
429
- }
430
-
431
- gpt_vocab::id gpt_sample_top_k_top_p(
432
- const gpt_vocab & vocab,
433
- const float * logits,
434
- int top_k,
435
- double top_p,
436
- double temp,
437
- std::mt19937 & rng) {
438
- int n_logits = vocab.id_to_token.size();
439
-
440
- std::vector<std::pair<double, gpt_vocab::id>> logits_id;
441
- logits_id.reserve(n_logits);
442
-
443
- {
444
- const double scale = 1.0/temp;
445
- for (int i = 0; i < n_logits; ++i) {
446
- logits_id.push_back(std::make_pair(logits[i]*scale, i));
447
- }
448
- }
449
-
450
- // find the top K tokens
451
- std::partial_sort(
452
- logits_id.begin(),
453
- logits_id.begin() + top_k, logits_id.end(),
454
- [](const std::pair<double, gpt_vocab::id> & a, const std::pair<double, gpt_vocab::id> & b) {
455
- return a.first > b.first;
456
- });
457
-
458
- logits_id.resize(top_k);
459
-
460
- double maxl = -INFINITY;
461
- for (const auto & kv : logits_id) {
462
- maxl = std::max(maxl, kv.first);
463
- }
464
-
465
- // compute probs for the top K tokens
466
- std::vector<double> probs;
467
- probs.reserve(logits_id.size());
468
-
469
- double sum = 0.0;
470
- for (const auto & kv : logits_id) {
471
- double p = exp(kv.first - maxl);
472
- probs.push_back(p);
473
- sum += p;
474
- }
475
-
476
- // normalize the probs
477
- for (auto & p : probs) {
478
- p /= sum;
479
- }
480
-
481
- if (top_p < 1.0f) {
482
- double cumsum = 0.0f;
483
- for (int i = 0; i < top_k; i++) {
484
- cumsum += probs[i];
485
- if (cumsum >= top_p) {
486
- top_k = i + 1;
487
- probs.resize(top_k);
488
- logits_id.resize(top_k);
489
- break;
490
- }
491
- }
492
-
493
- cumsum = 1.0/cumsum;
494
- for (int i = 0; i < (int) probs.size(); i++) {
495
- probs[i] *= cumsum;
496
- }
497
- }
498
-
499
- //printf("\n");
500
- //for (int i = 0; i < (int) probs.size(); i++) {
501
- // printf("%d: '%s' %f\n", i, vocab.id_to_token.at(logits_id[i].second).c_str(), probs[i]);
502
- //}
503
- //exit(0);
504
-
505
- std::discrete_distribution<> dist(probs.begin(), probs.end());
506
- int idx = dist(rng);
507
-
508
- return logits_id[idx].second;
509
- }
510
-
511
- gpt_vocab::id gpt_sample_top_k_top_p_repeat(
512
- const gpt_vocab & vocab,
513
- const float * logits,
514
- const int32_t * last_n_tokens_data,
515
- size_t last_n_tokens_data_size,
516
- int top_k,
517
- double top_p,
518
- double temp,
519
- int repeat_last_n,
520
- float repeat_penalty,
521
- std::mt19937 & rng) {
522
-
523
- int n_logits = vocab.id_to_token.size();
524
-
525
- const auto * plogits = logits;
526
-
527
- const auto last_n_tokens = std::vector<int32_t>(last_n_tokens_data, last_n_tokens_data + last_n_tokens_data_size);
528
-
529
- if (temp <= 0) {
530
- // select the token with the highest logit directly
531
- float max_logit = plogits[0];
532
- gpt_vocab::id max_id = 0;
533
-
534
- for (int i = 1; i < n_logits; ++i) {
535
- if (plogits[i] > max_logit) {
536
- max_logit = plogits[i];
537
- max_id = i;
538
- }
539
- }
540
- return max_id;
541
- }
542
-
543
-
544
- std::vector<std::pair<double, gpt_vocab::id>> logits_id;
545
- logits_id.reserve(n_logits);
546
-
547
- {
548
- const float scale = 1.0f/temp;
549
- for (int i = 0; i < n_logits; ++i) {
550
- // repetition penalty from ctrl paper (https://arxiv.org/abs/1909.05858)
551
- // credit https://github.com/facebookresearch/llama/compare/main...shawwn:llama:main
552
- if (repeat_last_n > 0 && std::find(last_n_tokens.end()-repeat_last_n, last_n_tokens.end(), i) != last_n_tokens.end()) {
553
- // if score < 0 then repetition penalty has to multiplied to reduce the previous token probability
554
- if (plogits[i] < 0.0f) {
555
- logits_id.push_back(std::make_pair(plogits[i]*scale*repeat_penalty, i));
556
- } else {
557
- logits_id.push_back(std::make_pair(plogits[i]*scale/repeat_penalty, i));
558
- }
559
- } else {
560
- logits_id.push_back(std::make_pair(plogits[i]*scale, i));
561
- }
562
- }
563
- }
564
-
565
- // find the top K tokens
566
- std::partial_sort(
567
- logits_id.begin(),
568
- logits_id.begin() + top_k, logits_id.end(),
569
- [](const std::pair<double, gpt_vocab::id> & a, const std::pair<double, gpt_vocab::id> & b) {
570
- return a.first > b.first;
571
- });
572
-
573
- logits_id.resize(top_k);
574
-
575
- double maxl = -INFINITY;
576
- for (const auto & kv : logits_id) {
577
- maxl = std::max(maxl, kv.first);
578
- }
579
-
580
- // compute probs for the top K tokens
581
- std::vector<double> probs;
582
- probs.reserve(logits_id.size());
583
-
584
- double sum = 0.0;
585
- for (const auto & kv : logits_id) {
586
- double p = exp(kv.first - maxl);
587
- probs.push_back(p);
588
- sum += p;
589
- }
590
-
591
- // normalize the probs
592
- for (auto & p : probs) {
593
- p /= sum;
594
- }
595
-
596
- if (top_p < 1.0f) {
597
- double cumsum = 0.0f;
598
- for (int i = 0; i < top_k; i++) {
599
- cumsum += probs[i];
600
- if (cumsum >= top_p) {
601
- top_k = i + 1;
602
- probs.resize(top_k);
603
- logits_id.resize(top_k);
604
- break;
605
- }
606
- }
607
-
608
- cumsum = 1.0/cumsum;
609
- for (int i = 0; i < (int) probs.size(); i++) {
610
- probs[i] *= cumsum;
611
- }
612
- }
613
-
614
- // printf("\n");
615
- // for (int i = 0; i < (int) probs.size(); i++) {
616
- // for (int i = 0; i < 10; i++) {
617
- // printf("%d: '%s' %f\n", i, vocab.id_to_token.at(logits_id[i].second).c_str(), probs[i]);
618
- // }
619
-
620
- std::discrete_distribution<> dist(probs.begin(), probs.end());
621
- int idx = dist(rng);
622
-
623
- return logits_id[idx].second;
624
-
625
- }
626
-
627
- bool is_wav_buffer(const std::string buf) {
628
- // RIFF ref: https://en.wikipedia.org/wiki/Resource_Interchange_File_Format
629
- // WAV ref: https://www.mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html
630
- if (buf.size() < 12 || buf.substr(0, 4) != "RIFF" || buf.substr(8, 4) != "WAVE") {
631
- return false;
632
- }
633
-
634
- uint32_t chunk_size = *reinterpret_cast<const uint32_t*>(buf.data() + 4);
635
- if (chunk_size + 8 != buf.size()) {
636
- return false;
637
- }
638
-
639
- return true;
640
- }
641
-
642
- bool read_wav(const std::string & fname, std::vector<float>& pcmf32, std::vector<std::vector<float>>& pcmf32s, bool stereo) {
643
- drwav wav;
644
- std::vector<uint8_t> wav_data; // used for pipe input from stdin or ffmpeg decoding output
645
-
646
- if (fname == "-") {
647
- {
648
- #ifdef _WIN32
649
- _setmode(_fileno(stdin), _O_BINARY);
650
- #endif
651
-
652
- uint8_t buf[1024];
653
- while (true)
654
- {
655
- const size_t n = fread(buf, 1, sizeof(buf), stdin);
656
- if (n == 0) {
657
- break;
658
- }
659
- wav_data.insert(wav_data.end(), buf, buf + n);
660
- }
661
- }
662
-
663
- if (drwav_init_memory(&wav, wav_data.data(), wav_data.size(), nullptr) == false) {
664
- fprintf(stderr, "error: failed to open WAV file from stdin\n");
665
- return false;
666
- }
667
-
668
- fprintf(stderr, "%s: read %zu bytes from stdin\n", __func__, wav_data.size());
669
- }
670
- else if (is_wav_buffer(fname)) {
671
- if (drwav_init_memory(&wav, fname.c_str(), fname.size(), nullptr) == false) {
672
- fprintf(stderr, "error: failed to open WAV file from fname buffer\n");
673
- return false;
674
- }
675
- }
676
- else if (drwav_init_file(&wav, fname.c_str(), nullptr) == false) {
677
- #if defined(WHISPER_FFMPEG)
678
- if (ffmpeg_decode_audio(fname, wav_data) != 0) {
679
- fprintf(stderr, "error: failed to ffmpeg decode '%s' \n", fname.c_str());
680
- return false;
681
- }
682
- if (drwav_init_memory(&wav, wav_data.data(), wav_data.size(), nullptr) == false) {
683
- fprintf(stderr, "error: failed to read wav data as wav \n");
684
- return false;
685
- }
686
- #else
687
- fprintf(stderr, "error: failed to open '%s' as WAV file\n", fname.c_str());
688
- return false;
689
- #endif
690
- }
691
-
692
- if (wav.channels != 1 && wav.channels != 2) {
693
- fprintf(stderr, "%s: WAV file '%s' must be mono or stereo\n", __func__, fname.c_str());
694
- drwav_uninit(&wav);
695
- return false;
696
- }
697
-
698
- if (stereo && wav.channels != 2) {
699
- fprintf(stderr, "%s: WAV file '%s' must be stereo for diarization\n", __func__, fname.c_str());
700
- drwav_uninit(&wav);
701
- return false;
702
- }
703
-
704
- if (wav.sampleRate != COMMON_SAMPLE_RATE) {
705
- fprintf(stderr, "%s: WAV file '%s' must be %i kHz\n", __func__, fname.c_str(), COMMON_SAMPLE_RATE/1000);
706
- drwav_uninit(&wav);
707
- return false;
708
- }
709
-
710
- if (wav.bitsPerSample != 16) {
711
- fprintf(stderr, "%s: WAV file '%s' must be 16-bit\n", __func__, fname.c_str());
712
- drwav_uninit(&wav);
713
- return false;
714
- }
715
-
716
- const uint64_t n = wav_data.empty() ? wav.totalPCMFrameCount : wav_data.size()/(wav.channels*wav.bitsPerSample/8);
717
-
718
- std::vector<int16_t> pcm16;
719
- pcm16.resize(n*wav.channels);
720
- drwav_read_pcm_frames_s16(&wav, n, pcm16.data());
721
- drwav_uninit(&wav);
722
-
723
- // convert to mono, float
724
- pcmf32.resize(n);
725
- if (wav.channels == 1) {
726
- for (uint64_t i = 0; i < n; i++) {
727
- pcmf32[i] = float(pcm16[i])/32768.0f;
728
- }
729
- } else {
730
- for (uint64_t i = 0; i < n; i++) {
731
- pcmf32[i] = float(pcm16[2*i] + pcm16[2*i + 1])/65536.0f;
732
- }
733
- }
734
-
735
- if (stereo) {
736
- // convert to stereo, float
737
- pcmf32s.resize(2);
738
-
739
- pcmf32s[0].resize(n);
740
- pcmf32s[1].resize(n);
741
- for (uint64_t i = 0; i < n; i++) {
742
- pcmf32s[0][i] = float(pcm16[2*i])/32768.0f;
743
- pcmf32s[1][i] = float(pcm16[2*i + 1])/32768.0f;
744
- }
745
- }
746
-
747
- return true;
748
- }
749
-
750
- void high_pass_filter(std::vector<float> & data, float cutoff, float sample_rate) {
751
- const float rc = 1.0f / (2.0f * M_PI * cutoff);
752
- const float dt = 1.0f / sample_rate;
753
- const float alpha = dt / (rc + dt);
754
-
755
- float y = data[0];
756
-
757
- for (size_t i = 1; i < data.size(); i++) {
758
- y = alpha * (y + data[i] - data[i - 1]);
759
- data[i] = y;
760
- }
761
- }
762
-
763
- bool vad_simple(std::vector<float> & pcmf32, int sample_rate, int last_ms, float vad_thold, float freq_thold, bool verbose) {
764
- const int n_samples = pcmf32.size();
765
- const int n_samples_last = (sample_rate * last_ms) / 1000;
766
-
767
- if (n_samples_last >= n_samples) {
768
- // not enough samples - assume no speech
769
- return false;
770
- }
771
-
772
- if (freq_thold > 0.0f) {
773
- high_pass_filter(pcmf32, freq_thold, sample_rate);
774
- }
775
-
776
- float energy_all = 0.0f;
777
- float energy_last = 0.0f;
778
-
779
- for (int i = 0; i < n_samples; i++) {
780
- energy_all += fabsf(pcmf32[i]);
781
-
782
- if (i >= n_samples - n_samples_last) {
783
- energy_last += fabsf(pcmf32[i]);
784
- }
785
- }
786
-
787
- energy_all /= n_samples;
788
- energy_last /= n_samples_last;
789
-
790
- if (verbose) {
791
- fprintf(stderr, "%s: energy_all: %f, energy_last: %f, vad_thold: %f, freq_thold: %f\n", __func__, energy_all, energy_last, vad_thold, freq_thold);
792
- }
793
-
794
- if (energy_last > vad_thold*energy_all) {
795
- return false;
796
- }
797
-
798
- return true;
799
- }
800
-
801
- float similarity(const std::string & s0, const std::string & s1) {
802
- const size_t len0 = s0.size() + 1;
803
- const size_t len1 = s1.size() + 1;
804
-
805
- std::vector<int> col(len1, 0);
806
- std::vector<int> prevCol(len1, 0);
807
-
808
- for (size_t i = 0; i < len1; i++) {
809
- prevCol[i] = i;
810
- }
811
-
812
- for (size_t i = 0; i < len0; i++) {
813
- col[0] = i;
814
- for (size_t j = 1; j < len1; j++) {
815
- col[j] = std::min(std::min(1 + col[j - 1], 1 + prevCol[j]), prevCol[j - 1] + (i > 0 && s0[i - 1] == s1[j - 1] ? 0 : 1));
816
- }
817
- col.swap(prevCol);
818
- }
819
-
820
- const float dist = prevCol[len1 - 1];
821
-
822
- return 1.0f - (dist / std::max(s0.size(), s1.size()));
823
- }
824
-
825
- bool sam_params_parse(int argc, char ** argv, sam_params & params) {
826
- for (int i = 1; i < argc; i++) {
827
- std::string arg = argv[i];
828
-
829
- if (arg == "-s" || arg == "--seed") {
830
- params.seed = std::stoi(argv[++i]);
831
- } else if (arg == "-t" || arg == "--threads") {
832
- params.n_threads = std::stoi(argv[++i]);
833
- } else if (arg == "-m" || arg == "--model") {
834
- params.model = argv[++i];
835
- } else if (arg == "-i" || arg == "--inp") {
836
- params.fname_inp = argv[++i];
837
- } else if (arg == "-o" || arg == "--out") {
838
- params.fname_out = argv[++i];
839
- } else if (arg == "-h" || arg == "--help") {
840
- sam_print_usage(argc, argv, params);
841
- exit(0);
842
- } else {
843
- fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
844
- sam_print_usage(argc, argv, params);
845
- exit(0);
846
- }
847
- }
848
-
849
- return true;
850
- }
851
-
852
- void sam_print_usage(int /*argc*/, char ** argv, const sam_params & params) {
853
- fprintf(stderr, "usage: %s [options]\n", argv[0]);
854
- fprintf(stderr, "\n");
855
- fprintf(stderr, "options:\n");
856
- fprintf(stderr, " -h, --help show this help message and exit\n");
857
- fprintf(stderr, " -s SEED, --seed SEED RNG seed (default: -1)\n");
858
- fprintf(stderr, " -t N, --threads N number of threads to use during computation (default: %d)\n", params.n_threads);
859
- fprintf(stderr, " -m FNAME, --model FNAME\n");
860
- fprintf(stderr, " model path (default: %s)\n", params.model.c_str());
861
- fprintf(stderr, " -i FNAME, --inp FNAME\n");
862
- fprintf(stderr, " input file (default: %s)\n", params.fname_inp.c_str());
863
- fprintf(stderr, " -o FNAME, --out FNAME\n");
864
- fprintf(stderr, " output file (default: %s)\n", params.fname_out.c_str());
865
- fprintf(stderr, "\n");
866
- }
867
-
868
- // 500 -> 00:05.000
869
- // 6000 -> 01:00.000
870
- std::string to_timestamp(int64_t t, bool comma) {
871
- int64_t msec = t * 10;
872
- int64_t hr = msec / (1000 * 60 * 60);
873
- msec = msec - hr * (1000 * 60 * 60);
874
- int64_t min = msec / (1000 * 60);
875
- msec = msec - min * (1000 * 60);
876
- int64_t sec = msec / 1000;
877
- msec = msec - sec * 1000;
878
-
879
- char buf[32];
880
- snprintf(buf, sizeof(buf), "%02d:%02d:%02d%s%03d", (int) hr, (int) min, (int) sec, comma ? "," : ".", (int) msec);
881
-
882
- return std::string(buf);
883
- }
884
-
885
- int timestamp_to_sample(int64_t t, int n_samples, int whisper_sample_rate) {
886
- return std::max(0, std::min((int) n_samples - 1, (int) ((t*whisper_sample_rate)/100)));
887
- }
888
-
889
- bool is_file_exist(const char *fileName)
890
- {
891
- std::ifstream infile(fileName);
892
- return infile.good();
893
- }
894
-
895
- bool speak_with_file(const std::string & command, const std::string & text, const std::string & path, int voice_id)
896
- {
897
- std::ofstream speak_file(path.c_str());
898
- if (speak_file.fail()) {
899
- fprintf(stderr, "%s: failed to open speak_file\n", __func__);
900
- return false;
901
- } else {
902
- speak_file.write(text.c_str(), text.size());
903
- speak_file.close();
904
- int ret = system((command + " " + std::to_string(voice_id) + " " + path).c_str());
905
- if (ret != 0) {
906
- fprintf(stderr, "%s: failed to speak\n", __func__);
907
- return false;
908
- }
909
- }
910
- return true;
911
- }