audio_recorder.py 76 KB

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