audio_recorder.py 113 KB

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