unity.cpp 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. #include "ggml/ggml.h"
  2. #include "ggml/ggml-alloc.h"
  3. #include "math.h"
  4. #include "model_loader.h"
  5. #include "fairseq2.h"
  6. #include "lib/unity_lib.h"
  7. #include <sndfile.h>
  8. #include <cstdlib>
  9. #include "ggml-alloc.h"
  10. #include <numeric>
  11. #include <algorithm>
  12. struct unity_params {
  13. int32_t n_threads = std::min(4, (int32_t) std::thread::hardware_concurrency());
  14. std::string model = "seamlessM4T_medium.ggml"; // model path
  15. std::string input_text = "";
  16. std::string tgt_lang = "eng";
  17. std::vector<std::string> files = {};
  18. bool text = false;
  19. SequenceGeneratorOptions opts = {
  20. /*beam_size*/ 5,
  21. /*min_seq_len*/ 1,
  22. /*soft_max_seq_len_a*/ 1,
  23. /*soft_max_seq_len_b*/ 200,
  24. /*hard_max_seq_len*/ 1000,
  25. /*len_penalty*/ 1.0,
  26. /*unk_penalty*/ 0.0,
  27. /*normalize_scores*/ true,
  28. /*mem_mb*/ 512
  29. };
  30. bool verbose = false;
  31. };
  32. void unity_print_usage(int /*argc*/, char ** argv, const unity_params & params) {
  33. fprintf(stderr, "usage: %s [options] file1 file2 ...\n", argv[0]);
  34. fprintf(stderr, "\n");
  35. fprintf(stderr, "options:\n");
  36. fprintf(stderr, " -h, --help show this help message and exit\n");
  37. fprintf(stderr, " -i, --input Input text for the text-2-text translation\n");
  38. fprintf(stderr, " -l, --tgt-lang Target translation lang (default: %s\n", params.tgt_lang);
  39. fprintf(stderr, " -t N, --threads N number of threads to use during computation (default: %d)\n", params.n_threads);
  40. fprintf(stderr, " -v, --verbose Print out word level confidence score and LID score (default: off)");
  41. fprintf(stderr, " -m FNAME, --model FNAME\n");
  42. fprintf(stderr, " model path (default: %s)\n", params.model.c_str());
  43. fprintf(stderr, " --text text output\n");
  44. fprintf(stderr, " --beam-size beam size (default: %d)\n", params.opts.beam_size);
  45. fprintf(stderr, " -M, --mem memory buffer, increase for long inputs (default: %d)\n", params.opts.mem_mb);
  46. fprintf(stderr, "\n");
  47. }
  48. std::string get_next_arg(int& i, int argc, char** argv, const std::string& flag, unity_params& params) {
  49. if (i + 1 < argc && argv[i + 1][0] != '-') {
  50. return argv[++i];
  51. } else {
  52. fprintf(stderr, "error: %s requires one argument.\n", flag.c_str());
  53. unity_print_usage(argc, argv, params);
  54. exit(0);
  55. }
  56. }
  57. bool unity_params_parse(int argc, char ** argv, unity_params & params) {
  58. for (int i = 1; i < argc; i++) {
  59. std::string arg = argv[i];
  60. if (arg == "-h" || arg == "--help") {
  61. unity_print_usage(argc, argv, params);
  62. } else if (arg == "-t" || arg == "--threads") {
  63. params.n_threads = std::stoi(get_next_arg(i, argc, argv, arg, params));
  64. } else if (arg == "-m" || arg == "--model") {
  65. params.model = get_next_arg(i, argc, argv, arg, params);
  66. } else if (arg == "-i" || arg == "--input") {
  67. params.input_text = get_next_arg(i, argc, argv, arg, params);
  68. } else if (arg == "-l" || arg == "--tgt-lang") {
  69. params.tgt_lang = get_next_arg(i, argc, argv, arg, params);
  70. } else if (arg == "--text") {
  71. params.text = true;
  72. } else if (arg == "-b" || arg == "--beam-size") {
  73. params.opts.beam_size = std::stoi(get_next_arg(i, argc, argv, arg, params));
  74. } else if (arg == "-v" || arg == "--verbose") {
  75. params.verbose = true;
  76. } else if (arg == "-M" || arg == "--mem") {
  77. params.opts.mem_mb = std::stoi(get_next_arg(i, argc, argv, arg, params));
  78. } else {
  79. params.files.push_back(std::string(arg));
  80. }
  81. }
  82. return true;
  83. }
  84. int main(int argc, char ** argv) {
  85. unity_params params;
  86. if (unity_params_parse(argc, argv, params) == false) {
  87. return 1;
  88. }
  89. fairseq2_model model;
  90. // load the model
  91. if (load_fairseq2_ggml_file(model, params.model.c_str())) {
  92. fprintf(stderr, "%s: failed to load model from '%s'\n", __func__, params.model.c_str());
  93. return 1;
  94. }
  95. // The ctx_size_mb mostly depends of input length and model dim.
  96. int ctx_size_mb = params.opts.mem_mb;
  97. auto encoder_buf = std::vector<uint8_t>(8 * 1024 * 1024); // Only tensor metadata goes in there
  98. auto encoder_fwd_buf = std::vector<uint8_t>(ctx_size_mb * 1024 * 1024 / 2);
  99. ggml_allocr* fwd_alloc = ggml_allocr_new(encoder_fwd_buf.data(), encoder_fwd_buf.capacity(), 8);
  100. char result_str[4096];
  101. std::string input;
  102. bool interactive = (params.files.size() == 0 && params.input_text.length() == 0);
  103. auto next_file = params.files.begin();
  104. // Flag for the input case: true --> s2st, false --> t2tt
  105. bool s2st_or_t2tt = true;
  106. // S2ST
  107. while (true) {
  108. if (interactive) {
  109. std::cout << "\nEnter audio_path and tgt_lang, separated by space (or 'exit' to quit):\n";
  110. std::getline(std::cin, input);
  111. if (input == "exit") {
  112. break;
  113. }
  114. } else {
  115. if (params.input_text.length() > 0) {
  116. break;
  117. }
  118. if (next_file == params.files.end() && s2st_or_t2tt) break;
  119. input = *(next_file++);
  120. }
  121. std::istringstream iss(input);
  122. std::string audio_path;
  123. std::string tgt_lang = params.tgt_lang;
  124. iss >> audio_path >> tgt_lang;
  125. if (audio_path == "-") {
  126. audio_path = "/proc/self/fd/0";
  127. }
  128. std::cerr << "Translating (Transcribing) " << audio_path << " to " << tgt_lang << "\n";
  129. SF_INFO info;
  130. SNDFILE* sndfile = sf_open(audio_path.c_str(), SFM_READ, &info);
  131. if (!sndfile) {
  132. std::cerr << "Could not open file\n";
  133. if (interactive) continue;
  134. else return 1;
  135. }
  136. // Load audio input
  137. GGML_ASSERT(info.samplerate == 16000);
  138. GGML_ASSERT(info.channels == 1);
  139. // stop at 30s. Ideally we should chunk input audio, but this will prevent most obvious OOM.
  140. int n_frames = std::min(info.samplerate * 30, (int)info.frames);
  141. std::vector<float> data(n_frames * info.channels);
  142. sf_readf_float(sndfile, data.data(), n_frames);
  143. Result result = unity_eval_speech(model, data, params.opts, tgt_lang, params.n_threads);
  144. std::string concat_transcription = std::accumulate(std::next(result.transcription.begin()), result.transcription.end(), result.transcription[0],
  145. [](const std::string& a, const std::string& b) {
  146. return a + " " + b;
  147. }
  148. );
  149. if (params.verbose) {
  150. std::cout << "Final transcription: " << concat_transcription << std::endl;
  151. std::cout << std::endl;
  152. std::cout << "Word level confidence score:" << std::endl;
  153. for (size_t i = 0; i < result.transcription.size(); ++i) {
  154. std::cout << "Word: " << result.transcription[i] << " | Score: " << result.word_confidence_scores[i] << std::endl;
  155. }
  156. std::cout << std::endl;
  157. std::cout << "LID scores: " << std::endl;
  158. for (const auto& kv : result.lid_scores) {
  159. std::cout << "Language: " << kv.first << "| Score: " << kv.second << std::endl;
  160. }
  161. } else {
  162. std::cout << concat_transcription << std::endl;
  163. }
  164. }
  165. // T2TT
  166. if (params.input_text.length() > 0) {
  167. // tokenize the input text
  168. Result result = unity_eval_text(model, params.input_text, params.opts, params.tgt_lang, params.n_threads);
  169. std::string concat_translation = std::accumulate(std::next(result.transcription.begin()), result.transcription.end(), result.transcription[0],
  170. [](const std::string& a, const std::string& b) {
  171. return a + " " + b;
  172. }
  173. );
  174. std::cout << "Translation: " << concat_translation << std::endl;
  175. }
  176. return 0;
  177. }