audio_recorder.py 75 KB

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