audio_recorder.py 63 KB

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