funasr-onnx-2pass.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. /**
  2. * Copyright FunASR (https://github.com/alibaba-damo-academy/FunASR). All Rights Reserved.
  3. * MIT License (https://opensource.org/licenses/MIT)
  4. */
  5. #ifndef _WIN32
  6. #include <sys/time.h>
  7. #else
  8. #include <win_func.h>
  9. #endif
  10. #include <iostream>
  11. #include <fstream>
  12. #include <sstream>
  13. #include <map>
  14. #include <glog/logging.h>
  15. #include "util.h"
  16. #include "funasrruntime.h"
  17. #include "tclap/CmdLine.h"
  18. #include "com-define.h"
  19. #include "audio.h"
  20. using namespace std;
  21. bool is_target_file(const std::string& filename, const std::string target) {
  22. std::size_t pos = filename.find_last_of(".");
  23. if (pos == std::string::npos) {
  24. return false;
  25. }
  26. std::string extension = filename.substr(pos + 1);
  27. return (extension == target);
  28. }
  29. void GetValue(TCLAP::ValueArg<std::string>& value_arg, string key, std::map<std::string, std::string>& model_path)
  30. {
  31. model_path.insert({key, value_arg.getValue()});
  32. LOG(INFO)<< key << " : " << value_arg.getValue();
  33. }
  34. int main(int argc, char** argv)
  35. {
  36. google::InitGoogleLogging(argv[0]);
  37. FLAGS_logtostderr = true;
  38. TCLAP::CmdLine cmd("funasr-onnx-2pass", ' ', "1.0");
  39. TCLAP::ValueArg<std::string> offline_model_dir("", OFFLINE_MODEL_DIR, "the asr offline model path, which contains model.onnx, config.yaml, am.mvn", true, "", "string");
  40. TCLAP::ValueArg<std::string> online_model_dir("", ONLINE_MODEL_DIR, "the asr online model path, which contains model.onnx, decoder.onnx, config.yaml, am.mvn", true, "", "string");
  41. TCLAP::ValueArg<std::string> quantize("", QUANTIZE, "true (Default), load the model of model.onnx in model_dir. If set true, load the model of model_quant.onnx in model_dir", false, "true", "string");
  42. TCLAP::ValueArg<std::string> vad_dir("", VAD_DIR, "the vad online model path, which contains model.onnx, vad.yaml, vad.mvn", false, "", "string");
  43. TCLAP::ValueArg<std::string> vad_quant("", VAD_QUANT, "true (Default), load the model of model.onnx in vad_dir. If set true, load the model of model_quant.onnx in vad_dir", false, "true", "string");
  44. TCLAP::ValueArg<std::string> punc_dir("", PUNC_DIR, "the punc online model path, which contains model.onnx, punc.yaml", false, "", "string");
  45. TCLAP::ValueArg<std::string> punc_quant("", PUNC_QUANT, "true (Default), load the model of model.onnx in punc_dir. If set true, load the model of model_quant.onnx in punc_dir", false, "true", "string");
  46. TCLAP::ValueArg<std::string> itn_dir("", ITN_DIR, "the itn model(fst) path, which contains zh_itn_tagger.fst and zh_itn_verbalizer.fst", false, "", "string");
  47. TCLAP::ValueArg<std::string> lm_dir("", LM_DIR, "the lm model path, which contains compiled models: TLG.fst, config.yaml, lexicon.txt ", false, "", "string");
  48. TCLAP::ValueArg<float> global_beam("", GLOB_BEAM, "the decoding beam for beam searching ", false, 3.0, "float");
  49. TCLAP::ValueArg<float> lattice_beam("", LAT_BEAM, "the lattice generation beam for beam searching ", false, 3.0, "float");
  50. TCLAP::ValueArg<float> am_scale("", AM_SCALE, "the acoustic scale for beam searching ", false, 10.0, "float");
  51. TCLAP::ValueArg<std::int32_t> fst_inc_wts("", FST_INC_WTS, "the fst hotwords incremental bias", false, 20, "int32_t");
  52. TCLAP::ValueArg<std::string> asr_mode("", ASR_MODE, "offline, online, 2pass", false, "2pass", "string");
  53. TCLAP::ValueArg<std::int32_t> onnx_thread("", "model-thread-num", "onnxruntime SetIntraOpNumThreads", false, 1, "int32_t");
  54. TCLAP::ValueArg<std::string> wav_path("", WAV_PATH, "the input could be: wav_path, e.g.: asr_example.wav; pcm_path, e.g.: asr_example.pcm; wav.scp, kaldi style wav list (wav_id \t wav_path)", true, "", "string");
  55. TCLAP::ValueArg<std::int32_t> audio_fs("", AUDIO_FS, "the sample rate of audio", false, 16000, "int32_t");
  56. TCLAP::ValueArg<std::string> hotword("", HOTWORD, "the hotword file, one hotword perline, Format: Hotword Weight (could be: 阿里巴巴 20)", false, "", "string");
  57. cmd.add(offline_model_dir);
  58. cmd.add(online_model_dir);
  59. cmd.add(quantize);
  60. cmd.add(vad_dir);
  61. cmd.add(vad_quant);
  62. cmd.add(punc_dir);
  63. cmd.add(punc_quant);
  64. cmd.add(lm_dir);
  65. cmd.add(global_beam);
  66. cmd.add(lattice_beam);
  67. cmd.add(am_scale);
  68. cmd.add(fst_inc_wts);
  69. cmd.add(itn_dir);
  70. cmd.add(wav_path);
  71. cmd.add(audio_fs);
  72. cmd.add(asr_mode);
  73. cmd.add(onnx_thread);
  74. cmd.add(hotword);
  75. cmd.parse(argc, argv);
  76. std::map<std::string, std::string> model_path;
  77. GetValue(offline_model_dir, OFFLINE_MODEL_DIR, model_path);
  78. GetValue(online_model_dir, ONLINE_MODEL_DIR, model_path);
  79. GetValue(quantize, QUANTIZE, model_path);
  80. GetValue(vad_dir, VAD_DIR, model_path);
  81. GetValue(vad_quant, VAD_QUANT, model_path);
  82. GetValue(punc_dir, PUNC_DIR, model_path);
  83. GetValue(punc_quant, PUNC_QUANT, model_path);
  84. GetValue(lm_dir, LM_DIR, model_path);
  85. GetValue(itn_dir, ITN_DIR, model_path);
  86. GetValue(wav_path, WAV_PATH, model_path);
  87. GetValue(asr_mode, ASR_MODE, model_path);
  88. struct timeval start, end;
  89. gettimeofday(&start, nullptr);
  90. int thread_num = onnx_thread.getValue();
  91. int asr_mode_ = -1;
  92. if(model_path[ASR_MODE] == "offline"){
  93. asr_mode_ = 0;
  94. }else if(model_path[ASR_MODE] == "online"){
  95. asr_mode_ = 1;
  96. }else if(model_path[ASR_MODE] == "2pass"){
  97. asr_mode_ = 2;
  98. }else{
  99. LOG(ERROR) << "Wrong asr-mode : " << model_path[ASR_MODE];
  100. exit(-1);
  101. }
  102. FUNASR_HANDLE tpass_handle=FunTpassInit(model_path, thread_num);
  103. if (!tpass_handle)
  104. {
  105. LOG(ERROR) << "FunTpassInit init failed";
  106. exit(-1);
  107. }
  108. float glob_beam = 3.0f;
  109. float lat_beam = 3.0f;
  110. float am_sc = 10.0f;
  111. if (lm_dir.isSet()) {
  112. glob_beam = global_beam.getValue();
  113. lat_beam = lattice_beam.getValue();
  114. am_sc = am_scale.getValue();
  115. }
  116. // init wfst decoder
  117. FUNASR_DEC_HANDLE decoder_handle = FunASRWfstDecoderInit(tpass_handle, ASR_TWO_PASS, glob_beam, lat_beam, am_sc);
  118. gettimeofday(&end, nullptr);
  119. long seconds = (end.tv_sec - start.tv_sec);
  120. long modle_init_micros = ((seconds * 1000000) + end.tv_usec) - (start.tv_usec);
  121. LOG(INFO) << "Model initialization takes " << (double)modle_init_micros / 1000000 << " s";
  122. // hotword file
  123. unordered_map<string, int> hws_map;
  124. std::string nn_hotwords_ = "";
  125. std::string hotword_path = hotword.getValue();
  126. LOG(INFO) << "hotword path: " << hotword_path;
  127. funasr::ExtractHws(hotword_path, hws_map, nn_hotwords_);
  128. // read wav_path
  129. vector<string> wav_list;
  130. vector<string> wav_ids;
  131. string default_id = "wav_default_id";
  132. string wav_path_ = model_path.at(WAV_PATH);
  133. if(is_target_file(wav_path_, "scp")){
  134. ifstream in(wav_path_);
  135. if (!in.is_open()) {
  136. LOG(ERROR) << "Failed to open file: " << model_path.at(WAV_SCP) ;
  137. return 0;
  138. }
  139. string line;
  140. while(getline(in, line))
  141. {
  142. istringstream iss(line);
  143. string column1, column2;
  144. iss >> column1 >> column2;
  145. wav_list.emplace_back(column2);
  146. wav_ids.emplace_back(column1);
  147. }
  148. in.close();
  149. }else{
  150. wav_list.emplace_back(wav_path_);
  151. wav_ids.emplace_back(default_id);
  152. }
  153. // load hotwords list and build graph
  154. FunWfstDecoderLoadHwsRes(decoder_handle, fst_inc_wts.getValue(), hws_map);
  155. std::vector<std::vector<float>> hotwords_embedding = CompileHotwordEmbedding(tpass_handle, nn_hotwords_, ASR_TWO_PASS);
  156. // init online features
  157. std::vector<int> chunk_size = {5,10,5};
  158. FUNASR_HANDLE tpass_online_handle=FunTpassOnlineInit(tpass_handle, chunk_size);
  159. float snippet_time = 0.0f;
  160. long taking_micros = 0;
  161. for (int i = 0; i < wav_list.size(); i++) {
  162. auto& wav_file = wav_list[i];
  163. auto& wav_id = wav_ids[i];
  164. int32_t sampling_rate_ = audio_fs.getValue();
  165. funasr::Audio audio(1);
  166. if(is_target_file(wav_file.c_str(), "wav")){
  167. if(!audio.LoadWav2Char(wav_file.c_str(), &sampling_rate_)){
  168. LOG(ERROR)<<"Failed to load "<< wav_file;
  169. exit(-1);
  170. }
  171. }else if(is_target_file(wav_file.c_str(), "pcm")){
  172. if (!audio.LoadPcmwav2Char(wav_file.c_str(), &sampling_rate_)){
  173. LOG(ERROR)<<"Failed to load "<< wav_file;
  174. exit(-1);
  175. }
  176. }else{
  177. if (!audio.FfmpegLoad(wav_file.c_str(), true)){
  178. LOG(ERROR)<<"Failed to load "<< wav_file;
  179. exit(-1);
  180. }
  181. }
  182. char* speech_buff = audio.GetSpeechChar();
  183. int buff_len = audio.GetSpeechLen()*2;
  184. int step = 800*2;
  185. bool is_final = false;
  186. string online_res="";
  187. string tpass_res="";
  188. string time_stamp_res="";
  189. std::vector<std::vector<string>> punc_cache(2);
  190. for (int sample_offset = 0; sample_offset < buff_len; sample_offset += std::min(step, buff_len - sample_offset)) {
  191. if (sample_offset + step >= buff_len - 1) {
  192. step = buff_len - sample_offset;
  193. is_final = true;
  194. } else {
  195. is_final = false;
  196. }
  197. gettimeofday(&start, nullptr);
  198. FUNASR_RESULT result = FunTpassInferBuffer(tpass_handle, tpass_online_handle,
  199. speech_buff+sample_offset, step, punc_cache, is_final, sampling_rate_, "pcm",
  200. (ASR_TYPE)asr_mode_, hotwords_embedding, true, decoder_handle);
  201. gettimeofday(&end, nullptr);
  202. seconds = (end.tv_sec - start.tv_sec);
  203. taking_micros += ((seconds * 1000000) + end.tv_usec) - (start.tv_usec);
  204. if (result)
  205. {
  206. string online_msg = FunASRGetResult(result, 0);
  207. online_res += online_msg;
  208. if(online_msg != ""){
  209. LOG(INFO)<< wav_id <<" : "<<online_msg;
  210. }
  211. string tpass_msg = FunASRGetTpassResult(result, 0);
  212. tpass_res += tpass_msg;
  213. if(tpass_msg != ""){
  214. LOG(INFO)<< wav_id <<" offline results : "<<tpass_msg;
  215. }
  216. string stamp = FunASRGetStamp(result);
  217. if(stamp !=""){
  218. LOG(INFO) << wav_ids[i] << " time stamp : " << stamp;
  219. if(time_stamp_res == ""){
  220. time_stamp_res += stamp;
  221. }else{
  222. time_stamp_res = time_stamp_res.erase(time_stamp_res.length()-1)
  223. + "," + stamp.substr(1);
  224. }
  225. }
  226. snippet_time += FunASRGetRetSnippetTime(result);
  227. FunASRFreeResult(result);
  228. }
  229. }
  230. if(asr_mode_==2){
  231. LOG(INFO) << wav_id << " Final online results "<<" : "<<online_res;
  232. }
  233. if(asr_mode_==1){
  234. LOG(INFO) << wav_id << " Final online results "<<" : "<<tpass_res;
  235. }
  236. if(asr_mode_==0 || asr_mode_==2){
  237. LOG(INFO) << wav_id << " Final offline results " <<" : "<<tpass_res;
  238. if(time_stamp_res!=""){
  239. LOG(INFO) << wav_id << " Final timestamp results " <<" : "<<time_stamp_res;
  240. }
  241. }
  242. }
  243. FunWfstDecoderUnloadHwsRes(decoder_handle);
  244. LOG(INFO) << "Audio length: " << (double)snippet_time << " s";
  245. LOG(INFO) << "Model inference takes: " << (double)taking_micros / 1000000 <<" s";
  246. LOG(INFO) << "Model inference RTF: " << (double)taking_micros/ (snippet_time*1000000);
  247. FunASRWfstDecoderUninit(decoder_handle);
  248. FunTpassOnlineUninit(tpass_online_handle);
  249. FunTpassUninit(tpass_handle);
  250. return 0;
  251. }