wss_srv_asr.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. import asyncio
  2. import json
  3. import websockets
  4. import time
  5. import logging
  6. import tracemalloc
  7. import numpy as np
  8. import ssl
  9. from parse_args import args
  10. from modelscope.pipelines import pipeline
  11. from modelscope.utils.constant import Tasks
  12. from modelscope.utils.logger import get_logger
  13. from funasr.runtime.python.onnxruntime.funasr_onnx.utils.frontend import load_bytes
  14. tracemalloc.start()
  15. logger = get_logger(log_level=logging.CRITICAL)
  16. logger.setLevel(logging.CRITICAL)
  17. websocket_users = set()
  18. print("model loading")
  19. # asr
  20. inference_pipeline_asr = pipeline(
  21. task=Tasks.auto_speech_recognition,
  22. model=args.asr_model,
  23. ngpu=args.ngpu,
  24. ncpu=args.ncpu,
  25. model_revision=None)
  26. # vad
  27. inference_pipeline_vad = pipeline(
  28. task=Tasks.voice_activity_detection,
  29. model=args.vad_model,
  30. model_revision=None,
  31. output_dir=None,
  32. batch_size=1,
  33. mode='online',
  34. ngpu=args.ngpu,
  35. ncpu=args.ncpu,
  36. )
  37. if args.punc_model != "":
  38. inference_pipeline_punc = pipeline(
  39. task=Tasks.punctuation,
  40. model=args.punc_model,
  41. model_revision="v1.0.2",
  42. ngpu=args.ngpu,
  43. ncpu=args.ncpu,
  44. )
  45. else:
  46. inference_pipeline_punc = None
  47. inference_pipeline_asr_online = pipeline(
  48. task=Tasks.auto_speech_recognition,
  49. model=args.asr_model_online,
  50. ngpu=args.ngpu,
  51. ncpu=args.ncpu,
  52. model_revision='v1.0.4',
  53. update_model='v1.0.4',
  54. mode='paraformer_streaming')
  55. print("model loaded! only support one client at the same time now!!!!")
  56. async def ws_reset(websocket):
  57. print("ws reset now, total num is ",len(websocket_users))
  58. websocket.param_dict_asr_online = {"cache": dict()}
  59. websocket.param_dict_vad = {'in_cache': dict(), "is_final": True}
  60. websocket.param_dict_asr_online["is_final"]=True
  61. audio_in=b''.join(np.zeros(int(16000),dtype=np.int16))
  62. inference_pipeline_vad(audio_in=audio_in, param_dict=websocket.param_dict_vad)
  63. inference_pipeline_asr_online(audio_in=audio_in, param_dict=websocket.param_dict_asr_online)
  64. await websocket.close()
  65. async def clear_websocket():
  66. for websocket in websocket_users:
  67. await ws_reset(websocket)
  68. websocket_users.clear()
  69. async def ws_serve(websocket, path):
  70. frames = []
  71. frames_asr = []
  72. frames_asr_online = []
  73. global websocket_users
  74. await clear_websocket()
  75. websocket_users.add(websocket)
  76. websocket.param_dict_asr = {}
  77. websocket.param_dict_asr_online = {"cache": dict()}
  78. websocket.param_dict_vad = {'in_cache': dict(), "is_final": False}
  79. websocket.param_dict_punc = {'cache': list()}
  80. websocket.vad_pre_idx = 0
  81. speech_start = False
  82. speech_end_i = False
  83. websocket.wav_name = "microphone"
  84. websocket.mode = "2pass"
  85. print("new user connected", flush=True)
  86. try:
  87. async for message in websocket:
  88. if isinstance(message, str):
  89. messagejson = json.loads(message)
  90. if "is_speaking" in messagejson:
  91. websocket.is_speaking = messagejson["is_speaking"]
  92. websocket.param_dict_asr_online["is_final"] = not websocket.is_speaking
  93. if "chunk_interval" in messagejson:
  94. websocket.chunk_interval = messagejson["chunk_interval"]
  95. if "wav_name" in messagejson:
  96. websocket.wav_name = messagejson.get("wav_name")
  97. if "chunk_size" in messagejson:
  98. websocket.param_dict_asr_online["chunk_size"] = messagejson["chunk_size"]
  99. if "mode" in messagejson:
  100. websocket.mode = messagejson["mode"]
  101. if len(frames_asr_online) > 0 or len(frames_asr) > 0 or not isinstance(message, str):
  102. if not isinstance(message, str):
  103. frames.append(message)
  104. duration_ms = len(message)//32
  105. websocket.vad_pre_idx += duration_ms
  106. # asr online
  107. frames_asr_online.append(message)
  108. websocket.param_dict_asr_online["is_final"] = speech_end_i
  109. if len(frames_asr_online) % websocket.chunk_interval == 0 or websocket.param_dict_asr_online["is_final"]:
  110. if websocket.mode == "2pass" or websocket.mode == "online":
  111. audio_in = b"".join(frames_asr_online)
  112. await async_asr_online(websocket, audio_in)
  113. frames_asr_online = []
  114. if speech_start:
  115. frames_asr.append(message)
  116. # vad online
  117. speech_start_i, speech_end_i = await async_vad(websocket, message)
  118. if speech_start_i:
  119. speech_start = True
  120. beg_bias = (websocket.vad_pre_idx-speech_start_i)//duration_ms
  121. frames_pre = frames[-beg_bias:]
  122. frames_asr = []
  123. frames_asr.extend(frames_pre)
  124. # asr punc offline
  125. if speech_end_i or not websocket.is_speaking:
  126. # print("vad end point")
  127. if websocket.mode == "2pass" or websocket.mode == "offline":
  128. audio_in = b"".join(frames_asr)
  129. await async_asr(websocket, audio_in)
  130. frames_asr = []
  131. speech_start = False
  132. # frames_asr_online = []
  133. # websocket.param_dict_asr_online = {"cache": dict()}
  134. if not websocket.is_speaking:
  135. websocket.vad_pre_idx = 0
  136. frames = []
  137. websocket.param_dict_vad = {'in_cache': dict()}
  138. else:
  139. frames = frames[-20:]
  140. except websockets.ConnectionClosed:
  141. print("ConnectionClosed...", websocket_users,flush=True)
  142. await ws_reset(websocket)
  143. websocket_users.remove(websocket)
  144. except websockets.InvalidState:
  145. print("InvalidState...")
  146. except Exception as e:
  147. print("Exception:", e)
  148. async def async_vad(websocket, audio_in):
  149. segments_result = inference_pipeline_vad(audio_in=audio_in, param_dict=websocket.param_dict_vad)
  150. speech_start = False
  151. speech_end = False
  152. if len(segments_result) == 0 or len(segments_result["text"]) > 1:
  153. return speech_start, speech_end
  154. if segments_result["text"][0][0] != -1:
  155. speech_start = segments_result["text"][0][0]
  156. if segments_result["text"][0][1] != -1:
  157. speech_end = True
  158. return speech_start, speech_end
  159. async def async_asr(websocket, audio_in):
  160. if len(audio_in) > 0:
  161. # print(len(audio_in))
  162. audio_in = load_bytes(audio_in)
  163. rec_result = inference_pipeline_asr(audio_in=audio_in,
  164. param_dict=websocket.param_dict_asr)
  165. # print(rec_result)
  166. if inference_pipeline_punc is not None and 'text' in rec_result and len(rec_result["text"])>0:
  167. rec_result = inference_pipeline_punc(text_in=rec_result['text'],
  168. param_dict=websocket.param_dict_punc)
  169. # print("offline", rec_result)
  170. if 'text' in rec_result:
  171. message = json.dumps({"mode": "2pass-offline", "text": rec_result["text"], "wav_name": websocket.wav_name})
  172. await websocket.send(message)
  173. async def async_asr_online(websocket, audio_in):
  174. if len(audio_in) > 0:
  175. audio_in = load_bytes(audio_in)
  176. # print(websocket.param_dict_asr_online.get("is_final", False))
  177. rec_result = inference_pipeline_asr_online(audio_in=audio_in,
  178. param_dict=websocket.param_dict_asr_online)
  179. # print(rec_result)
  180. if websocket.mode == "2pass" and websocket.param_dict_asr_online.get("is_final", False):
  181. return
  182. # websocket.param_dict_asr_online["cache"] = dict()
  183. if "text" in rec_result:
  184. if rec_result["text"] != "sil" and rec_result["text"] != "waiting_for_more_voice":
  185. # print("online", rec_result)
  186. message = json.dumps({"mode": "2pass-online", "text": rec_result["text"], "wav_name": websocket.wav_name})
  187. await websocket.send(message)
  188. if len(args.certfile)>0:
  189. ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
  190. # Generate with Lets Encrypt, copied to this location, chown to current user and 400 permissions
  191. ssl_cert = args.certfile
  192. ssl_key = args.keyfile
  193. ssl_context.load_cert_chain(ssl_cert, keyfile=ssl_key)
  194. start_server = websockets.serve(ws_serve, args.host, args.port, subprotocols=["binary"], ping_interval=None,ssl=ssl_context)
  195. else:
  196. start_server = websockets.serve(ws_serve, args.host, args.port, subprotocols=["binary"], ping_interval=None)
  197. asyncio.get_event_loop().run_until_complete(start_server)
  198. asyncio.get_event_loop().run_forever()