wss_client_asr.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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 message(id):
  159. global websocket,voices,offline_msg_done
  160. text_print = ""
  161. text_print_2pass_online = ""
  162. text_print_2pass_offline = ""
  163. try:
  164. while True:
  165. meg = await websocket.recv()
  166. meg = json.loads(meg)
  167. wav_name = meg.get("wav_name", "demo")
  168. text = meg["text"]
  169. if ibest_writer is not None:
  170. ibest_writer["text"][wav_name] = text
  171. if meg["mode"] == "online":
  172. text_print += "{}".format(text)
  173. text_print = text_print[-args.words_max_print:]
  174. os.system('clear')
  175. print("\rpid" + str(id) + ": " + text_print)
  176. elif meg["mode"] == "offline":
  177. text_print += "{}".format(text)
  178. text_print = text_print[-args.words_max_print:]
  179. os.system('clear')
  180. print("\rpid" + str(id) + ": " + text_print)
  181. offline_msg_done=True
  182. else:
  183. if meg["mode"] == "2pass-online":
  184. text_print_2pass_online += "{}".format(text)
  185. text_print = text_print_2pass_offline + text_print_2pass_online
  186. else:
  187. text_print_2pass_online = ""
  188. text_print = text_print_2pass_offline + "{}".format(text)
  189. text_print_2pass_offline += "{}".format(text)
  190. text_print = text_print[-args.words_max_print:]
  191. os.system('clear')
  192. print("\rpid" + str(id) + ": " + text_print)
  193. except Exception as e:
  194. print("Exception:", e)
  195. #traceback.print_exc()
  196. #await websocket.close()
  197. async def print_messge():
  198. global websocket
  199. while True:
  200. try:
  201. meg = await websocket.recv()
  202. meg = json.loads(meg)
  203. print(meg)
  204. except Exception as e:
  205. print("Exception:", e)
  206. #traceback.print_exc()
  207. exit(0)
  208. async def ws_client(id, chunk_begin, chunk_size):
  209. if args.audio_in is None:
  210. chunk_begin=0
  211. chunk_size=1
  212. global websocket,voices,offline_msg_done
  213. for i in range(chunk_begin,chunk_begin+chunk_size):
  214. offline_msg_done=False
  215. voices = Queue()
  216. if args.ssl == 1:
  217. ssl_context = ssl.SSLContext()
  218. ssl_context.check_hostname = False
  219. ssl_context.verify_mode = ssl.CERT_NONE
  220. uri = "wss://{}:{}".format(args.host, args.port)
  221. else:
  222. uri = "ws://{}:{}".format(args.host, args.port)
  223. ssl_context = None
  224. print("connect to", uri)
  225. async with websockets.connect(uri, subprotocols=["binary"], ping_interval=None, ssl=ssl_context) as websocket:
  226. if args.audio_in is not None:
  227. task = asyncio.create_task(record_from_scp(i, 1))
  228. else:
  229. task = asyncio.create_task(record_microphone())
  230. #task2 = asyncio.create_task(ws_send())
  231. task3 = asyncio.create_task(message(str(id)+"_"+str(i))) #processid+fileid
  232. await asyncio.gather(task, task3)
  233. exit(0)
  234. def one_thread(id, chunk_begin, chunk_size):
  235. asyncio.get_event_loop().run_until_complete(ws_client(id, chunk_begin, chunk_size))
  236. asyncio.get_event_loop().run_forever()
  237. if __name__ == '__main__':
  238. # for microphone
  239. if args.audio_in is None:
  240. p = Process(target=one_thread, args=(0, 0, 0))
  241. p.start()
  242. p.join()
  243. print('end')
  244. else:
  245. # calculate the number of wavs for each preocess
  246. if args.audio_in.endswith(".scp"):
  247. f_scp = open(args.audio_in)
  248. wavs = f_scp.readlines()
  249. else:
  250. wavs = [args.audio_in]
  251. for wav in wavs:
  252. wav_splits = wav.strip().split()
  253. wav_name = wav_splits[0] if len(wav_splits) > 1 else "demo"
  254. wav_path = wav_splits[1] if len(wav_splits) > 1 else wav_splits[0]
  255. audio_type = os.path.splitext(wav_path)[-1].lower()
  256. if audio_type not in SUPPORT_AUDIO_TYPE_SETS:
  257. raise NotImplementedError(
  258. f'Not supported audio type: {audio_type}')
  259. total_len = len(wavs)
  260. if total_len >= args.test_thread_num:
  261. chunk_size = int(total_len / args.test_thread_num)
  262. remain_wavs = total_len - chunk_size * args.test_thread_num
  263. else:
  264. chunk_size = 1
  265. remain_wavs = 0
  266. process_list = []
  267. chunk_begin = 0
  268. for i in range(args.test_thread_num):
  269. now_chunk_size = chunk_size
  270. if remain_wavs > 0:
  271. now_chunk_size = chunk_size + 1
  272. remain_wavs = remain_wavs - 1
  273. # process i handle wavs at chunk_begin and size of now_chunk_size
  274. p = Process(target=one_thread, args=(i, chunk_begin, now_chunk_size))
  275. chunk_begin = chunk_begin + now_chunk_size
  276. p.start()
  277. process_list.append(p)
  278. for i in process_list:
  279. p.join()
  280. print('end')