funasr_wss_client.py 14 KB

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