audio_recorder.py 94 KB

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