ws_server_offline.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  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. print("model loaded")
  47. async def ws_serve(websocket, path):
  48. frames = []
  49. frames_asr = []
  50. global websocket_users
  51. websocket_users.add(websocket)
  52. websocket.param_dict_asr = {}
  53. websocket.param_dict_vad = {'in_cache': dict(), "is_final": False}
  54. websocket.param_dict_punc = {'cache': list()}
  55. websocket.vad_pre_idx = 0
  56. speech_start = False
  57. try:
  58. async for message in websocket:
  59. message = json.loads(message)
  60. is_finished = message["is_finished"]
  61. if not is_finished:
  62. audio = bytes(message['audio'], 'ISO-8859-1')
  63. frames.append(audio)
  64. duration_ms = len(audio)//32
  65. websocket.vad_pre_idx += duration_ms
  66. is_speaking = message["is_speaking"]
  67. websocket.param_dict_vad["is_final"] = not is_speaking
  68. websocket.wav_name = message.get("wav_name", "demo")
  69. if speech_start:
  70. frames_asr.append(audio)
  71. speech_start_i, speech_end_i = await async_vad(websocket, audio)
  72. if speech_start_i:
  73. speech_start = True
  74. beg_bias = (websocket.vad_pre_idx-speech_start_i)//duration_ms
  75. frames_pre = frames[-beg_bias:]
  76. frames_asr = []
  77. frames_asr.extend(frames_pre)
  78. if speech_end_i or not is_speaking:
  79. audio_in = b"".join(frames_asr)
  80. await async_asr(websocket, audio_in)
  81. frames_asr = []
  82. speech_start = False
  83. if not is_speaking:
  84. websocket.vad_pre_idx = 0
  85. frames = []
  86. else:
  87. frames = frames[-10:]
  88. except websockets.ConnectionClosed:
  89. print("ConnectionClosed...", websocket_users)
  90. websocket_users.remove(websocket)
  91. except websockets.InvalidState:
  92. print("InvalidState...")
  93. except Exception as e:
  94. print("Exception:", e)
  95. async def async_vad(websocket, audio_in):
  96. segments_result = inference_pipeline_vad(audio_in=audio_in, param_dict=websocket.param_dict_vad)
  97. speech_start = False
  98. speech_end = False
  99. if len(segments_result) == 0 or len(segments_result["text"]) > 1:
  100. return speech_start, speech_end
  101. if segments_result["text"][0][0] != -1:
  102. speech_start = segments_result["text"][0][0]
  103. if segments_result["text"][0][1] != -1:
  104. speech_end = True
  105. return speech_start, speech_end
  106. async def async_asr(websocket, audio_in):
  107. if len(audio_in) > 0:
  108. # print(len(audio_in))
  109. audio_in = load_bytes(audio_in)
  110. rec_result = inference_pipeline_asr(audio_in=audio_in,
  111. param_dict=websocket.param_dict_asr)
  112. # print(rec_result)
  113. if inference_pipeline_punc is not None and 'text' in rec_result and len(rec_result["text"])>0:
  114. rec_result = inference_pipeline_punc(text_in=rec_result['text'],
  115. param_dict=websocket.param_dict_punc)
  116. # print(rec_result)
  117. message = json.dumps({"mode": "offline", "text": [rec_result["text"]], "wav_name": websocket.wav_name})
  118. await websocket.send(message)
  119. start_server = websockets.serve(ws_serve, args.host, args.port, subprotocols=["binary"], ping_interval=None)
  120. asyncio.get_event_loop().run_until_complete(start_server)
  121. asyncio.get_event_loop().run_forever()