audio_recorder.py 94 KB

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