wss_srv_asr.py 9.0 KB

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