audio_recorder.py 76 KB

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