funasr_wss_client.py 11 KB

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