wss_srv_asr.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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.6',
  53. mode='paraformer_streaming')
  54. print("model loaded")
  55. async def ws_serve(websocket, path):
  56. frames = []
  57. frames_asr = []
  58. frames_asr_online = []
  59. global websocket_users
  60. websocket_users.add(websocket)
  61. websocket.param_dict_asr = {}
  62. websocket.param_dict_asr_online = {"cache": dict()}
  63. websocket.param_dict_vad = {'in_cache': dict(), "is_final": False}
  64. websocket.param_dict_punc = {'cache': list()}
  65. websocket.vad_pre_idx = 0
  66. speech_start = False
  67. speech_end_i = False
  68. websocket.wav_name = "microphone"
  69. websocket.mode = "2pass"
  70. print("new user connected", flush=True)
  71. try:
  72. async for message in websocket:
  73. if isinstance(message, str):
  74. messagejson = json.loads(message)
  75. if "is_speaking" in messagejson:
  76. websocket.is_speaking = messagejson["is_speaking"]
  77. websocket.param_dict_asr_online["is_final"] = not websocket.is_speaking
  78. if "chunk_interval" in messagejson:
  79. websocket.chunk_interval = messagejson["chunk_interval"]
  80. if "wav_name" in messagejson:
  81. websocket.wav_name = messagejson.get("wav_name")
  82. if "chunk_size" in messagejson:
  83. websocket.param_dict_asr_online["chunk_size"] = messagejson["chunk_size"]
  84. if "mode" in messagejson:
  85. websocket.mode = messagejson["mode"]
  86. if len(frames_asr_online) > 0 or len(frames_asr) > 0 or not isinstance(message, str):
  87. if not isinstance(message, str):
  88. frames.append(message)
  89. duration_ms = len(message)//32
  90. websocket.vad_pre_idx += duration_ms
  91. # asr online
  92. frames_asr_online.append(message)
  93. websocket.param_dict_asr_online["is_final"] = speech_end_i
  94. if len(frames_asr_online) % websocket.chunk_interval == 0 or websocket.param_dict_asr_online["is_final"]:
  95. if websocket.mode == "2pass" or websocket.mode == "online":
  96. audio_in = b"".join(frames_asr_online)
  97. await async_asr_online(websocket, audio_in)
  98. frames_asr_online = []
  99. if speech_start:
  100. frames_asr.append(message)
  101. # vad online
  102. speech_start_i, speech_end_i = await async_vad(websocket, message)
  103. if speech_start_i:
  104. speech_start = True
  105. beg_bias = (websocket.vad_pre_idx-speech_start_i)//duration_ms
  106. frames_pre = frames[-beg_bias:]
  107. frames_asr = []
  108. frames_asr.extend(frames_pre)
  109. # asr punc offline
  110. if speech_end_i or not websocket.is_speaking:
  111. # print("vad end point")
  112. if websocket.mode == "2pass" or websocket.mode == "offline":
  113. audio_in = b"".join(frames_asr)
  114. await async_asr(websocket, audio_in)
  115. frames_asr = []
  116. speech_start = False
  117. # frames_asr_online = []
  118. # websocket.param_dict_asr_online = {"cache": dict()}
  119. if not websocket.is_speaking:
  120. websocket.vad_pre_idx = 0
  121. frames = []
  122. websocket.param_dict_vad = {'in_cache': dict()}
  123. else:
  124. frames = frames[-20:]
  125. except websockets.ConnectionClosed:
  126. print("ConnectionClosed...", websocket_users)
  127. websocket_users.remove(websocket)
  128. except websockets.InvalidState:
  129. print("InvalidState...")
  130. except Exception as e:
  131. print("Exception:", e)
  132. async def async_vad(websocket, audio_in):
  133. segments_result = inference_pipeline_vad(audio_in=audio_in, param_dict=websocket.param_dict_vad)
  134. speech_start = False
  135. speech_end = False
  136. if len(segments_result) == 0 or len(segments_result["text"]) > 1:
  137. return speech_start, speech_end
  138. if segments_result["text"][0][0] != -1:
  139. speech_start = segments_result["text"][0][0]
  140. if segments_result["text"][0][1] != -1:
  141. speech_end = True
  142. return speech_start, speech_end
  143. async def async_asr(websocket, audio_in):
  144. if len(audio_in) > 0:
  145. # print(len(audio_in))
  146. audio_in = load_bytes(audio_in)
  147. rec_result = inference_pipeline_asr(audio_in=audio_in,
  148. param_dict=websocket.param_dict_asr)
  149. # print(rec_result)
  150. if inference_pipeline_punc is not None and 'text' in rec_result and len(rec_result["text"])>0:
  151. rec_result = inference_pipeline_punc(text_in=rec_result['text'],
  152. param_dict=websocket.param_dict_punc)
  153. # print("offline", rec_result)
  154. if 'text' in rec_result:
  155. message = json.dumps({"mode": "2pass-offline", "text": rec_result["text"], "wav_name": websocket.wav_name})
  156. await websocket.send(message)
  157. async def async_asr_online(websocket, audio_in):
  158. if len(audio_in) > 0:
  159. audio_in = load_bytes(audio_in)
  160. # print(websocket.param_dict_asr_online.get("is_final", False))
  161. rec_result = inference_pipeline_asr_online(audio_in=audio_in,
  162. param_dict=websocket.param_dict_asr_online)
  163. # print(rec_result)
  164. if websocket.mode == "2pass" and websocket.param_dict_asr_online.get("is_final", False):
  165. return
  166. # websocket.param_dict_asr_online["cache"] = dict()
  167. if "text" in rec_result:
  168. if rec_result["text"] != "sil" and rec_result["text"] != "waiting_for_more_voice":
  169. # print("online", rec_result)
  170. message = json.dumps({"mode": "2pass-online", "text": rec_result["text"], "wav_name": websocket.wav_name})
  171. await websocket.send(message)
  172. if len(args.certfile)>0:
  173. ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
  174. # Generate with Lets Encrypt, copied to this location, chown to current user and 400 permissions
  175. ssl_cert = args.certfile
  176. ssl_key = args.keyfile
  177. ssl_context.load_cert_chain(ssl_cert, keyfile=ssl_key)
  178. start_server = websockets.serve(ws_serve, args.host, args.port, subprotocols=["binary"], ping_interval=None,ssl=ssl_context)
  179. else:
  180. start_server = websockets.serve(ws_serve, args.host, args.port, subprotocols=["binary"], ping_interval=None)
  181. asyncio.get_event_loop().run_until_complete(start_server)
  182. asyncio.get_event_loop().run_forever()