ws_server_2pass.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. import asyncio
  2. import json
  3. import websockets
  4. import time
  5. import logging
  6. import tracemalloc
  7. import numpy as np
  8. from parse_args import args
  9. from modelscope.pipelines import pipeline
  10. from modelscope.utils.constant import Tasks
  11. from modelscope.utils.logger import get_logger
  12. from funasr.runtime.python.onnxruntime.funasr_onnx.utils.frontend import load_bytes
  13. tracemalloc.start()
  14. logger = get_logger(log_level=logging.CRITICAL)
  15. logger.setLevel(logging.CRITICAL)
  16. websocket_users = set()
  17. print("model loading")
  18. # asr
  19. inference_pipeline_asr = pipeline(
  20. task=Tasks.auto_speech_recognition,
  21. model=args.asr_model,
  22. ngpu=args.ngpu,
  23. ncpu=args.ncpu,
  24. model_revision=None)
  25. # vad
  26. inference_pipeline_vad = pipeline(
  27. task=Tasks.voice_activity_detection,
  28. model=args.vad_model,
  29. model_revision=None,
  30. output_dir=None,
  31. batch_size=1,
  32. mode='online',
  33. ngpu=args.ngpu,
  34. ncpu=args.ncpu,
  35. )
  36. if args.punc_model != "":
  37. inference_pipeline_punc = pipeline(
  38. task=Tasks.punctuation,
  39. model=args.punc_model,
  40. model_revision=None,
  41. ngpu=args.ngpu,
  42. ncpu=args.ncpu,
  43. )
  44. else:
  45. inference_pipeline_punc = None
  46. inference_pipeline_asr_online = pipeline(
  47. task=Tasks.auto_speech_recognition,
  48. model=args.asr_model_online,
  49. ngpu=args.ngpu,
  50. ncpu=args.ncpu,
  51. model_revision='v1.0.4')
  52. print("model loaded")
  53. async def ws_serve(websocket, path):
  54. frames = []
  55. frames_asr = []
  56. frames_asr_online = []
  57. global websocket_users
  58. websocket_users.add(websocket)
  59. websocket.param_dict_asr = {}
  60. websocket.param_dict_asr_online = {"cache": dict()}
  61. websocket.param_dict_vad = {'in_cache': dict(), "is_final": False}
  62. websocket.param_dict_punc = {'cache': list()}
  63. websocket.vad_pre_idx = 0
  64. speech_start = False
  65. try:
  66. async for message in websocket:
  67. message = json.loads(message)
  68. is_finished = message["is_finished"]
  69. if not is_finished:
  70. audio = bytes(message['audio'], 'ISO-8859-1')
  71. frames.append(audio)
  72. duration_ms = len(audio)//32
  73. websocket.vad_pre_idx += duration_ms
  74. is_speaking = message["is_speaking"]
  75. websocket.param_dict_vad["is_final"] = not is_speaking
  76. websocket.param_dict_asr_online["is_final"] = not is_speaking
  77. websocket.param_dict_asr_online["chunk_size"] = message["chunk_size"]
  78. websocket.wav_name = message.get("wav_name", "demo")
  79. # asr online
  80. frames_asr_online.append(audio)
  81. if len(frames_asr_online) % message["chunk_interval"] == 0:
  82. audio_in = b"".join(frames_asr_online)
  83. await async_asr_online(websocket, audio_in)
  84. frames_asr_online = []
  85. if speech_start:
  86. frames_asr.append(audio)
  87. # vad online
  88. speech_start_i, speech_end_i = await async_vad(websocket, audio)
  89. if speech_start_i:
  90. speech_start = True
  91. beg_bias = (websocket.vad_pre_idx-speech_start_i)//duration_ms
  92. frames_pre = frames[-beg_bias:]
  93. frames_asr = []
  94. frames_asr.extend(frames_pre)
  95. # asr punc offline
  96. if speech_end_i or not is_speaking:
  97. audio_in = b"".join(frames_asr)
  98. await async_asr(websocket, audio_in)
  99. frames_asr = []
  100. speech_start = False
  101. frames_asr_online = []
  102. websocket.param_dict_asr_online = {"cache": dict()}
  103. if not is_speaking:
  104. websocket.vad_pre_idx = 0
  105. frames = []
  106. websocket.param_dict_vad = {'in_cache': dict()}
  107. else:
  108. frames = frames[-20:]
  109. except websockets.ConnectionClosed:
  110. print("ConnectionClosed...", websocket_users)
  111. websocket_users.remove(websocket)
  112. except websockets.InvalidState:
  113. print("InvalidState...")
  114. except Exception as e:
  115. print("Exception:", e)
  116. async def async_vad(websocket, audio_in):
  117. segments_result = inference_pipeline_vad(audio_in=audio_in, param_dict=websocket.param_dict_vad)
  118. speech_start = False
  119. speech_end = False
  120. if len(segments_result) == 0 or len(segments_result["text"]) > 1:
  121. return speech_start, speech_end
  122. if segments_result["text"][0][0] != -1:
  123. speech_start = segments_result["text"][0][0]
  124. if segments_result["text"][0][1] != -1:
  125. speech_end = True
  126. return speech_start, speech_end
  127. async def async_asr(websocket, audio_in):
  128. if len(audio_in) > 0:
  129. # print(len(audio_in))
  130. audio_in = load_bytes(audio_in)
  131. rec_result = inference_pipeline_asr(audio_in=audio_in,
  132. param_dict=websocket.param_dict_asr)
  133. # print(rec_result)
  134. if inference_pipeline_punc is not None and 'text' in rec_result and len(rec_result["text"])>0:
  135. rec_result = inference_pipeline_punc(text_in=rec_result['text'],
  136. param_dict=websocket.param_dict_punc)
  137. # print("offline", rec_result)
  138. message = json.dumps({"mode": "2pass-offline", "text": rec_result["text"], "wav_name": websocket.wav_name})
  139. await websocket.send(message)
  140. async def async_asr_online(websocket, audio_in):
  141. if len(audio_in) > 0:
  142. audio_in = load_bytes(audio_in)
  143. rec_result = inference_pipeline_asr_online(audio_in=audio_in,
  144. param_dict=websocket.param_dict_asr_online)
  145. if websocket.param_dict_asr_online["is_final"]:
  146. websocket.param_dict_asr_online["cache"] = dict()
  147. if "text" in rec_result:
  148. if rec_result["text"] != "sil" and rec_result["text"] != "waiting_for_more_voice":
  149. # print("online", rec_result)
  150. message = json.dumps({"mode": "2pass-online", "text": rec_result["text"], "wav_name": websocket.wav_name})
  151. await websocket.send(message)
  152. start_server = websockets.serve(ws_serve, args.host, args.port, subprotocols=["binary"], ping_interval=None)
  153. asyncio.get_event_loop().run_until_complete(start_server)
  154. asyncio.get_event_loop().run_forever()