audio_recorder.py 86 KB

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