stt_server.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  1. """
  2. Speech-to-Text (STT) Server with Real-Time Transcription and WebSocket Interface
  3. This server provides real-time speech-to-text (STT) transcription using the RealtimeSTT library. It allows clients to connect via WebSocket to send audio data and receive real-time transcription updates. The server supports configurable audio recording parameters, voice activity detection (VAD), and wake word detection. It is designed to handle continuous transcription as well as post-recording processing, enabling real-time feedback with the option to improve final transcription quality after the complete sentence is recognized.
  4. ### Features:
  5. - Real-time transcription using pre-configured or user-defined STT models.
  6. - WebSocket-based communication for control and data handling.
  7. - Flexible recording and transcription options, including configurable pauses for sentence detection.
  8. - Supports Silero and WebRTC VAD for robust voice activity detection.
  9. ### Starting the Server:
  10. You can start the server using the command-line interface (CLI) command `stt-server`, passing the desired configuration options.
  11. ```bash
  12. stt-server [OPTIONS]
  13. ```
  14. ### Available Parameters:
  15. - `-m, --model`: Model path or size; default 'large-v2'.
  16. - `-r, --rt-model, --realtime_model_type`: Real-time model size; default 'tiny.en'.
  17. - `-l, --lang, --language`: Language code for transcription; default 'en'.
  18. - `-i, --input-device, --input_device_index`: Audio input device index; default 1.
  19. - `-c, --control, --control_port`: WebSocket control port; default 8011.
  20. - `-d, --data, --data_port`: WebSocket data port; default 8012.
  21. - `-w, --wake_words`: Wake word(s) to trigger listening; default "".
  22. - `-D, --debug`: Enable debug logging.
  23. - `-W, --write`: Save audio to WAV file.
  24. - `--silero_sensitivity`: Silero VAD sensitivity (0-1); default 0.05.
  25. - `--silero_use_onnx`: Use Silero ONNX model; default False.
  26. - `--webrtc_sensitivity`: WebRTC VAD sensitivity (0-3); default 3.
  27. - `--min_length_of_recording`: Minimum recording duration in seconds; default 1.1.
  28. - `--min_gap_between_recordings`: Min time between recordings in seconds; default 0.
  29. - `--enable_realtime_transcription`: Enable real-time transcription; default True.
  30. - `--realtime_processing_pause`: Pause between audio chunk processing; default 0.02.
  31. - `--silero_deactivity_detection`: Use Silero for end-of-speech detection; default True.
  32. - `--early_transcription_on_silence`: Start transcription after silence in seconds; default 0.2.
  33. - `--beam_size`: Beam size for main model; default 5.
  34. - `--beam_size_realtime`: Beam size for real-time model; default 3.
  35. - `--initial_prompt`: Initial transcription guidance prompt.
  36. - `--end_of_sentence_detection_pause`: Silence duration for sentence end detection; default 0.45.
  37. - `--unknown_sentence_detection_pause`: Pause duration for incomplete sentence detection; default 0.7.
  38. - `--mid_sentence_detection_pause`: Pause for mid-sentence break; default 2.0.
  39. - `--wake_words_sensitivity`: Wake word detection sensitivity (0-1); default 0.5.
  40. - `--wake_word_timeout`: Wake word timeout in seconds; default 5.0.
  41. - `--wake_word_activation_delay`: Delay before wake word activation; default 20.
  42. - `--wakeword_backend`: Backend for wake word detection; default 'none'.
  43. - `--openwakeword_model_paths`: Paths to OpenWakeWord models.
  44. - `--openwakeword_inference_framework`: OpenWakeWord inference framework; default 'tensorflow'.
  45. - `--wake_word_buffer_duration`: Wake word buffer duration in seconds; default 1.0.
  46. - `--use_main_model_for_realtime`: Use main model for real-time transcription.
  47. - `--use_extended_logging`: Enable extensive log messages.
  48. - `--logchunks`: Log incoming audio chunks.
  49. ### WebSocket Interface:
  50. The server supports two WebSocket connections:
  51. 1. **Control WebSocket**: Used to send and receive commands, such as setting parameters or calling recorder methods.
  52. 2. **Data WebSocket**: Used to send audio data for transcription and receive real-time transcription updates.
  53. The server will broadcast real-time transcription updates to all connected clients on the data WebSocket.
  54. """
  55. from .install_packages import check_and_install_packages
  56. from datetime import datetime
  57. import logging
  58. import asyncio
  59. import pyaudio
  60. import sys
  61. debug_logging = False
  62. extended_logging = False
  63. send_recorded_chunk = False
  64. log_incoming_chunks = False
  65. stt_optimizations = False
  66. writechunks = False#
  67. wav_file = None
  68. loglevel = logging.WARNING
  69. FORMAT = pyaudio.paInt16
  70. CHANNELS = 1
  71. if sys.platform == 'win32':
  72. asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
  73. check_and_install_packages([
  74. {
  75. 'module_name': 'RealtimeSTT', # Import module
  76. 'attribute': 'AudioToTextRecorder', # Specific class to check
  77. 'install_name': 'RealtimeSTT', # Package name for pip install
  78. },
  79. {
  80. 'module_name': 'websockets', # Import module
  81. 'install_name': 'websockets', # Package name for pip install
  82. },
  83. {
  84. 'module_name': 'numpy', # Import module
  85. 'install_name': 'numpy', # Package name for pip install
  86. },
  87. {
  88. 'module_name': 'scipy.signal', # Submodule of scipy
  89. 'attribute': 'resample', # Specific function to check
  90. 'install_name': 'scipy', # Package name for pip install
  91. }
  92. ])
  93. # Define ANSI color codes for terminal output
  94. class bcolors:
  95. HEADER = '\033[95m' # Magenta
  96. OKBLUE = '\033[94m' # Blue
  97. OKCYAN = '\033[96m' # Cyan
  98. OKGREEN = '\033[92m' # Green
  99. WARNING = '\033[93m' # Yellow
  100. FAIL = '\033[91m' # Red
  101. ENDC = '\033[0m' # Reset to default
  102. BOLD = '\033[1m'
  103. UNDERLINE = '\033[4m'
  104. print(f"{bcolors.BOLD}{bcolors.OKCYAN}Starting server, please wait...{bcolors.ENDC}")
  105. # Initialize colorama
  106. from colorama import init, Fore, Style
  107. init()
  108. from RealtimeSTT import AudioToTextRecorder
  109. from scipy.signal import resample
  110. import numpy as np
  111. import websockets
  112. import threading
  113. import logging
  114. import wave
  115. import json
  116. import time
  117. global_args = None
  118. recorder = None
  119. recorder_config = {}
  120. recorder_ready = threading.Event()
  121. recorder_thread = None
  122. stop_recorder = False
  123. prev_text = ""
  124. # Define allowed methods and parameters for security
  125. allowed_methods = [
  126. 'set_microphone',
  127. 'abort',
  128. 'stop',
  129. 'clear_audio_queue',
  130. 'wakeup',
  131. 'shutdown',
  132. 'text',
  133. ]
  134. allowed_parameters = [
  135. 'silero_sensitivity',
  136. 'wake_word_activation_delay',
  137. 'post_speech_silence_duration',
  138. 'listen_start',
  139. 'recording_stop_time',
  140. 'last_transcription_bytes',
  141. 'last_transcription_bytes_b64',
  142. ]
  143. # Queues and connections for control and data
  144. control_connections = set()
  145. data_connections = set()
  146. control_queue = asyncio.Queue()
  147. audio_queue = asyncio.Queue()
  148. def preprocess_text(text):
  149. # Remove leading whitespaces
  150. text = text.lstrip()
  151. # Remove starting ellipses if present
  152. if text.startswith("..."):
  153. text = text[3:]
  154. # Remove any leading whitespaces again after ellipses removal
  155. text = text.lstrip()
  156. # Uppercase the first letter
  157. if text:
  158. text = text[0].upper() + text[1:]
  159. return text
  160. def debug_print(message):
  161. if debug_logging:
  162. timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  163. thread_name = threading.current_thread().name
  164. print(f"{Fore.CYAN}[DEBUG][{timestamp}][{thread_name}] {message}{Style.RESET_ALL}", file=sys.stderr)
  165. def text_detected(text, loop):
  166. global prev_text
  167. text = preprocess_text(text)
  168. if stt_optimizations:
  169. sentence_end_marks = ['.', '!', '?', '。']
  170. if text.endswith("..."):
  171. recorder.post_speech_silence_duration = global_args.mid_sentence_detection_pause
  172. elif text and text[-1] in sentence_end_marks and prev_text and prev_text[-1] in sentence_end_marks:
  173. recorder.post_speech_silence_duration = global_args.end_of_sentence_detection_pause
  174. else:
  175. recorder.post_speech_silence_duration = global_args.unknown_sentence_detection_pause
  176. prev_text = text
  177. # Put the message in the audio queue to be sent to clients
  178. message = json.dumps({
  179. 'type': 'realtime',
  180. 'text': text
  181. })
  182. asyncio.run_coroutine_threadsafe(audio_queue.put(message), loop)
  183. # Get current timestamp in HH:MM:SS.nnn format
  184. timestamp = datetime.now().strftime('%H:%M:%S.%f')[:-3]
  185. if extended_logging:
  186. print(f" [{timestamp}] Realtime text: {bcolors.OKCYAN}{text}{bcolors.ENDC}\n", flush=True, end="")
  187. else:
  188. print(f"\r[{timestamp}] {bcolors.OKCYAN}{text}{bcolors.ENDC}", flush=True, end='')
  189. def on_recording_start(loop):
  190. # Send a message to the client indicating recording has started
  191. message = json.dumps({
  192. 'type': 'recording_start'
  193. })
  194. asyncio.run_coroutine_threadsafe(audio_queue.put(message), loop)
  195. def on_recording_stop(loop):
  196. # Send a message to the client indicating recording has stopped
  197. message = json.dumps({
  198. 'type': 'recording_stop'
  199. })
  200. asyncio.run_coroutine_threadsafe(audio_queue.put(message), loop)
  201. def on_vad_detect_start(loop):
  202. message = json.dumps({
  203. 'type': 'vad_detect_start'
  204. })
  205. asyncio.run_coroutine_threadsafe(audio_queue.put(message), loop)
  206. def on_vad_detect_stop(loop):
  207. message = json.dumps({
  208. 'type': 'vad_detect_stop'
  209. })
  210. asyncio.run_coroutine_threadsafe(audio_queue.put(message), loop)
  211. def on_wakeword_detected(loop):
  212. # Send a message to the client when wake word detection starts
  213. message = json.dumps({
  214. 'type': 'wakeword_detected'
  215. })
  216. asyncio.run_coroutine_threadsafe(audio_queue.put(message), loop)
  217. def on_wakeword_detection_start(loop):
  218. # Send a message to the client when wake word detection starts
  219. message = json.dumps({
  220. 'type': 'wakeword_detection_start'
  221. })
  222. asyncio.run_coroutine_threadsafe(audio_queue.put(message), loop)
  223. def on_wakeword_detection_end(loop):
  224. # Send a message to the client when wake word detection ends
  225. message = json.dumps({
  226. 'type': 'wakeword_detection_end'
  227. })
  228. asyncio.run_coroutine_threadsafe(audio_queue.put(message), loop)
  229. def on_transcription_start(loop):
  230. # Send a message to the client when transcription starts
  231. message = json.dumps({
  232. 'type': 'transcription_start'
  233. })
  234. asyncio.run_coroutine_threadsafe(audio_queue.put(message), loop)
  235. # def on_realtime_transcription_update(text, loop):
  236. # # Send real-time transcription updates to the client
  237. # text = preprocess_text(text)
  238. # message = json.dumps({
  239. # 'type': 'realtime_update',
  240. # 'text': text
  241. # })
  242. # asyncio.run_coroutine_threadsafe(audio_queue.put(message), loop)
  243. # def on_recorded_chunk(chunk, loop):
  244. # if send_recorded_chunk:
  245. # bytes_b64 = base64.b64encode(chunk.tobytes()).decode('utf-8')
  246. # message = json.dumps({
  247. # 'type': 'recorded_chunk',
  248. # 'bytes': bytes_b64
  249. # })
  250. # asyncio.run_coroutine_threadsafe(audio_queue.put(message), loop)
  251. # Define the server's arguments
  252. def parse_arguments():
  253. global debug_logging, extended_logging, loglevel, writechunks, log_incoming_chunks
  254. import argparse
  255. parser = argparse.ArgumentParser(description='Start the Speech-to-Text (STT) server with various configuration options.')
  256. parser.add_argument('-m', '--model', type=str, default='large-v2',
  257. help='Path to the STT model or model size. Options include: tiny, tiny.en, base, base.en, small, small.en, medium, medium.en, large-v1, large-v2, or any huggingface CTranslate2 STT model such as deepdml/faster-whisper-large-v3-turbo-ct2. Default is large-v2.')
  258. parser.add_argument('-r', '--rt-model', '--realtime_model_type', type=str, default='tiny.en',
  259. help='Model size for real-time transcription. Options same as --model. This is used only if real-time transcription is enabled (enable_realtime_transcription). Default is tiny.en.')
  260. parser.add_argument('-l', '--lang', '--language', type=str, default='en',
  261. help='Language code for the STT model to transcribe in a specific language. Leave this empty for auto-detection based on input audio. Default is en. List of supported language codes: https://github.com/openai/whisper/blob/main/whisper/tokenizer.py#L11-L110')
  262. parser.add_argument('-i', '--input-device', '--input_device_index', type=int, default=1,
  263. help='Index of the audio input device to use. Use this option to specify a particular microphone or audio input device based on your system. Default is 1.')
  264. parser.add_argument('-c', '--control', '--control_port', type=int, default=8011,
  265. help='The port number used for the control WebSocket connection. Control connections are used to send and receive commands to the server. Default is port 8011.')
  266. parser.add_argument('-d', '--data', '--data_port', type=int, default=8012,
  267. help='The port number used for the data WebSocket connection. Data connections are used to send audio data and receive transcription updates in real time. Default is port 8012.')
  268. parser.add_argument('-w', '--wake_words', type=str, default="",
  269. help='Specify the wake word(s) that will trigger the server to start listening. For example, setting this to "Jarvis" will make the system start transcribing when it detects the wake word "Jarvis". Default is "Jarvis".')
  270. parser.add_argument('-D', '--debug', action='store_true', help='Enable debug logging for detailed server operations')
  271. parser.add_argument("-W", "--write", metavar="FILE",
  272. help="Save received audio to a WAV file")
  273. parser.add_argument('--silero_sensitivity', type=float, default=0.05,
  274. help='Sensitivity level for Silero Voice Activity Detection (VAD), with a range from 0 to 1. Lower values make the model less sensitive, useful for noisy environments. Default is 0.05.')
  275. parser.add_argument('--silero_use_onnx', action='store_true', default=False,
  276. help='Enable ONNX version of Silero model for faster performance with lower resource usage. Default is False.')
  277. parser.add_argument('--webrtc_sensitivity', type=int, default=3,
  278. help='Sensitivity level for WebRTC Voice Activity Detection (VAD), with a range from 0 to 3. Higher values make the model less sensitive, useful for cleaner environments. Default is 3.')
  279. parser.add_argument('--min_length_of_recording', type=float, default=1.1,
  280. help='Minimum duration of valid recordings in seconds. This prevents very short recordings from being processed, which could be caused by noise or accidental sounds. Default is 1.1 seconds.')
  281. parser.add_argument('--min_gap_between_recordings', type=float, default=0,
  282. help='Minimum time (in seconds) between consecutive recordings. Setting this helps avoid overlapping recordings when there’s a brief silence between them. Default is 0 seconds.')
  283. parser.add_argument('--enable_realtime_transcription', action='store_true', default=True,
  284. help='Enable continuous real-time transcription of audio as it is received. When enabled, transcriptions are sent in near real-time. Default is True.')
  285. parser.add_argument('--realtime_processing_pause', type=float, default=0.02,
  286. help='Time interval (in seconds) between processing audio chunks for real-time transcription. Lower values increase responsiveness but may put more load on the CPU. Default is 0.02 seconds.')
  287. parser.add_argument('--silero_deactivity_detection', action='store_true', default=True,
  288. help='Use the Silero model for end-of-speech detection. This option can provide more robust silence detection in noisy environments, though it consumes more GPU resources. Default is True.')
  289. parser.add_argument('--early_transcription_on_silence', type=float, default=0.2,
  290. help='Start transcription after the specified seconds of silence. This is useful when you want to trigger transcription mid-speech when there is a brief pause. Should be lower than post_speech_silence_duration. Set to 0 to disable. Default is 0.2 seconds.')
  291. parser.add_argument('--beam_size', type=int, default=5,
  292. help='Beam size for the main transcription model. Larger values may improve transcription accuracy but increase the processing time. Default is 5.')
  293. parser.add_argument('--beam_size_realtime', type=int, default=3,
  294. help='Beam size for the real-time transcription model. A smaller beam size allows for faster real-time processing but may reduce accuracy. Default is 3.')
  295. parser.add_argument('--initial_prompt', type=str,
  296. default='End incomplete sentences with ellipses. Examples: Complete: The sky is blue. Incomplete: When the sky... Complete: She walked home. Incomplete: Because he...',
  297. help='Initial prompt that guides the transcription model to produce transcriptions in a particular style or format. The default provides instructions for handling sentence completions and ellipsis usage.')
  298. parser.add_argument('--end_of_sentence_detection_pause', type=float, default=0.45,
  299. help='The duration of silence (in seconds) that the model should interpret as the end of a sentence. This helps the system detect when to finalize the transcription of a sentence. Default is 0.45 seconds.')
  300. parser.add_argument('--unknown_sentence_detection_pause', type=float, default=0.7,
  301. help='The duration of pause (in seconds) that the model should interpret as an incomplete or unknown sentence. This is useful for identifying when a sentence is trailing off or unfinished. Default is 0.7 seconds.')
  302. parser.add_argument('--mid_sentence_detection_pause', type=float, default=2.0,
  303. help='The duration of pause (in seconds) that the model should interpret as a mid-sentence break. Longer pauses can indicate a pause in speech but not necessarily the end of a sentence. Default is 2.0 seconds.')
  304. parser.add_argument('--wake_words_sensitivity', type=float, default=0.5,
  305. help='Sensitivity level for wake word detection, with a range from 0 (most sensitive) to 1 (least sensitive). Adjust this value based on your environment to ensure reliable wake word detection. Default is 0.5.')
  306. parser.add_argument('--wake_word_timeout', type=float, default=5.0,
  307. help='Maximum time in seconds that the system will wait for a wake word before timing out. After this timeout, the system stops listening for wake words until reactivated. Default is 5.0 seconds.')
  308. parser.add_argument('--wake_word_activation_delay', type=float, default=20,
  309. help='The delay in seconds before the wake word detection is activated after the system starts listening. This prevents false positives during the start of a session. Default is 0.5 seconds.')
  310. parser.add_argument('--wakeword_backend', type=str, default='none',
  311. help='The backend used for wake word detection. You can specify different backends such as "default" or any custom implementations depending on your setup. Default is "pvporcupine".')
  312. parser.add_argument('--openwakeword_model_paths', type=str, nargs='*',
  313. help='A list of file paths to OpenWakeWord models. This is useful if you are using OpenWakeWord for wake word detection and need to specify custom models.')
  314. parser.add_argument('--openwakeword_inference_framework', type=str, default='tensorflow',
  315. help='The inference framework to use for OpenWakeWord models. Supported frameworks could include "tensorflow", "pytorch", etc. Default is "tensorflow".')
  316. parser.add_argument('--wake_word_buffer_duration', type=float, default=1.0,
  317. help='Duration of the buffer in seconds for wake word detection. This sets how long the system will store the audio before and after detecting the wake word. Default is 1.0 seconds.')
  318. parser.add_argument('--use_main_model_for_realtime', action='store_true',
  319. help='Enable this option if you want to use the main model for real-time transcription, instead of the smaller, faster real-time model. Using the main model may provide better accuracy but at the cost of higher processing time.')
  320. parser.add_argument('--use_extended_logging', action='store_true',
  321. help='Writes extensive log messages for the recording worker, that processes the audio chunks.')
  322. parser.add_argument('--logchunks', action='store_true', help='Enable logging of incoming audio chunks (periods)')
  323. # Parse arguments
  324. args = parser.parse_args()
  325. debug_logging = args.debug
  326. extended_logging = args.use_extended_logging
  327. writechunks = args.write
  328. log_incoming_chunks = args.logchunks
  329. if debug_logging:
  330. loglevel = logging.DEBUG
  331. logging.basicConfig(level=loglevel, format='[%(asctime)s] %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
  332. else:
  333. loglevel = logging.WARNING
  334. # Replace escaped newlines with actual newlines in initial_prompt
  335. if args.initial_prompt:
  336. args.initial_prompt = args.initial_prompt.replace("\\n", "\n")
  337. return args
  338. def _recorder_thread(loop):
  339. global recorder, prev_text, stop_recorder
  340. print(f"{bcolors.OKGREEN}Initializing RealtimeSTT server with parameters:{bcolors.ENDC}")
  341. for key, value in recorder_config.items():
  342. print(f" {bcolors.OKBLUE}{key}{bcolors.ENDC}: {value}")
  343. recorder = AudioToTextRecorder(**recorder_config)
  344. print(f"{bcolors.OKGREEN}{bcolors.BOLD}RealtimeSTT initialized{bcolors.ENDC}")
  345. recorder_ready.set()
  346. def process_text(full_sentence):
  347. full_sentence = preprocess_text(full_sentence)
  348. message = json.dumps({
  349. 'type': 'fullSentence',
  350. 'text': full_sentence
  351. })
  352. # Use the passed event loop here
  353. asyncio.run_coroutine_threadsafe(audio_queue.put(message), loop)
  354. timestamp = datetime.now().strftime('%H:%M:%S.%f')[:-3]
  355. if extended_logging:
  356. print(f" [{timestamp}] Full text: {bcolors.BOLD}Sentence:{bcolors.ENDC} {bcolors.OKGREEN}{full_sentence}{bcolors.ENDC}\n", flush=True, end="")
  357. else:
  358. print(f"\r[{timestamp}] {bcolors.BOLD}Sentence:{bcolors.ENDC} {bcolors.OKGREEN}{full_sentence}{bcolors.ENDC}\n")
  359. try:
  360. while not stop_recorder:
  361. recorder.text(process_text)
  362. except KeyboardInterrupt:
  363. print(f"{bcolors.WARNING}Exiting application due to keyboard interrupt{bcolors.ENDC}")
  364. def decode_and_resample(
  365. audio_data,
  366. original_sample_rate,
  367. target_sample_rate):
  368. # Decode 16-bit PCM data to numpy array
  369. if original_sample_rate == target_sample_rate:
  370. return audio_data
  371. audio_np = np.frombuffer(audio_data, dtype=np.int16)
  372. # Calculate the number of samples after resampling
  373. num_original_samples = len(audio_np)
  374. num_target_samples = int(num_original_samples * target_sample_rate /
  375. original_sample_rate)
  376. # Resample the audio
  377. resampled_audio = resample(audio_np, num_target_samples)
  378. return resampled_audio.astype(np.int16).tobytes()
  379. async def control_handler(websocket, path):
  380. debug_print(f"New control connection from {websocket.remote_address}")
  381. print(f"{bcolors.OKGREEN}Control client connected{bcolors.ENDC}")
  382. global recorder
  383. control_connections.add(websocket)
  384. try:
  385. async for message in websocket:
  386. debug_print(f"Received control message: {message[:200]}...")
  387. if not recorder_ready.is_set():
  388. print(f"{bcolors.WARNING}Recorder not ready{bcolors.ENDC}")
  389. continue
  390. if isinstance(message, str):
  391. # Handle text message (command)
  392. try:
  393. command_data = json.loads(message)
  394. command = command_data.get("command")
  395. if command == "set_parameter":
  396. parameter = command_data.get("parameter")
  397. value = command_data.get("value")
  398. if parameter in allowed_parameters and hasattr(recorder, parameter):
  399. setattr(recorder, parameter, value)
  400. # Format the value for output
  401. if isinstance(value, float):
  402. value_formatted = f"{value:.2f}"
  403. else:
  404. value_formatted = value
  405. timestamp = datetime.now().strftime('%H:%M:%S.%f')[:-3]
  406. if extended_logging:
  407. print(f" [{timestamp}] {bcolors.OKGREEN}Set recorder.{parameter} to: {bcolors.OKBLUE}{value_formatted}{bcolors.ENDC}")
  408. # Optionally send a response back to the client
  409. await websocket.send(json.dumps({"status": "success", "message": f"Parameter {parameter} set to {value}"}))
  410. else:
  411. if not parameter in allowed_parameters:
  412. print(f"{bcolors.WARNING}Parameter {parameter} is not allowed (set_parameter){bcolors.ENDC}")
  413. await websocket.send(json.dumps({"status": "error", "message": f"Parameter {parameter} is not allowed (set_parameter)"}))
  414. else:
  415. print(f"{bcolors.WARNING}Parameter {parameter} does not exist (set_parameter){bcolors.ENDC}")
  416. await websocket.send(json.dumps({"status": "error", "message": f"Parameter {parameter} does not exist (set_parameter)"}))
  417. elif command == "get_parameter":
  418. parameter = command_data.get("parameter")
  419. request_id = command_data.get("request_id") # Get the request_id from the command data
  420. if parameter in allowed_parameters and hasattr(recorder, parameter):
  421. value = getattr(recorder, parameter)
  422. if isinstance(value, float):
  423. value_formatted = f"{value:.2f}"
  424. else:
  425. value_formatted = f"{value}"
  426. value_truncated = value_formatted[:39] + "…" if len(value_formatted) > 40 else value_formatted
  427. timestamp = datetime.now().strftime('%H:%M:%S.%f')[:-3]
  428. if extended_logging:
  429. print(f" [{timestamp}] {bcolors.OKGREEN}Get recorder.{parameter}: {bcolors.OKBLUE}{value_truncated}{bcolors.ENDC}")
  430. response = {"status": "success", "parameter": parameter, "value": value}
  431. if request_id is not None:
  432. response["request_id"] = request_id
  433. await websocket.send(json.dumps(response))
  434. else:
  435. if not parameter in allowed_parameters:
  436. print(f"{bcolors.WARNING}Parameter {parameter} is not allowed (get_parameter){bcolors.ENDC}")
  437. await websocket.send(json.dumps({"status": "error", "message": f"Parameter {parameter} is not allowed (get_parameter)"}))
  438. else:
  439. print(f"{bcolors.WARNING}Parameter {parameter} does not exist (get_parameter){bcolors.ENDC}")
  440. await websocket.send(json.dumps({"status": "error", "message": f"Parameter {parameter} does not exist (get_parameter)"}))
  441. elif command == "call_method":
  442. method_name = command_data.get("method")
  443. if method_name in allowed_methods:
  444. method = getattr(recorder, method_name, None)
  445. if method and callable(method):
  446. args = command_data.get("args", [])
  447. kwargs = command_data.get("kwargs", {})
  448. method(*args, **kwargs)
  449. timestamp = datetime.now().strftime('%H:%M:%S.%f')[:-3]
  450. print(f" [{timestamp}] {bcolors.OKGREEN}Called method recorder.{bcolors.OKBLUE}{method_name}{bcolors.ENDC}")
  451. await websocket.send(json.dumps({"status": "success", "message": f"Method {method_name} called"}))
  452. else:
  453. print(f"{bcolors.WARNING}Recorder does not have method {method_name}{bcolors.ENDC}")
  454. await websocket.send(json.dumps({"status": "error", "message": f"Recorder does not have method {method_name}"}))
  455. else:
  456. print(f"{bcolors.WARNING}Method {method_name} is not allowed{bcolors.ENDC}")
  457. await websocket.send(json.dumps({"status": "error", "message": f"Method {method_name} is not allowed"}))
  458. else:
  459. print(f"{bcolors.WARNING}Unknown command: {command}{bcolors.ENDC}")
  460. await websocket.send(json.dumps({"status": "error", "message": f"Unknown command {command}"}))
  461. except json.JSONDecodeError:
  462. print(f"{bcolors.WARNING}Received invalid JSON command{bcolors.ENDC}")
  463. await websocket.send(json.dumps({"status": "error", "message": "Invalid JSON command"}))
  464. else:
  465. print(f"{bcolors.WARNING}Received unknown message type on control connection{bcolors.ENDC}")
  466. except websockets.exceptions.ConnectionClosed as e:
  467. print(f"{bcolors.WARNING}Control client disconnected: {e}{bcolors.ENDC}")
  468. finally:
  469. control_connections.remove(websocket)
  470. async def data_handler(websocket, path):
  471. global writechunks, wav_file
  472. print(f"{bcolors.OKGREEN}Data client connected{bcolors.ENDC}")
  473. data_connections.add(websocket)
  474. try:
  475. while True:
  476. message = await websocket.recv()
  477. if isinstance(message, bytes):
  478. if debug_logging:
  479. debug_print(f"Received audio chunk (size: {len(message)} bytes)")
  480. elif log_incoming_chunks:
  481. print(".", end='', flush=True)
  482. # Handle binary message (audio data)
  483. metadata_length = int.from_bytes(message[:4], byteorder='little')
  484. metadata_json = message[4:4+metadata_length].decode('utf-8')
  485. metadata = json.loads(metadata_json)
  486. sample_rate = metadata['sampleRate']
  487. debug_print(f"Processing audio chunk with sample rate {sample_rate}")
  488. chunk = message[4+metadata_length:]
  489. if writechunks:
  490. if not wav_file:
  491. wav_file = wave.open(writechunks, 'wb')
  492. wav_file.setnchannels(CHANNELS)
  493. wav_file.setsampwidth(pyaudio.get_sample_size(FORMAT))
  494. wav_file.setframerate(sample_rate)
  495. wav_file.writeframes(chunk)
  496. resampled_chunk = decode_and_resample(chunk, sample_rate, 16000)
  497. debug_print(f"Resampled chunk size: {len(resampled_chunk)} bytes")
  498. recorder.feed_audio(resampled_chunk)
  499. else:
  500. print(f"{bcolors.WARNING}Received non-binary message on data connection{bcolors.ENDC}")
  501. except websockets.exceptions.ConnectionClosed as e:
  502. print(f"{bcolors.WARNING}Data client disconnected: {e}{bcolors.ENDC}")
  503. finally:
  504. data_connections.remove(websocket)
  505. recorder.clear_audio_queue() # Ensure audio queue is cleared if client disconnects
  506. async def broadcast_audio_messages():
  507. while True:
  508. message = await audio_queue.get()
  509. for conn in list(data_connections):
  510. try:
  511. timestamp = datetime.now().strftime('%H:%M:%S.%f')[:-3]
  512. if extended_logging:
  513. print(f" [{timestamp}] Sending message: {bcolors.OKBLUE}{message}{bcolors.ENDC}\n", flush=True, end="")
  514. await conn.send(message)
  515. except websockets.exceptions.ConnectionClosed:
  516. data_connections.remove(conn)
  517. # Helper function to create event loop bound closures for callbacks
  518. def make_callback(loop, callback):
  519. def inner_callback(*args, **kwargs):
  520. callback(*args, **kwargs, loop=loop)
  521. return inner_callback
  522. async def main_async():
  523. global stop_recorder, recorder_config, global_args
  524. args = parse_arguments()
  525. global_args = args
  526. # Get the event loop here and pass it to the recorder thread
  527. loop = asyncio.get_event_loop()
  528. recorder_config = {
  529. 'model': args.model,
  530. 'realtime_model_type': args.rt_model,
  531. 'language': args.lang,
  532. 'input_device_index': args.input_device,
  533. 'silero_sensitivity': args.silero_sensitivity,
  534. 'silero_use_onnx': args.silero_use_onnx,
  535. 'webrtc_sensitivity': args.webrtc_sensitivity,
  536. 'post_speech_silence_duration': args.unknown_sentence_detection_pause,
  537. 'min_length_of_recording': args.min_length_of_recording,
  538. 'min_gap_between_recordings': args.min_gap_between_recordings,
  539. 'enable_realtime_transcription': args.enable_realtime_transcription,
  540. 'realtime_processing_pause': args.realtime_processing_pause,
  541. 'silero_deactivity_detection': args.silero_deactivity_detection,
  542. 'early_transcription_on_silence': args.early_transcription_on_silence,
  543. 'beam_size': args.beam_size,
  544. 'beam_size_realtime': args.beam_size_realtime,
  545. 'initial_prompt': args.initial_prompt,
  546. 'wake_words': args.wake_words,
  547. 'wake_words_sensitivity': args.wake_words_sensitivity,
  548. 'wake_word_timeout': args.wake_word_timeout,
  549. 'wake_word_activation_delay': args.wake_word_activation_delay,
  550. 'wakeword_backend': args.wakeword_backend,
  551. 'openwakeword_model_paths': args.openwakeword_model_paths,
  552. 'openwakeword_inference_framework': args.openwakeword_inference_framework,
  553. 'wake_word_buffer_duration': args.wake_word_buffer_duration,
  554. 'use_main_model_for_realtime': args.use_main_model_for_realtime,
  555. 'spinner': False,
  556. 'use_microphone': False,
  557. 'on_realtime_transcription_update': make_callback(loop, text_detected),
  558. 'on_recording_start': make_callback(loop, on_recording_start),
  559. 'on_recording_stop': make_callback(loop, on_recording_stop),
  560. 'on_vad_detect_start': make_callback(loop, on_vad_detect_start),
  561. 'on_vad_detect_stop': make_callback(loop, on_vad_detect_stop),
  562. 'on_wakeword_detected': make_callback(loop, on_wakeword_detected),
  563. 'on_wakeword_detection_start': make_callback(loop, on_wakeword_detection_start),
  564. 'on_wakeword_detection_end': make_callback(loop, on_wakeword_detection_end),
  565. 'on_transcription_start': make_callback(loop, on_transcription_start),
  566. # 'on_recorded_chunk': make_callback(loop, on_recorded_chunk),
  567. 'no_log_file': True, # Disable logging to file
  568. 'use_extended_logging': args.use_extended_logging,
  569. 'level': loglevel,
  570. }
  571. try:
  572. # Attempt to start control and data servers
  573. control_server = await websockets.serve(control_handler, "localhost", args.control)
  574. data_server = await websockets.serve(data_handler, "localhost", args.data)
  575. print(f"{bcolors.OKGREEN}Control server started on {bcolors.OKBLUE}ws://localhost:{args.control}{bcolors.ENDC}")
  576. print(f"{bcolors.OKGREEN}Data server started on {bcolors.OKBLUE}ws://localhost:{args.data}{bcolors.ENDC}")
  577. # Start the broadcast and recorder threads
  578. broadcast_task = asyncio.create_task(broadcast_audio_messages())
  579. recorder_thread = threading.Thread(target=_recorder_thread, args=(loop,))
  580. recorder_thread.start()
  581. recorder_ready.wait()
  582. print(f"{bcolors.OKGREEN}Server started. Press Ctrl+C to stop the server.{bcolors.ENDC}")
  583. # Run server tasks
  584. await asyncio.gather(control_server.wait_closed(), data_server.wait_closed(), broadcast_task)
  585. except OSError as e:
  586. print(f"{bcolors.FAIL}Error: Could not start server on specified ports. It’s possible another instance of the server is already running, or the ports are being used by another application.{bcolors.ENDC}")
  587. except KeyboardInterrupt:
  588. print(f"{bcolors.WARNING}Server interrupted by user, shutting down...{bcolors.ENDC}")
  589. finally:
  590. # Shutdown procedures for recorder and server threads
  591. await shutdown_procedure()
  592. print(f"{bcolors.OKGREEN}Server shutdown complete.{bcolors.ENDC}")
  593. async def shutdown_procedure():
  594. global stop_recorder, recorder_thread
  595. if recorder:
  596. stop_recorder = True
  597. recorder.abort()
  598. recorder.stop()
  599. recorder.shutdown()
  600. print(f"{bcolors.OKGREEN}Recorder shut down{bcolors.ENDC}")
  601. if recorder_thread:
  602. recorder_thread.join()
  603. print(f"{bcolors.OKGREEN}Recorder thread finished{bcolors.ENDC}")
  604. tasks = [t for t in asyncio.all_tasks() if t is not asyncio.current_task()]
  605. for task in tasks:
  606. task.cancel()
  607. await asyncio.gather(*tasks, return_exceptions=True)
  608. print(f"{bcolors.OKGREEN}All tasks cancelled, closing event loop now.{bcolors.ENDC}")
  609. def main():
  610. try:
  611. asyncio.run(main_async())
  612. except KeyboardInterrupt:
  613. # Capture any final KeyboardInterrupt to prevent it from showing up in logs
  614. print(f"{bcolors.WARNING}Server interrupted by user.{bcolors.ENDC}")
  615. exit(0)
  616. if __name__ == '__main__':
  617. main()