audio_recorder.py 66 KB

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