wss_client_asr.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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=False,
  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. ibest_writer = None
  69. if args.output_dir is not None:
  70. writer = DatadirWriter(args.output_dir)
  71. ibest_writer = writer[f"1best_recog"]
  72. async def record_microphone():
  73. is_finished = False
  74. import pyaudio
  75. # print("2")
  76. global voices
  77. FORMAT = pyaudio.paInt16
  78. CHANNELS = 1
  79. RATE = 16000
  80. chunk_size = 60 * args.chunk_size[1] / args.chunk_interval
  81. CHUNK = int(RATE / 1000 * chunk_size)
  82. p = pyaudio.PyAudio()
  83. stream = p.open(format=FORMAT,
  84. channels=CHANNELS,
  85. rate=RATE,
  86. input=True,
  87. frames_per_buffer=CHUNK)
  88. message = json.dumps({"mode": args.mode, "chunk_size": args.chunk_size, "chunk_interval": args.chunk_interval,
  89. "wav_name": "microphone", "is_speaking": True})
  90. voices.put(message)
  91. while True:
  92. data = stream.read(CHUNK)
  93. message = data
  94. voices.put(message)
  95. await asyncio.sleep(0.005)
  96. async def record_from_scp(chunk_begin, chunk_size):
  97. global voices
  98. is_finished = False
  99. if args.audio_in.endswith(".scp"):
  100. f_scp = open(args.audio_in)
  101. wavs = f_scp.readlines()
  102. else:
  103. wavs = [args.audio_in]
  104. if chunk_size > 0:
  105. wavs = wavs[chunk_begin:chunk_begin + chunk_size]
  106. for wav in wavs:
  107. wav_splits = wav.strip().split()
  108. wav_name = wav_splits[0] if len(wav_splits) > 1 else "demo"
  109. wav_path = wav_splits[1] if len(wav_splits) > 1 else wav_splits[0]
  110. if wav_path.endswith(".pcm"):
  111. with open(wav_path, "rb") as f:
  112. audio_bytes = f.read()
  113. elif wav_path.endswith(".wav"):
  114. import wave
  115. with wave.open(wav_path, "rb") as wav_file:
  116. params = wav_file.getparams()
  117. frames = wav_file.readframes(wav_file.getnframes())
  118. audio_bytes = bytes(frames)
  119. else:
  120. raise NotImplementedError(
  121. f'Not supported audio type')
  122. # stride = int(args.chunk_size/1000*16000*2)
  123. stride = int(60 * args.chunk_size[1] / args.chunk_interval / 1000 * 16000 * 2)
  124. chunk_num = (len(audio_bytes) - 1) // stride + 1
  125. # print(stride)
  126. # send first time
  127. message = json.dumps({"mode": args.mode, "chunk_size": args.chunk_size, "chunk_interval": args.chunk_interval,
  128. "wav_name": wav_name, "is_speaking": True})
  129. voices.put(message)
  130. is_speaking = True
  131. for i in range(chunk_num):
  132. beg = i * stride
  133. data = audio_bytes[beg:beg + stride]
  134. message = data
  135. voices.put(message)
  136. if i == chunk_num - 1:
  137. is_speaking = False
  138. message = json.dumps({"is_speaking": is_speaking})
  139. voices.put(message)
  140. # print("data_chunk: ", len(data_chunk))
  141. # print(voices.qsize())
  142. sleep_duration = 0.001 if args.send_without_sleep else 60 * args.chunk_size[1] / args.chunk_interval / 1000
  143. await asyncio.sleep(sleep_duration)
  144. async def ws_send():
  145. global voices
  146. global websocket
  147. print("started to sending data!")
  148. while True:
  149. while not voices.empty():
  150. data = voices.get()
  151. voices.task_done()
  152. try:
  153. await websocket.send(data)
  154. except Exception as e:
  155. print('Exception occurred:', e)
  156. traceback.print_exc()
  157. exit(0)
  158. await asyncio.sleep(0.005)
  159. await asyncio.sleep(0.005)
  160. async def message(id):
  161. global websocket
  162. text_print = ""
  163. text_print_2pass_online = ""
  164. text_print_2pass_offline = ""
  165. while True:
  166. try:
  167. meg = await websocket.recv()
  168. meg = json.loads(meg)
  169. wav_name = meg.get("wav_name", "demo")
  170. # print(wav_name)
  171. text = meg["text"]
  172. if ibest_writer is not None:
  173. ibest_writer["text"][wav_name] = text
  174. if meg["mode"] == "online":
  175. text_print += "{}".format(text)
  176. text_print = text_print[-args.words_max_print:]
  177. os.system('clear')
  178. print("\rpid" + str(id) + ": " + text_print)
  179. elif meg["mode"] == "offline":
  180. text_print += "{}".format(text)
  181. text_print = text_print[-args.words_max_print:]
  182. os.system('clear')
  183. print("\rpid" + str(id) + ": " + text_print)
  184. else:
  185. if meg["mode"] == "2pass-online":
  186. text_print_2pass_online += "{}".format(text)
  187. text_print = text_print_2pass_offline + text_print_2pass_online
  188. else:
  189. text_print_2pass_online = ""
  190. text_print = text_print_2pass_offline + "{}".format(text)
  191. text_print_2pass_offline += "{}".format(text)
  192. text_print = text_print[-args.words_max_print:]
  193. os.system('clear')
  194. print("\rpid" + str(id) + ": " + text_print)
  195. except Exception as e:
  196. print("Exception:", e)
  197. traceback.print_exc()
  198. exit(0)
  199. async def print_messge():
  200. global websocket
  201. while True:
  202. try:
  203. meg = await websocket.recv()
  204. meg = json.loads(meg)
  205. print(meg)
  206. except Exception as e:
  207. print("Exception:", e)
  208. traceback.print_exc()
  209. exit(0)
  210. async def ws_client(id, chunk_begin, chunk_size):
  211. global websocket
  212. if args.ssl == 1:
  213. ssl_context = ssl.SSLContext()
  214. ssl_context.check_hostname = False
  215. ssl_context.verify_mode = ssl.CERT_NONE
  216. uri = "wss://{}:{}".format(args.host, args.port)
  217. else:
  218. uri = "ws://{}:{}".format(args.host, args.port)
  219. ssl_context = None
  220. print("connect to", uri)
  221. async for websocket in websockets.connect(uri, subprotocols=["binary"], ping_interval=None, ssl=ssl_context):
  222. if args.audio_in is not None:
  223. task = asyncio.create_task(record_from_scp(chunk_begin, chunk_size))
  224. else:
  225. task = asyncio.create_task(record_microphone())
  226. task2 = asyncio.create_task(ws_send())
  227. task3 = asyncio.create_task(message(id))
  228. await asyncio.gather(task, task2, task3)
  229. def one_thread(id, chunk_begin, chunk_size):
  230. asyncio.get_event_loop().run_until_complete(ws_client(id, chunk_begin, chunk_size))
  231. asyncio.get_event_loop().run_forever()
  232. if __name__ == '__main__':
  233. # for microphone
  234. if args.audio_in is None:
  235. p = Process(target=one_thread, args=(0, 0, 0))
  236. p.start()
  237. p.join()
  238. print('end')
  239. else:
  240. # calculate the number of wavs for each preocess
  241. if args.audio_in.endswith(".scp"):
  242. f_scp = open(args.audio_in)
  243. wavs = f_scp.readlines()
  244. else:
  245. wavs = [args.audio_in]
  246. for wav in wavs:
  247. wav_splits = wav.strip().split()
  248. wav_name = wav_splits[0] if len(wav_splits) > 1 else "demo"
  249. wav_path = wav_splits[1] if len(wav_splits) > 1 else wav_splits[0]
  250. audio_type = os.path.splitext(wav_path)[-1].lower()
  251. if audio_type not in SUPPORT_AUDIO_TYPE_SETS:
  252. raise NotImplementedError(
  253. f'Not supported audio type: {audio_type}')
  254. total_len = len(wavs)
  255. if total_len >= args.test_thread_num:
  256. chunk_size = int(total_len / args.test_thread_num)
  257. remain_wavs = total_len - chunk_size * args.test_thread_num
  258. else:
  259. chunk_size = 1
  260. remain_wavs = 0
  261. process_list = []
  262. chunk_begin = 0
  263. for i in range(args.test_thread_num):
  264. now_chunk_size = chunk_size
  265. if remain_wavs > 0:
  266. now_chunk_size = chunk_size + 1
  267. remain_wavs = remain_wavs - 1
  268. # process i handle wavs at chunk_begin and size of now_chunk_size
  269. p = Process(target=one_thread, args=(i, chunk_begin, now_chunk_size))
  270. chunk_begin = chunk_begin + now_chunk_size
  271. p.start()
  272. process_list.append(p)
  273. for i in process_list:
  274. p.join()
  275. print('end')