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