audio_recorder.py 123 KB

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