audio_recorder.py 65 KB

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