audio_recorder.py 93 KB

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