audio_recorder.py 108 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409
  1. """
  2. The AudioToTextRecorder class in the provided code facilitates
  3. fast speech-to-text transcription.
  4. The class employs the faster_whisper library to transcribe the recorded audio
  5. into text using machine learning models, which can be run either on a GPU or
  6. CPU. Voice activity detection (VAD) is built in, meaning the software can
  7. automatically start or stop recording based on the presence or absence of
  8. speech. It integrates wake word detection through the pvporcupine library,
  9. allowing the software to initiate recording when a specific word or phrase
  10. is spoken. The system provides real-time feedback and can be further
  11. customized.
  12. Features:
  13. - Voice Activity Detection: Automatically starts/stops recording when speech
  14. is detected or when speech ends.
  15. - Wake Word Detection: Starts recording when a specified wake word (or words)
  16. is detected.
  17. - Event Callbacks: Customizable callbacks for when recording starts
  18. or finishes.
  19. - Fast Transcription: Returns the transcribed text from the audio as fast
  20. as possible.
  21. Author: Kolja Beigel
  22. """
  23. from typing import Iterable, List, Optional, Union
  24. import torch.multiprocessing as mp
  25. import torch
  26. from ctypes import c_bool
  27. from openwakeword.model import Model
  28. from scipy.signal import resample
  29. from scipy import signal
  30. import signal as system_signal
  31. import faster_whisper
  32. import openwakeword
  33. import collections
  34. import numpy as np
  35. import pvporcupine
  36. import traceback
  37. import threading
  38. import webrtcvad
  39. import itertools
  40. import datetime
  41. import platform
  42. import pyaudio
  43. import logging
  44. import struct
  45. import base64
  46. import queue
  47. import halo
  48. import time
  49. import copy
  50. import os
  51. import re
  52. import gc
  53. # Set OpenMP runtime duplicate library handling to OK (Use only for development!)
  54. os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'
  55. INIT_MODEL_TRANSCRIPTION = "tiny"
  56. INIT_MODEL_TRANSCRIPTION_REALTIME = "tiny"
  57. INIT_REALTIME_PROCESSING_PAUSE = 0.2
  58. INIT_SILERO_SENSITIVITY = 0.4
  59. INIT_WEBRTC_SENSITIVITY = 3
  60. INIT_POST_SPEECH_SILENCE_DURATION = 0.6
  61. INIT_MIN_LENGTH_OF_RECORDING = 0.5
  62. INIT_MIN_GAP_BETWEEN_RECORDINGS = 0
  63. INIT_WAKE_WORDS_SENSITIVITY = 0.6
  64. INIT_PRE_RECORDING_BUFFER_DURATION = 1.0
  65. INIT_WAKE_WORD_ACTIVATION_DELAY = 0.0
  66. INIT_WAKE_WORD_TIMEOUT = 5.0
  67. INIT_WAKE_WORD_BUFFER_DURATION = 0.1
  68. ALLOWED_LATENCY_LIMIT = 100
  69. TIME_SLEEP = 0.02
  70. SAMPLE_RATE = 16000
  71. BUFFER_SIZE = 512
  72. INT16_MAX_ABS_VALUE = 32768.0
  73. INIT_HANDLE_BUFFER_OVERFLOW = False
  74. if platform.system() != 'Darwin':
  75. INIT_HANDLE_BUFFER_OVERFLOW = True
  76. class TranscriptionWorker:
  77. def __init__(self, conn, stdout_pipe, model_path, compute_type, gpu_device_index, device,
  78. ready_event, shutdown_event, interrupt_stop_event, beam_size, initial_prompt, suppress_tokens):
  79. self.conn = conn
  80. self.stdout_pipe = stdout_pipe
  81. self.model_path = model_path
  82. self.compute_type = compute_type
  83. self.gpu_device_index = gpu_device_index
  84. self.device = device
  85. self.ready_event = ready_event
  86. self.shutdown_event = shutdown_event
  87. self.interrupt_stop_event = interrupt_stop_event
  88. self.beam_size = beam_size
  89. self.initial_prompt = initial_prompt
  90. self.suppress_tokens = suppress_tokens
  91. self.queue = queue.Queue()
  92. def custom_print(self, *args, **kwargs):
  93. message = ' '.join(map(str, args))
  94. try:
  95. self.stdout_pipe.send(message)
  96. except (BrokenPipeError, EOFError, OSError):
  97. pass
  98. def poll_connection(self):
  99. while not self.shutdown_event.is_set():
  100. if self.conn.poll(0.01):
  101. try:
  102. data = self.conn.recv()
  103. self.queue.put(data)
  104. except Exception as e:
  105. logging.error(f"Error receiving data from connection: {e}")
  106. else:
  107. time.sleep(TIME_SLEEP)
  108. def run(self):
  109. if __name__ == "__main__":
  110. system_signal.signal(system_signal.SIGINT, system_signal.SIG_IGN)
  111. __builtins__['print'] = self.custom_print
  112. logging.info(f"Initializing faster_whisper main transcription model {self.model_path}")
  113. try:
  114. model = faster_whisper.WhisperModel(
  115. model_size_or_path=self.model_path,
  116. device=self.device,
  117. compute_type=self.compute_type,
  118. device_index=self.gpu_device_index,
  119. )
  120. except Exception as e:
  121. logging.exception(f"Error initializing main faster_whisper transcription model: {e}")
  122. raise
  123. self.ready_event.set()
  124. logging.debug("Faster_whisper main speech to text transcription model initialized successfully")
  125. # Start the polling thread
  126. polling_thread = threading.Thread(target=self.poll_connection)
  127. polling_thread.start()
  128. try:
  129. while not self.shutdown_event.is_set():
  130. try:
  131. audio, language = self.queue.get(timeout=0.1)
  132. try:
  133. segments, info = model.transcribe(
  134. audio,
  135. language=language if language else None,
  136. beam_size=self.beam_size,
  137. initial_prompt=self.initial_prompt,
  138. suppress_tokens=self.suppress_tokens
  139. )
  140. transcription = " ".join(seg.text for seg in segments).strip()
  141. logging.debug(f"Final text detected with main model: {transcription}")
  142. self.conn.send(('success', (transcription, info)))
  143. except Exception as e:
  144. logging.error(f"General error in transcription: {e}")
  145. self.conn.send(('error', str(e)))
  146. except queue.Empty:
  147. continue
  148. except KeyboardInterrupt:
  149. self.interrupt_stop_event.set()
  150. logging.debug("Transcription worker process finished due to KeyboardInterrupt")
  151. break
  152. except Exception as e:
  153. logging.error(f"General error in processing queue item: {e}")
  154. finally:
  155. __builtins__['print'] = print # Restore the original print function
  156. self.conn.close()
  157. self.stdout_pipe.close()
  158. self.shutdown_event.set() # Ensure the polling thread will stop
  159. polling_thread.join() # Wait for the polling thread to finish
  160. class AudioToTextRecorder:
  161. """
  162. A class responsible for capturing audio from the microphone, detecting
  163. voice activity, and then transcribing the captured audio using the
  164. `faster_whisper` model.
  165. """
  166. def __init__(self,
  167. model: str = INIT_MODEL_TRANSCRIPTION,
  168. language: str = "",
  169. compute_type: str = "default",
  170. input_device_index: int = None,
  171. gpu_device_index: Union[int, List[int]] = 0,
  172. device: str = "cuda",
  173. on_recording_start=None,
  174. on_recording_stop=None,
  175. on_transcription_start=None,
  176. ensure_sentence_starting_uppercase=True,
  177. ensure_sentence_ends_with_period=True,
  178. use_microphone=True,
  179. spinner=True,
  180. level=logging.WARNING,
  181. # Realtime transcription parameters
  182. enable_realtime_transcription=False,
  183. use_main_model_for_realtime=False,
  184. realtime_model_type=INIT_MODEL_TRANSCRIPTION_REALTIME,
  185. realtime_processing_pause=INIT_REALTIME_PROCESSING_PAUSE,
  186. on_realtime_transcription_update=None,
  187. on_realtime_transcription_stabilized=None,
  188. # Voice activation parameters
  189. silero_sensitivity: float = INIT_SILERO_SENSITIVITY,
  190. silero_use_onnx: bool = False,
  191. silero_deactivity_detection: bool = False,
  192. webrtc_sensitivity: int = INIT_WEBRTC_SENSITIVITY,
  193. post_speech_silence_duration: float = (
  194. INIT_POST_SPEECH_SILENCE_DURATION
  195. ),
  196. min_length_of_recording: float = (
  197. INIT_MIN_LENGTH_OF_RECORDING
  198. ),
  199. min_gap_between_recordings: float = (
  200. INIT_MIN_GAP_BETWEEN_RECORDINGS
  201. ),
  202. pre_recording_buffer_duration: float = (
  203. INIT_PRE_RECORDING_BUFFER_DURATION
  204. ),
  205. on_vad_detect_start=None,
  206. on_vad_detect_stop=None,
  207. # Wake word parameters
  208. wakeword_backend: str = "pvporcupine",
  209. openwakeword_model_paths: str = None,
  210. openwakeword_inference_framework: str = "onnx",
  211. wake_words: str = "",
  212. wake_words_sensitivity: float = INIT_WAKE_WORDS_SENSITIVITY,
  213. wake_word_activation_delay: float = (
  214. INIT_WAKE_WORD_ACTIVATION_DELAY
  215. ),
  216. wake_word_timeout: float = INIT_WAKE_WORD_TIMEOUT,
  217. wake_word_buffer_duration: float = INIT_WAKE_WORD_BUFFER_DURATION,
  218. on_wakeword_detected=None,
  219. on_wakeword_timeout=None,
  220. on_wakeword_detection_start=None,
  221. on_wakeword_detection_end=None,
  222. on_recorded_chunk=None,
  223. debug_mode=False,
  224. handle_buffer_overflow: bool = INIT_HANDLE_BUFFER_OVERFLOW,
  225. beam_size: int = 5,
  226. beam_size_realtime: int = 3,
  227. buffer_size: int = BUFFER_SIZE,
  228. sample_rate: int = SAMPLE_RATE,
  229. initial_prompt: Optional[Union[str, Iterable[int]]] = None,
  230. suppress_tokens: Optional[List[int]] = [-1],
  231. print_transcription_time: bool = False,
  232. early_transcription_on_silence: int = 0,
  233. allowed_latency_limit: int = ALLOWED_LATENCY_LIMIT,
  234. no_log_file: bool = False,
  235. use_extended_logging: bool = False,
  236. ):
  237. """
  238. Initializes an audio recorder and transcription
  239. and wake word detection.
  240. Args:
  241. - model (str, default="tiny"): Specifies the size of the transcription
  242. model to use or the path to a converted model directory.
  243. Valid options are 'tiny', 'tiny.en', 'base', 'base.en',
  244. 'small', 'small.en', 'medium', 'medium.en', 'large-v1',
  245. 'large-v2'.
  246. If a specific size is provided, the model is downloaded
  247. from the Hugging Face Hub.
  248. - language (str, default=""): Language code for speech-to-text engine.
  249. If not specified, the model will attempt to detect the language
  250. automatically.
  251. - compute_type (str, default="default"): Specifies the type of
  252. computation to be used for transcription.
  253. See https://opennmt.net/CTranslate2/quantization.html.
  254. - input_device_index (int, default=0): The index of the audio input
  255. device to use.
  256. - gpu_device_index (int, default=0): Device ID to use.
  257. The model can also be loaded on multiple GPUs by passing a list of
  258. IDs (e.g. [0, 1, 2, 3]). In that case, multiple transcriptions can
  259. run in parallel when transcribe() is called from multiple Python
  260. threads
  261. - device (str, default="cuda"): Device for model to use. Can either be
  262. "cuda" or "cpu".
  263. - on_recording_start (callable, default=None): Callback function to be
  264. called when recording of audio to be transcripted starts.
  265. - on_recording_stop (callable, default=None): Callback function to be
  266. called when recording of audio to be transcripted stops.
  267. - on_transcription_start (callable, default=None): Callback function
  268. to be called when transcription of audio to text starts.
  269. - ensure_sentence_starting_uppercase (bool, default=True): Ensures
  270. that every sentence detected by the algorithm starts with an
  271. uppercase letter.
  272. - ensure_sentence_ends_with_period (bool, default=True): Ensures that
  273. every sentence that doesn't end with punctuation such as "?", "!"
  274. ends with a period
  275. - use_microphone (bool, default=True): Specifies whether to use the
  276. microphone as the audio input source. If set to False, the
  277. audio input source will be the audio data sent through the
  278. feed_audio() method.
  279. - spinner (bool, default=True): Show spinner animation with current
  280. state.
  281. - level (int, default=logging.WARNING): Logging level.
  282. - enable_realtime_transcription (bool, default=False): Enables or
  283. disables real-time transcription of audio. When set to True, the
  284. audio will be transcribed continuously as it is being recorded.
  285. - use_main_model_for_realtime (str, default=False):
  286. If True, use the main transcription model for both regular and
  287. real-time transcription. If False, use a separate model specified
  288. by realtime_model_type for real-time transcription.
  289. Using a single model can save memory and potentially improve
  290. performance, but may not be optimized for real-time processing.
  291. Using separate models allows for a smaller, faster model for
  292. real-time transcription while keeping a more accurate model for
  293. final transcription.
  294. - realtime_model_type (str, default="tiny"): Specifies the machine
  295. learning model to be used for real-time transcription. Valid
  296. options include 'tiny', 'tiny.en', 'base', 'base.en', 'small',
  297. 'small.en', 'medium', 'medium.en', 'large-v1', 'large-v2'.
  298. - realtime_processing_pause (float, default=0.1): Specifies the time
  299. interval in seconds after a chunk of audio gets transcribed. Lower
  300. values will result in more "real-time" (frequent) transcription
  301. updates but may increase computational load.
  302. - on_realtime_transcription_update = A callback function that is
  303. triggered whenever there's an update in the real-time
  304. transcription. The function is called with the newly transcribed
  305. text as its argument.
  306. - on_realtime_transcription_stabilized = A callback function that is
  307. triggered when the transcribed text stabilizes in quality. The
  308. stabilized text is generally more accurate but may arrive with a
  309. slight delay compared to the regular real-time updates.
  310. - silero_sensitivity (float, default=SILERO_SENSITIVITY): Sensitivity
  311. for the Silero Voice Activity Detection model ranging from 0
  312. (least sensitive) to 1 (most sensitive). Default is 0.5.
  313. - silero_use_onnx (bool, default=False): Enables usage of the
  314. pre-trained model from Silero in the ONNX (Open Neural Network
  315. Exchange) format instead of the PyTorch format. This is
  316. recommended for faster performance.
  317. - silero_deactivity_detection (bool, default=False): Enables the Silero
  318. model for end-of-speech detection. More robust against background
  319. noise. Utilizes additional GPU resources but improves accuracy in
  320. noisy environments. When False, uses the default WebRTC VAD,
  321. which is more sensitive but may continue recording longer due
  322. to background sounds.
  323. - webrtc_sensitivity (int, default=WEBRTC_SENSITIVITY): Sensitivity
  324. for the WebRTC Voice Activity Detection engine ranging from 0
  325. (least aggressive / most sensitive) to 3 (most aggressive,
  326. least sensitive). Default is 3.
  327. - post_speech_silence_duration (float, default=0.2): Duration in
  328. seconds of silence that must follow speech before the recording
  329. is considered to be completed. This ensures that any brief
  330. pauses during speech don't prematurely end the recording.
  331. - min_gap_between_recordings (float, default=1.0): Specifies the
  332. minimum time interval in seconds that should exist between the
  333. end of one recording session and the beginning of another to
  334. prevent rapid consecutive recordings.
  335. - min_length_of_recording (float, default=1.0): Specifies the minimum
  336. duration in seconds that a recording session should last to ensure
  337. meaningful audio capture, preventing excessively short or
  338. fragmented recordings.
  339. - pre_recording_buffer_duration (float, default=0.2): Duration in
  340. seconds for the audio buffer to maintain pre-roll audio
  341. (compensates speech activity detection latency)
  342. - on_vad_detect_start (callable, default=None): Callback function to
  343. be called when the system listens for voice activity.
  344. - on_vad_detect_stop (callable, default=None): Callback function to be
  345. called when the system stops listening for voice activity.
  346. - wakeword_backend (str, default="pvporcupine"): Specifies the backend
  347. library to use for wake word detection. Supported options include
  348. 'pvporcupine' for using the Porcupine wake word engine or 'oww' for
  349. using the OpenWakeWord engine.
  350. - openwakeword_model_paths (str, default=None): Comma-separated paths
  351. to model files for the openwakeword library. These paths point to
  352. custom models that can be used for wake word detection when the
  353. openwakeword library is selected as the wakeword_backend.
  354. - openwakeword_inference_framework (str, default="onnx"): Specifies
  355. the inference framework to use with the openwakeword library.
  356. Can be either 'onnx' for Open Neural Network Exchange format
  357. or 'tflite' for TensorFlow Lite.
  358. - wake_words (str, default=""): Comma-separated string of wake words to
  359. initiate recording when using the 'pvporcupine' wakeword backend.
  360. Supported wake words include: 'alexa', 'americano', 'blueberry',
  361. 'bumblebee', 'computer', 'grapefruits', 'grasshopper', 'hey google',
  362. 'hey siri', 'jarvis', 'ok google', 'picovoice', 'porcupine',
  363. 'terminator'. For the 'openwakeword' backend, wake words are
  364. automatically extracted from the provided model files, so specifying
  365. them here is not necessary.
  366. - wake_words_sensitivity (float, default=0.5): Sensitivity for wake
  367. word detection, ranging from 0 (least sensitive) to 1 (most
  368. sensitive). Default is 0.5.
  369. - wake_word_activation_delay (float, default=0): Duration in seconds
  370. after the start of monitoring before the system switches to wake
  371. word activation if no voice is initially detected. If set to
  372. zero, the system uses wake word activation immediately.
  373. - wake_word_timeout (float, default=5): Duration in seconds after a
  374. wake word is recognized. If no subsequent voice activity is
  375. detected within this window, the system transitions back to an
  376. inactive state, awaiting the next wake word or voice activation.
  377. - wake_word_buffer_duration (float, default=0.1): Duration in seconds
  378. to buffer audio data during wake word detection. This helps in
  379. cutting out the wake word from the recording buffer so it does not
  380. falsely get detected along with the following spoken text, ensuring
  381. cleaner and more accurate transcription start triggers.
  382. Increase this if parts of the wake word get detected as text.
  383. - on_wakeword_detected (callable, default=None): Callback function to
  384. be called when a wake word is detected.
  385. - on_wakeword_timeout (callable, default=None): Callback function to
  386. be called when the system goes back to an inactive state after when
  387. no speech was detected after wake word activation
  388. - on_wakeword_detection_start (callable, default=None): Callback
  389. function to be called when the system starts to listen for wake
  390. words
  391. - on_wakeword_detection_end (callable, default=None): Callback
  392. function to be called when the system stops to listen for
  393. wake words (e.g. because of timeout or wake word detected)
  394. - on_recorded_chunk (callable, default=None): Callback function to be
  395. called when a chunk of audio is recorded. The function is called
  396. with the recorded audio chunk as its argument.
  397. - debug_mode (bool, default=False): If set to True, the system will
  398. print additional debug information to the console.
  399. - handle_buffer_overflow (bool, default=True): If set to True, the system
  400. will log a warning when an input overflow occurs during recording and
  401. remove the data from the buffer.
  402. - beam_size (int, default=5): The beam size to use for beam search
  403. decoding.
  404. - beam_size_realtime (int, default=3): The beam size to use for beam
  405. search decoding in the real-time transcription model.
  406. - buffer_size (int, default=512): The buffer size to use for audio
  407. recording. Changing this may break functionality.
  408. - sample_rate (int, default=16000): The sample rate to use for audio
  409. recording. Changing this will very probably functionality (as the
  410. WebRTC VAD model is very sensitive towards the sample rate).
  411. - initial_prompt (str or iterable of int, default=None): Initial
  412. prompt to be fed to the transcription models.
  413. - suppress_tokens (list of int, default=[-1]): Tokens to be suppressed
  414. from the transcription output.
  415. - print_transcription_time (bool, default=False): Logs processing time
  416. of main model transcription
  417. - early_transcription_on_silence (int, default=0): If set, the
  418. system will transcribe audio faster when silence is detected.
  419. Transcription will start after the specified milliseconds, so
  420. keep this value lower than post_speech_silence_duration.
  421. Ideally around post_speech_silence_duration minus the estimated
  422. transcription time with the main model.
  423. If silence lasts longer than post_speech_silence_duration, the
  424. recording is stopped, and the transcription is submitted. If
  425. voice activity resumes within this period, the transcription
  426. is discarded. Results in faster final transcriptions to the cost
  427. of additional GPU load due to some unnecessary final transcriptions.
  428. - allowed_latency_limit (int, default=100): Maximal amount of chunks
  429. that can be unprocessed in queue before discarding chunks.
  430. - no_log_file (bool, default=False): Skips writing of debug log file.
  431. - use_extended_logging (bool, default=False): Writes extensive
  432. log messages for the recording worker, that processes the audio
  433. chunks.
  434. Raises:
  435. Exception: Errors related to initializing transcription
  436. model, wake word detection, or audio recording.
  437. """
  438. self.language = language
  439. self.compute_type = compute_type
  440. self.input_device_index = input_device_index
  441. self.gpu_device_index = gpu_device_index
  442. self.device = device
  443. self.wake_words = wake_words
  444. self.wake_word_activation_delay = wake_word_activation_delay
  445. self.wake_word_timeout = wake_word_timeout
  446. self.wake_word_buffer_duration = wake_word_buffer_duration
  447. self.ensure_sentence_starting_uppercase = (
  448. ensure_sentence_starting_uppercase
  449. )
  450. self.ensure_sentence_ends_with_period = (
  451. ensure_sentence_ends_with_period
  452. )
  453. self.use_microphone = mp.Value(c_bool, use_microphone)
  454. self.min_gap_between_recordings = min_gap_between_recordings
  455. self.min_length_of_recording = min_length_of_recording
  456. self.pre_recording_buffer_duration = pre_recording_buffer_duration
  457. self.post_speech_silence_duration = post_speech_silence_duration
  458. self.on_recording_start = on_recording_start
  459. self.on_recording_stop = on_recording_stop
  460. self.on_wakeword_detected = on_wakeword_detected
  461. self.on_wakeword_timeout = on_wakeword_timeout
  462. self.on_vad_detect_start = on_vad_detect_start
  463. self.on_vad_detect_stop = on_vad_detect_stop
  464. self.on_wakeword_detection_start = on_wakeword_detection_start
  465. self.on_wakeword_detection_end = on_wakeword_detection_end
  466. self.on_recorded_chunk = on_recorded_chunk
  467. self.on_transcription_start = on_transcription_start
  468. self.enable_realtime_transcription = enable_realtime_transcription
  469. self.use_main_model_for_realtime = use_main_model_for_realtime
  470. self.main_model_type = model
  471. self.realtime_model_type = realtime_model_type
  472. self.realtime_processing_pause = realtime_processing_pause
  473. self.on_realtime_transcription_update = (
  474. on_realtime_transcription_update
  475. )
  476. self.on_realtime_transcription_stabilized = (
  477. on_realtime_transcription_stabilized
  478. )
  479. self.debug_mode = debug_mode
  480. self.handle_buffer_overflow = handle_buffer_overflow
  481. self.beam_size = beam_size
  482. self.beam_size_realtime = beam_size_realtime
  483. self.allowed_latency_limit = allowed_latency_limit
  484. self.level = level
  485. self.audio_queue = mp.Queue()
  486. self.buffer_size = buffer_size
  487. self.sample_rate = sample_rate
  488. self.recording_start_time = 0
  489. self.recording_stop_time = 0
  490. self.wake_word_detect_time = 0
  491. self.silero_check_time = 0
  492. self.silero_working = False
  493. self.speech_end_silence_start = 0
  494. self.silero_sensitivity = silero_sensitivity
  495. self.silero_deactivity_detection = silero_deactivity_detection
  496. self.listen_start = 0
  497. self.spinner = spinner
  498. self.halo = None
  499. self.state = "inactive"
  500. self.wakeword_detected = False
  501. self.text_storage = []
  502. self.realtime_stabilized_text = ""
  503. self.realtime_stabilized_safetext = ""
  504. self.is_webrtc_speech_active = False
  505. self.is_silero_speech_active = False
  506. self.recording_thread = None
  507. self.realtime_thread = None
  508. self.audio_interface = None
  509. self.audio = None
  510. self.stream = None
  511. self.start_recording_event = threading.Event()
  512. self.stop_recording_event = threading.Event()
  513. self.last_transcription_bytes = None
  514. self.last_transcription_bytes_b64 = None
  515. self.initial_prompt = initial_prompt
  516. self.suppress_tokens = suppress_tokens
  517. self.use_wake_words = wake_words or wakeword_backend in {'oww', 'openwakeword', 'openwakewords'}
  518. self.detected_language = None
  519. self.detected_language_probability = 0
  520. self.detected_realtime_language = None
  521. self.detected_realtime_language_probability = 0
  522. self.transcription_lock = threading.Lock()
  523. self.shutdown_lock = threading.Lock()
  524. self.transcribe_count = 0
  525. self.print_transcription_time = print_transcription_time
  526. self.early_transcription_on_silence = early_transcription_on_silence
  527. self.use_extended_logging = use_extended_logging
  528. # Initialize the logging configuration with the specified level
  529. log_format = 'RealTimeSTT: %(name)s - %(levelname)s - %(message)s'
  530. # Adjust file_log_format to include milliseconds
  531. file_log_format = '%(asctime)s.%(msecs)03d - ' + log_format
  532. # Get the root logger
  533. logger = logging.getLogger()
  534. logger.setLevel(logging.DEBUG) # Set the root logger's level to DEBUG
  535. # Remove any existing handlers
  536. logger.handlers = []
  537. # Create a console handler and set its level
  538. console_handler = logging.StreamHandler()
  539. console_handler.setLevel(level)
  540. console_handler.setFormatter(logging.Formatter(log_format))
  541. # Add the handlers to the logger
  542. if not no_log_file:
  543. # Create a file handler and set its level
  544. file_handler = logging.FileHandler('realtimesst.log')
  545. file_handler.setLevel(logging.DEBUG)
  546. file_handler.setFormatter(logging.Formatter(
  547. file_log_format,
  548. datefmt='%Y-%m-%d %H:%M:%S'
  549. ))
  550. logger.addHandler(file_handler)
  551. logger.addHandler(console_handler)
  552. self.is_shut_down = False
  553. self.shutdown_event = mp.Event()
  554. try:
  555. # Only set the start method if it hasn't been set already
  556. if mp.get_start_method(allow_none=True) is None:
  557. mp.set_start_method("spawn")
  558. except RuntimeError as e:
  559. logging.info(f"Start method has already been set. Details: {e}")
  560. logging.info("Starting RealTimeSTT")
  561. self.interrupt_stop_event = mp.Event()
  562. self.was_interrupted = mp.Event()
  563. self.main_transcription_ready_event = mp.Event()
  564. self.parent_transcription_pipe, child_transcription_pipe = mp.Pipe()
  565. self.parent_stdout_pipe, child_stdout_pipe = mp.Pipe()
  566. # Set device for model
  567. self.device = "cuda" if self.device == "cuda" and torch.cuda.is_available() else "cpu"
  568. self.transcript_process = self._start_thread(
  569. target=AudioToTextRecorder._transcription_worker,
  570. args=(
  571. child_transcription_pipe,
  572. child_stdout_pipe,
  573. model,
  574. self.compute_type,
  575. self.gpu_device_index,
  576. self.device,
  577. self.main_transcription_ready_event,
  578. self.shutdown_event,
  579. self.interrupt_stop_event,
  580. self.beam_size,
  581. self.initial_prompt,
  582. self.suppress_tokens
  583. )
  584. )
  585. # Start audio data reading process
  586. if self.use_microphone.value:
  587. logging.info("Initializing audio recording"
  588. " (creating pyAudio input stream,"
  589. f" sample rate: {self.sample_rate}"
  590. f" buffer size: {self.buffer_size}"
  591. )
  592. self.reader_process = self._start_thread(
  593. target=AudioToTextRecorder._audio_data_worker,
  594. args=(
  595. self.audio_queue,
  596. self.sample_rate,
  597. self.buffer_size,
  598. self.input_device_index,
  599. self.shutdown_event,
  600. self.interrupt_stop_event,
  601. self.use_microphone
  602. )
  603. )
  604. # Initialize the realtime transcription model
  605. if self.enable_realtime_transcription and not self.use_main_model_for_realtime:
  606. try:
  607. logging.info("Initializing faster_whisper realtime "
  608. f"transcription model {self.realtime_model_type}"
  609. )
  610. self.realtime_model_type = faster_whisper.WhisperModel(
  611. model_size_or_path=self.realtime_model_type,
  612. device=self.device,
  613. compute_type=self.compute_type,
  614. device_index=self.gpu_device_index
  615. )
  616. except Exception as e:
  617. logging.exception("Error initializing faster_whisper "
  618. f"realtime transcription model: {e}"
  619. )
  620. raise
  621. logging.debug("Faster_whisper realtime speech to text "
  622. "transcription model initialized successfully")
  623. # Setup wake word detection
  624. if wake_words or wakeword_backend in {'oww', 'openwakeword', 'openwakewords'}:
  625. self.wakeword_backend = wakeword_backend
  626. self.wake_words_list = [
  627. word.strip() for word in wake_words.lower().split(',')
  628. ]
  629. self.wake_words_sensitivity = wake_words_sensitivity
  630. self.wake_words_sensitivities = [
  631. float(wake_words_sensitivity)
  632. for _ in range(len(self.wake_words_list))
  633. ]
  634. if self.wakeword_backend in {'pvp', 'pvporcupine'}:
  635. try:
  636. self.porcupine = pvporcupine.create(
  637. keywords=self.wake_words_list,
  638. sensitivities=self.wake_words_sensitivities
  639. )
  640. self.buffer_size = self.porcupine.frame_length
  641. self.sample_rate = self.porcupine.sample_rate
  642. except Exception as e:
  643. logging.exception(
  644. "Error initializing porcupine "
  645. f"wake word detection engine: {e}"
  646. )
  647. raise
  648. logging.debug(
  649. "Porcupine wake word detection engine initialized successfully"
  650. )
  651. elif self.wakeword_backend in {'oww', 'openwakeword', 'openwakewords'}:
  652. openwakeword.utils.download_models()
  653. try:
  654. if openwakeword_model_paths:
  655. model_paths = openwakeword_model_paths.split(',')
  656. self.owwModel = Model(
  657. wakeword_models=model_paths,
  658. inference_framework=openwakeword_inference_framework
  659. )
  660. logging.info(
  661. "Successfully loaded wakeword model(s): "
  662. f"{openwakeword_model_paths}"
  663. )
  664. else:
  665. self.owwModel = Model(
  666. inference_framework=openwakeword_inference_framework)
  667. self.oww_n_models = len(self.owwModel.models.keys())
  668. if not self.oww_n_models:
  669. logging.error(
  670. "No wake word models loaded."
  671. )
  672. for model_key in self.owwModel.models.keys():
  673. logging.info(
  674. "Successfully loaded openwakeword model: "
  675. f"{model_key}"
  676. )
  677. except Exception as e:
  678. logging.exception(
  679. "Error initializing openwakeword "
  680. f"wake word detection engine: {e}"
  681. )
  682. raise
  683. logging.debug(
  684. "Open wake word detection engine initialized successfully"
  685. )
  686. else:
  687. logging.exception(f"Wakeword engine {self.wakeword_backend} unknown/unsupported. Please specify one of: pvporcupine, openwakeword.")
  688. # Setup voice activity detection model WebRTC
  689. try:
  690. logging.info("Initializing WebRTC voice with "
  691. f"Sensitivity {webrtc_sensitivity}"
  692. )
  693. self.webrtc_vad_model = webrtcvad.Vad()
  694. self.webrtc_vad_model.set_mode(webrtc_sensitivity)
  695. except Exception as e:
  696. logging.exception("Error initializing WebRTC voice "
  697. f"activity detection engine: {e}"
  698. )
  699. raise
  700. logging.debug("WebRTC VAD voice activity detection "
  701. "engine initialized successfully"
  702. )
  703. # Setup voice activity detection model Silero VAD
  704. try:
  705. self.silero_vad_model, _ = torch.hub.load(
  706. repo_or_dir="snakers4/silero-vad",
  707. model="silero_vad",
  708. verbose=False,
  709. onnx=silero_use_onnx
  710. )
  711. except Exception as e:
  712. logging.exception(f"Error initializing Silero VAD "
  713. f"voice activity detection engine: {e}"
  714. )
  715. raise
  716. logging.debug("Silero VAD voice activity detection "
  717. "engine initialized successfully"
  718. )
  719. self.audio_buffer = collections.deque(
  720. maxlen=int((self.sample_rate // self.buffer_size) *
  721. self.pre_recording_buffer_duration)
  722. )
  723. self.last_words_buffer = collections.deque(
  724. maxlen=int((self.sample_rate // self.buffer_size) *
  725. 0.3)
  726. )
  727. self.frames = []
  728. # Recording control flags
  729. self.is_recording = False
  730. self.is_running = True
  731. self.start_recording_on_voice_activity = False
  732. self.stop_recording_on_voice_deactivity = False
  733. # Start the recording worker thread
  734. self.recording_thread = threading.Thread(target=self._recording_worker)
  735. self.recording_thread.daemon = True
  736. self.recording_thread.start()
  737. # Start the realtime transcription worker thread
  738. self.realtime_thread = threading.Thread(target=self._realtime_worker)
  739. self.realtime_thread.daemon = True
  740. self.realtime_thread.start()
  741. # Wait for transcription models to start
  742. logging.debug('Waiting for main transcription model to start')
  743. self.main_transcription_ready_event.wait()
  744. logging.debug('Main transcription model ready')
  745. self.stdout_thread = threading.Thread(target=self._read_stdout)
  746. self.stdout_thread.daemon = True
  747. self.stdout_thread.start()
  748. logging.debug('RealtimeSTT initialization completed successfully')
  749. def _start_thread(self, target=None, args=()):
  750. """
  751. Implement a consistent threading model across the library.
  752. This method is used to start any thread in this library. It uses the
  753. standard threading. Thread for Linux and for all others uses the pytorch
  754. MultiProcessing library 'Process'.
  755. Args:
  756. target (callable object): is the callable object to be invoked by
  757. the run() method. Defaults to None, meaning nothing is called.
  758. args (tuple): is a list or tuple of arguments for the target
  759. invocation. Defaults to ().
  760. """
  761. if (platform.system() == 'Linux'):
  762. thread = threading.Thread(target=target, args=args)
  763. thread.deamon = True
  764. thread.start()
  765. return thread
  766. else:
  767. thread = mp.Process(target=target, args=args)
  768. thread.start()
  769. return thread
  770. def _read_stdout(self):
  771. while not self.shutdown_event.is_set():
  772. try:
  773. if self.parent_stdout_pipe.poll(0.1):
  774. logging.debug("Receive from stdout pipe")
  775. message = self.parent_stdout_pipe.recv()
  776. logging.info(message)
  777. except (BrokenPipeError, EOFError, OSError):
  778. # The pipe probably has been closed, so we ignore the error
  779. pass
  780. except KeyboardInterrupt: # handle manual interruption (Ctrl+C)
  781. logging.info("KeyboardInterrupt in read from stdout detected, exiting...")
  782. break
  783. except Exception as e:
  784. logging.error(f"Unexpected error in read from stdout: {e}")
  785. logging.error(traceback.format_exc()) # Log the full traceback here
  786. break
  787. time.sleep(0.1)
  788. def _transcription_worker(*args, **kwargs):
  789. worker = TranscriptionWorker(*args, **kwargs)
  790. worker.run()
  791. @staticmethod
  792. def _audio_data_worker(audio_queue,
  793. target_sample_rate,
  794. buffer_size,
  795. input_device_index,
  796. shutdown_event,
  797. interrupt_stop_event,
  798. use_microphone):
  799. """
  800. Worker method that handles the audio recording process.
  801. This method runs in a separate process and is responsible for:
  802. - Setting up the audio input stream for recording at the highest possible sample rate.
  803. - Continuously reading audio data from the input stream, resampling if necessary,
  804. preprocessing the data, and placing complete chunks in a queue.
  805. - Handling errors during the recording process.
  806. - Gracefully terminating the recording process when a shutdown event is set.
  807. Args:
  808. audio_queue (queue.Queue): A queue where recorded audio data is placed.
  809. target_sample_rate (int): The desired sample rate for the output audio (for Silero VAD).
  810. buffer_size (int): The number of samples expected by the Silero VAD model.
  811. input_device_index (int): The index of the audio input device.
  812. shutdown_event (threading.Event): An event that, when set, signals this worker method to terminate.
  813. interrupt_stop_event (threading.Event): An event to signal keyboard interrupt.
  814. use_microphone (multiprocessing.Value): A shared value indicating whether to use the microphone.
  815. Raises:
  816. Exception: If there is an error while initializing the audio recording.
  817. """
  818. import pyaudio
  819. import numpy as np
  820. from scipy import signal
  821. if __name__ == '__main__':
  822. system_signal.signal(system_signal.SIGINT, system_signal.SIG_IGN)
  823. def get_highest_sample_rate(audio_interface, device_index):
  824. """Get the highest supported sample rate for the specified device."""
  825. try:
  826. device_info = audio_interface.get_device_info_by_index(device_index)
  827. max_rate = int(device_info['defaultSampleRate'])
  828. if 'supportedSampleRates' in device_info:
  829. supported_rates = [int(rate) for rate in device_info['supportedSampleRates']]
  830. if supported_rates:
  831. max_rate = max(supported_rates)
  832. return max_rate
  833. except Exception as e:
  834. logging.warning(f"Failed to get highest sample rate: {e}")
  835. return 48000 # Fallback to a common high sample rate
  836. def initialize_audio_stream(audio_interface, sample_rate, chunk_size):
  837. nonlocal input_device_index
  838. """Initialize the audio stream with error handling."""
  839. while not shutdown_event.is_set():
  840. try:
  841. # Check and assign the input device index if it is not set
  842. if input_device_index is None:
  843. default_device = audio_interface.get_default_input_device_info()
  844. input_device_index = default_device['index']
  845. stream = audio_interface.open(
  846. format=pyaudio.paInt16,
  847. channels=1,
  848. rate=sample_rate,
  849. input=True,
  850. frames_per_buffer=chunk_size,
  851. input_device_index=input_device_index,
  852. )
  853. logging.info("Microphone connected successfully.")
  854. return stream
  855. except Exception as e:
  856. logging.error(f"Microphone connection failed: {e}. Retrying...")
  857. input_device_index = None
  858. time.sleep(3) # Wait for 3 seconds before retrying
  859. def preprocess_audio(chunk, original_sample_rate, target_sample_rate):
  860. """Preprocess audio chunk similar to feed_audio method."""
  861. if isinstance(chunk, np.ndarray):
  862. # Handle stereo to mono conversion if necessary
  863. if chunk.ndim == 2:
  864. chunk = np.mean(chunk, axis=1)
  865. # Resample to target_sample_rate if necessary
  866. if original_sample_rate != target_sample_rate:
  867. num_samples = int(len(chunk) * target_sample_rate / original_sample_rate)
  868. chunk = signal.resample(chunk, num_samples)
  869. # Ensure data type is int16
  870. chunk = chunk.astype(np.int16)
  871. else:
  872. # If chunk is bytes, convert to numpy array
  873. chunk = np.frombuffer(chunk, dtype=np.int16)
  874. # Resample if necessary
  875. if original_sample_rate != target_sample_rate:
  876. num_samples = int(len(chunk) * target_sample_rate / original_sample_rate)
  877. chunk = signal.resample(chunk, num_samples)
  878. chunk = chunk.astype(np.int16)
  879. return chunk.tobytes()
  880. audio_interface = None
  881. stream = None
  882. device_sample_rate = None
  883. chunk_size = 1024 # Increased chunk size for better performance
  884. def setup_audio():
  885. nonlocal audio_interface, stream, device_sample_rate, input_device_index
  886. try:
  887. audio_interface = pyaudio.PyAudio()
  888. if input_device_index is None:
  889. try:
  890. default_device = audio_interface.get_default_input_device_info()
  891. input_device_index = default_device['index']
  892. except OSError as e:
  893. input_device_index = None
  894. sample_rates_to_try = [16000] # Try 16000 Hz first
  895. if input_device_index is not None:
  896. highest_rate = get_highest_sample_rate(audio_interface, input_device_index)
  897. if highest_rate != 16000:
  898. sample_rates_to_try.append(highest_rate)
  899. else:
  900. sample_rates_to_try.append(48000) # Fallback sample rate
  901. for rate in sample_rates_to_try:
  902. try:
  903. device_sample_rate = rate
  904. stream = initialize_audio_stream(audio_interface, device_sample_rate, chunk_size)
  905. if stream is not None:
  906. logging.debug(f"Audio recording initialized successfully at {device_sample_rate} Hz, reading {chunk_size} frames at a time")
  907. # logging.error(f"Audio recording initialized successfully at {device_sample_rate} Hz, reading {chunk_size} frames at a time")
  908. return True
  909. except Exception as e:
  910. logging.warning(f"Failed to initialize audio23 stream at {device_sample_rate} Hz: {e}")
  911. continue
  912. # If we reach here, none of the sample rates worked
  913. raise Exception("Failed to initialize audio stream12 with all sample rates.")
  914. except Exception as e:
  915. logging.exception(f"Error initializing pyaudio audio recording: {e}")
  916. if audio_interface:
  917. audio_interface.terminate()
  918. return False
  919. if not setup_audio():
  920. raise Exception("Failed to set up audio recording.")
  921. buffer = bytearray()
  922. silero_buffer_size = 2 * buffer_size # silero complains if too short
  923. time_since_last_buffer_message = 0
  924. try:
  925. while not shutdown_event.is_set():
  926. try:
  927. data = stream.read(chunk_size, exception_on_overflow=False)
  928. if use_microphone.value:
  929. processed_data = preprocess_audio(data, device_sample_rate, target_sample_rate)
  930. buffer += processed_data
  931. # Check if the buffer has reached or exceeded the silero_buffer_size
  932. while len(buffer) >= silero_buffer_size:
  933. # Extract silero_buffer_size amount of data from the buffer
  934. to_process = buffer[:silero_buffer_size]
  935. buffer = buffer[silero_buffer_size:]
  936. # Feed the extracted data to the audio_queue
  937. if time_since_last_buffer_message:
  938. time_passed = time.time() - time_since_last_buffer_message
  939. if time_passed > 1:
  940. logging.debug("_audio_data_worker writing audio data into queue.")
  941. time_since_last_buffer_message = time.time()
  942. else:
  943. time_since_last_buffer_message = time.time()
  944. audio_queue.put(to_process)
  945. except OSError as e:
  946. if e.errno == pyaudio.paInputOverflowed:
  947. logging.warning("Input overflowed. Frame dropped.")
  948. else:
  949. logging.error(f"OSError during recording: {e}")
  950. # Attempt to reinitialize the stream
  951. logging.info("Attempting to reinitialize the audio stream...")
  952. try:
  953. if stream:
  954. stream.stop_stream()
  955. stream.close()
  956. except Exception as e:
  957. pass
  958. if audio_interface:
  959. audio_interface.terminate()
  960. # Wait a bit before trying to reinitialize
  961. time.sleep(1)
  962. if not setup_audio():
  963. logging.error("Failed to reinitialize audio stream. Exiting.")
  964. break
  965. else:
  966. logging.info("Audio stream reinitialized successfully.")
  967. continue
  968. except Exception as e:
  969. logging.error(f"Unknown error during recording: {e}")
  970. tb_str = traceback.format_exc()
  971. logging.error(f"Traceback: {tb_str}")
  972. logging.error(f"Error: {e}")
  973. # Attempt to reinitialize the stream
  974. logging.info("Attempting to reinitialize the audio stream...")
  975. if stream:
  976. stream.stop_stream()
  977. stream.close()
  978. if audio_interface:
  979. audio_interface.terminate()
  980. # Wait a bit before trying to reinitialize
  981. time.sleep(0.5)
  982. if not setup_audio():
  983. logging.error("Failed to reinitialize audio stream. Exiting.")
  984. break
  985. else:
  986. logging.info("Audio stream reinitialized successfully.")
  987. continue
  988. except KeyboardInterrupt:
  989. interrupt_stop_event.set()
  990. logging.debug("Audio data worker process finished due to KeyboardInterrupt")
  991. finally:
  992. # After recording stops, feed any remaining audio data
  993. if buffer:
  994. audio_queue.put(bytes(buffer))
  995. if stream:
  996. stream.stop_stream()
  997. stream.close()
  998. if audio_interface:
  999. audio_interface.terminate()
  1000. def wakeup(self):
  1001. """
  1002. If in wake work modus, wake up as if a wake word was spoken.
  1003. """
  1004. self.listen_start = time.time()
  1005. def abort(self):
  1006. self.start_recording_on_voice_activity = False
  1007. self.stop_recording_on_voice_deactivity = False
  1008. self._set_state("inactive")
  1009. self.interrupt_stop_event.set()
  1010. self.was_interrupted.wait()
  1011. self.was_interrupted.clear()
  1012. def wait_audio(self):
  1013. """
  1014. Waits for the start and completion of the audio recording process.
  1015. This method is responsible for:
  1016. - Waiting for voice activity to begin recording if not yet started.
  1017. - Waiting for voice inactivity to complete the recording.
  1018. - Setting the audio buffer from the recorded frames.
  1019. - Resetting recording-related attributes.
  1020. Side effects:
  1021. - Updates the state of the instance.
  1022. - Modifies the audio attribute to contain the processed audio data.
  1023. """
  1024. try:
  1025. logging.info("Setting listen time")
  1026. if self.listen_start == 0:
  1027. self.listen_start = time.time()
  1028. # If not yet started recording, wait for voice activity to initiate.
  1029. if not self.is_recording and not self.frames:
  1030. self._set_state("listening")
  1031. self.start_recording_on_voice_activity = True
  1032. # Wait until recording starts
  1033. logging.debug('Waiting for recording start')
  1034. while not self.interrupt_stop_event.is_set():
  1035. if self.start_recording_event.wait(timeout=0.02):
  1036. break
  1037. # If recording is ongoing, wait for voice inactivity
  1038. # to finish recording.
  1039. if self.is_recording:
  1040. self.stop_recording_on_voice_deactivity = True
  1041. # Wait until recording stops
  1042. logging.debug('Waiting for recording stop')
  1043. while not self.interrupt_stop_event.is_set():
  1044. if (self.stop_recording_event.wait(timeout=0.02)):
  1045. break
  1046. # Convert recorded frames to the appropriate audio format.
  1047. audio_array = np.frombuffer(b''.join(self.frames), dtype=np.int16)
  1048. self.audio = audio_array.astype(np.float32) / INT16_MAX_ABS_VALUE
  1049. self.frames.clear()
  1050. # Reset recording-related timestamps
  1051. self.recording_stop_time = 0
  1052. self.listen_start = 0
  1053. self._set_state("inactive")
  1054. except KeyboardInterrupt:
  1055. logging.info("KeyboardInterrupt in wait_audio, shutting down")
  1056. self.shutdown()
  1057. raise # Re-raise the exception after cleanup
  1058. def transcribe(self):
  1059. """
  1060. Transcribes audio captured by this class instance using the
  1061. `faster_whisper` model.
  1062. Automatically starts recording upon voice activity if not manually
  1063. started using `recorder.start()`.
  1064. Automatically stops recording upon voice deactivity if not manually
  1065. stopped with `recorder.stop()`.
  1066. Processes the recorded audio to generate transcription.
  1067. Args:
  1068. on_transcription_finished (callable, optional): Callback function
  1069. to be executed when transcription is ready.
  1070. If provided, transcription will be performed asynchronously,
  1071. and the callback will receive the transcription as its argument.
  1072. If omitted, the transcription will be performed synchronously,
  1073. and the result will be returned.
  1074. Returns (if no callback is set):
  1075. str: The transcription of the recorded audio.
  1076. Raises:
  1077. Exception: If there is an error during the transcription process.
  1078. """
  1079. self._set_state("transcribing")
  1080. audio_copy = copy.deepcopy(self.audio)
  1081. start_time = 0
  1082. with self.transcription_lock:
  1083. try:
  1084. if self.transcribe_count == 0:
  1085. logging.debug("Adding transcription request, no early transcription started")
  1086. start_time = time.time() # Start timing
  1087. self.parent_transcription_pipe.send((audio_copy, self.language))
  1088. self.transcribe_count += 1
  1089. while self.transcribe_count > 0:
  1090. logging.debug(F"Receive from parent_transcription_pipe after sendiung transcription request, transcribe_count: {self.transcribe_count}")
  1091. status, result = self.parent_transcription_pipe.recv()
  1092. self.transcribe_count -= 1
  1093. self.allowed_to_early_transcribe = True
  1094. self._set_state("inactive")
  1095. if status == 'success':
  1096. segments, info = result
  1097. self.detected_language = info.language if info.language_probability > 0 else None
  1098. self.detected_language_probability = info.language_probability
  1099. self.last_transcription_bytes = copy.deepcopy(audio_copy)
  1100. self.last_transcription_bytes_b64 = base64.b64encode(self.last_transcription_bytes.tobytes()).decode('utf-8')
  1101. transcription = self._preprocess_output(segments)
  1102. end_time = time.time() # End timing
  1103. transcription_time = end_time - start_time
  1104. if start_time:
  1105. if self.print_transcription_time:
  1106. print(f"Model {self.main_model_type} completed transcription in {transcription_time:.2f} seconds")
  1107. else:
  1108. logging.debug(f"Model {self.main_model_type} completed transcription in {transcription_time:.2f} seconds")
  1109. return transcription
  1110. else:
  1111. logging.error(f"Transcription error: {result}")
  1112. raise Exception(result)
  1113. except Exception as e:
  1114. logging.error(f"Error during transcription: {str(e)}")
  1115. raise e
  1116. def _process_wakeword(self, data):
  1117. """
  1118. Processes audio data to detect wake words.
  1119. """
  1120. if self.wakeword_backend in {'pvp', 'pvporcupine'}:
  1121. pcm = struct.unpack_from(
  1122. "h" * self.buffer_size,
  1123. data
  1124. )
  1125. porcupine_index = self.porcupine.process(pcm)
  1126. if self.debug_mode:
  1127. logging.info(f"wake words porcupine_index: {porcupine_index}")
  1128. return self.porcupine.process(pcm)
  1129. elif self.wakeword_backend in {'oww', 'openwakeword', 'openwakewords'}:
  1130. pcm = np.frombuffer(data, dtype=np.int16)
  1131. prediction = self.owwModel.predict(pcm)
  1132. max_score = -1
  1133. max_index = -1
  1134. wake_words_in_prediction = len(self.owwModel.prediction_buffer.keys())
  1135. self.wake_words_sensitivities
  1136. if wake_words_in_prediction:
  1137. for idx, mdl in enumerate(self.owwModel.prediction_buffer.keys()):
  1138. scores = list(self.owwModel.prediction_buffer[mdl])
  1139. if scores[-1] >= self.wake_words_sensitivity and scores[-1] > max_score:
  1140. max_score = scores[-1]
  1141. max_index = idx
  1142. if self.debug_mode:
  1143. logging.info(f"wake words oww max_index, max_score: {max_index} {max_score}")
  1144. return max_index
  1145. else:
  1146. if self.debug_mode:
  1147. logging.info(f"wake words oww_index: -1")
  1148. return -1
  1149. if self.debug_mode:
  1150. logging.info("wake words no match")
  1151. return -1
  1152. def text(self,
  1153. on_transcription_finished=None,
  1154. ):
  1155. """
  1156. Transcribes audio captured by this class instance
  1157. using the `faster_whisper` model.
  1158. - Automatically starts recording upon voice activity if not manually
  1159. started using `recorder.start()`.
  1160. - Automatically stops recording upon voice deactivity if not manually
  1161. stopped with `recorder.stop()`.
  1162. - Processes the recorded audio to generate transcription.
  1163. Args:
  1164. on_transcription_finished (callable, optional): Callback function
  1165. to be executed when transcription is ready.
  1166. If provided, transcription will be performed asynchronously, and
  1167. the callback will receive the transcription as its argument.
  1168. If omitted, the transcription will be performed synchronously,
  1169. and the result will be returned.
  1170. Returns (if not callback is set):
  1171. str: The transcription of the recorded audio
  1172. """
  1173. self.interrupt_stop_event.clear()
  1174. self.was_interrupted.clear()
  1175. try:
  1176. self.wait_audio()
  1177. except KeyboardInterrupt:
  1178. logging.info("KeyboardInterrupt in text() method")
  1179. self.shutdown()
  1180. raise # Re-raise the exception after cleanup
  1181. if self.is_shut_down or self.interrupt_stop_event.is_set():
  1182. if self.interrupt_stop_event.is_set():
  1183. self.was_interrupted.set()
  1184. return ""
  1185. if on_transcription_finished:
  1186. threading.Thread(target=on_transcription_finished,
  1187. args=(self.transcribe(),)).start()
  1188. else:
  1189. return self.transcribe()
  1190. def start(self):
  1191. """
  1192. Starts recording audio directly without waiting for voice activity.
  1193. """
  1194. # Ensure there's a minimum interval
  1195. # between stopping and starting recording
  1196. if (time.time() - self.recording_stop_time
  1197. < self.min_gap_between_recordings):
  1198. logging.info("Attempted to start recording "
  1199. "too soon after stopping."
  1200. )
  1201. return self
  1202. logging.info("recording started")
  1203. self._set_state("recording")
  1204. self.text_storage = []
  1205. self.realtime_stabilized_text = ""
  1206. self.realtime_stabilized_safetext = ""
  1207. self.wakeword_detected = False
  1208. self.wake_word_detect_time = 0
  1209. self.frames = []
  1210. self.is_recording = True
  1211. self.recording_start_time = time.time()
  1212. self.is_silero_speech_active = False
  1213. self.is_webrtc_speech_active = False
  1214. self.stop_recording_event.clear()
  1215. self.start_recording_event.set()
  1216. if self.on_recording_start:
  1217. self.on_recording_start()
  1218. return self
  1219. def stop(self):
  1220. """
  1221. Stops recording audio.
  1222. """
  1223. # Ensure there's a minimum interval
  1224. # between starting and stopping recording
  1225. if (time.time() - self.recording_start_time
  1226. < self.min_length_of_recording):
  1227. logging.info("Attempted to stop recording "
  1228. "too soon after starting."
  1229. )
  1230. return self
  1231. logging.info("recording stopped")
  1232. self.is_recording = False
  1233. self.recording_stop_time = time.time()
  1234. self.is_silero_speech_active = False
  1235. self.is_webrtc_speech_active = False
  1236. self.silero_check_time = 0
  1237. self.start_recording_event.clear()
  1238. self.stop_recording_event.set()
  1239. if self.on_recording_stop:
  1240. self.on_recording_stop()
  1241. return self
  1242. def listen(self):
  1243. """
  1244. Puts recorder in immediate "listen" state.
  1245. This is the state after a wake word detection, for example.
  1246. The recorder now "listens" for voice activation.
  1247. Once voice is detected we enter "recording" state.
  1248. """
  1249. self.listen_start = time.time()
  1250. self._set_state("listening")
  1251. self.start_recording_on_voice_activity = True
  1252. def feed_audio(self, chunk, original_sample_rate=16000):
  1253. """
  1254. Feed an audio chunk into the processing pipeline. Chunks are
  1255. accumulated until the buffer size is reached, and then the accumulated
  1256. data is fed into the audio_queue.
  1257. """
  1258. # Check if the buffer attribute exists, if not, initialize it
  1259. if not hasattr(self, 'buffer'):
  1260. self.buffer = bytearray()
  1261. # Check if input is a NumPy array
  1262. if isinstance(chunk, np.ndarray):
  1263. # Handle stereo to mono conversion if necessary
  1264. if chunk.ndim == 2:
  1265. chunk = np.mean(chunk, axis=1)
  1266. # Resample to 16000 Hz if necessary
  1267. if original_sample_rate != 16000:
  1268. num_samples = int(len(chunk) * 16000 / original_sample_rate)
  1269. chunk = resample(chunk, num_samples)
  1270. # Ensure data type is int16
  1271. chunk = chunk.astype(np.int16)
  1272. # Convert the NumPy array to bytes
  1273. chunk = chunk.tobytes()
  1274. # Append the chunk to the buffer
  1275. self.buffer += chunk
  1276. buf_size = 2 * self.buffer_size # silero complains if too short
  1277. # Check if the buffer has reached or exceeded the buffer_size
  1278. while len(self.buffer) >= buf_size:
  1279. # Extract self.buffer_size amount of data from the buffer
  1280. to_process = self.buffer[:buf_size]
  1281. self.buffer = self.buffer[buf_size:]
  1282. # Feed the extracted data to the audio_queue
  1283. self.audio_queue.put(to_process)
  1284. def set_microphone(self, microphone_on=True):
  1285. """
  1286. Set the microphone on or off.
  1287. """
  1288. logging.info("Setting microphone to: " + str(microphone_on))
  1289. self.use_microphone.value = microphone_on
  1290. def shutdown(self):
  1291. """
  1292. Safely shuts down the audio recording by stopping the
  1293. recording worker and closing the audio stream.
  1294. """
  1295. with self.shutdown_lock:
  1296. if self.is_shut_down:
  1297. return
  1298. print("\033[91mRealtimeSTT shutting down\033[0m")
  1299. # logging.debug("RealtimeSTT shutting down")
  1300. # Force wait_audio() and text() to exit
  1301. self.is_shut_down = True
  1302. self.start_recording_event.set()
  1303. self.stop_recording_event.set()
  1304. self.shutdown_event.set()
  1305. self.is_recording = False
  1306. self.is_running = False
  1307. logging.debug('Finishing recording thread')
  1308. if self.recording_thread:
  1309. self.recording_thread.join()
  1310. logging.debug('Terminating reader process')
  1311. # Give it some time to finish the loop and cleanup.
  1312. if self.use_microphone.value:
  1313. self.reader_process.join(timeout=10)
  1314. if self.reader_process.is_alive():
  1315. logging.warning("Reader process did not terminate "
  1316. "in time. Terminating forcefully."
  1317. )
  1318. self.reader_process.terminate()
  1319. logging.debug('Terminating transcription process')
  1320. self.transcript_process.join(timeout=10)
  1321. if self.transcript_process.is_alive():
  1322. logging.warning("Transcript process did not terminate "
  1323. "in time. Terminating forcefully."
  1324. )
  1325. self.transcript_process.terminate()
  1326. self.parent_transcription_pipe.close()
  1327. logging.debug('Finishing realtime thread')
  1328. if self.realtime_thread:
  1329. self.realtime_thread.join()
  1330. if self.enable_realtime_transcription:
  1331. if self.realtime_model_type:
  1332. del self.realtime_model_type
  1333. self.realtime_model_type = None
  1334. gc.collect()
  1335. def _recording_worker(self):
  1336. """
  1337. The main worker method which constantly monitors the audio
  1338. input for voice activity and accordingly starts/stops the recording.
  1339. """
  1340. if self.use_extended_logging:
  1341. logging.debug('Debug: Entering try block')
  1342. last_inner_try_time = 0
  1343. try:
  1344. if self.use_extended_logging:
  1345. logging.debug('Debug: Initializing variables')
  1346. time_since_last_buffer_message = 0
  1347. was_recording = False
  1348. delay_was_passed = False
  1349. wakeword_detected_time = None
  1350. wakeword_samples_to_remove = None
  1351. self.allowed_to_early_transcribe = True
  1352. if self.use_extended_logging:
  1353. logging.debug('Debug: Starting main loop')
  1354. # Continuously monitor audio for voice activity
  1355. while self.is_running:
  1356. if self.use_extended_logging:
  1357. logging.debug('Debug: Entering inner try block')
  1358. if last_inner_try_time:
  1359. last_processing_time = time.time() - last_inner_try_time
  1360. if last_processing_time > 0.1:
  1361. if self.use_extended_logging:
  1362. logging.warning('### WARNING: PROCESSING TOOK TOO LONG')
  1363. last_inner_try_time = time.time()
  1364. try:
  1365. if self.use_extended_logging:
  1366. logging.debug('Debug: Trying to get data from audio queue')
  1367. try:
  1368. data = self.audio_queue.get(timeout=0.01)
  1369. self.last_words_buffer.append(data)
  1370. except queue.Empty:
  1371. if self.use_extended_logging:
  1372. logging.debug('Debug: Queue is empty, checking if still running')
  1373. if not self.is_running:
  1374. if self.use_extended_logging:
  1375. logging.debug('Debug: Not running, breaking loop')
  1376. break
  1377. if self.use_extended_logging:
  1378. logging.debug('Debug: Continuing to next iteration')
  1379. continue
  1380. if self.use_extended_logging:
  1381. logging.debug('Debug: Checking for on_recorded_chunk callback')
  1382. if self.on_recorded_chunk:
  1383. if self.use_extended_logging:
  1384. logging.debug('Debug: Calling on_recorded_chunk')
  1385. self.on_recorded_chunk(data)
  1386. if self.use_extended_logging:
  1387. logging.debug('Debug: Checking if handle_buffer_overflow is True')
  1388. if self.handle_buffer_overflow:
  1389. if self.use_extended_logging:
  1390. logging.debug('Debug: Handling buffer overflow')
  1391. # Handle queue overflow
  1392. if (self.audio_queue.qsize() >
  1393. self.allowed_latency_limit):
  1394. if self.use_extended_logging:
  1395. logging.debug('Debug: Queue size exceeds limit, logging warnings')
  1396. logging.warning("Audio queue size exceeds "
  1397. "latency limit. Current size: "
  1398. f"{self.audio_queue.qsize()}. "
  1399. "Discarding old audio chunks."
  1400. )
  1401. if self.use_extended_logging:
  1402. logging.debug('Debug: Discarding old chunks if necessary')
  1403. while (self.audio_queue.qsize() >
  1404. self.allowed_latency_limit):
  1405. data = self.audio_queue.get()
  1406. except BrokenPipeError:
  1407. logging.error("BrokenPipeError _recording_worker")
  1408. self.is_running = False
  1409. break
  1410. if self.use_extended_logging:
  1411. logging.debug('Debug: Updating time_since_last_buffer_message')
  1412. # Feed the extracted data to the audio_queue
  1413. if time_since_last_buffer_message:
  1414. time_passed = time.time() - time_since_last_buffer_message
  1415. if time_passed > 1:
  1416. if self.use_extended_logging:
  1417. logging.debug("_recording_worker processing audio data")
  1418. time_since_last_buffer_message = time.time()
  1419. else:
  1420. time_since_last_buffer_message = time.time()
  1421. if self.use_extended_logging:
  1422. logging.debug('Debug: Initializing failed_stop_attempt')
  1423. failed_stop_attempt = False
  1424. if self.use_extended_logging:
  1425. logging.debug('Debug: Checking if not recording')
  1426. if not self.is_recording:
  1427. if self.use_extended_logging:
  1428. logging.debug('Debug: Handling not recording state')
  1429. # Handle not recording state
  1430. time_since_listen_start = (time.time() - self.listen_start
  1431. if self.listen_start else 0)
  1432. wake_word_activation_delay_passed = (
  1433. time_since_listen_start >
  1434. self.wake_word_activation_delay
  1435. )
  1436. if self.use_extended_logging:
  1437. logging.debug('Debug: Handling wake-word timeout callback')
  1438. # Handle wake-word timeout callback
  1439. if wake_word_activation_delay_passed \
  1440. and not delay_was_passed:
  1441. if self.use_wake_words and self.wake_word_activation_delay:
  1442. if self.on_wakeword_timeout:
  1443. if self.use_extended_logging:
  1444. logging.debug('Debug: Calling on_wakeword_timeout')
  1445. self.on_wakeword_timeout()
  1446. delay_was_passed = wake_word_activation_delay_passed
  1447. if self.use_extended_logging:
  1448. logging.debug('Debug: Setting state and spinner text')
  1449. # Set state and spinner text
  1450. if not self.recording_stop_time:
  1451. if self.use_wake_words \
  1452. and wake_word_activation_delay_passed \
  1453. and not self.wakeword_detected:
  1454. if self.use_extended_logging:
  1455. logging.debug('Debug: Setting state to "wakeword"')
  1456. self._set_state("wakeword")
  1457. else:
  1458. if self.listen_start:
  1459. if self.use_extended_logging:
  1460. logging.debug('Debug: Setting state to "listening"')
  1461. self._set_state("listening")
  1462. else:
  1463. if self.use_extended_logging:
  1464. logging.debug('Debug: Setting state to "inactive"')
  1465. self._set_state("inactive")
  1466. if self.use_extended_logging:
  1467. logging.debug('Debug: Checking wake word conditions')
  1468. if self.use_wake_words and wake_word_activation_delay_passed:
  1469. try:
  1470. if self.use_extended_logging:
  1471. logging.debug('Debug: Processing wakeword')
  1472. wakeword_index = self._process_wakeword(data)
  1473. except struct.error:
  1474. logging.error("Error unpacking audio data "
  1475. "for wake word processing.")
  1476. continue
  1477. except Exception as e:
  1478. logging.error(f"Wake word processing error: {e}")
  1479. continue
  1480. if self.use_extended_logging:
  1481. logging.debug('Debug: Checking if wake word detected')
  1482. # If a wake word is detected
  1483. if wakeword_index >= 0:
  1484. if self.use_extended_logging:
  1485. logging.debug('Debug: Wake word detected, updating variables')
  1486. self.wake_word_detect_time = time.time()
  1487. wakeword_detected_time = time.time()
  1488. wakeword_samples_to_remove = int(self.sample_rate * self.wake_word_buffer_duration)
  1489. self.wakeword_detected = True
  1490. if self.on_wakeword_detected:
  1491. if self.use_extended_logging:
  1492. logging.debug('Debug: Calling on_wakeword_detected')
  1493. self.on_wakeword_detected()
  1494. if self.use_extended_logging:
  1495. logging.debug('Debug: Checking voice activity conditions')
  1496. # Check for voice activity to
  1497. # trigger the start of recording
  1498. if ((not self.use_wake_words
  1499. or not wake_word_activation_delay_passed)
  1500. and self.start_recording_on_voice_activity) \
  1501. or self.wakeword_detected:
  1502. if self.use_extended_logging:
  1503. logging.debug('Debug: Checking if voice is active')
  1504. if self._is_voice_active():
  1505. if self.use_extended_logging:
  1506. logging.debug('Debug: Voice activity detected')
  1507. logging.info("voice activity detected")
  1508. if self.use_extended_logging:
  1509. logging.debug('Debug: Starting recording')
  1510. self.start()
  1511. self.start_recording_on_voice_activity = False
  1512. if self.use_extended_logging:
  1513. logging.debug('Debug: Adding buffered audio to frames')
  1514. # Add the buffered audio
  1515. # to the recording frames
  1516. self.frames.extend(list(self.audio_buffer))
  1517. self.audio_buffer.clear()
  1518. if self.use_extended_logging:
  1519. logging.debug('Debug: Resetting Silero VAD model states')
  1520. self.silero_vad_model.reset_states()
  1521. else:
  1522. if self.use_extended_logging:
  1523. logging.debug('Debug: Checking voice activity')
  1524. data_copy = data[:]
  1525. self._check_voice_activity(data_copy)
  1526. if self.use_extended_logging:
  1527. logging.debug('Debug: Resetting speech_end_silence_start')
  1528. self.speech_end_silence_start = 0
  1529. else:
  1530. if self.use_extended_logging:
  1531. logging.debug('Debug: Handling recording state')
  1532. # If we are currently recording
  1533. if wakeword_samples_to_remove and wakeword_samples_to_remove > 0:
  1534. if self.use_extended_logging:
  1535. logging.debug('Debug: Removing wakeword samples')
  1536. # Remove samples from the beginning of self.frames
  1537. samples_removed = 0
  1538. while wakeword_samples_to_remove > 0 and self.frames:
  1539. frame = self.frames[0]
  1540. frame_samples = len(frame) // 2 # Assuming 16-bit audio
  1541. if wakeword_samples_to_remove >= frame_samples:
  1542. self.frames.pop(0)
  1543. samples_removed += frame_samples
  1544. wakeword_samples_to_remove -= frame_samples
  1545. else:
  1546. self.frames[0] = frame[wakeword_samples_to_remove * 2:]
  1547. samples_removed += wakeword_samples_to_remove
  1548. samples_to_remove = 0
  1549. wakeword_samples_to_remove = 0
  1550. if self.use_extended_logging:
  1551. logging.debug('Debug: Checking if stop_recording_on_voice_deactivity is True')
  1552. # Stop the recording if silence is detected after speech
  1553. if self.stop_recording_on_voice_deactivity:
  1554. if self.use_extended_logging:
  1555. logging.debug('Debug: Determining if speech is detected')
  1556. is_speech = (
  1557. self._is_silero_speech(data) if self.silero_deactivity_detection
  1558. else self._is_webrtc_speech(data, True)
  1559. )
  1560. if self.use_extended_logging:
  1561. logging.debug('Debug: Formatting speech_end_silence_start')
  1562. if not self.speech_end_silence_start:
  1563. str_speech_end_silence_start = "0"
  1564. else:
  1565. str_speech_end_silence_start = datetime.datetime.fromtimestamp(self.speech_end_silence_start).strftime('%H:%M:%S.%f')[:-3]
  1566. if self.use_extended_logging:
  1567. logging.debug(f"is_speech: {is_speech}, str_speech_end_silence_start: {str_speech_end_silence_start}")
  1568. if self.use_extended_logging:
  1569. logging.debug('Debug: Checking if speech is not detected')
  1570. if not is_speech:
  1571. if self.use_extended_logging:
  1572. logging.debug('Debug: Handling voice deactivity')
  1573. # Voice deactivity was detected, so we start
  1574. # measuring silence time before stopping recording
  1575. if self.speech_end_silence_start == 0 and \
  1576. (time.time() - self.recording_start_time > self.min_length_of_recording):
  1577. self.speech_end_silence_start = time.time()
  1578. if self.use_extended_logging:
  1579. logging.debug('Debug: Checking early transcription conditions')
  1580. if self.speech_end_silence_start and self.early_transcription_on_silence and len(self.frames) > 0 and \
  1581. (time.time() - self.speech_end_silence_start > self.early_transcription_on_silence) and \
  1582. self.allowed_to_early_transcribe:
  1583. if self.use_extended_logging:
  1584. logging.debug("Debug:Adding early transcription request")
  1585. self.transcribe_count += 1
  1586. audio_array = np.frombuffer(b''.join(self.frames), dtype=np.int16)
  1587. audio = audio_array.astype(np.float32) / INT16_MAX_ABS_VALUE
  1588. if self.use_extended_logging:
  1589. logging.debug("Debug: early transcription request pipe send")
  1590. self.parent_transcription_pipe.send((audio, self.language))
  1591. if self.use_extended_logging:
  1592. logging.debug("Debug: early transcription request pipe send return")
  1593. self.allowed_to_early_transcribe = False
  1594. else:
  1595. if self.use_extended_logging:
  1596. logging.debug('Debug: Handling speech detection')
  1597. if self.speech_end_silence_start:
  1598. if self.use_extended_logging:
  1599. logging.info("Resetting self.speech_end_silence_start")
  1600. self.speech_end_silence_start = 0
  1601. self.allowed_to_early_transcribe = True
  1602. if self.use_extended_logging:
  1603. logging.debug('Debug: Checking if silence duration exceeds threshold')
  1604. # Wait for silence to stop recording after speech
  1605. if self.speech_end_silence_start and time.time() - \
  1606. self.speech_end_silence_start >= \
  1607. self.post_speech_silence_duration:
  1608. if self.use_extended_logging:
  1609. logging.debug('Debug: Formatting silence start time')
  1610. # Get time in desired format (HH:MM:SS.nnn)
  1611. silence_start_time = datetime.datetime.fromtimestamp(self.speech_end_silence_start).strftime('%H:%M:%S.%f')[:-3]
  1612. if self.use_extended_logging:
  1613. logging.debug('Debug: Calculating time difference')
  1614. # Calculate time difference
  1615. time_diff = time.time() - self.speech_end_silence_start
  1616. if self.use_extended_logging:
  1617. logging.debug('Debug: Logging voice deactivity detection')
  1618. logging.info(f"voice deactivity detected at {silence_start_time}, "
  1619. f"time since silence start: {time_diff:.3f} seconds")
  1620. logging.debug('Debug: Appending data to frames and stopping recording')
  1621. self.frames.append(data)
  1622. self.stop()
  1623. if not self.is_recording:
  1624. if self.use_extended_logging:
  1625. logging.debug('Debug: Resetting speech_end_silence_start')
  1626. self.speech_end_silence_start = 0
  1627. if self.use_extended_logging:
  1628. logging.debug('Debug: Handling non-wake word scenario')
  1629. else:
  1630. if self.use_extended_logging:
  1631. logging.debug('Debug: Setting failed_stop_attempt to True')
  1632. failed_stop_attempt = True
  1633. if self.use_extended_logging:
  1634. logging.debug('Debug: Checking if recording stopped')
  1635. if not self.is_recording and was_recording:
  1636. if self.use_extended_logging:
  1637. logging.debug('Debug: Resetting after stopping recording')
  1638. # Reset after stopping recording to ensure clean state
  1639. self.stop_recording_on_voice_deactivity = False
  1640. if self.use_extended_logging:
  1641. logging.debug('Debug: Checking Silero time')
  1642. if time.time() - self.silero_check_time > 0.1:
  1643. self.silero_check_time = 0
  1644. if self.use_extended_logging:
  1645. logging.debug('Debug: Handling wake word timeout')
  1646. # Handle wake word timeout (waited to long initiating
  1647. # speech after wake word detection)
  1648. if self.wake_word_detect_time and time.time() - \
  1649. self.wake_word_detect_time > self.wake_word_timeout:
  1650. self.wake_word_detect_time = 0
  1651. if self.wakeword_detected and self.on_wakeword_timeout:
  1652. if self.use_extended_logging:
  1653. logging.debug('Debug: Calling on_wakeword_timeout')
  1654. self.on_wakeword_timeout()
  1655. self.wakeword_detected = False
  1656. if self.use_extended_logging:
  1657. logging.debug('Debug: Updating was_recording')
  1658. was_recording = self.is_recording
  1659. if self.use_extended_logging:
  1660. logging.debug('Debug: Checking if recording and not failed stop attempt')
  1661. if self.is_recording and not failed_stop_attempt:
  1662. if self.use_extended_logging:
  1663. logging.debug('Debug: Appending data to frames')
  1664. self.frames.append(data)
  1665. if self.use_extended_logging:
  1666. logging.debug('Debug: Checking if not recording or speech end silence start')
  1667. if not self.is_recording or self.speech_end_silence_start:
  1668. if self.use_extended_logging:
  1669. logging.debug('Debug: Appending data to audio buffer')
  1670. self.audio_buffer.append(data)
  1671. except Exception as e:
  1672. logging.debug('Debug: Caught exception in main try block')
  1673. if not self.interrupt_stop_event.is_set():
  1674. logging.error(f"Unhandled exeption in _recording_worker: {e}")
  1675. raise
  1676. if self.use_extended_logging:
  1677. logging.debug('Debug: Exiting _recording_worker method')
  1678. def _realtime_worker(self):
  1679. """
  1680. Performs real-time transcription if the feature is enabled.
  1681. The method is responsible transcribing recorded audio frames
  1682. in real-time based on the specified resolution interval.
  1683. The transcribed text is stored in `self.realtime_transcription_text`
  1684. and a callback
  1685. function is invoked with this text if specified.
  1686. """
  1687. try:
  1688. logging.debug('Starting realtime worker')
  1689. # Return immediately if real-time transcription is not enabled
  1690. if not self.enable_realtime_transcription:
  1691. return
  1692. # Continue running as long as the main process is active
  1693. while self.is_running:
  1694. # Check if the recording is active
  1695. if self.is_recording:
  1696. # Sleep for the duration of the transcription resolution
  1697. time.sleep(self.realtime_processing_pause)
  1698. # Convert the buffer frames to a NumPy array
  1699. audio_array = np.frombuffer(
  1700. b''.join(self.frames),
  1701. dtype=np.int16
  1702. )
  1703. logging.debug(f"Current realtime buffer size: {len(audio_array)}")
  1704. # Normalize the array to a [-1, 1] range
  1705. audio_array = audio_array.astype(np.float32) / \
  1706. INT16_MAX_ABS_VALUE
  1707. if self.use_main_model_for_realtime:
  1708. with self.transcription_lock:
  1709. try:
  1710. self.parent_transcription_pipe.send((audio_array, self.language))
  1711. if self.parent_transcription_pipe.poll(timeout=5): # Wait for 5 seconds
  1712. logging.debug("Receive from realtime worker after transcription request to main model")
  1713. status, result = self.parent_transcription_pipe.recv()
  1714. if status == 'success':
  1715. segments, info = result
  1716. self.detected_realtime_language = info.language if info.language_probability > 0 else None
  1717. self.detected_realtime_language_probability = info.language_probability
  1718. realtime_text = segments
  1719. logging.debug(f"Realtime text detected with main model: {realtime_text}")
  1720. else:
  1721. logging.error(f"Realtime transcription error: {result}")
  1722. continue
  1723. else:
  1724. logging.warning("Realtime transcription timed out")
  1725. continue
  1726. except Exception as e:
  1727. logging.error(f"Error in realtime transcription: {str(e)}")
  1728. continue
  1729. else:
  1730. # Perform transcription and assemble the text
  1731. segments, info = self.realtime_model_type.transcribe(
  1732. audio_array,
  1733. language=self.language if self.language else None,
  1734. beam_size=self.beam_size_realtime,
  1735. initial_prompt=self.initial_prompt,
  1736. suppress_tokens=self.suppress_tokens,
  1737. )
  1738. self.detected_realtime_language = info.language if info.language_probability > 0 else None
  1739. self.detected_realtime_language_probability = info.language_probability
  1740. realtime_text = " ".join(
  1741. seg.text for seg in segments
  1742. )
  1743. logging.debug(f"Realtime text detected: {realtime_text}")
  1744. # double check recording state
  1745. # because it could have changed mid-transcription
  1746. if self.is_recording and time.time() - \
  1747. self.recording_start_time > 0.5:
  1748. # logging.debug('Starting realtime transcription')
  1749. self.realtime_transcription_text = realtime_text
  1750. self.realtime_transcription_text = \
  1751. self.realtime_transcription_text.strip()
  1752. self.text_storage.append(
  1753. self.realtime_transcription_text
  1754. )
  1755. # Take the last two texts in storage, if they exist
  1756. if len(self.text_storage) >= 2:
  1757. last_two_texts = self.text_storage[-2:]
  1758. # Find the longest common prefix
  1759. # between the two texts
  1760. prefix = os.path.commonprefix(
  1761. [last_two_texts[0], last_two_texts[1]]
  1762. )
  1763. # This prefix is the text that was transcripted
  1764. # two times in the same way
  1765. # Store as "safely detected text"
  1766. if len(prefix) >= \
  1767. len(self.realtime_stabilized_safetext):
  1768. # Only store when longer than the previous
  1769. # as additional security
  1770. self.realtime_stabilized_safetext = prefix
  1771. # Find parts of the stabilized text
  1772. # in the freshly transcripted text
  1773. matching_pos = self._find_tail_match_in_text(
  1774. self.realtime_stabilized_safetext,
  1775. self.realtime_transcription_text
  1776. )
  1777. if matching_pos < 0:
  1778. if self.realtime_stabilized_safetext:
  1779. self._on_realtime_transcription_stabilized(
  1780. self._preprocess_output(
  1781. self.realtime_stabilized_safetext,
  1782. True
  1783. )
  1784. )
  1785. else:
  1786. self._on_realtime_transcription_stabilized(
  1787. self._preprocess_output(
  1788. self.realtime_transcription_text,
  1789. True
  1790. )
  1791. )
  1792. else:
  1793. # We found parts of the stabilized text
  1794. # in the transcripted text
  1795. # We now take the stabilized text
  1796. # and add only the freshly transcripted part to it
  1797. output_text = self.realtime_stabilized_safetext + \
  1798. self.realtime_transcription_text[matching_pos:]
  1799. # This yields us the "left" text part as stabilized
  1800. # AND at the same time delivers fresh detected
  1801. # parts on the first run without the need for
  1802. # two transcriptions
  1803. self._on_realtime_transcription_stabilized(
  1804. self._preprocess_output(output_text, True)
  1805. )
  1806. # Invoke the callback with the transcribed text
  1807. self._on_realtime_transcription_update(
  1808. self._preprocess_output(
  1809. self.realtime_transcription_text,
  1810. True
  1811. )
  1812. )
  1813. # If not recording, sleep briefly before checking again
  1814. else:
  1815. time.sleep(TIME_SLEEP)
  1816. except Exception as e:
  1817. logging.error(f"Unhandled exeption in _realtime_worker: {e}")
  1818. raise
  1819. def _is_silero_speech(self, chunk):
  1820. """
  1821. Returns true if speech is detected in the provided audio data
  1822. Args:
  1823. data (bytes): raw bytes of audio data (1024 raw bytes with
  1824. 16000 sample rate and 16 bits per sample)
  1825. """
  1826. if self.sample_rate != 16000:
  1827. pcm_data = np.frombuffer(chunk, dtype=np.int16)
  1828. data_16000 = signal.resample_poly(
  1829. pcm_data, 16000, self.sample_rate)
  1830. chunk = data_16000.astype(np.int16).tobytes()
  1831. self.silero_working = True
  1832. audio_chunk = np.frombuffer(chunk, dtype=np.int16)
  1833. audio_chunk = audio_chunk.astype(np.float32) / INT16_MAX_ABS_VALUE
  1834. vad_prob = self.silero_vad_model(
  1835. torch.from_numpy(audio_chunk),
  1836. SAMPLE_RATE).item()
  1837. is_silero_speech_active = vad_prob > (1 - self.silero_sensitivity)
  1838. if is_silero_speech_active:
  1839. self.is_silero_speech_active = True
  1840. self.silero_working = False
  1841. return is_silero_speech_active
  1842. def _is_webrtc_speech(self, chunk, all_frames_must_be_true=False):
  1843. """
  1844. Returns true if speech is detected in the provided audio data
  1845. Args:
  1846. data (bytes): raw bytes of audio data (1024 raw bytes with
  1847. 16000 sample rate and 16 bits per sample)
  1848. """
  1849. if self.sample_rate != 16000:
  1850. pcm_data = np.frombuffer(chunk, dtype=np.int16)
  1851. data_16000 = signal.resample_poly(
  1852. pcm_data, 16000, self.sample_rate)
  1853. chunk = data_16000.astype(np.int16).tobytes()
  1854. # Number of audio frames per millisecond
  1855. frame_length = int(16000 * 0.01) # for 10ms frame
  1856. num_frames = int(len(chunk) / (2 * frame_length))
  1857. speech_frames = 0
  1858. for i in range(num_frames):
  1859. start_byte = i * frame_length * 2
  1860. end_byte = start_byte + frame_length * 2
  1861. frame = chunk[start_byte:end_byte]
  1862. if self.webrtc_vad_model.is_speech(frame, 16000):
  1863. speech_frames += 1
  1864. if not all_frames_must_be_true:
  1865. if self.debug_mode:
  1866. logging.info(f"Speech detected in frame {i + 1}"
  1867. f" of {num_frames}")
  1868. return True
  1869. if all_frames_must_be_true:
  1870. if self.debug_mode and speech_frames == num_frames:
  1871. logging.info(f"Speech detected in {speech_frames} of "
  1872. f"{num_frames} frames")
  1873. elif self.debug_mode:
  1874. logging.info(f"Speech not detected in all {num_frames} frames")
  1875. return speech_frames == num_frames
  1876. else:
  1877. if self.debug_mode:
  1878. logging.info(f"Speech not detected in any of {num_frames} frames")
  1879. return False
  1880. def _check_voice_activity(self, data):
  1881. """
  1882. Initiate check if voice is active based on the provided data.
  1883. Args:
  1884. data: The audio data to be checked for voice activity.
  1885. """
  1886. self.is_webrtc_speech_active = self._is_webrtc_speech(data)
  1887. # First quick performing check for voice activity using WebRTC
  1888. if self.is_webrtc_speech_active:
  1889. if not self.silero_working:
  1890. self.silero_working = True
  1891. # Run the intensive check in a separate thread
  1892. threading.Thread(
  1893. target=self._is_silero_speech,
  1894. args=(data,)).start()
  1895. def clear_audio_queue(self):
  1896. """
  1897. Safely empties the audio queue to ensure no remaining audio
  1898. fragments get processed e.g. after waking up the recorder.
  1899. """
  1900. self.audio_buffer.clear()
  1901. try:
  1902. while True:
  1903. self.audio_queue.get_nowait()
  1904. except:
  1905. # PyTorch's mp.Queue doesn't have a specific Empty exception
  1906. # so we catch any exception that might occur when the queue is empty
  1907. pass
  1908. def _is_voice_active(self):
  1909. """
  1910. Determine if voice is active.
  1911. Returns:
  1912. bool: True if voice is active, False otherwise.
  1913. """
  1914. return self.is_webrtc_speech_active and self.is_silero_speech_active
  1915. def _set_state(self, new_state):
  1916. """
  1917. Update the current state of the recorder and execute
  1918. corresponding state-change callbacks.
  1919. Args:
  1920. new_state (str): The new state to set.
  1921. """
  1922. # Check if the state has actually changed
  1923. if new_state == self.state:
  1924. return
  1925. # Store the current state for later comparison
  1926. old_state = self.state
  1927. # Update to the new state
  1928. self.state = new_state
  1929. # Log the state change
  1930. logging.info(f"State changed from '{old_state}' to '{new_state}'")
  1931. # Execute callbacks based on transitioning FROM a particular state
  1932. if old_state == "listening":
  1933. if self.on_vad_detect_stop:
  1934. self.on_vad_detect_stop()
  1935. elif old_state == "wakeword":
  1936. if self.on_wakeword_detection_end:
  1937. self.on_wakeword_detection_end()
  1938. # Execute callbacks based on transitioning TO a particular state
  1939. if new_state == "listening":
  1940. if self.on_vad_detect_start:
  1941. self.on_vad_detect_start()
  1942. self._set_spinner("speak now")
  1943. if self.spinner and self.halo:
  1944. self.halo._interval = 250
  1945. elif new_state == "wakeword":
  1946. if self.on_wakeword_detection_start:
  1947. self.on_wakeword_detection_start()
  1948. self._set_spinner(f"say {self.wake_words}")
  1949. if self.spinner and self.halo:
  1950. self.halo._interval = 500
  1951. elif new_state == "transcribing":
  1952. if self.on_transcription_start:
  1953. self.on_transcription_start()
  1954. self._set_spinner("transcribing")
  1955. if self.spinner and self.halo:
  1956. self.halo._interval = 50
  1957. elif new_state == "recording":
  1958. self._set_spinner("recording")
  1959. if self.spinner and self.halo:
  1960. self.halo._interval = 100
  1961. elif new_state == "inactive":
  1962. if self.spinner and self.halo:
  1963. self.halo.stop()
  1964. self.halo = None
  1965. def _set_spinner(self, text):
  1966. """
  1967. Update the spinner's text or create a new
  1968. spinner with the provided text.
  1969. Args:
  1970. text (str): The text to be displayed alongside the spinner.
  1971. """
  1972. if self.spinner:
  1973. # If the Halo spinner doesn't exist, create and start it
  1974. if self.halo is None:
  1975. self.halo = halo.Halo(text=text)
  1976. self.halo.start()
  1977. # If the Halo spinner already exists, just update the text
  1978. else:
  1979. self.halo.text = text
  1980. def _preprocess_output(self, text, preview=False):
  1981. """
  1982. Preprocesses the output text by removing any leading or trailing
  1983. whitespace, converting all whitespace sequences to a single space
  1984. character, and capitalizing the first character of the text.
  1985. Args:
  1986. text (str): The text to be preprocessed.
  1987. Returns:
  1988. str: The preprocessed text.
  1989. """
  1990. text = re.sub(r'\s+', ' ', text.strip())
  1991. if self.ensure_sentence_starting_uppercase:
  1992. if text:
  1993. text = text[0].upper() + text[1:]
  1994. # Ensure the text ends with a proper punctuation
  1995. # if it ends with an alphanumeric character
  1996. if not preview:
  1997. if self.ensure_sentence_ends_with_period:
  1998. if text and text[-1].isalnum():
  1999. text += '.'
  2000. return text
  2001. def _find_tail_match_in_text(self, text1, text2, length_of_match=10):
  2002. """
  2003. Find the position where the last 'n' characters of text1
  2004. match with a substring in text2.
  2005. This method takes two texts, extracts the last 'n' characters from
  2006. text1 (where 'n' is determined by the variable 'length_of_match'), and
  2007. searches for an occurrence of this substring in text2, starting from
  2008. the end of text2 and moving towards the beginning.
  2009. Parameters:
  2010. - text1 (str): The text containing the substring that we want to find
  2011. in text2.
  2012. - text2 (str): The text in which we want to find the matching
  2013. substring.
  2014. - length_of_match(int): The length of the matching string that we are
  2015. looking for
  2016. Returns:
  2017. int: The position (0-based index) in text2 where the matching
  2018. substring starts. If no match is found or either of the texts is
  2019. too short, returns -1.
  2020. """
  2021. # Check if either of the texts is too short
  2022. if len(text1) < length_of_match or len(text2) < length_of_match:
  2023. return -1
  2024. # The end portion of the first text that we want to compare
  2025. target_substring = text1[-length_of_match:]
  2026. # Loop through text2 from right to left
  2027. for i in range(len(text2) - length_of_match + 1):
  2028. # Extract the substring from text2
  2029. # to compare with the target_substring
  2030. current_substring = text2[len(text2) - i - length_of_match:
  2031. len(text2) - i]
  2032. # Compare the current_substring with the target_substring
  2033. if current_substring == target_substring:
  2034. # Position in text2 where the match starts
  2035. return len(text2) - i
  2036. return -1
  2037. def _on_realtime_transcription_stabilized(self, text):
  2038. """
  2039. Callback method invoked when the real-time transcription stabilizes.
  2040. This method is called internally when the transcription text is
  2041. considered "stable" meaning it's less likely to change significantly
  2042. with additional audio input. It notifies any registered external
  2043. listener about the stabilized text if recording is still ongoing.
  2044. This is particularly useful for applications that need to display
  2045. live transcription results to users and want to highlight parts of the
  2046. transcription that are less likely to change.
  2047. Args:
  2048. text (str): The stabilized transcription text.
  2049. """
  2050. if self.on_realtime_transcription_stabilized:
  2051. if self.is_recording:
  2052. self.on_realtime_transcription_stabilized(text)
  2053. def _on_realtime_transcription_update(self, text):
  2054. """
  2055. Callback method invoked when there's an update in the real-time
  2056. transcription.
  2057. This method is called internally whenever there's a change in the
  2058. transcription text, notifying any registered external listener about
  2059. the update if recording is still ongoing. This provides a mechanism
  2060. for applications to receive and possibly display live transcription
  2061. updates, which could be partial and still subject to change.
  2062. Args:
  2063. text (str): The updated transcription text.
  2064. """
  2065. if self.on_realtime_transcription_update:
  2066. if self.is_recording:
  2067. self.on_realtime_transcription_update(text)
  2068. def __enter__(self):
  2069. """
  2070. Method to setup the context manager protocol.
  2071. This enables the instance to be used in a `with` statement, ensuring
  2072. proper resource management. When the `with` block is entered, this
  2073. method is automatically called.
  2074. Returns:
  2075. self: The current instance of the class.
  2076. """
  2077. return self
  2078. def __exit__(self, exc_type, exc_value, traceback):
  2079. """
  2080. Method to define behavior when the context manager protocol exits.
  2081. This is called when exiting the `with` block and ensures that any
  2082. necessary cleanup or resource release processes are executed, such as
  2083. shutting down the system properly.
  2084. Args:
  2085. exc_type (Exception or None): The type of the exception that
  2086. caused the context to be exited, if any.
  2087. exc_value (Exception or None): The exception instance that caused
  2088. the context to be exited, if any.
  2089. traceback (Traceback or None): The traceback corresponding to the
  2090. exception, if any.
  2091. """
  2092. self.shutdown()