forked from ggerganov/whisper.cpp
-
Notifications
You must be signed in to change notification settings - Fork 61
/
talk-llama.cpp
2383 lines (2076 loc) · 103 KB
/
talk-llama.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// talk-llama-fast
// based on https://github.com/ggerganov/whisper.cpp
// XTTS + wav2lip support by Mozer
#include "common-sdl.h"
#include "common.h"
#include "console.h"
#include "console.cpp"
#include "whisper.h"
#include "llama.h"
#include <cassert>
#include <cstdio>
#include <fstream>
#include <regex>
#include <string>
#include <thread>
#include <vector>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <cctype>
#include <locale>
#include <codecvt>
//#include <mutex>
#include <queue>
// for xtts_play_allowed.txt
#include <Windows.h> // for win.
// for linux - google yourself
//#include <windows.h>
//#include <sys/types.h>
//#pragma comment(lib,"ws2_32.lib")
#include <clocale>
#include <curl/curl.h>
#include <unordered_set>
#include <ctype.h>
#include <map>
#include <iterator>
#include <ctime>
// global
std::string g_hotkey_pressed = "";
std::vector<llama_token> llama_tokenize(struct llama_context * ctx, const std::string & text, bool add_bos) {
auto * model = llama_get_model(ctx);
// upper limit for the number of tokens
int n_tokens = text.length() + add_bos;
std::vector<llama_token> result(n_tokens);
n_tokens = llama_tokenize(model, text.data(), text.length(), result.data(), result.size(), add_bos, false);
if (n_tokens < 0) {
result.resize(-n_tokens);
int check = llama_tokenize(model, text.data(), text.length(), result.data(), result.size(), add_bos, false);
GGML_ASSERT(check == -n_tokens);
} else {
result.resize(n_tokens);
}
return result;
}
std::string llama_token_to_piece(const struct llama_context * ctx, llama_token token) {
std::vector<char> result(8, 0);
const int n_tokens = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
if (n_tokens < 0) {
result.resize(-n_tokens);
int check = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
GGML_ASSERT(check == -n_tokens);
} else {
result.resize(n_tokens);
}
return std::string(result.data(), result.size());
}
// command-line parameters
struct whisper_params {
int32_t n_threads = std::min(4, (int32_t) std::thread::hardware_concurrency());
int32_t voice_ms = 10000;
int32_t capture_id = -1;
int32_t max_tokens = 32;
int32_t audio_ctx = 0;
int32_t n_gpu_layers = 999;
float vad_thold = 0.6f;
float vad_start_thold = 0.000270f; // 0 to turn off, you can see your current energy_last (loudness level) when running with --print-energy param
float vad_last_ms = 1250;
float freq_thold = 100.0f;
bool speed_up = false;
bool translate = false;
bool print_special = false;
bool print_energy = false;
bool no_timestamps = true;
bool verbose_prompt = false;
bool verbose = false;
bool use_gpu = true;
bool allow_newline = false;
bool multi_chars = false;
bool xtts_intro = false;
bool seqrep = false;
bool push_to_talk = false;
int split_after = 0;
int sleep_before_xtts = 0; // in ms
std::string person = "Georgi";
std::string bot_name = "LLaMA";
std::string xtts_voice = "emma_1";
std::string wake_cmd = "";
std::string heard_ok = "";
std::string language = "en";
std::string model_wsp = "models/ggml-base.en.bin";
std::string model_llama = "models/ggml-llama-7B.bin";
std::string speak = "./examples/talk-llama/speak";
std::string xtts_control_path = "c:\\DATA\\LLM\\xtts\\xtts_play_allowed.txt";
std::string xtts_url = "http://localhost:8020/";
std::string google_url = "http://localhost:8003/";
std::string prompt = "";
std::string fname_out;
std::string path_session = ""; // path to file for saving/loading model eval state
std::string stop_words = "";
int32_t ctx_size = 2048;
int32_t batch_size = 64;
int32_t n_predict = 64;
int32_t min_tokens = 0;
float temp = 0.9;
float top_k = 40;
float top_p = 1.0f;
float min_p = 0.0f;
float repeat_penalty = 1.10;
int repeat_last_n = 256;
};
void whisper_print_usage(int argc, const char ** argv, const whisper_params & params);
bool whisper_params_parse(int argc, const char ** argv, whisper_params & params) {
for (int i = 1; i < argc; i++) {
std::string arg = argv[i];
if (arg == "-h" || arg == "--help") {
whisper_print_usage(argc, argv, params);
exit(0);
}
else if (arg == "-t" || arg == "--threads") { params.n_threads = std::stoi(argv[++i]); }
else if (arg == "-vms" || arg == "--voice-ms") { params.voice_ms = std::stoi(argv[++i]); }
else if (arg == "-c" || arg == "--capture") { params.capture_id = std::stoi(argv[++i]); }
else if (arg == "-mt" || arg == "--max-tokens") { params.max_tokens = std::stoi(argv[++i]); }
else if (arg == "-ac" || arg == "--audio-ctx") { params.audio_ctx = std::stoi(argv[++i]); }
else if (arg == "-ngl" || arg == "--n-gpu-layers") { params.n_gpu_layers = std::stoi(argv[++i]); }
else if (arg == "-vth" || arg == "--vad-thold") { params.vad_thold = std::stof(argv[++i]); }
else if (arg == "-vths"|| arg == "--vad-start-thold"){ params.vad_start_thold= std::stof(argv[++i]); }
else if (arg == "-vlm" || arg == "--vad-last-ms") { params.vad_last_ms = std::stoi(argv[++i]); }
else if (arg == "-fth" || arg == "--freq-thold") { params.freq_thold = std::stof(argv[++i]); }
else if (arg == "-su" || arg == "--speed-up") { params.speed_up = true; }
else if (arg == "-tr" || arg == "--translate") { params.translate = true; }
else if (arg == "-ps" || arg == "--print-special") { params.print_special = true; }
else if (arg == "-pe" || arg == "--print-energy") { params.print_energy = true; }
else if (arg == "-vp" || arg == "--verbose-prompt") { params.verbose_prompt = true; }
else if (arg == "--verbose") { params.verbose = true; }
else if (arg == "-ng" || arg == "--no-gpu") { params.use_gpu = false; }
else if (arg == "-p" || arg == "--person") { params.person = argv[++i]; }
else if (arg == "-bn" || arg == "--bot-name") { params.bot_name = argv[++i]; }
else if (arg == "--session") { params.path_session = argv[++i]; }
else if (arg == "-w" || arg == "--wake-command") { params.wake_cmd = argv[++i]; }
else if (arg == "-ho" || arg == "--heard-ok") { params.heard_ok = argv[++i]; }
else if (arg == "-l" || arg == "--language") { params.language = argv[++i]; }
else if (arg == "-mw" || arg == "--model-whisper") { params.model_wsp = argv[++i]; }
else if (arg == "-ml" || arg == "--model-llama") { params.model_llama = argv[++i]; }
else if (arg == "-s" || arg == "--speak") { params.speak = argv[++i]; }
else if (arg == "--ctx_size") { params.ctx_size = std::stoi(argv[++i]); }
else if (arg == "-b" || arg == "--batch-size") { params.batch_size = std::stoi(argv[++i]); }
else if (arg == "-n" || arg == "--n_predict") { params.n_predict = std::stoi(argv[++i]); }
else if (arg == "--temp") { params.temp = std::stof(argv[++i]); }
else if (arg == "--top_k") { params.top_k = std::stof(argv[++i]); }
else if (arg == "--top_p") { params.top_p = std::stof(argv[++i]); }
else if (arg == "--min_p") { params.min_p = std::stof(argv[++i]); }
else if (arg == "--repeat_penalty") { params.repeat_penalty = std::stof(argv[++i]); }
else if (arg == "--repeat_last_n") { params.repeat_last_n = std::stoi(argv[++i]); }
else if (arg == "--xtts-voice") { params.xtts_voice = argv[++i]; }
else if (arg == "--xtts-url") { params.xtts_url = argv[++i]; }
else if (arg == "--google-url") { params.google_url = argv[++i]; }
else if (arg == "--xtts-control-path") { params.xtts_control_path = argv[++i]; }
else if (arg == "--allow-newline") { params.allow_newline = true; }
else if (arg == "--multi-chars") { params.multi_chars = true; }
else if (arg == "--xtts-intro") { params.xtts_intro = true; }
else if (arg == "--sleep-before-xtts") { params.sleep_before_xtts = std::stoi(argv[++i]); }
else if (arg == "--seqrep") { params.seqrep = true; }
else if (arg == "--push-to-talk") { params.push_to_talk = true; }
else if (arg == "--split-after") { params.split_after = std::stoi(argv[++i]); }
else if (arg == "--min-tokens") { params.min_tokens = std::stoi(argv[++i]); }
else if (arg == "--stop-words") { params.stop_words = argv[++i]; }
else if (arg == "--prompt-file") {
std::ifstream file(argv[++i]);
std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), back_inserter(params.prompt));
if (params.prompt.back() == '\n') {
params.prompt.pop_back();
}
}
else if (arg == "-f" || arg == "--file") { params.fname_out = argv[++i]; }
else if (arg == "-ng" || arg == "--no-gpu") { params.use_gpu = false; }
else {
fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
whisper_print_usage(argc, argv, params);
exit(0);
}
}
return true;
}
void whisper_print_usage(int /*argc*/, const char ** argv, const whisper_params & params) {
fprintf(stderr, "\n");
fprintf(stderr, "usage: %s [options]\n", argv[0]);
fprintf(stderr, "\n");
fprintf(stderr, "options:\n");
fprintf(stderr, " -h, --help [default] show this help message and exit\n");
fprintf(stderr, " -t N, --threads N [%-7d] number of threads to use during computation\n", params.n_threads);
fprintf(stderr, " -vms N, --voice-ms N [%-7d] voice duration in milliseconds\n", params.voice_ms);
fprintf(stderr, " -c ID, --capture ID [%-7d] capture device ID\n", params.capture_id);
fprintf(stderr, " -mt N, --max-tokens N [%-7d] maximum number of tokens per audio chunk\n", params.max_tokens);
fprintf(stderr, " -ac N, --audio-ctx N [%-7d] audio context size (0 - all)\n", params.audio_ctx);
fprintf(stderr, " -ngl N, --n-gpu-layers N [%-7d] number of layers to store in VRAM\n", params.n_gpu_layers);
fprintf(stderr, " -vth N, --vad-thold N [%-7.2f] voice avg activity detection threshold\n", params.vad_thold);
fprintf(stderr, " -vths N, --vad-start-thold N [%-7.6f] vad min level to stop tts, 0: off, 0.000270: default\n",params.vad_start_thold);
fprintf(stderr, " -vlm N, --vad-last-ms N [%-7d] vad min silence after speech, ms\n", params.vad_last_ms);
fprintf(stderr, " -fth N, --freq-thold N [%-7.2f] high-pass frequency cutoff\n", params.freq_thold);
fprintf(stderr, " -su, --speed-up [%-7s] speed up audio by x2 (reduced accuracy)\n", params.speed_up ? "true" : "false");
fprintf(stderr, " -tr, --translate [%-7s] translate from source language to english\n", params.translate ? "true" : "false");
fprintf(stderr, " -ps, --print-special [%-7s] print special tokens\n", params.print_special ? "true" : "false");
fprintf(stderr, " -pe, --print-energy [%-7s] print sound energy (for debugging)\n", params.print_energy ? "true" : "false");
fprintf(stderr, " -vp, --verbose-prompt [%-7s] print prompt at start\n", params.verbose_prompt ? "true" : "false");
fprintf(stderr, " --verbose [%-7s] print speed\n", params.verbose ? "true" : "false");
fprintf(stderr, " -ng, --no-gpu [%-7s] disable GPU\n", params.use_gpu ? "false" : "true");
fprintf(stderr, " -p NAME, --person NAME [%-7s] person name (for prompt selection)\n", params.person.c_str());
fprintf(stderr, " -bn NAME, --bot-name NAME [%-7s] bot name (to display)\n", params.bot_name.c_str());
fprintf(stderr, " -w TEXT, --wake-command T [%-7s] wake-up command to listen for\n", params.wake_cmd.c_str());
fprintf(stderr, " -ho TEXT, --heard-ok TEXT [%-7s] said by TTS before generating reply\n", params.heard_ok.c_str());
fprintf(stderr, " -l LANG, --language LANG [%-7s] spoken language\n", params.language.c_str());
fprintf(stderr, " -mw FILE, --model-whisper [%-7s] whisper model file\n", params.model_wsp.c_str());
fprintf(stderr, " -ml FILE, --model-llama [%-7s] llama model file\n", params.model_llama.c_str());
fprintf(stderr, " -s FILE, --speak TEXT [%-7s] command for TTS\n", params.speak.c_str());
fprintf(stderr, " --prompt-file FNAME [%-7s] file with custom prompt to start dialog\n", "");
fprintf(stderr, " --session FNAME file to cache model state in (may be large!) (default: none)\n");
fprintf(stderr, " -f FNAME, --file FNAME [%-7s] text output file name\n", params.fname_out.c_str());
fprintf(stderr, " --ctx_size N [%-7d] Size of the prompt context\n", params.ctx_size);
fprintf(stderr, " -b N, --batch-size N [%-7d] Size of input batch size\n", params.batch_size);
fprintf(stderr, " -n N, --n_predict N [%-7d] Max number of tokens to predict\n", params.n_predict);
fprintf(stderr, " --temp N [%-7.2f] Temperature \n", params.temp);
fprintf(stderr, " --top_k N [%-7.2f] top_k \n", params.top_k);
fprintf(stderr, " --top_p N [%-7.2f] top_p \n", params.top_p);
fprintf(stderr, " --min_p N [%-7.2f] min_p \n", params.min_p);
fprintf(stderr, " --repeat_penalty N [%-7.2f] repeat_penalty \n", params.repeat_penalty);
fprintf(stderr, " --repeat_last_n N [%-7d] repeat_last_n \n", params.repeat_last_n);
fprintf(stderr, " --xtts-voice NAME [%-7s] xtts voice without .wav\n", params.xtts_voice.c_str());
fprintf(stderr, " --xtts-url TEXT [%-7s] xtts/silero server URL, with trailing slash\n", params.xtts_url.c_str());
fprintf(stderr, " --xtts-control-path FNAME [%-7s] not used anymore\n", params.xtts_control_path.c_str());
fprintf(stderr, " --xtts-intro [%-7s] xtts instant short random intro like Hmmm.\n", params.xtts_intro ? "true" : "false");
fprintf(stderr, " --sleep-before-xtts [%-7d] sleep llama inference before xtts, ms.\n", params.sleep_before_xtts);
fprintf(stderr, " --google-url TEXT [%-7s] langchain google-serper server URL, with /\n", params.google_url.c_str());
fprintf(stderr, " --allow-newline [%-7s] allow new line in llama output\n", params.allow_newline ? "true" : "false");
fprintf(stderr, " --multi-chars [%-7s] xtts will use same wav name as in llama output\n", params.multi_chars ? "true" : "false");
fprintf(stderr, " --push-to-talk [%-7s] hold Alt to speak\n", params.push_to_talk ? "true" : "false");
fprintf(stderr, " --seqrep [%-7s] sequence repetition penalty, search last 20 in 300\n",params.seqrep ? "true" : "false");
fprintf(stderr, " --split-after N [%-7d] split after first n tokens for tts\n", params.split_after);
fprintf(stderr, " --min-tokens N [%-7d] min new tokens to output\n", params.min_tokens);
fprintf(stderr, " --stop-words TEXT [%-7s] llama stop w: separated by ; \n", params.stop_words.c_str());
fprintf(stderr, "\n");
}
// returns seconds since epoch with milliseconds. e.g. 15244.575 (15244 s and 575 ms)
float get_current_time_ms() {
auto now = std::chrono::high_resolution_clock::now();
// Convert to milliseconds since the Unix epoch
auto duration = now.time_since_epoch();
float millis = (float)std::chrono::duration_cast<std::chrono::milliseconds>(duration).count() / 1000;
return millis;
}
std::string transcribe(
whisper_context * ctx,
const whisper_params & params,
const std::vector<float> & pcmf32,
const std::string prompt_text,
float & prob,
int64_t & t_ms) {
const auto t_start = std::chrono::high_resolution_clock::now();
//printf("%.3f in transcribe\n", get_current_time_ms());
prob = 0.0f;
t_ms = 0;
std::vector<whisper_token> prompt_tokens;
whisper_full_params wparams = whisper_full_default_params(WHISPER_SAMPLING_GREEDY);
prompt_tokens.resize(1024);
prompt_tokens.resize(whisper_tokenize(ctx, prompt_text.c_str(), prompt_tokens.data(), prompt_tokens.size()));
wparams.print_progress = false;
wparams.print_special = params.print_special;
wparams.print_realtime = false;
wparams.print_timestamps = !params.no_timestamps;
wparams.translate = params.translate;
wparams.no_context = true;
wparams.single_segment = true;
wparams.max_tokens = params.max_tokens;
wparams.language = params.language.c_str();
wparams.n_threads = params.n_threads;
wparams.prompt_tokens = prompt_tokens.empty() ? nullptr : prompt_tokens.data();
wparams.prompt_n_tokens = prompt_tokens.empty() ? 0 : prompt_tokens.size();
wparams.audio_ctx = params.audio_ctx;
wparams.speed_up = params.speed_up;
wparams.no_timestamps = true;
if (whisper_full(ctx, wparams, pcmf32.data(), pcmf32.size()) != 0) {
return "";
}
int prob_n = 0;
std::string result;
const int n_segments = whisper_full_n_segments(ctx);
for (int i = 0; i < n_segments; ++i) {
const char * text = whisper_full_get_segment_text(ctx, i);
result += text;
const int n_tokens = whisper_full_n_tokens(ctx, i);
for (int j = 0; j < n_tokens; ++j) {
const auto token = whisper_full_get_token_data(ctx, i, j);
prob += token.p;
++prob_n;
}
}
//printf("%.3f after n_segments\n", get_current_time_ms());
if (prob_n > 0) {
prob /= prob_n;
}
const auto t_end = std::chrono::high_resolution_clock::now();
t_ms = std::chrono::duration_cast<std::chrono::milliseconds>(t_end - t_start).count();
// print hex
//printf("whisper result:\n");
//for (char ch : result) printf("%X ", ch);
//printf("\n\n");
return result;
}
std::vector<std::string> get_words(const std::string &txt) {
std::vector<std::string> words;
std::istringstream iss(txt);
std::string word;
while (iss >> word) {
words.push_back(word);
}
return words;
}
std::string getTempDir() {
TCHAR path_buf[MAX_PATH];
DWORD ret_val = GetTempPath(MAX_PATH, path_buf);
if ( ret_val > MAX_PATH || (ret_val == 0) )
{
printf("GetTempPath failed");
return "";
} else {
return path_buf;
}
}
// OLD
// writes to file 0 or 1
// @path: not used anymore, we store in temp
// @xtts_play_allowed: 0=dont play xtts, 1=xtts can play
void allow_xtts_file(std::string path, int xtts_play_allowed) {
try{
std::string temp_path = getTempDir();
path = temp_path+"xtts_play_allowed.txt";
const std::string fileName{path};
std::ifstream readStream{fileName};
std::string singleLine;
bool doesExistAndIsReadable{readStream.good()};
if(!doesExistAndIsReadable){
printf("Notice: %s file not found. Let's create it.", path.c_str());
// Create the file with the given value
std::ofstream writeStream(fileName);
writeStream << xtts_play_allowed;
writeStream.flush();
writeStream.close();
}
else {
// Read the existing value from the file
std::getline(readStream, singleLine);
readStream.close();
int stored_value = stoi(singleLine);
if (stored_value != xtts_play_allowed)
{
std::ofstream writeStream{fileName};
writeStream << xtts_play_allowed;
writeStream.flush();
writeStream.close();
}
}
} catch(...) { // exception handler
}
}
// trim from start (in place)
inline void ltrim(std::string &s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](unsigned char ch) {
return !std::isspace(ch);
}));
}
// trim from end (in place)
inline void rtrim(std::string &s) {
s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) {
return !std::isspace(ch);
}).base(), s.end());
}
// trim from both ends (in place)
inline void trim(std::string &s) {
rtrim(s);
ltrim(s);
}
bool IsPunctuationMark(char c) {
switch (static_cast<unsigned char>(c)) {
case ',':
[[fallthrough]];
case '.':
[[fallthrough]];
case '?':
return true;
case ':':
return true;
case '!':
return true;
default:
return false;
}
}
std::string StripPunctuationMarks(const std::string& text) {
std::string cleanText;
for (const auto& c : text) {
if (!IsPunctuationMark(c)) {
cleanText += c;
}
}
return cleanText;
}
std::string LowerCase(const std::string& text) {
std::string lowerCasedText;
for (const auto& c : text) {
lowerCasedText += std::tolower(c, std::locale());
}
return lowerCasedText;
}
// get part of the string that is after the @command (please google weather in london -> weather in london)
std::string ParseCommandAndGetKeyword(std::string textHeardTrimmed, const std::string& command="google") {
textHeardTrimmed = StripPunctuationMarks(textHeardTrimmed);
//std::string sanitizedInput = LowerCase(textHeardTrimmed); // LowerCase not working with utf8 non-latin chars
std::string sanitizedInput = textHeardTrimmed;
std::size_t pos = 0;
bool startsWithPrefix = false;
static const std::unordered_set<std::string> please_needles{"can you hear me", "Can you hear me", "Are you here", "are you here", "Do you hear me", "do you hear me", "Пожалуйста", "пожалуйста", "Позови", "позови", "ты тут", "Ты тут", "ты здесь", "Ты здесь", "Ты слышишь меня", "ты слышишь меня", "ты меня слышишь", "Ты меня слышишь", "Hey", "hey", "please", "Please", "can you", "Can you", "let's", "Let's", "What do you think", "Что ты думаешь", "что ты думаешь", "Что ты об этом думаешь", "что ты об этом думаешь"};
std::string result_param = "";
// remove please_needles
for(const auto& prefix : please_needles) {
sanitizedInput = ::replace(sanitizedInput, prefix, "");
}
trim(sanitizedInput);
//fprintf(stdout, "sanitizedInput: %s\n", sanitizedInput.c_str());
if (command=="google")
{
static const std::unordered_set<std::string> prefixNeedles{"Погугли", "погугли", "угли", "углe", "По гугле", "По угли"};
// find start prefixNeedles
for(const auto& prefix : prefixNeedles) {
if(sanitizedInput.compare(0,prefix.length(),prefix)==0) {
pos = prefix.length()+1;
startsWithPrefix = true;
break;
}
}
}
// if not starts with prefixNeedles, find exact command
if(!startsWithPrefix || pos==std::string::npos) {
//fprintf(stdout, "goin to search %s in %s\n", command.c_str(), sanitizedInput.c_str());
pos = sanitizedInput.find(command); // call
if (pos != std::string::npos) pos = pos + command.size()+1;
else
{
pos = sanitizedInput.find("Call");
if (pos != std::string::npos) pos = pos + command.size()+1;
pos = 0; // command not found
}
}
if (command=="call")
{
// russian name fixes: Позови Алису -> Алиса
int last_n = sanitizedInput.size() - 1;
if (sanitizedInput[last_n-1] == static_cast<char>(0xD1) && sanitizedInput[last_n] == static_cast<char>(0x83)) { sanitizedInput[last_n-1] = 0xD0; sanitizedInput[last_n] = 0xB0; } // у -> а
else if (sanitizedInput[last_n-1] == static_cast<char>(0xD1) && sanitizedInput[last_n] == static_cast<char>(0x8E)) { sanitizedInput[last_n-1] = 0xD0; sanitizedInput[last_n] = 0x8F; } // ю -> я
//else if (sanitizedInput[last_n-1] == static_cast<char>(0xD0) && sanitizedInput[last_n] == static_cast<char>(0xB0)) { sanitizedInput = sanitizedInput.substr(0, sanitizedInput.size()-2); } // Олега -> Олег
textHeardTrimmed = sanitizedInput;
}
result_param = textHeardTrimmed.substr(pos);
return result_param;
}
static size_t WriteCallback(char* ptr, size_t size, size_t nmemb, void* userdata) {
((std::string*)userdata)->append((const char*)ptr, size * nmemb);
return size * nmemb;
}
std::string RemoveTrailingCharacters(const std::string &inputString, const char targetCharacter) {
auto lastNonTargetPosition = std::find_if(inputString.rbegin(), inputString.rend(), [targetCharacter](auto ch) {
return ch != targetCharacter;
});
return std::string(inputString.begin(), lastNonTargetPosition.base());
}
std::string RemoveTrailingCharactersUtf8(const std::string& inputString, const std::u32string& targetCharacter) {
std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> converter;
std::u32string u32_input = converter.from_bytes(inputString);
auto lastNonTargetPosition = std::find_if(u32_input.rbegin(), u32_input.rend(), [&targetCharacter](char32_t ch) {
return targetCharacter.find(ch) == std::u32string::npos;
});
std::string result = converter.to_bytes(std::u32string(u32_input.begin(), lastNonTargetPosition.base()));
return result;
}
std::string UrlEncode(const std::string& str) {
CURL* curl = curl_easy_init();
if (curl) {
char* encodedUrl = curl_easy_escape(curl, str.c_str(), str.length());
std::string escapedUrl(encodedUrl);
curl_free(encodedUrl);
curl_easy_cleanup(curl);
return escapedUrl;
}
return {};
}
// blocking
std::string send_curl_json(const std::string &url, const std::map<std::string, std::string>& params) {
CURL *curl;
CURLcode res;
std::string readBuffer;
/* Initialize curl */
curl = curl_easy_init();
if (!curl) {
throw std::runtime_error("Failed to initialize curl");
}
try {
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_VERBOSE, 0L);
/* Convert map to query string */
std::ostringstream oss;
bool firstParam = true;
oss << "{";
for (auto param : params) {
if (!firstParam) oss<< ',';
oss << "\"" << param.first << "\":\"" << param.second << "\"";
firstParam=false;
};
oss << "}";
fprintf(stdout, "send_curl_json: %s\n",oss.str().c_str());
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, curl_slist_append(nullptr, "Content-Type:application/json"));
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, oss.str().c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
res = curl_easy_perform(curl);
if (res != CURLE_OK) {
throw std::runtime_error(std::string("cURL error: ") + curl_easy_strerror(res));
} else {
//std::cout << "Request successful!" << std::endl;
}
}
catch(...) { // exception handler
}
curl_easy_cleanup(curl);
return readBuffer;
}
// simple curl
std::string send_curl(std::string url)
{
CURL *curl;
CURLcode res;
std::string readBuffer;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
}
return readBuffer;
}
int utf8_length(const std::string& str)
{
int c,i,ix,q;
for (q=0, i=0, ix=str.length(); i < ix; i++, q++)
{
c = (unsigned char) str[i];
if (c>=0 && c<=127) i+=0;
else if ((c & 0xE0) == 0xC0) i+=1;
else if ((c & 0xF0) == 0xE0) i+=2;
else if ((c & 0xF8) == 0xF0) i+=3;
//else if (($c & 0xFC) == 0xF8) i+=4; // 111110bb //byte 5, unnecessary in 4 byte UTF-8
//else if (($c & 0xFE) == 0xFC) i+=5; // 1111110b //byte 6, unnecessary in 4 byte UTF-8
else return 0;//invalid utf8
}
return q;
}
std::string utf8_substr(const std::string& str, unsigned int start, unsigned int leng)
{
if (leng==0) { return ""; }
unsigned int c, i, ix, q, min=std::string::npos, max=std::string::npos;
for (q=0, i=0, ix=str.length(); i < ix; i++, q++)
{
if (q==start){ min=i; }
if (q<=start+leng || leng==std::string::npos){ max=i; }
c = (unsigned char) str[i];
if (
//c>=0 &&
c<=127) i+=0;
else if ((c & 0xE0) == 0xC0) i+=1;
else if ((c & 0xF0) == 0xE0) i+=2;
else if ((c & 0xF8) == 0xF0) i+=3;
//else if (($c & 0xFC) == 0xF8) i+=4; // 111110bb //byte 5, unnecessary in 4 byte UTF-8
//else if (($c & 0xFE) == 0xFC) i+=5; // 1111110b //byte 6, unnecessary in 4 byte UTF-8
else return "";//invalid utf8
}
if (q<=start+leng || leng==std::string::npos){ max=i; }
if (min==std::string::npos || max==std::string::npos) { return ""; }
return str.substr(min,max);
}
std::string translit_en_ru(IN const std::string &str) {
std::string strRes;
std::string szEngABC = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::string szRusABC = "абцдефгхийклмнопкрстуввхйзАБЦДЕФГХИЙКЛМНОПКРСТУВВХЙЗ";
char szRusABC_arr[104];
int lastIndex = 0;
for (char ch : szRusABC)
{
szRusABC_arr[lastIndex] = ch;
lastIndex++;
}
for (int i=0; i<str.size(); i++)
{
size_t pCh = szEngABC.find_first_of(str[i]);
if (pCh != std::string::npos) {
strRes += szRusABC_arr[2*pCh];
strRes += szRusABC_arr[2*pCh+1];
//fprintf(stdout, "en:%c, ru:%s, pos: %d\n", str[i], strRes, pCh);
} else {
strRes += str[i];
}
}
//printf hex
//fprintf(stdout, "strRes %s:\n", strRes.c_str());
//for (char ch : strRes) printf("%X ", ch);
//printf("\n\n");
return strRes;
}
// returns name or ""
std::string find_name(const std::string& str) {
if (str.size()>=4)
{
// Search for '\n' character
size_t pos = str.find("\n");
if (pos != std::string::npos && pos + 4 <= str.length()) {
// If found, search for ':' after '\n'
size_t endPos = str.find(": ", pos);
if (endPos == std::string::npos || endPos >= str.length()) {
return "";
}
// Get the subtring before ' :'
std::string substr = str.substr(pos + 1, endPos - pos - 1);
// Remove leading and trailing spaces
while (*substr.begin() == ' ') {
substr.erase(substr.begin());
}
while(*substr.rbegin()==' ') {
substr.pop_back();
}
// Return trimmed substring if its length is less than or equal to 20 characters
if (substr.length() < 2 || substr.length() > 20) {
return "";
} else {
return substr;
}
}
}
return "";
}
// async curl, but it's still blocking for some reason
// use in a new thread for non-blocking
// doesn't wait for responce
void send_tts_async(std::string text, std::string speaker_wav="emma_1", std::string language="en", std::string tts_url="http://localhost:8020/", int reply_part=0)
{
// remove text between parentheses using regex
if (text[0] == '(' && text[text.size()-1] != ')') text=+")"; // missing )
else if (text[0] != '(' && text[text.size()-1] == ')') text="("+text; // missing (
std::regex paren_regex(R"(\([^()]*\))"); // Raw string literal for regex pattern
text = std::regex_replace(text, paren_regex, "");
trim(text);
text = ::replace(text, "...", ".");
text = ::replace(text, "..", ".");
text = ::replace(text, "…", ".");
text = ::replace(text, "??", "?");
text = ::replace(text, "!!!", "!");
text = ::replace(text, "!!", "!");
text = ::replace(text, "?!", "?");
text = ::replace(text, "\"", "");
text = ::replace(text, ")", "");
text = ::replace(text, "(", "");
text = ::replace(text, " ?", "?");
text = ::replace(text, " !", "!");
text = ::replace(text, " .", ".");
text = ::replace(text, " ,", ",");
if (text == "!" || text == "?" || text == ".") text = "";
else if (text == speaker_wav+": ") text = "";
else if (text == speaker_wav+":") text = "";
else if (text[text.size()-1] == ':') text[text.size()-1] = ' ';
else if (text[text.size()-1] == '-') text[text.size()-1] = ' ';
else if (text[text.size()-1] == '(') text[text.size()-1] = ' ';
else if (text[text.size()-1] == ',') text[text.size()-1] = ' ';
else if (text[text.size()-1] == '.') text[text.size()-1] = ' ';
speaker_wav = ::replace(speaker_wav, ":", "");
speaker_wav = ::replace(speaker_wav, "\n", "");
speaker_wav = ::replace(speaker_wav, "\r", "");
speaker_wav = ::replace(speaker_wav, "\"", "");
trim(speaker_wav);
if (speaker_wav.size()<2) speaker_wav = "emma_1";
trim(text);
if (text[0] == '!' || text[0] == '?' || text[0] == '.' || text[0] == ',' && text.size()>=2) text = utf8_substr(text, 1, utf8_length(text));
if (text[text.size()-1] == ',' && text.size()>=2) text = utf8_substr(text, 0, utf8_length(text)-1);
trim(text);
if (text.back() == ':' && text.length() < 15 && text.find(' ') == std::string::npos) text = "";
if (text.size()>=1 && text != "." && text != "," && text != "!" && text != "\n")
{
trim(text);
text = ::replace(text, "\r", "");
text = ::replace(text, "\n", " ");
text = ::replace(text, "\"", "");
text = ::replace(text, "..", ".");
tts_url= tts_url + "tts_to_audio/";
CURL *http_handle;
CURLM *multi_handle;
int still_running = 1;
curl_global_init(CURL_GLOBAL_DEFAULT);
http_handle = curl_easy_init();
std::string data = "{\"text\":\""+text+"\", \"language\":\""+language+"\", \"speaker_wav\":\""+speaker_wav+"\", \"reply_part\":\""+std::to_string(reply_part)+"\"}";
//fprintf(stdout, "\n[data (%s)]\n", data.c_str());
curl_easy_setopt(http_handle, CURLOPT_HTTPHEADER, curl_slist_append(nullptr, "Content-Type:application/json"));
curl_easy_setopt(http_handle, CURLOPT_URL, tts_url.c_str());
curl_easy_setopt(http_handle, CURLOPT_POSTFIELDS, data.c_str());
curl_easy_setopt(http_handle, CURLOPT_VERBOSE, 0L);
std::string responseData;
curl_easy_setopt(http_handle, CURLOPT_WRITEDATA, &responseData);
curl_easy_setopt(http_handle, CURLOPT_WRITEFUNCTION, WriteCallback);
multi_handle = curl_multi_init();
curl_multi_add_handle(multi_handle, http_handle);
do {
CURLMcode mc = curl_multi_perform(multi_handle, &still_running);
if(still_running) mc = curl_multi_poll(multi_handle, NULL, 0, 1000, NULL);// wait for activity, timeout or "nothing"
if(mc)
break;
} while(still_running);
curl_easy_cleanup(http_handle);
curl_multi_cleanup(multi_handle);
curl_global_cleanup();
}
}
std::queue<std::string> input_queue; // global
//std::mutex input_mutex;
bool keyboard_input_running = true; // global, not used yet
void input_thread_func() {
std::string line;
std::string buffer;
bool found_another_line = true;
while (keyboard_input_running) {
do {
found_another_line = console::readline(line, false);
buffer += line;
} while (found_another_line);
//printf(" '%s' ", buffer.c_str());
trim(buffer); // keyboard input
// if you paste multiple passages from clipboard, make sure to hit Enter after pasting
// otherwise last passage won't be pasted (bug). Alternatively you can manually add \n after last passage in copied text
//std::lock_guard<std::mutex> lock(input_mutex); // was blocking, TODO if really needed
input_queue.push(buffer);
buffer = "";
}
}
// windows only
bool IsConsoleWindowFocused(HWND cur_window_handle) {
return (cur_window_handle == GetForegroundWindow());
}
// Stop: Ctrl+Space
// Regenerate: Ctrl+Right
// Delete: Ctrl+Delete
// Reset: Ctrl+R
// modifies global var string g_hotkey_pressed
void keyboard_shortcut_func(HWND cur_window_handle) {
bool b_ctr_space_processed = false;
bool b_ctr_right_processed = false;
bool b_ctr_delete_processed = false;
bool b_ctr_r_processed = false;
bool b_ctr_space_prev = false;
bool b_ctr_right_prev = false;
bool b_ctr_delete_prev = false;
bool b_ctr_r_prev = false;
bool b_ctr_space = false;
bool b_ctr_right = false;
bool b_ctr_delete = false;
bool b_ctr_r = false;
bool b_alt = false;
bool isFocused = false;
g_hotkey_pressed = "";
while (true) {
isFocused = IsConsoleWindowFocused(cur_window_handle);
if (isFocused) {
b_ctr_space = GetAsyncKeyState(VK_CONTROL) & GetAsyncKeyState(VK_SPACE) & 0x8000;
b_ctr_right = GetAsyncKeyState(VK_CONTROL) & GetAsyncKeyState(VK_RIGHT) & 0x8000;
b_ctr_delete = GetAsyncKeyState(VK_CONTROL) & GetAsyncKeyState(VK_DELETE) & 0x8000;
b_ctr_r = GetAsyncKeyState(VK_CONTROL) & GetAsyncKeyState('R') & 0x8000;
b_alt = GetAsyncKeyState(VK_MENU) & 0x8000;
if (b_alt)
{
g_hotkey_pressed = "Alt";
std::this_thread::sleep_for(std::chrono::milliseconds(100));
continue; // no further if-else for Alt PTT
}
if (b_ctr_space && !b_ctr_space_prev) {
if (!b_ctr_space_processed) {
fflush(stdout);
printf("\b"); // remove printed symbols
fflush(stdout);
g_hotkey_pressed = "Ctrl+Space";
b_ctr_space_processed = true;
}
}
else if (!b_ctr_space && b_ctr_space_prev && b_ctr_space_processed) {
b_ctr_space_processed = false;
}
if (b_ctr_right && !b_ctr_right_prev) {
if (!b_ctr_right_processed) {
fflush(stdout);
printf("\b"); // remove printed symbols
fflush(stdout);
g_hotkey_pressed = "Ctrl+Right";
b_ctr_right_processed = true;
}
}
else if (!b_ctr_right && b_ctr_right_prev && b_ctr_right_processed) {
b_ctr_right_processed = false;
}
if (b_ctr_delete && !b_ctr_delete_prev) {
if (!b_ctr_delete_processed) {
fflush(stdout);
printf("\b"); // remove printed symbols
fflush(stdout);
g_hotkey_pressed = "Ctrl+Delete";
b_ctr_delete_processed = true;
}
}
else if (!b_ctr_delete && b_ctr_delete_prev && b_ctr_delete_processed) {
b_ctr_delete_processed = false;
}
if (b_ctr_r && !b_ctr_r_prev) {
if (!b_ctr_r_processed) {
fflush(stdout);
printf("\b\b"); // remove printed ^R
fflush(stdout);
g_hotkey_pressed = "Ctrl+R";
b_ctr_r_processed = true;
}
}
else if (!b_ctr_r && b_ctr_r_prev && b_ctr_r_processed) {
b_ctr_r_processed = false;
}
b_ctr_space_prev = b_ctr_space;
b_ctr_right_prev = b_ctr_right;
b_ctr_delete_prev = b_ctr_delete;
b_ctr_r_prev = b_ctr_r;
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
const std::string k_prompt_whisper = R"(A conversation with a person called {1}.)";
const std::string k_prompt_whisper_ru = R"({1}, Алиса.)";
const std::string k_prompt_llama = R"(Text transcript of a never ending dialog, where {0} interacts with an AI assistant named {1}.
{1} is helpful, kind, honest, friendly, good at writing and never fails to answer {0}’s requests immediately and with details and precision.
There are no annotations like (30 seconds passed...) or (to himself), just what {0} and {1} say aloud to each other.
The transcript only includes text, it does not include markup like HTML and Markdown.
{1} responds with short and concise answers.
{0}{4} Hello, {1}!
{1}{4} Hello {0}! How may I help you today?
{0}{4} What time is it?
{1}{4} It is {2} o'clock, {5}, year {3}.
{0}{4} What is a cat?
{1}{4} A cat is a domestic species of small carnivorous mammal. It is the only domesticated species in the family Felidae.
{0}{4} Name a color.
{1}{4} Blue
{0}{4})";