wss_client_asr.py 10 KB

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