funasr_wss_client.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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("--hotword",
  34. type=str,
  35. default="",
  36. help="hotword file path, one hotword perline (e.g.:阿里巴巴 20)")
  37. parser.add_argument("--audio_in",
  38. type=str,
  39. default=None,
  40. help="audio_in")
  41. parser.add_argument("--audio_fs",
  42. type=int,
  43. default=16000,
  44. help="audio_fs")
  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("--use_itn",
  66. type=int,
  67. default=1,
  68. help="1 for using itn, 0 for not itn")
  69. parser.add_argument("--mode",
  70. type=str,
  71. default="2pass",
  72. help="offline, online, 2pass")
  73. args = parser.parse_args()
  74. args.chunk_size = [int(x) for x in args.chunk_size.split(",")]
  75. print(args)
  76. # voices = asyncio.Queue()
  77. from queue import Queue
  78. voices = Queue()
  79. offline_msg_done=False
  80. if args.output_dir is not None:
  81. # if os.path.exists(args.output_dir):
  82. # os.remove(args.output_dir)
  83. if not os.path.exists(args.output_dir):
  84. os.makedirs(args.output_dir)
  85. async def record_microphone():
  86. is_finished = False
  87. import pyaudio
  88. # print("2")
  89. global voices
  90. FORMAT = pyaudio.paInt16
  91. CHANNELS = 1
  92. RATE = 16000
  93. chunk_size = 60 * args.chunk_size[1] / args.chunk_interval
  94. CHUNK = int(RATE / 1000 * chunk_size)
  95. p = pyaudio.PyAudio()
  96. stream = p.open(format=FORMAT,
  97. channels=CHANNELS,
  98. rate=RATE,
  99. input=True,
  100. frames_per_buffer=CHUNK)
  101. # hotwords
  102. fst_dict = {}
  103. hotword_msg = ""
  104. if args.hotword.strip() != "":
  105. f_scp = open(args.hotword)
  106. hot_lines = f_scp.readlines()
  107. for line in hot_lines:
  108. words = line.strip().split(" ")
  109. if len(words) < 2:
  110. print("Please checkout format of hotwords")
  111. continue
  112. try:
  113. fst_dict[" ".join(words[:-1])] = int(words[-1])
  114. except ValueError:
  115. print("Please checkout format of hotwords")
  116. hotword_msg=json.dumps(fst_dict)
  117. use_itn=True
  118. if args.use_itn == 0:
  119. use_itn=False
  120. message = json.dumps({"mode": args.mode, "chunk_size": args.chunk_size, "chunk_interval": args.chunk_interval,
  121. "wav_name": "microphone", "is_speaking": True, "hotwords":hotword_msg, "itn": use_itn})
  122. #voices.put(message)
  123. await websocket.send(message)
  124. while True:
  125. data = stream.read(CHUNK)
  126. message = data
  127. #voices.put(message)
  128. await websocket.send(message)
  129. await asyncio.sleep(0.005)
  130. async def record_from_scp(chunk_begin, chunk_size):
  131. global voices
  132. is_finished = False
  133. if args.audio_in.endswith(".scp"):
  134. f_scp = open(args.audio_in)
  135. wavs = f_scp.readlines()
  136. else:
  137. wavs = [args.audio_in]
  138. # hotwords
  139. fst_dict = {}
  140. hotword_msg = ""
  141. if args.hotword.strip() != "":
  142. f_scp = open(args.hotword)
  143. hot_lines = f_scp.readlines()
  144. for line in hot_lines:
  145. words = line.strip().split(" ")
  146. if len(words) < 2:
  147. print("Please checkout format of hotwords")
  148. continue
  149. try:
  150. fst_dict[" ".join(words[:-1])] = int(words[-1])
  151. except ValueError:
  152. print("Please checkout format of hotwords")
  153. hotword_msg=json.dumps(fst_dict)
  154. print (hotword_msg)
  155. sample_rate = args.audio_fs
  156. wav_format = "pcm"
  157. use_itn=True
  158. if args.use_itn == 0:
  159. use_itn=False
  160. if chunk_size > 0:
  161. wavs = wavs[chunk_begin:chunk_begin + chunk_size]
  162. for wav in wavs:
  163. wav_splits = wav.strip().split()
  164. wav_name = wav_splits[0] if len(wav_splits) > 1 else "demo"
  165. wav_path = wav_splits[1] if len(wav_splits) > 1 else wav_splits[0]
  166. if not len(wav_path.strip())>0:
  167. continue
  168. if wav_path.endswith(".pcm"):
  169. with open(wav_path, "rb") as f:
  170. audio_bytes = f.read()
  171. elif wav_path.endswith(".wav"):
  172. import wave
  173. with wave.open(wav_path, "rb") as wav_file:
  174. params = wav_file.getparams()
  175. sample_rate = wav_file.getframerate()
  176. frames = wav_file.readframes(wav_file.getnframes())
  177. audio_bytes = bytes(frames)
  178. else:
  179. wav_format = "others"
  180. with open(wav_path, "rb") as f:
  181. audio_bytes = f.read()
  182. stride = int(60 * args.chunk_size[1] / args.chunk_interval / 1000 * sample_rate * 2)
  183. chunk_num = (len(audio_bytes) - 1) // stride + 1
  184. # print(stride)
  185. # send first time
  186. message = json.dumps({"mode": args.mode, "chunk_size": args.chunk_size, "chunk_interval": args.chunk_interval, "audio_fs":sample_rate,
  187. "wav_name": wav_name, "wav_format": wav_format, "is_speaking": True, "hotwords":hotword_msg, "itn": use_itn})
  188. #voices.put(message)
  189. await websocket.send(message)
  190. is_speaking = True
  191. for i in range(chunk_num):
  192. beg = i * stride
  193. data = audio_bytes[beg:beg + stride]
  194. message = data
  195. #voices.put(message)
  196. await websocket.send(message)
  197. if i == chunk_num - 1:
  198. is_speaking = False
  199. message = json.dumps({"is_speaking": is_speaking})
  200. #voices.put(message)
  201. await websocket.send(message)
  202. sleep_duration = 0.001 if args.mode == "offline" else 60 * args.chunk_size[1] / args.chunk_interval / 1000
  203. await asyncio.sleep(sleep_duration)
  204. if not args.mode=="offline":
  205. await asyncio.sleep(2)
  206. # offline model need to wait for message recved
  207. if args.mode=="offline":
  208. global offline_msg_done
  209. while not offline_msg_done:
  210. await asyncio.sleep(1)
  211. await websocket.close()
  212. async def message(id):
  213. global websocket,voices,offline_msg_done
  214. text_print = ""
  215. text_print_2pass_online = ""
  216. text_print_2pass_offline = ""
  217. if args.output_dir is not None:
  218. ibest_writer = open(os.path.join(args.output_dir, "text.{}".format(id)), "a", encoding="utf-8")
  219. else:
  220. ibest_writer = None
  221. try:
  222. while True:
  223. meg = await websocket.recv()
  224. meg = json.loads(meg)
  225. wav_name = meg.get("wav_name", "demo")
  226. text = meg["text"]
  227. timestamp=""
  228. offline_msg_done = meg.get("is_final", False)
  229. if "timestamp" in meg:
  230. timestamp = meg["timestamp"]
  231. if ibest_writer is not None:
  232. if timestamp !="":
  233. text_write_line = "{}\t{}\t{}\n".format(wav_name, text, timestamp)
  234. else:
  235. text_write_line = "{}\t{}\n".format(wav_name, text)
  236. ibest_writer.write(text_write_line)
  237. if 'mode' not in meg:
  238. continue
  239. if meg["mode"] == "online":
  240. text_print += "{}".format(text)
  241. text_print = text_print[-args.words_max_print:]
  242. os.system('clear')
  243. print("\rpid" + str(id) + ": " + text_print)
  244. elif meg["mode"] == "offline":
  245. if timestamp !="":
  246. text_print += "{} timestamp: {}".format(text, timestamp)
  247. else:
  248. text_print += "{}".format(text)
  249. # text_print = text_print[-args.words_max_print:]
  250. # os.system('clear')
  251. print("\rpid" + str(id) + ": " + wav_name + ": " + text_print)
  252. offline_msg_done = True
  253. else:
  254. if meg["mode"] == "2pass-online":
  255. text_print_2pass_online += "{}".format(text)
  256. text_print = text_print_2pass_offline + text_print_2pass_online
  257. else:
  258. text_print_2pass_online = ""
  259. text_print = text_print_2pass_offline + "{}".format(text)
  260. text_print_2pass_offline += "{}".format(text)
  261. text_print = text_print[-args.words_max_print:]
  262. os.system('clear')
  263. print("\rpid" + str(id) + ": " + text_print)
  264. # offline_msg_done=True
  265. except Exception as e:
  266. print("Exception:", e)
  267. #traceback.print_exc()
  268. #await websocket.close()
  269. async def ws_client(id, chunk_begin, chunk_size):
  270. if args.audio_in is None:
  271. chunk_begin=0
  272. chunk_size=1
  273. global websocket,voices,offline_msg_done
  274. for i in range(chunk_begin,chunk_begin+chunk_size):
  275. offline_msg_done=False
  276. voices = Queue()
  277. if args.ssl == 1:
  278. ssl_context = ssl.SSLContext()
  279. ssl_context.check_hostname = False
  280. ssl_context.verify_mode = ssl.CERT_NONE
  281. uri = "wss://{}:{}".format(args.host, args.port)
  282. else:
  283. uri = "ws://{}:{}".format(args.host, args.port)
  284. ssl_context = None
  285. print("connect to", uri)
  286. async with websockets.connect(uri, subprotocols=["binary"], ping_interval=None, ssl=ssl_context) as websocket:
  287. if args.audio_in is not None:
  288. task = asyncio.create_task(record_from_scp(i, 1))
  289. else:
  290. task = asyncio.create_task(record_microphone())
  291. task3 = asyncio.create_task(message(str(id)+"_"+str(i))) #processid+fileid
  292. await asyncio.gather(task, task3)
  293. exit(0)
  294. def one_thread(id, chunk_begin, chunk_size):
  295. asyncio.get_event_loop().run_until_complete(ws_client(id, chunk_begin, chunk_size))
  296. asyncio.get_event_loop().run_forever()
  297. if __name__ == '__main__':
  298. # for microphone
  299. if args.audio_in is None:
  300. p = Process(target=one_thread, args=(0, 0, 0))
  301. p.start()
  302. p.join()
  303. print('end')
  304. else:
  305. # calculate the number of wavs for each preocess
  306. if args.audio_in.endswith(".scp"):
  307. f_scp = open(args.audio_in)
  308. wavs = f_scp.readlines()
  309. else:
  310. wavs = [args.audio_in]
  311. for wav in wavs:
  312. wav_splits = wav.strip().split()
  313. wav_name = wav_splits[0] if len(wav_splits) > 1 else "demo"
  314. wav_path = wav_splits[1] if len(wav_splits) > 1 else wav_splits[0]
  315. audio_type = os.path.splitext(wav_path)[-1].lower()
  316. total_len = len(wavs)
  317. if total_len >= args.thread_num:
  318. chunk_size = int(total_len / args.thread_num)
  319. remain_wavs = total_len - chunk_size * args.thread_num
  320. else:
  321. chunk_size = 1
  322. remain_wavs = 0
  323. process_list = []
  324. chunk_begin = 0
  325. for i in range(args.thread_num):
  326. now_chunk_size = chunk_size
  327. if remain_wavs > 0:
  328. now_chunk_size = chunk_size + 1
  329. remain_wavs = remain_wavs - 1
  330. # process i handle wavs at chunk_begin and size of now_chunk_size
  331. p = Process(target=one_thread, args=(i, chunk_begin, now_chunk_size))
  332. chunk_begin = chunk_begin + now_chunk_size
  333. p.start()
  334. process_list.append(p)
  335. for i in process_list:
  336. p.join()
  337. print('end')