stt_server.py 37 KB

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