funasr_wss_client.py 11 KB

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