funasr_wss_client.py 13 KB

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