audio_recorder.py 118 KB

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