wss_client_asr.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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. SUPPORT_AUDIO_TYPE_SETS = ['.wav', '.pcm']
  14. logging.basicConfig(level=logging.ERROR)
  15. parser = argparse.ArgumentParser()
  16. parser.add_argument("--host",
  17. type=str,
  18. default="localhost",
  19. required=False,
  20. help="host ip, localhost, 0.0.0.0")
  21. parser.add_argument("--port",
  22. type=int,
  23. default=10095,
  24. required=False,
  25. help="grpc server port")
  26. parser.add_argument("--chunk_size",
  27. type=str,
  28. default="5, 10, 5",
  29. help="chunk")
  30. parser.add_argument("--chunk_interval",
  31. type=int,
  32. default=10,
  33. help="chunk")
  34. parser.add_argument("--audio_in",
  35. type=str,
  36. default=None,
  37. help="audio_in")
  38. parser.add_argument("--send_without_sleep",
  39. action="store_true",
  40. default=True,
  41. help="if audio_in is set, send_without_sleep")
  42. parser.add_argument("--test_thread_num",
  43. type=int,
  44. default=1,
  45. help="test_thread_num")
  46. parser.add_argument("--words_max_print",
  47. type=int,
  48. default=10000,
  49. help="chunk")
  50. parser.add_argument("--output_dir",
  51. type=str,
  52. default=None,
  53. help="output_dir")
  54. parser.add_argument("--ssl",
  55. type=int,
  56. default=1,
  57. help="1 for ssl connect, 0 for no ssl")
  58. parser.add_argument("--mode",
  59. type=str,
  60. default="2pass",
  61. help="offline, online, 2pass")
  62. args = parser.parse_args()
  63. args.chunk_size = [int(x) for x in args.chunk_size.split(",")]
  64. print(args)
  65. # voices = asyncio.Queue()
  66. from queue import Queue
  67. voices = Queue()
  68. offline_msg_done=False
  69. ibest_writer = None
  70. if args.output_dir is not None:
  71. writer = DatadirWriter(args.output_dir)
  72. ibest_writer = writer[f"1best_recog"]
  73. async def record_microphone():
  74. is_finished = False
  75. import pyaudio
  76. # print("2")
  77. global voices
  78. FORMAT = pyaudio.paInt16
  79. CHANNELS = 1
  80. RATE = 16000
  81. chunk_size = 60 * args.chunk_size[1] / args.chunk_interval
  82. CHUNK = int(RATE / 1000 * chunk_size)
  83. p = pyaudio.PyAudio()
  84. stream = p.open(format=FORMAT,
  85. channels=CHANNELS,
  86. rate=RATE,
  87. input=True,
  88. frames_per_buffer=CHUNK)
  89. message = json.dumps({"mode": args.mode, "chunk_size": args.chunk_size, "chunk_interval": args.chunk_interval,
  90. "wav_name": "microphone", "is_speaking": True})
  91. voices.put(message)
  92. while True:
  93. data = stream.read(CHUNK)
  94. message = data
  95. voices.put(message)
  96. await asyncio.sleep(0.005)
  97. async def record_from_scp(chunk_begin, chunk_size):
  98. global voices
  99. is_finished = False
  100. if args.audio_in.endswith(".scp"):
  101. f_scp = open(args.audio_in)
  102. wavs = f_scp.readlines()
  103. else:
  104. wavs = [args.audio_in]
  105. if chunk_size > 0:
  106. wavs = wavs[chunk_begin:chunk_begin + chunk_size]
  107. for wav in wavs:
  108. wav_splits = wav.strip().split()
  109. wav_name = wav_splits[0] if len(wav_splits) > 1 else "demo"
  110. wav_path = wav_splits[1] if len(wav_splits) > 1 else wav_splits[0]
  111. if not len(wav_path.strip())>0:
  112. continue
  113. if wav_path.endswith(".pcm"):
  114. with open(wav_path, "rb") as f:
  115. audio_bytes = f.read()
  116. elif wav_path.endswith(".wav"):
  117. import wave
  118. with wave.open(wav_path, "rb") as wav_file:
  119. params = wav_file.getparams()
  120. frames = wav_file.readframes(wav_file.getnframes())
  121. audio_bytes = bytes(frames)
  122. else:
  123. raise NotImplementedError(
  124. f'Not supported audio type')
  125. # stride = int(args.chunk_size/1000*16000*2)
  126. stride = int(60 * args.chunk_size[1] / args.chunk_interval / 1000 * 16000 * 2)
  127. chunk_num = (len(audio_bytes) - 1) // stride + 1
  128. # print(stride)
  129. # send first time
  130. message = json.dumps({"mode": args.mode, "chunk_size": args.chunk_size, "chunk_interval": args.chunk_interval,
  131. "wav_name": wav_name, "is_speaking": True})
  132. #voices.put(message)
  133. await websocket.send(message)
  134. is_speaking = True
  135. for i in range(chunk_num):
  136. beg = i * stride
  137. data = audio_bytes[beg:beg + stride]
  138. message = data
  139. #voices.put(message)
  140. await websocket.send(message)
  141. if i == chunk_num - 1:
  142. is_speaking = False
  143. message = json.dumps({"is_speaking": is_speaking})
  144. #voices.put(message)
  145. await websocket.send(message)
  146. sleep_duration = 0.001 if args.mode == "offline" else 60 * args.chunk_size[1] / args.chunk_interval / 1000
  147. await asyncio.sleep(sleep_duration)
  148. # when all data sent, we need to close websocket
  149. while not voices.empty():
  150. await asyncio.sleep(1)
  151. await asyncio.sleep(3)
  152. # offline model need to wait for message recved
  153. if args.mode=="offline":
  154. global offline_msg_done
  155. while not offline_msg_done:
  156. await asyncio.sleep(1)
  157. await websocket.close()
  158. async def ws_send():
  159. global voices
  160. global websocket
  161. print("started to sending data!")
  162. while True:
  163. while not voices.empty():
  164. data = voices.get()
  165. voices.task_done()
  166. try:
  167. await websocket.send(data)
  168. except Exception as e:
  169. print('Exception occurred:', e)
  170. traceback.print_exc()
  171. exit(0)
  172. await asyncio.sleep(0.005)
  173. await asyncio.sleep(0.005)
  174. async def message(id):
  175. global websocket,voices,offline_msg_done
  176. text_print = ""
  177. text_print_2pass_online = ""
  178. text_print_2pass_offline = ""
  179. try:
  180. while True:
  181. meg = await websocket.recv()
  182. meg = json.loads(meg)
  183. wav_name = meg.get("wav_name", "demo")
  184. text = meg["text"]
  185. if ibest_writer is not None:
  186. ibest_writer["text"][wav_name] = text
  187. if meg["mode"] == "online":
  188. text_print += "{}".format(text)
  189. text_print = text_print[-args.words_max_print:]
  190. os.system('clear')
  191. print("\rpid" + str(id) + ": " + text_print)
  192. elif meg["mode"] == "offline":
  193. text_print += "{}".format(text)
  194. text_print = text_print[-args.words_max_print:]
  195. os.system('clear')
  196. print("\rpid" + str(id) + ": " + text_print)
  197. offline_msg_done=True
  198. else:
  199. if meg["mode"] == "2pass-online":
  200. text_print_2pass_online += "{}".format(text)
  201. text_print = text_print_2pass_offline + text_print_2pass_online
  202. else:
  203. text_print_2pass_online = ""
  204. text_print = text_print_2pass_offline + "{}".format(text)
  205. text_print_2pass_offline += "{}".format(text)
  206. text_print = text_print[-args.words_max_print:]
  207. os.system('clear')
  208. print("\rpid" + str(id) + ": " + text_print)
  209. except Exception as e:
  210. print("Exception:", e)
  211. #traceback.print_exc()
  212. #await websocket.close()
  213. async def print_messge():
  214. global websocket
  215. while True:
  216. try:
  217. meg = await websocket.recv()
  218. meg = json.loads(meg)
  219. print(meg)
  220. except Exception as e:
  221. print("Exception:", e)
  222. #traceback.print_exc()
  223. exit(0)
  224. async def ws_client(id, chunk_begin, chunk_size):
  225. if args.audio_in is None:
  226. chunk_begin=0
  227. chunk_size=1
  228. global websocket,voices,offline_msg_done
  229. for i in range(chunk_begin,chunk_begin+chunk_size):
  230. offline_msg_done=False
  231. voices = Queue()
  232. if args.ssl == 1:
  233. ssl_context = ssl.SSLContext()
  234. ssl_context.check_hostname = False
  235. ssl_context.verify_mode = ssl.CERT_NONE
  236. uri = "wss://{}:{}".format(args.host, args.port)
  237. else:
  238. uri = "ws://{}:{}".format(args.host, args.port)
  239. ssl_context = None
  240. print("connect to", uri)
  241. async with websockets.connect(uri, subprotocols=["binary"], ping_interval=None, ssl=ssl_context) as websocket:
  242. if args.audio_in is not None:
  243. task = asyncio.create_task(record_from_scp(i, 1))
  244. else:
  245. task = asyncio.create_task(record_microphone())
  246. task2 = asyncio.create_task(ws_send())
  247. task3 = asyncio.create_task(message(str(id)+"_"+str(i))) #processid+fileid
  248. await asyncio.gather(task, task2, task3)
  249. exit(0)
  250. def one_thread(id, chunk_begin, chunk_size):
  251. asyncio.get_event_loop().run_until_complete(ws_client(id, chunk_begin, chunk_size))
  252. asyncio.get_event_loop().run_forever()
  253. if __name__ == '__main__':
  254. # for microphone
  255. if args.audio_in is None:
  256. p = Process(target=one_thread, args=(0, 0, 0))
  257. p.start()
  258. p.join()
  259. print('end')
  260. else:
  261. # calculate the number of wavs for each preocess
  262. if args.audio_in.endswith(".scp"):
  263. f_scp = open(args.audio_in)
  264. wavs = f_scp.readlines()
  265. else:
  266. wavs = [args.audio_in]
  267. for wav in wavs:
  268. wav_splits = wav.strip().split()
  269. wav_name = wav_splits[0] if len(wav_splits) > 1 else "demo"
  270. wav_path = wav_splits[1] if len(wav_splits) > 1 else wav_splits[0]
  271. audio_type = os.path.splitext(wav_path)[-1].lower()
  272. if audio_type not in SUPPORT_AUDIO_TYPE_SETS:
  273. raise NotImplementedError(
  274. f'Not supported audio type: {audio_type}')
  275. total_len = len(wavs)
  276. if total_len >= args.test_thread_num:
  277. chunk_size = int(total_len / args.test_thread_num)
  278. remain_wavs = total_len - chunk_size * args.test_thread_num
  279. else:
  280. chunk_size = 1
  281. remain_wavs = 0
  282. process_list = []
  283. chunk_begin = 0
  284. for i in range(args.test_thread_num):
  285. now_chunk_size = chunk_size
  286. if remain_wavs > 0:
  287. now_chunk_size = chunk_size + 1
  288. remain_wavs = remain_wavs - 1
  289. # process i handle wavs at chunk_begin and size of now_chunk_size
  290. p = Process(target=one_thread, args=(i, chunk_begin, now_chunk_size))
  291. chunk_begin = chunk_begin + now_chunk_size
  292. p.start()
  293. process_list.append(p)
  294. for i in process_list:
  295. p.join()
  296. print('end')