unity.cpp 8.1 KB

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