funasr-onnx-2pass-rtf.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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 <atomic>
  15. #include <mutex>
  16. #include <thread>
  17. #include <glog/logging.h>
  18. #include "util.h"
  19. #include "funasrruntime.h"
  20. #include "tclap/CmdLine.h"
  21. #include "com-define.h"
  22. #include "audio.h"
  23. using namespace std;
  24. std::atomic<int> wav_index(0);
  25. std::mutex mtx;
  26. bool is_target_file(const std::string& filename, const std::string target) {
  27. std::size_t pos = filename.find_last_of(".");
  28. if (pos == std::string::npos) {
  29. return false;
  30. }
  31. std::string extension = filename.substr(pos + 1);
  32. return (extension == target);
  33. }
  34. void GetValue(TCLAP::ValueArg<std::string>& value_arg, string key, std::map<std::string, std::string>& model_path)
  35. {
  36. model_path.insert({key, value_arg.getValue()});
  37. LOG(INFO)<< key << " : " << value_arg.getValue();
  38. }
  39. void runReg(FUNASR_HANDLE tpass_handle, std::vector<int> chunk_size, vector<string> wav_list, vector<string> wav_ids, int audio_fs,
  40. float* total_length, long* total_time, int core_id, ASR_TYPE asr_mode_, string nn_hotwords_,
  41. float glob_beam, float lat_beam, float am_scale, int inc_bias, unordered_map<string, int> hws_map) {
  42. struct timeval start, end;
  43. long seconds = 0;
  44. float n_total_length = 0.0f;
  45. long n_total_time = 0;
  46. FUNASR_DEC_HANDLE decoder_handle = FunASRWfstDecoderInit(tpass_handle, ASR_TWO_PASS, glob_beam, lat_beam, am_scale);
  47. // load hotwords list and build graph
  48. FunWfstDecoderLoadHwsRes(decoder_handle, inc_bias, hws_map);
  49. std::vector<std::vector<float>> hotwords_embedding = CompileHotwordEmbedding(tpass_handle, nn_hotwords_, ASR_TWO_PASS);
  50. // init online features
  51. FUNASR_HANDLE tpass_online_handle=FunTpassOnlineInit(tpass_handle, chunk_size);
  52. // warm up
  53. for (size_t i = 0; i < 2; i++)
  54. {
  55. int32_t sampling_rate_ = audio_fs;
  56. funasr::Audio audio(1);
  57. if(is_target_file(wav_list[0].c_str(), "wav")){
  58. if(!audio.LoadWav2Char(wav_list[0].c_str(), &sampling_rate_)){
  59. LOG(ERROR)<<"Failed to load "<< wav_list[0];
  60. exit(-1);
  61. }
  62. }else if(is_target_file(wav_list[0].c_str(), "pcm")){
  63. if (!audio.LoadPcmwav2Char(wav_list[0].c_str(), &sampling_rate_)){
  64. LOG(ERROR)<<"Failed to load "<< wav_list[0];
  65. exit(-1);
  66. }
  67. }else{
  68. if (!audio.FfmpegLoad(wav_list[0].c_str(), true)){
  69. LOG(ERROR)<<"Failed to load "<< wav_list[0];
  70. exit(-1);
  71. }
  72. }
  73. char* speech_buff = audio.GetSpeechChar();
  74. int buff_len = audio.GetSpeechLen()*2;
  75. int step = 1600*2;
  76. bool is_final = false;
  77. std::vector<std::vector<string>> punc_cache(2);
  78. for (int sample_offset = 0; sample_offset < buff_len; sample_offset += std::min(step, buff_len - sample_offset)) {
  79. if (sample_offset + step >= buff_len - 1) {
  80. step = buff_len - sample_offset;
  81. is_final = true;
  82. } else {
  83. is_final = false;
  84. }
  85. FUNASR_RESULT result = FunTpassInferBuffer(tpass_handle, tpass_online_handle, speech_buff+sample_offset, step, punc_cache, is_final,
  86. sampling_rate_, "pcm", (ASR_TYPE)asr_mode_, hotwords_embedding, true, decoder_handle);
  87. if (result)
  88. {
  89. FunASRFreeResult(result);
  90. }
  91. }
  92. }
  93. while (true) {
  94. // 使用原子变量获取索引并递增
  95. int i = wav_index.fetch_add(1);
  96. if (i >= wav_list.size()) {
  97. break;
  98. }
  99. int32_t sampling_rate_ = audio_fs;
  100. funasr::Audio audio(1);
  101. if(is_target_file(wav_list[i].c_str(), "wav")){
  102. if(!audio.LoadWav2Char(wav_list[i].c_str(), &sampling_rate_)){
  103. LOG(ERROR)<<"Failed to load "<< wav_list[i];
  104. exit(-1);
  105. }
  106. }else if(is_target_file(wav_list[i].c_str(), "pcm")){
  107. if (!audio.LoadPcmwav2Char(wav_list[i].c_str(), &sampling_rate_)){
  108. LOG(ERROR)<<"Failed to load "<< wav_list[i];
  109. exit(-1);
  110. }
  111. }else{
  112. if (!audio.FfmpegLoad(wav_list[i].c_str(), true)){
  113. LOG(ERROR)<<"Failed to load "<< wav_list[i];
  114. exit(-1);
  115. }
  116. }
  117. char* speech_buff = audio.GetSpeechChar();
  118. int buff_len = audio.GetSpeechLen()*2;
  119. int step = 1600*2;
  120. bool is_final = false;
  121. string online_res="";
  122. string tpass_res="";
  123. string time_stamp_res="";
  124. std::vector<std::vector<string>> punc_cache(2);
  125. for (int sample_offset = 0; sample_offset < buff_len; sample_offset += std::min(step, buff_len - sample_offset)) {
  126. if (sample_offset + step >= buff_len - 1) {
  127. step = buff_len - sample_offset;
  128. is_final = true;
  129. } else {
  130. is_final = false;
  131. }
  132. gettimeofday(&start, nullptr);
  133. FUNASR_RESULT result = FunTpassInferBuffer(tpass_handle, tpass_online_handle, speech_buff+sample_offset, step, punc_cache, is_final,
  134. sampling_rate_, "pcm", (ASR_TYPE)asr_mode_, hotwords_embedding, true, decoder_handle);
  135. gettimeofday(&end, nullptr);
  136. seconds = (end.tv_sec - start.tv_sec);
  137. long taking_micros = ((seconds * 1000000) + end.tv_usec) - (start.tv_usec);
  138. n_total_time += taking_micros;
  139. if (result)
  140. {
  141. string online_msg = FunASRGetResult(result, 0);
  142. online_res += online_msg;
  143. if(online_msg != ""){
  144. LOG(INFO) <<"Thread: " << this_thread::get_id() <<" " << wav_ids[i] <<" : "<<online_msg;
  145. }
  146. string tpass_msg = FunASRGetTpassResult(result, 0);
  147. tpass_res += tpass_msg;
  148. if(tpass_msg != ""){
  149. LOG(INFO) <<"Thread: " << this_thread::get_id() <<" " << wav_ids[i] <<" offline results : "<<tpass_msg;
  150. }
  151. string stamp = FunASRGetStamp(result);
  152. if(stamp !=""){
  153. LOG(INFO) <<"Thread: " << this_thread::get_id() <<" " << wav_ids[i] << " time stamp : " << stamp;
  154. if(time_stamp_res == ""){
  155. time_stamp_res += stamp;
  156. }else{
  157. time_stamp_res = time_stamp_res.erase(time_stamp_res.length()-1)
  158. + "," + stamp.substr(1);
  159. }
  160. }
  161. float snippet_time = FunASRGetRetSnippetTime(result);
  162. n_total_length += snippet_time;
  163. FunASRFreeResult(result);
  164. }
  165. else
  166. {
  167. LOG(ERROR) << ("No return data!\n");
  168. }
  169. }
  170. if(asr_mode_ == 2){
  171. LOG(INFO) <<"Thread: " << this_thread::get_id() <<" " << wav_ids[i] << " Final online results "<<" : "<<online_res;
  172. }
  173. if(asr_mode_==1){
  174. LOG(INFO) <<"Thread: " << this_thread::get_id() <<" " << wav_ids[i] << " Final online results "<<" : "<<tpass_res;
  175. }
  176. if(asr_mode_ == 0 || asr_mode_==2){
  177. LOG(INFO) <<"Thread: " << this_thread::get_id() <<" " << wav_ids[i] << " Final offline results " <<" : "<<tpass_res;
  178. if(time_stamp_res!=""){
  179. LOG(INFO) <<"Thread: " << this_thread::get_id() <<" " << wav_ids[i] << " Final timestamp results " <<" : "<<time_stamp_res;
  180. }
  181. }
  182. }
  183. {
  184. lock_guard<mutex> guard(mtx);
  185. *total_length += n_total_length;
  186. if(*total_time < n_total_time){
  187. *total_time = n_total_time;
  188. }
  189. }
  190. FunWfstDecoderUnloadHwsRes(decoder_handle);
  191. FunASRWfstDecoderUninit(decoder_handle);
  192. FunTpassOnlineUninit(tpass_online_handle);
  193. }
  194. int main(int argc, char** argv)
  195. {
  196. google::InitGoogleLogging(argv[0]);
  197. FLAGS_logtostderr = true;
  198. TCLAP::CmdLine cmd("funasr-onnx-2pass", ' ', "1.0");
  199. 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");
  200. 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");
  201. 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");
  202. TCLAP::ValueArg<std::string> vad_dir("", VAD_DIR, "the vad online model path, which contains model.onnx, vad.yaml, vad.mvn", false, "", "string");
  203. 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");
  204. TCLAP::ValueArg<std::string> punc_dir("", PUNC_DIR, "the punc online model path, which contains model.onnx, punc.yaml", false, "", "string");
  205. 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");
  206. 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");
  207. TCLAP::ValueArg<std::string> lm_dir("", LM_DIR, "the lm model path, which contains compiled models: TLG.fst, config.yaml, lexicon.txt ", false, "", "string");
  208. TCLAP::ValueArg<float> global_beam("", GLOB_BEAM, "the decoding beam for beam searching ", false, 3.0, "float");
  209. TCLAP::ValueArg<float> lattice_beam("", LAT_BEAM, "the lattice generation beam for beam searching ", false, 3.0, "float");
  210. TCLAP::ValueArg<float> am_scale("", AM_SCALE, "the acoustic scale for beam searching ", false, 10.0, "float");
  211. TCLAP::ValueArg<std::int32_t> fst_inc_wts("", FST_INC_WTS, "the fst hotwords incremental bias", false, 20, "int32_t");
  212. TCLAP::ValueArg<std::string> asr_mode("", ASR_MODE, "offline, online, 2pass", false, "2pass", "string");
  213. TCLAP::ValueArg<std::int32_t> onnx_thread("", "model-thread-num", "onnxruntime SetIntraOpNumThreads", false, 1, "int32_t");
  214. TCLAP::ValueArg<std::int32_t> thread_num_("", THREAD_NUM, "multi-thread num for rtf", false, 1, "int32_t");
  215. 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");
  216. TCLAP::ValueArg<std::int32_t> audio_fs("", AUDIO_FS, "the sample rate of audio", false, 16000, "int32_t");
  217. TCLAP::ValueArg<std::string> hotword("", HOTWORD, "the hotword file, one hotword perline, Format: Hotword Weight (could be: 阿里巴巴 20)", false, "", "string");
  218. cmd.add(offline_model_dir);
  219. cmd.add(online_model_dir);
  220. cmd.add(quantize);
  221. cmd.add(vad_dir);
  222. cmd.add(vad_quant);
  223. cmd.add(punc_dir);
  224. cmd.add(punc_quant);
  225. cmd.add(itn_dir);
  226. cmd.add(lm_dir);
  227. cmd.add(global_beam);
  228. cmd.add(lattice_beam);
  229. cmd.add(am_scale);
  230. cmd.add(fst_inc_wts);
  231. cmd.add(wav_path);
  232. cmd.add(audio_fs);
  233. cmd.add(asr_mode);
  234. cmd.add(onnx_thread);
  235. cmd.add(thread_num_);
  236. cmd.add(hotword);
  237. cmd.parse(argc, argv);
  238. std::map<std::string, std::string> model_path;
  239. GetValue(offline_model_dir, OFFLINE_MODEL_DIR, model_path);
  240. GetValue(online_model_dir, ONLINE_MODEL_DIR, model_path);
  241. GetValue(quantize, QUANTIZE, model_path);
  242. GetValue(vad_dir, VAD_DIR, model_path);
  243. GetValue(vad_quant, VAD_QUANT, model_path);
  244. GetValue(punc_dir, PUNC_DIR, model_path);
  245. GetValue(punc_quant, PUNC_QUANT, model_path);
  246. GetValue(itn_dir, ITN_DIR, model_path);
  247. GetValue(lm_dir, LM_DIR, model_path);
  248. GetValue(wav_path, WAV_PATH, model_path);
  249. GetValue(asr_mode, ASR_MODE, model_path);
  250. struct timeval start, end;
  251. gettimeofday(&start, nullptr);
  252. int thread_num = onnx_thread.getValue();
  253. int asr_mode_ = -1;
  254. if(model_path[ASR_MODE] == "offline"){
  255. asr_mode_ = 0;
  256. }else if(model_path[ASR_MODE] == "online"){
  257. asr_mode_ = 1;
  258. }else if(model_path[ASR_MODE] == "2pass"){
  259. asr_mode_ = 2;
  260. }else{
  261. LOG(ERROR) << "Wrong asr-mode : " << model_path[ASR_MODE];
  262. exit(-1);
  263. }
  264. FUNASR_HANDLE tpass_hanlde=FunTpassInit(model_path, thread_num);
  265. if (!tpass_hanlde)
  266. {
  267. LOG(ERROR) << "FunTpassInit init failed";
  268. exit(-1);
  269. }
  270. float glob_beam = 3.0f;
  271. float lat_beam = 3.0f;
  272. float am_sc = 10.0f;
  273. if (lm_dir.isSet()) {
  274. glob_beam = global_beam.getValue();
  275. lat_beam = lattice_beam.getValue();
  276. am_sc = am_scale.getValue();
  277. }
  278. gettimeofday(&end, nullptr);
  279. long seconds = (end.tv_sec - start.tv_sec);
  280. long modle_init_micros = ((seconds * 1000000) + end.tv_usec) - (start.tv_usec);
  281. LOG(INFO) << "Model initialization takes " << (double)modle_init_micros / 1000000 << " s";
  282. // hotword file
  283. unordered_map<string, int> hws_map;
  284. std::string nn_hotwords_ = "";
  285. std::string hotword_path = hotword.getValue();
  286. LOG(INFO) << "hotword path: " << hotword_path;
  287. funasr::ExtractHws(hotword_path, hws_map, nn_hotwords_);
  288. // read wav_path
  289. vector<string> wav_list;
  290. vector<string> wav_ids;
  291. string default_id = "wav_default_id";
  292. string wav_path_ = model_path.at(WAV_PATH);
  293. if(is_target_file(wav_path_, "scp")){
  294. ifstream in(wav_path_);
  295. if (!in.is_open()) {
  296. LOG(ERROR) << "Failed to open file: " << model_path.at(WAV_SCP) ;
  297. return 0;
  298. }
  299. string line;
  300. while(getline(in, line))
  301. {
  302. istringstream iss(line);
  303. string column1, column2;
  304. iss >> column1 >> column2;
  305. wav_list.emplace_back(column2);
  306. wav_ids.emplace_back(column1);
  307. }
  308. in.close();
  309. }else{
  310. wav_list.emplace_back(wav_path_);
  311. wav_ids.emplace_back(default_id);
  312. }
  313. std::vector<int> chunk_size = {5,10,5};
  314. // 多线程测试
  315. float total_length = 0.0f;
  316. long total_time = 0;
  317. std::vector<std::thread> threads;
  318. int rtf_threds = thread_num_.getValue();
  319. for (int i = 0; i < rtf_threds; i++)
  320. {
  321. threads.emplace_back(thread(runReg, tpass_hanlde, chunk_size, wav_list, wav_ids, audio_fs.getValue(), &total_length, &total_time, i, (ASR_TYPE)asr_mode_, nn_hotwords_,
  322. glob_beam, lat_beam, am_sc, fst_inc_wts.getValue(), hws_map));
  323. }
  324. for (auto& thread : threads)
  325. {
  326. thread.join();
  327. }
  328. LOG(INFO) << "total_time_wav " << (long)(total_length * 1000) << " ms";
  329. LOG(INFO) << "total_time_comput " << total_time / 1000 << " ms";
  330. LOG(INFO) << "total_rtf " << (double)total_time/ (total_length*1000000);
  331. LOG(INFO) << "speedup " << 1.0/((double)total_time/ (total_length*1000000));
  332. FunTpassUninit(tpass_hanlde);
  333. return 0;
  334. }