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

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