stt_server.py 41 KB

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