funasr_wss_client.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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="5, 10, 5",
  28. help="chunk")
  29. parser.add_argument("--chunk_interval",
  30. type=int,
  31. default=10,
  32. help="chunk")
  33. parser.add_argument("--audio_in",
  34. type=str,
  35. default=None,
  36. help="audio_in")
  37. parser.add_argument("--send_without_sleep",
  38. action="store_true",
  39. default=True,
  40. help="if audio_in is set, send_without_sleep")
  41. parser.add_argument("--thread_num",
  42. type=int,
  43. default=1,
  44. help="thread_num")
  45. parser.add_argument("--words_max_print",
  46. type=int,
  47. default=10000,
  48. help="chunk")
  49. parser.add_argument("--output_dir",
  50. type=str,
  51. default=None,
  52. help="output_dir")
  53. parser.add_argument("--ssl",
  54. type=int,
  55. default=1,
  56. help="1 for ssl connect, 0 for no ssl")
  57. parser.add_argument("--mode",
  58. type=str,
  59. default="2pass",
  60. help="offline, online, 2pass")
  61. args = parser.parse_args()
  62. args.chunk_size = [int(x) for x in args.chunk_size.split(",")]
  63. print(args)
  64. # voices = asyncio.Queue()
  65. from queue import Queue
  66. voices = Queue()
  67. offline_msg_done=False
  68. if args.output_dir is not None:
  69. # if os.path.exists(args.output_dir):
  70. # os.remove(args.output_dir)
  71. if not os.path.exists(args.output_dir):
  72. os.makedirs(args.output_dir)
  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. import ffmpeg
  126. try:
  127. # This launches a subprocess to decode audio while down-mixing and resampling as necessary.
  128. # Requires the ffmpeg CLI and `ffmpeg-python` package to be installed.
  129. audio_bytes, _ = (
  130. ffmpeg.input(wav_path, threads=0)
  131. .output("-", format="s16le", acodec="pcm_s16le", ac=1, ar=16000)
  132. .run(cmd=["ffmpeg", "-nostdin"], capture_stdout=True, capture_stderr=True)
  133. )
  134. except ffmpeg.Error as e:
  135. raise RuntimeError(f"Failed to load audio: {e.stderr.decode()}") from e
  136. # stride = int(args.chunk_size/1000*16000*2)
  137. stride = int(60 * args.chunk_size[1] / args.chunk_interval / 1000 * 16000 * 2)
  138. chunk_num = (len(audio_bytes) - 1) // stride + 1
  139. # print(stride)
  140. # send first time
  141. message = json.dumps({"mode": args.mode, "chunk_size": args.chunk_size, "chunk_interval": args.chunk_interval,
  142. "wav_name": wav_name, "is_speaking": True})
  143. #voices.put(message)
  144. await websocket.send(message)
  145. is_speaking = True
  146. for i in range(chunk_num):
  147. beg = i * stride
  148. data = audio_bytes[beg:beg + stride]
  149. message = data
  150. #voices.put(message)
  151. await websocket.send(message)
  152. if i == chunk_num - 1:
  153. is_speaking = False
  154. message = json.dumps({"is_speaking": is_speaking})
  155. #voices.put(message)
  156. await websocket.send(message)
  157. sleep_duration = 0.001 if args.mode == "offline" else 60 * args.chunk_size[1] / args.chunk_interval / 1000
  158. await asyncio.sleep(sleep_duration)
  159. if not args.mode=="offline":
  160. await asyncio.sleep(2)
  161. # offline model need to wait for message recved
  162. if args.mode=="offline":
  163. global offline_msg_done
  164. while not offline_msg_done:
  165. await asyncio.sleep(1)
  166. await websocket.close()
  167. async def message(id):
  168. global websocket,voices,offline_msg_done
  169. text_print = ""
  170. text_print_2pass_online = ""
  171. text_print_2pass_offline = ""
  172. if args.output_dir is not None:
  173. ibest_writer = open(os.path.join(args.output_dir, "text.{}".format(id)), "a", encoding="utf-8")
  174. else:
  175. ibest_writer = None
  176. try:
  177. while True:
  178. meg = await websocket.recv()
  179. meg = json.loads(meg)
  180. print(meg)
  181. wav_name = meg.get("wav_name", "demo")
  182. text = meg["text"]
  183. if ibest_writer is not None:
  184. text_write_line = "{}\t{}\n".format(wav_name, text)
  185. ibest_writer.write(text_write_line)
  186. if meg["mode"] == "online":
  187. text_print += "{}".format(text)
  188. text_print = text_print[-args.words_max_print:]
  189. os.system('clear')
  190. print("\rpid" + str(id) + ": " + text_print)
  191. elif meg["mode"] == "offline":
  192. text_print += "{}".format(text)
  193. # text_print = text_print[-args.words_max_print:]
  194. # os.system('clear')
  195. print("\rpid" + str(id) + ": " + wav_name + ": " + text_print)
  196. offline_msg_done = True
  197. else:
  198. if meg["mode"] == "2pass-online":
  199. text_print_2pass_online += "{}".format(text)
  200. text_print = text_print_2pass_offline + text_print_2pass_online
  201. else:
  202. text_print_2pass_online = ""
  203. text_print = text_print_2pass_offline + "{}".format(text)
  204. text_print_2pass_offline += "{}".format(text)
  205. text_print = text_print[-args.words_max_print:]
  206. os.system('clear')
  207. print("\rpid" + str(id) + ": " + text_print)
  208. offline_msg_done=True
  209. except Exception as e:
  210. print("Exception:", e)
  211. #traceback.print_exc()
  212. #await websocket.close()
  213. async def ws_client(id, chunk_begin, chunk_size):
  214. if args.audio_in is None:
  215. chunk_begin=0
  216. chunk_size=1
  217. global websocket,voices,offline_msg_done
  218. for i in range(chunk_begin,chunk_begin+chunk_size):
  219. offline_msg_done=False
  220. voices = Queue()
  221. if args.ssl == 1:
  222. ssl_context = ssl.SSLContext()
  223. ssl_context.check_hostname = False
  224. ssl_context.verify_mode = ssl.CERT_NONE
  225. uri = "wss://{}:{}".format(args.host, args.port)
  226. else:
  227. uri = "ws://{}:{}".format(args.host, args.port)
  228. ssl_context = None
  229. print("connect to", uri)
  230. async with websockets.connect(uri, subprotocols=["binary"], ping_interval=None, ssl=ssl_context) as websocket:
  231. if args.audio_in is not None:
  232. task = asyncio.create_task(record_from_scp(i, 1))
  233. else:
  234. task = asyncio.create_task(record_microphone())
  235. task3 = asyncio.create_task(message(str(id)+"_"+str(i))) #processid+fileid
  236. await asyncio.gather(task, task3)
  237. exit(0)
  238. def one_thread(id, chunk_begin, chunk_size):
  239. asyncio.get_event_loop().run_until_complete(ws_client(id, chunk_begin, chunk_size))
  240. asyncio.get_event_loop().run_forever()
  241. if __name__ == '__main__':
  242. # for microphone
  243. if args.audio_in is None:
  244. p = Process(target=one_thread, args=(0, 0, 0))
  245. p.start()
  246. p.join()
  247. print('end')
  248. else:
  249. # calculate the number of wavs for each preocess
  250. if args.audio_in.endswith(".scp"):
  251. f_scp = open(args.audio_in)
  252. wavs = f_scp.readlines()
  253. else:
  254. wavs = [args.audio_in]
  255. for wav in wavs:
  256. wav_splits = wav.strip().split()
  257. wav_name = wav_splits[0] if len(wav_splits) > 1 else "demo"
  258. wav_path = wav_splits[1] if len(wav_splits) > 1 else wav_splits[0]
  259. audio_type = os.path.splitext(wav_path)[-1].lower()
  260. total_len = len(wavs)
  261. if total_len >= args.thread_num:
  262. chunk_size = int(total_len / args.thread_num)
  263. remain_wavs = total_len - chunk_size * args.thread_num
  264. else:
  265. chunk_size = 1
  266. remain_wavs = 0
  267. process_list = []
  268. chunk_begin = 0
  269. for i in range(args.thread_num):
  270. now_chunk_size = chunk_size
  271. if remain_wavs > 0:
  272. now_chunk_size = chunk_size + 1
  273. remain_wavs = remain_wavs - 1
  274. # process i handle wavs at chunk_begin and size of now_chunk_size
  275. p = Process(target=one_thread, args=(i, chunk_begin, now_chunk_size))
  276. chunk_begin = chunk_begin + now_chunk_size
  277. p.start()
  278. process_list.append(p)
  279. for i in process_list:
  280. p.join()
  281. print('end')