funasr_wss_client.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. # -*- encoding: utf-8 -*-
  2. import os
  3. import time
  4. import websockets, ssl
  5. import asyncio
  6. # import threading
  7. import argparse
  8. import json
  9. import traceback
  10. from multiprocessing import Process
  11. # from funasr.fileio.datadir_writer import DatadirWriter
  12. import logging
  13. logging.basicConfig(level=logging.ERROR)
  14. logger = logging.getLogger("main")
  15. logger.setLevel(logging.INFO)
  16. parser = argparse.ArgumentParser()
  17. parser.add_argument("--host",
  18. type=str,
  19. default="localhost",
  20. required=False,
  21. help="host ip, localhost, 0.0.0.0")
  22. parser.add_argument("--port",
  23. type=int,
  24. default=10095,
  25. required=False,
  26. help="grpc server port")
  27. parser.add_argument("--chunk_size",
  28. type=str,
  29. default="5, 10, 5",
  30. help="chunk")
  31. parser.add_argument("--encoder_chunk_look_back",
  32. type=int,
  33. default=4,
  34. help="chunk")
  35. parser.add_argument("--decoder_chunk_look_back",
  36. type=int,
  37. default=0,
  38. help="chunk")
  39. parser.add_argument("--chunk_interval",
  40. type=int,
  41. default=10,
  42. help="chunk")
  43. parser.add_argument("--hotword",
  44. type=str,
  45. default="",
  46. help="hotword file path, one hotword perline (e.g.:阿里巴巴 20)")
  47. parser.add_argument("--audio_in",
  48. type=str,
  49. default=None,
  50. help="audio_in")
  51. parser.add_argument("--audio_fs",
  52. type=int,
  53. default=16000,
  54. help="audio_fs")
  55. parser.add_argument("--send_without_sleep",
  56. action="store_true",
  57. default=True,
  58. help="if audio_in is set, send_without_sleep")
  59. parser.add_argument("--thread_num",
  60. type=int,
  61. default=1,
  62. help="thread_num")
  63. parser.add_argument("--words_max_print",
  64. type=int,
  65. default=10000,
  66. help="chunk")
  67. parser.add_argument("--output_dir",
  68. type=str,
  69. default=None,
  70. help="output_dir")
  71. parser.add_argument("--ssl",
  72. type=int,
  73. default=1,
  74. help="1 for ssl connect, 0 for no ssl")
  75. parser.add_argument("--use_itn",
  76. type=int,
  77. default=1,
  78. help="1 for using itn, 0 for not itn")
  79. parser.add_argument("--mode",
  80. type=str,
  81. default="2pass",
  82. help="offline, online, 2pass")
  83. # args = parser.parse_args()
  84. args, unparsed = parser.parse_known_args()
  85. args.chunk_size = [int(x) for x in args.chunk_size.split(",")]
  86. logger.debug(f"args: {args}")
  87. # voices = asyncio.Queue()
  88. from queue import Queue
  89. voices = Queue()
  90. offline_msg_done=False
  91. if args.output_dir is not None:
  92. # if os.path.exists(args.output_dir):
  93. # os.remove(args.output_dir)
  94. if not os.path.exists(args.output_dir):
  95. os.makedirs(args.output_dir)
  96. async def record_microphone():
  97. is_finished = False
  98. import pyaudio
  99. # print("2")
  100. global voices
  101. FORMAT = pyaudio.paInt16
  102. CHANNELS = 1
  103. RATE = 16000
  104. chunk_size = 60 * args.chunk_size[1] / args.chunk_interval
  105. CHUNK = int(RATE / 1000 * chunk_size)
  106. p = pyaudio.PyAudio()
  107. stream = p.open(format=FORMAT,
  108. channels=CHANNELS,
  109. rate=RATE,
  110. input=True,
  111. frames_per_buffer=CHUNK)
  112. # hotwords
  113. fst_dict = {}
  114. hotword_msg = ""
  115. if args.hotword.strip() != "":
  116. if os.path.exists(args.hotword):
  117. f_scp = open(args.hotword)
  118. hot_lines = f_scp.readlines()
  119. for line in hot_lines:
  120. words = line.strip().split(" ")
  121. if len(words) < 2:
  122. print("Please checkout format of hotwords")
  123. continue
  124. try:
  125. fst_dict[" ".join(words[:-1])] = int(words[-1])
  126. except ValueError:
  127. print("Please checkout format of hotwords")
  128. hotword_msg = json.dumps(fst_dict)
  129. else:
  130. hotword_msg = args.hotword
  131. use_itn = True
  132. if args.use_itn == 0:
  133. use_itn=False
  134. message = json.dumps({"mode": args.mode,
  135. "chunk_size": args.chunk_size,
  136. "chunk_interval": args.chunk_interval,
  137. "encoder_chunk_look_back": args.encoder_chunk_look_back,
  138. "decoder_chunk_look_back": args.decoder_chunk_look_back,
  139. "wav_name": "microphone",
  140. "is_speaking": True,
  141. "hotwords": hotword_msg,
  142. "itn": use_itn,
  143. })
  144. #voices.put(message)
  145. await websocket.send(message)
  146. while True:
  147. data = stream.read(CHUNK)
  148. message = data
  149. #voices.put(message)
  150. await websocket.send(message)
  151. await asyncio.sleep(0.005)
  152. async def record_from_scp(chunk_begin, chunk_size):
  153. global voices
  154. is_finished = False
  155. print(f"args: {args}")
  156. if args.audio_in.endswith(".scp"):
  157. f_scp = open(args.audio_in)
  158. wavs = f_scp.readlines()
  159. else:
  160. wavs = [args.audio_in]
  161. # hotwords
  162. fst_dict = {}
  163. hotword_msg = ""
  164. if args.hotword.strip() != "":
  165. if os.path.exists(args.hotword):
  166. f_scp = open(args.hotword)
  167. hot_lines = f_scp.readlines()
  168. for line in hot_lines:
  169. words = line.strip().split(" ")
  170. if len(words) < 2:
  171. print("Please checkout format of hotwords")
  172. continue
  173. try:
  174. fst_dict[" ".join(words[:-1])] = int(words[-1])
  175. except ValueError:
  176. print("Please checkout format of hotwords")
  177. hotword_msg = json.dumps(fst_dict)
  178. else:
  179. hotword_msg = args.hotword
  180. print ("hotword_msg: ", hotword_msg)
  181. sample_rate = args.audio_fs
  182. wav_format = "pcm"
  183. use_itn=True
  184. if args.use_itn == 0:
  185. use_itn=False
  186. if chunk_size > 0:
  187. wavs = wavs[chunk_begin:chunk_begin + chunk_size]
  188. for wav in wavs:
  189. wav_splits = wav.strip().split()
  190. wav_name = wav_splits[0] if len(wav_splits) > 1 else "demo"
  191. wav_path = wav_splits[1] if len(wav_splits) > 1 else wav_splits[0]
  192. if not len(wav_path.strip())>0:
  193. continue
  194. if wav_path.endswith(".pcm"):
  195. with open(wav_path, "rb") as f:
  196. audio_bytes = f.read()
  197. elif wav_path.endswith(".wav"):
  198. import wave
  199. with wave.open(wav_path, "rb") as wav_file:
  200. params = wav_file.getparams()
  201. sample_rate = wav_file.getframerate()
  202. frames = wav_file.readframes(wav_file.getnframes())
  203. audio_bytes = bytes(frames)
  204. else:
  205. wav_format = "others"
  206. with open(wav_path, "rb") as f:
  207. audio_bytes = f.read()
  208. stride = int(60 * args.chunk_size[1] / args.chunk_interval / 1000 * sample_rate * 2)
  209. chunk_num = (len(audio_bytes) - 1) // stride + 1
  210. # print(stride)
  211. # send first time
  212. message = json.dumps({"mode": args.mode,
  213. "chunk_size": args.chunk_size,
  214. "chunk_interval": args.chunk_interval,
  215. "encoder_chunk_look_back": args.encoder_chunk_look_back,
  216. "decoder_chunk_look_back": args.decoder_chunk_look_back,
  217. "audio_fs":sample_rate,
  218. "wav_name": wav_name,
  219. "wav_format": wav_format,
  220. "is_speaking": True,
  221. "hotwords": hotword_msg,
  222. "itn": use_itn})
  223. #voices.put(message)
  224. print("send message")
  225. await websocket.send(message)
  226. is_speaking = True
  227. for i in range(chunk_num):
  228. beg = i * stride
  229. data = audio_bytes[beg:beg + stride]
  230. message = data
  231. #voices.put(message)
  232. await websocket.send(message)
  233. if i == chunk_num - 1:
  234. is_speaking = False
  235. message = json.dumps({"is_speaking": is_speaking})
  236. #voices.put(message)
  237. await websocket.send(message)
  238. sleep_duration = 0.001 if args.mode == "offline" else 60 * args.chunk_size[1] / args.chunk_interval / 1000
  239. await asyncio.sleep(sleep_duration)
  240. if not args.mode=="offline":
  241. await asyncio.sleep(2)
  242. # offline model need to wait for message recved
  243. if args.mode=="offline":
  244. global offline_msg_done
  245. while not offline_msg_done:
  246. await asyncio.sleep(1)
  247. await websocket.close()
  248. async def message(id):
  249. global websocket,voices,offline_msg_done
  250. text_print = ""
  251. text_print_2pass_online = ""
  252. text_print_2pass_offline = ""
  253. if args.output_dir is not None:
  254. ibest_writer = open(os.path.join(args.output_dir, "text.{}".format(id)), "a", encoding="utf-8")
  255. else:
  256. ibest_writer = None
  257. try:
  258. while True:
  259. meg = await websocket.recv()
  260. meg = json.loads(meg)
  261. wav_name = meg.get("wav_name", "demo")
  262. text = meg["text"]
  263. timestamp=""
  264. offline_msg_done = meg.get("is_final", False)
  265. if "timestamp" in meg:
  266. timestamp = meg["timestamp"]
  267. if ibest_writer is not None:
  268. if timestamp !="":
  269. text_write_line = "{}\t{}\t{}\n".format(wav_name, text, timestamp)
  270. else:
  271. text_write_line = "{}\t{}\n".format(wav_name, text)
  272. ibest_writer.write(text_write_line)
  273. if 'mode' not in meg:
  274. continue
  275. if meg["mode"] == "online":
  276. text_print += "{}".format(text)
  277. text_print = text_print[-args.words_max_print:]
  278. os.system('clear')
  279. print("\rpid" + str(id) + ": " + text_print)
  280. elif meg["mode"] == "offline":
  281. if timestamp !="":
  282. text_print += "{} timestamp: {}".format(text, timestamp)
  283. else:
  284. text_print += "{}".format(text)
  285. # text_print = text_print[-args.words_max_print:]
  286. # os.system('clear')
  287. print("\rpid" + str(id) + ": " + wav_name + ": " + text_print)
  288. offline_msg_done = True
  289. else:
  290. if meg["mode"] == "2pass-online":
  291. text_print_2pass_online += "{}".format(text)
  292. text_print = text_print_2pass_offline + text_print_2pass_online
  293. else:
  294. text_print_2pass_online = ""
  295. text_print = text_print_2pass_offline + "{}".format(text)
  296. text_print_2pass_offline += "{}".format(text)
  297. text_print = text_print[-args.words_max_print:]
  298. os.system('clear')
  299. print("\rpid" + str(id) + ": " + text_print)
  300. # offline_msg_done=True
  301. except Exception as e:
  302. print("Exception:", e)
  303. #traceback.print_exc()
  304. #await websocket.close()
  305. import builtins
  306. async def ws_client(id, chunk_begin, chunk_size, proc_args=None):
  307. global args
  308. args = proc_args
  309. logger.info(f"sub process: {args}")
  310. if args.audio_in is None:
  311. chunk_begin=0
  312. chunk_size=1
  313. global websocket,voices,offline_msg_done
  314. for i in range(chunk_begin,chunk_begin+chunk_size):
  315. offline_msg_done=False
  316. voices = Queue()
  317. if args.ssl == 1:
  318. ssl_context = ssl.SSLContext()
  319. ssl_context.check_hostname = False
  320. ssl_context.verify_mode = ssl.CERT_NONE
  321. uri = "wss://{}:{}".format(args.host, args.port)
  322. else:
  323. uri = "ws://{}:{}".format(args.host, args.port)
  324. ssl_context = None
  325. print("connect to", uri)
  326. async with websockets.connect(uri, subprotocols=["binary"], ping_interval=None, ssl=ssl_context) as websocket:
  327. if args.audio_in is not None:
  328. print(f"i = {i}")
  329. task = asyncio.create_task(record_from_scp(i, 1))
  330. else:
  331. task = asyncio.create_task(record_microphone())
  332. task3 = asyncio.create_task(message(str(id)+"_"+str(i))) #processid+fileid
  333. await asyncio.gather(task, task3)
  334. os._exit(0)
  335. # builtins.exit(0)
  336. def one_thread(id, chunk_begin, chunk_size, args):
  337. asyncio.get_event_loop().run_until_complete(ws_client(id, chunk_begin, chunk_size,args))
  338. asyncio.get_event_loop().run_forever()
  339. if __name__ == '__main__':
  340. import multiprocessing
  341. multiprocessing.freeze_support()
  342. # for microphone
  343. if args.audio_in is None:
  344. logger.info(f"args.audio_in is None")
  345. p = Process(target=one_thread, args=(0, 0, 0))
  346. p.start()
  347. p.join()
  348. print('end')
  349. else:
  350. # calculate the number of wavs for each preocess
  351. if args.audio_in.endswith(".scp"):
  352. f_scp = open(args.audio_in)
  353. wavs = f_scp.readlines()
  354. else:
  355. wavs = [args.audio_in]
  356. for wav in wavs:
  357. wav_splits = wav.strip().split()
  358. wav_name = wav_splits[0] if len(wav_splits) > 1 else "demo"
  359. wav_path = wav_splits[1] if len(wav_splits) > 1 else wav_splits[0]
  360. audio_type = os.path.splitext(wav_path)[-1].lower()
  361. logger.debug(f"wavs: {wavs}")
  362. total_len = len(wavs)
  363. if total_len >= args.thread_num:
  364. chunk_size = int(total_len / args.thread_num)
  365. remain_wavs = total_len - chunk_size * args.thread_num
  366. else:
  367. chunk_size = 1
  368. remain_wavs = 0
  369. process_list = []
  370. chunk_begin = 0
  371. for i in range(args.thread_num):
  372. now_chunk_size = chunk_size
  373. if remain_wavs > 0:
  374. now_chunk_size = chunk_size + 1
  375. remain_wavs = remain_wavs - 1
  376. # process i handle wavs at chunk_begin and size of now_chunk_size
  377. p = Process(target=one_thread, args=(i, chunk_begin, now_chunk_size, args))
  378. chunk_begin = chunk_begin + now_chunk_size
  379. p.start()
  380. process_list.append(p)
  381. for i in process_list:
  382. p.join()
  383. print('end')