audio_recorder.py 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180
  1. """
  2. The AudioToTextRecorder class in the provided code facilitates fast speech-to-text transcription.
  3. The class employs the faster_whisper library to transcribe the recorded audio
  4. into text using machine learning models, which can be run either on a GPU or CPU.
  5. Voice activity detection (VAD) is built in, meaning the software can automatically
  6. start or stop recording based on the presence or absence of speech.
  7. It integrates wake word detection through the pvporcupine library, allowing the
  8. software to initiate recording when a specific word or phrase is spoken.
  9. The system provides real-time feedback and can be further customized.
  10. Features:
  11. - Voice Activity Detection: Automatically starts/stops recording when speech is detected or when speech ends.
  12. - Wake Word Detection: Starts recording when a specified wake word (or words) is detected.
  13. - Event Callbacks: Customizable callbacks for when recording starts or finishes.
  14. - Fast Transcription: Returns the transcribed text from the audio as fast as possible.
  15. Author: Kolja Beigel
  16. """
  17. from multiprocessing import Process, Pipe, Event, Manager
  18. import faster_whisper
  19. import collections
  20. import numpy as np
  21. import pvporcupine
  22. import collections
  23. import traceback
  24. import threading
  25. import webrtcvad
  26. import itertools
  27. import pyaudio
  28. import logging
  29. import struct
  30. import torch
  31. import halo
  32. import time
  33. import os
  34. import re
  35. INIT_MODEL_TRANSCRIPTION = "tiny"
  36. INIT_MODEL_TRANSCRIPTION_REALTIME = "tiny"
  37. INIT_REALTIME_PROCESSING_PAUSE = 0.2
  38. INIT_SILERO_SENSITIVITY = 0.4
  39. INIT_WEBRTC_SENSITIVITY = 3
  40. INIT_POST_SPEECH_SILENCE_DURATION = 0.6
  41. INIT_MIN_LENGTH_OF_RECORDING = 0.5
  42. INIT_MIN_GAP_BETWEEN_RECORDINGS = 0
  43. INIT_WAKE_WORDS_SENSITIVITY = 0.6
  44. INIT_PRE_RECORDING_BUFFER_DURATION = 1.0
  45. INIT_WAKE_WORD_ACTIVATION_DELAY = 0.0
  46. INIT_WAKE_WORD_TIMEOUT = 5.0
  47. ALLOWED_LATENCY_LIMIT = 10
  48. TIME_SLEEP = 0.02
  49. SAMPLE_RATE = 16000
  50. BUFFER_SIZE = 512
  51. INT16_MAX_ABS_VALUE = 32768.0
  52. class AudioToTextRecorder:
  53. """
  54. A class responsible for capturing audio from the microphone, detecting voice activity, and then transcribing the captured audio using the `faster_whisper` model.
  55. """
  56. def __init__(self,
  57. model: str = INIT_MODEL_TRANSCRIPTION,
  58. language: str = "",
  59. on_recording_start = None,
  60. on_recording_stop = None,
  61. on_transcription_start = None,
  62. ensure_sentence_starting_uppercase = True,
  63. ensure_sentence_ends_with_period = True,
  64. spinner = True,
  65. level=logging.WARNING,
  66. # Realtime transcription parameters
  67. enable_realtime_transcription = False,
  68. realtime_model_type = INIT_MODEL_TRANSCRIPTION_REALTIME,
  69. realtime_processing_pause = INIT_REALTIME_PROCESSING_PAUSE,
  70. on_realtime_transcription_update = None,
  71. on_realtime_transcription_stabilized = None,
  72. # Voice activation parameters
  73. silero_sensitivity: float = INIT_SILERO_SENSITIVITY,
  74. silero_use_onnx: bool = False,
  75. webrtc_sensitivity: int = INIT_WEBRTC_SENSITIVITY,
  76. post_speech_silence_duration: float = INIT_POST_SPEECH_SILENCE_DURATION,
  77. min_length_of_recording: float = INIT_MIN_LENGTH_OF_RECORDING,
  78. min_gap_between_recordings: float = INIT_MIN_GAP_BETWEEN_RECORDINGS,
  79. pre_recording_buffer_duration: float = INIT_PRE_RECORDING_BUFFER_DURATION,
  80. on_vad_detect_start = None,
  81. on_vad_detect_stop = None,
  82. # Wake word parameters
  83. wake_words: str = "",
  84. wake_words_sensitivity: float = INIT_WAKE_WORDS_SENSITIVITY,
  85. wake_word_activation_delay: float = INIT_WAKE_WORD_ACTIVATION_DELAY,
  86. wake_word_timeout: float = INIT_WAKE_WORD_TIMEOUT,
  87. on_wakeword_detected = None,
  88. on_wakeword_timeout = None,
  89. on_wakeword_detection_start = None,
  90. on_wakeword_detection_end = None,
  91. ):
  92. """
  93. Initializes an audio recorder and transcription and wake word detection.
  94. Args:
  95. - model (str, default="tiny"): Specifies the size of the transcription model to use or the path to a converted model directory.
  96. Valid options are 'tiny', 'tiny.en', 'base', 'base.en', 'small', 'small.en', 'medium', 'medium.en', 'large-v1', 'large-v2'.
  97. If a specific size is provided, the model is downloaded from the Hugging Face Hub.
  98. - language (str, default=""): Language code for speech-to-text engine. If not specified, the model will attempt to detect the language automatically.
  99. - on_recording_start (callable, default=None): Callback function to be called when recording of audio to be transcripted starts.
  100. - on_recording_stop (callable, default=None): Callback function to be called when recording of audio to be transcripted stops.
  101. - on_transcription_start (callable, default=None): Callback function to be called when transcription of audio to text starts.
  102. - ensure_sentence_starting_uppercase (bool, default=True): Ensures that every sentence detected by the algorithm starts with an uppercase letter.
  103. - ensure_sentence_ends_with_period (bool, default=True): Ensures that every sentence that doesn't end with punctuation such as "?", "!" ends with a period
  104. - spinner (bool, default=True): Show spinner animation with current state.
  105. - level (int, default=logging.WARNING): Logging level.
  106. - enable_realtime_transcription (bool, default=False): Enables or disables real-time transcription of audio. When set to True, the audio will be transcribed continuously as it is being recorded.
  107. - realtime_model_type (str, default="tiny"): Specifies the machine learning model to be used for real-time transcription. Valid options include 'tiny', 'tiny.en', 'base', 'base.en', 'small', 'small.en', 'medium', 'medium.en', 'large-v1', 'large-v2'.
  108. - realtime_processing_pause (float, default=0.1): Specifies the time interval in seconds after a chunk of audio gets transcribed. Lower values will result in more "real-time" (frequent) transcription updates but may increase computational load.
  109. - on_realtime_transcription_update = A callback function that is triggered whenever there's an update in the real-time transcription. The function is called with the newly transcribed text as its argument.
  110. - on_realtime_transcription_stabilized = A callback function that is triggered when the transcribed text stabilizes in quality. The stabilized text is generally more accurate but may arrive with a slight delay compared to the regular real-time updates.
  111. - silero_sensitivity (float, default=SILERO_SENSITIVITY): Sensitivity for the Silero Voice Activity Detection model ranging from 0 (least sensitive) to 1 (most sensitive). Default is 0.5.
  112. - silero_use_onnx (bool, default=False): Enables usage of the pre-trained model from Silero in the ONNX (Open Neural Network Exchange) format instead of the PyTorch format. This is recommended for faster performance.
  113. - webrtc_sensitivity (int, default=WEBRTC_SENSITIVITY): Sensitivity for the WebRTC Voice Activity Detection engine ranging from 0 (least aggressive / most sensitive) to 3 (most aggressive, least sensitive). Default is 3.
  114. - post_speech_silence_duration (float, default=0.2): Duration in seconds of silence that must follow speech before the recording is considered to be completed. This ensures that any brief pauses during speech don't prematurely end the recording.
  115. - min_gap_between_recordings (float, default=1.0): Specifies the minimum time interval in seconds that should exist between the end of one recording session and the beginning of another to prevent rapid consecutive recordings.
  116. - min_length_of_recording (float, default=1.0): Specifies the minimum duration in seconds that a recording session should last to ensure meaningful audio capture, preventing excessively short or fragmented recordings.
  117. - pre_recording_buffer_duration (float, default=0.2): Duration in seconds for the audio buffer to maintain pre-roll audio (compensates speech activity detection latency)
  118. - on_vad_detect_start (callable, default=None): Callback function to be called when the system listens for voice activity.
  119. - on_vad_detect_stop (callable, default=None): Callback function to be called when the system stops listening for voice activity.
  120. - wake_words (str, default=""): Comma-separated string of wake words to initiate recording. Supported wake words include:
  121. 'alexa', 'americano', 'blueberry', 'bumblebee', 'computer', 'grapefruits', 'grasshopper', 'hey google', 'hey siri', 'jarvis', 'ok google', 'picovoice', 'porcupine', 'terminator'.
  122. - wake_words_sensitivity (float, default=0.5): Sensitivity for wake word detection, ranging from 0 (least sensitive) to 1 (most sensitive). Default is 0.5.
  123. - wake_word_activation_delay (float, default=0): Duration in seconds after the start of monitoring before the system switches to wake word activation if no voice is initially detected. If set to zero, the system uses wake word activation immediately.
  124. - wake_word_timeout (float, default=5): Duration in seconds after a wake word is recognized. If no subsequent voice activity is detected within this window, the system transitions back to an inactive state, awaiting the next wake word or voice activation.
  125. - on_wakeword_detected (callable, default=None): Callback function to be called when a wake word is detected.
  126. - on_wakeword_timeout (callable, default=None): Callback function to be called when the system goes back to an inactive state after when no speech was detected after wake word activation
  127. - on_wakeword_detection_start (callable, default=None): Callback function to be called when the system starts to listen for wake words
  128. - on_wakeword_detection_end (callable, default=None): Callback function to be called when the system stops to listen for wake words (e.g. because of timeout or wake word detected)
  129. Raises:
  130. Exception: Errors related to initializing transcription model, wake word detection, or audio recording.
  131. """
  132. self.language = language
  133. self.wake_words = wake_words
  134. self.wake_word_activation_delay = wake_word_activation_delay
  135. self.wake_word_timeout = wake_word_timeout
  136. self.ensure_sentence_starting_uppercase = ensure_sentence_starting_uppercase
  137. self.ensure_sentence_ends_with_period = ensure_sentence_ends_with_period
  138. self.min_gap_between_recordings = min_gap_between_recordings
  139. self.min_length_of_recording = min_length_of_recording
  140. self.pre_recording_buffer_duration = pre_recording_buffer_duration
  141. self.post_speech_silence_duration = post_speech_silence_duration
  142. self.on_recording_start = on_recording_start
  143. self.on_recording_stop = on_recording_stop
  144. self.on_wakeword_detected = on_wakeword_detected
  145. self.on_wakeword_timeout = on_wakeword_timeout
  146. self.on_vad_detect_start = on_vad_detect_start
  147. self.on_vad_detect_stop = on_vad_detect_stop
  148. self.on_wakeword_detection_start = on_wakeword_detection_start
  149. self.on_wakeword_detection_end = on_wakeword_detection_end
  150. self.on_transcription_start = on_transcription_start
  151. self.enable_realtime_transcription = enable_realtime_transcription
  152. self.realtime_model_type = realtime_model_type
  153. self.realtime_processing_pause = realtime_processing_pause
  154. self.on_realtime_transcription_update = on_realtime_transcription_update
  155. self.on_realtime_transcription_stabilized = on_realtime_transcription_stabilized
  156. self.allowed_latency_limit = ALLOWED_LATENCY_LIMIT
  157. self.level = level
  158. manager = Manager()
  159. self.audio_queue = manager.Queue()
  160. self.buffer_size = BUFFER_SIZE
  161. self.sample_rate = SAMPLE_RATE
  162. self.recording_start_time = 0
  163. self.recording_stop_time = 0
  164. self.wake_word_detect_time = 0
  165. self.silero_check_time = 0
  166. self.silero_working = False
  167. self.speech_end_silence_start = 0
  168. self.silero_sensitivity = silero_sensitivity
  169. self.listen_start = 0
  170. self.spinner = spinner
  171. self.halo = None
  172. self.state = "inactive"
  173. self.wakeword_detected = False
  174. self.text_storage = []
  175. self.realtime_stabilized_text = ""
  176. self.realtime_stabilized_safetext = ""
  177. self.is_webrtc_speech_active = False
  178. self.is_silero_speech_active = False
  179. self.recording_thread = None
  180. self.realtime_thread = None
  181. self.audio_interface = None
  182. self.audio = None
  183. self.stream = None
  184. self.start_recording_event = threading.Event()
  185. self.stop_recording_event = threading.Event()
  186. # Initialize the logging configuration with the specified level
  187. log_format = 'RealTimeSTT: %(name)s - %(levelname)s - %(message)s'
  188. # Create a logger
  189. logger = logging.getLogger()
  190. logger.setLevel(level) # Set the root logger's level
  191. # Create a file handler and set its level
  192. file_handler = logging.FileHandler('realtimesst.log')
  193. file_handler.setLevel(logging.DEBUG)
  194. file_handler.setFormatter(logging.Formatter(log_format))
  195. # Create a console handler and set its level
  196. console_handler = logging.StreamHandler()
  197. console_handler.setLevel(level)
  198. console_handler.setFormatter(logging.Formatter(log_format))
  199. # Add the handlers to the logger
  200. logger.addHandler(file_handler)
  201. logger.addHandler(console_handler)
  202. self.is_shut_down = False
  203. self.shutdown_event = Event()
  204. logging.info(f"Starting RealTimeSTT")
  205. # Start transcription process
  206. self.interrupt_stop_event = Event()
  207. self.main_transcription_ready_event = Event()
  208. self.parent_transcription_pipe, child_transcription_pipe = Pipe()
  209. self.transcript_process = Process(target=AudioToTextRecorder._transcription_worker, args=(child_transcription_pipe, model, self.main_transcription_ready_event, self.shutdown_event, self.interrupt_stop_event))
  210. self.transcript_process.start()
  211. # Start audio data reading process
  212. self.reader_process = Process(target=AudioToTextRecorder._audio_data_worker, args=(self.audio_queue, self.sample_rate, self.buffer_size, self.shutdown_event, self.interrupt_stop_event))
  213. self.reader_process.start()
  214. # Initialize the realtime transcription model
  215. if self.enable_realtime_transcription:
  216. try:
  217. logging.info(f"Initializing faster_whisper realtime transcription model {self.realtime_model_type}")
  218. self.realtime_model_type = faster_whisper.WhisperModel(model_size_or_path=self.realtime_model_type, device='cuda' if torch.cuda.is_available() else 'cpu')
  219. except Exception as e:
  220. logging.exception(f"Error initializing faster_whisper realtime transcription model: {e}")
  221. raise
  222. logging.debug('Faster_whisper realtime speech to text transcription model initialized successfully')
  223. # Setup wake word detection
  224. if wake_words:
  225. self.wake_words_list = [word.strip() for word in wake_words.lower().split(',')]
  226. sensitivity_list = [float(wake_words_sensitivity) for _ in range(len(self.wake_words_list))]
  227. try:
  228. self.porcupine = pvporcupine.create(keywords=self.wake_words_list, sensitivities=sensitivity_list)
  229. self.buffer_size = self.porcupine.frame_length
  230. self.sample_rate = self.porcupine.sample_rate
  231. except Exception as e:
  232. logging.exception(f"Error initializing porcupine wake word detection engine: {e}")
  233. raise
  234. logging.debug('Porcupine wake word detection engine initialized successfully')
  235. # Setup voice activity detection model WebRTC
  236. try:
  237. logging.info(f"Initializing WebRTC voice with Sensitivity {webrtc_sensitivity}")
  238. self.webrtc_vad_model = webrtcvad.Vad()
  239. self.webrtc_vad_model.set_mode(webrtc_sensitivity)
  240. except Exception as e:
  241. logging.exception(f"Error initializing WebRTC voice activity detection engine: {e}")
  242. raise
  243. logging.debug('WebRTC VAD voice activity detection engine initialized successfully')
  244. # Setup voice activity detection model Silero VAD
  245. try:
  246. self.silero_vad_model, _ = torch.hub.load(
  247. repo_or_dir="snakers4/silero-vad",
  248. model="silero_vad",
  249. verbose=False,
  250. onnx=silero_use_onnx
  251. )
  252. except Exception as e:
  253. logging.exception(f"Error initializing Silero VAD voice activity detection engine: {e}")
  254. raise
  255. logging.debug('Silero VAD voice activity detection engine initialized successfully')
  256. self.audio_buffer = collections.deque(maxlen=int((self.sample_rate // self.buffer_size) * self.pre_recording_buffer_duration))
  257. self.frames = []
  258. # Recording control flags
  259. self.is_recording = False
  260. self.is_running = True
  261. self.start_recording_on_voice_activity = False
  262. self.stop_recording_on_voice_deactivity = False
  263. # Start the recording worker thread
  264. self.recording_thread = threading.Thread(target=self._recording_worker)
  265. self.recording_thread.daemon = True
  266. self.recording_thread.start()
  267. # Start the realtime transcription worker thread
  268. self.realtime_thread = threading.Thread(target=self._realtime_worker)
  269. self.realtime_thread.daemon = True
  270. self.realtime_thread.start()
  271. # Wait for transcription models to start
  272. logging.debug('Waiting for main transcription model to start')
  273. self.main_transcription_ready_event.wait()
  274. logging.debug('Main transcription model ready')
  275. logging.debug('RealtimeSTT initialization completed successfully')
  276. @staticmethod
  277. def _transcription_worker(conn, model_path, ready_event, shutdown_event, interrupt_stop_event):
  278. """
  279. Worker method that handles the continuous process of transcribing audio data.
  280. This method runs in a separate process and is responsible for:
  281. - Initializing the `faster_whisper` model used for transcription.
  282. - Receiving audio data sent through a pipe and using the model to transcribe it.
  283. - Sending transcription results back through the pipe.
  284. - Continuously checking for a shutdown event to gracefully terminate the transcription process.
  285. Args:
  286. conn (multiprocessing.Connection): The connection endpoint used for receiving audio data and sending transcription results.
  287. model_path (str): The path to the pre-trained faster_whisper model for transcription.
  288. ready_event (threading.Event): An event that is set when the transcription model is successfully initialized and ready.
  289. shutdown_event (threading.Event): An event that, when set, signals this worker method to terminate.
  290. Raises:
  291. Exception: If there is an error while initializing the transcription model.
  292. """
  293. logging.info(f"Initializing faster_whisper main transcription model {model_path}")
  294. try:
  295. model = faster_whisper.WhisperModel(
  296. model_size_or_path=model_path,
  297. device='cuda' if torch.cuda.is_available() else 'cpu'
  298. )
  299. except Exception as e:
  300. logging.exception(f"Error initializing main faster_whisper transcription model: {e}")
  301. raise
  302. ready_event.set()
  303. logging.debug('Faster_whisper main speech to text transcription model initialized successfully')
  304. while not shutdown_event.is_set():
  305. try:
  306. if conn.poll(0.5):
  307. audio, language = conn.recv()
  308. try:
  309. segments = model.transcribe(audio, language=language if language else None)[0]
  310. transcription = " ".join(seg.text for seg in segments).strip()
  311. conn.send(('success', transcription))
  312. except faster_whisper.WhisperError as e:
  313. logging.error(f"Whisper transcription error: {e}")
  314. conn.send(('error', str(e)))
  315. except Exception as e:
  316. logging.error(f"General transcription error: {e}")
  317. conn.send(('error', str(e)))
  318. else:
  319. # If there's no data, sleep for a short while to prevent busy waiting
  320. time.sleep(0.02)
  321. except KeyboardInterrupt:
  322. interrupt_stop_event.set()
  323. logging.debug('Transcription worker process finished due to KeyboardInterrupt')
  324. break
  325. @staticmethod
  326. def _audio_data_worker(audio_queue, sample_rate, buffer_size, shutdown_event, interrupt_stop_event):
  327. """
  328. Worker method that handles the audio recording process.
  329. This method runs in a separate process and is responsible for:
  330. - Setting up the audio input stream for recording.
  331. - Continuously reading audio data from the input stream and placing it in a queue.
  332. - Handling errors during the recording process, including input overflow.
  333. - Gracefully terminating the recording process when a shutdown event is set.
  334. Args:
  335. audio_queue (queue.Queue): A queue where recorded audio data is placed.
  336. sample_rate (int): The sample rate of the audio input stream.
  337. buffer_size (int): The size of the buffer used in the audio input stream.
  338. shutdown_event (threading.Event): An event that, when set, signals this worker method to terminate.
  339. Raises:
  340. Exception: If there is an error while initializing the audio recording.
  341. """
  342. logging.info("Initializing audio recording (creating pyAudio input stream)")
  343. try:
  344. audio_interface = pyaudio.PyAudio()
  345. stream = audio_interface.open(rate=sample_rate, format=pyaudio.paInt16, channels=1, input=True, frames_per_buffer=buffer_size)
  346. except Exception as e:
  347. logging.exception(f"Error initializing pyaudio audio recording: {e}")
  348. raise
  349. logging.debug('Audio recording (pyAudio input stream) initialized successfully')
  350. try:
  351. while not shutdown_event.is_set():
  352. try:
  353. data = stream.read(buffer_size)
  354. except OSError as e:
  355. if e.errno == pyaudio.paInputOverflowed:
  356. logging.warning("Input overflowed. Frame dropped.")
  357. else:
  358. logging.error(f"Error during recording: {e}")
  359. tb_str = traceback.format_exc()
  360. print (f"Traceback: {tb_str}")
  361. print (f"Error: {e}")
  362. continue
  363. except Exception as e:
  364. logging.error(f"Error during recording: {e}")
  365. tb_str = traceback.format_exc()
  366. print (f"Traceback: {tb_str}")
  367. print (f"Error: {e}")
  368. continue
  369. audio_queue.put(data)
  370. except KeyboardInterrupt:
  371. interrupt_stop_event.set()
  372. logging.debug('Audio data worker process finished due to KeyboardInterrupt')
  373. finally:
  374. stream.stop_stream()
  375. stream.close()
  376. audio_interface.terminate()
  377. def wait_audio(self):
  378. """
  379. Waits for the start and completion of the audio recording process.
  380. This method is responsible for:
  381. - Waiting for voice activity to begin recording if not yet started.
  382. - Waiting for voice inactivity to complete the recording.
  383. - Setting the audio buffer from the recorded frames.
  384. - Resetting recording-related attributes.
  385. Side effects:
  386. - Updates the state of the instance.
  387. - Modifies the audio attribute to contain the processed audio data.
  388. """
  389. self.listen_start = time.time()
  390. # If not yet started recording, wait for voice activity to initiate.
  391. if not self.is_recording and not self.frames:
  392. self._set_state("listening")
  393. self.start_recording_on_voice_activity = True
  394. # Wait until recording starts
  395. while not self.interrupt_stop_event.is_set():
  396. if (self.start_recording_event.wait(timeout=0.5)): break
  397. # If recording is ongoing, wait for voice inactivity to finish recording.
  398. if self.is_recording:
  399. self.stop_recording_on_voice_deactivity = True
  400. # Wait until recording stops
  401. while not self.interrupt_stop_event.is_set():
  402. if (self.stop_recording_event.wait(timeout=0.5)): break
  403. # Convert recorded frames to the appropriate audio format.
  404. audio_array = np.frombuffer(b''.join(self.frames), dtype=np.int16)
  405. self.audio = audio_array.astype(np.float32) / INT16_MAX_ABS_VALUE
  406. self.frames.clear()
  407. # Reset recording-related timestamps
  408. self.recording_stop_time = 0
  409. self.listen_start = 0
  410. self._set_state("inactive")
  411. def transcribe(self):
  412. """
  413. Transcribes audio captured by this class instance using the `faster_whisper` model.
  414. Automatically starts recording upon voice activity if not manually started using `recorder.start()`.
  415. Automatically stops recording upon voice deactivity if not manually stopped with `recorder.stop()`.
  416. Processes the recorded audio to generate transcription.
  417. Args:
  418. on_transcription_finished (callable, optional): Callback function to be executed when transcription is ready.
  419. If provided, transcription will be performed asynchronously, and the callback will receive the transcription
  420. as its argument. If omitted, the transcription will be performed synchronously, and the result will be returned.
  421. Returns (if no callback is set):
  422. str: The transcription of the recorded audio.
  423. Raises:
  424. Exception: If there is an error during the transcription process.
  425. """
  426. self._set_state("transcribing")
  427. self.parent_transcription_pipe.send((self.audio, self.language))
  428. status, result = self.parent_transcription_pipe.recv()
  429. self._set_state("inactive")
  430. if status == 'success':
  431. return self._preprocess_output(result)
  432. else:
  433. logging.error(result)
  434. raise Exception(result)
  435. def text(self,
  436. on_transcription_finished = None,
  437. ):
  438. """
  439. Transcribes audio captured by this class instance using the `faster_whisper` model.
  440. - Automatically starts recording upon voice activity if not manually started using `recorder.start()`.
  441. - Automatically stops recording upon voice deactivity if not manually stopped with `recorder.stop()`.
  442. - Processes the recorded audio to generate transcription.
  443. Args:
  444. on_transcription_finished (callable, optional): Callback function to be executed when transcription is ready.
  445. If provided, transcription will be performed asynchronously, and the callback will receive the transcription
  446. as its argument. If omitted, the transcription will be performed synchronously, and the result will be returned.
  447. Returns (if not callback is set):
  448. str: The transcription of the recorded audio
  449. """
  450. self.wait_audio()
  451. if self.is_shut_down or self.interrupt_stop_event.is_set():
  452. return ""
  453. if on_transcription_finished:
  454. threading.Thread(target=on_transcription_finished, args=(self.transcribe(),)).start()
  455. else:
  456. return self.transcribe()
  457. def start(self):
  458. """
  459. Starts recording audio directly without waiting for voice activity.
  460. """
  461. # Ensure there's a minimum interval between stopping and starting recording
  462. if time.time() - self.recording_stop_time < self.min_gap_between_recordings:
  463. logging.info("Attempted to start recording too soon after stopping.")
  464. return self
  465. logging.info("recording started")
  466. self._set_state("recording")
  467. self.text_storage = []
  468. self.realtime_stabilized_text = ""
  469. self.realtime_stabilized_safetext = ""
  470. self.wakeword_detected = False
  471. self.wake_word_detect_time = 0
  472. self.frames = []
  473. self.is_recording = True
  474. self.recording_start_time = time.time()
  475. self.is_silero_speech_active = False
  476. self.is_webrtc_speech_active = False
  477. self.stop_recording_event.clear()
  478. self.start_recording_event.set()
  479. if self.on_recording_start:
  480. self.on_recording_start()
  481. return self
  482. def stop(self):
  483. """
  484. Stops recording audio.
  485. """
  486. # Ensure there's a minimum interval between starting and stopping recording
  487. if time.time() - self.recording_start_time < self.min_length_of_recording:
  488. logging.info("Attempted to stop recording too soon after starting.")
  489. return self
  490. logging.info("recording stopped")
  491. self.is_recording = False
  492. self.recording_stop_time = time.time()
  493. self.is_silero_speech_active = False
  494. self.is_webrtc_speech_active = False
  495. self.silero_check_time = 0
  496. self.start_recording_event.clear()
  497. self.stop_recording_event.set()
  498. if self.on_recording_stop:
  499. self.on_recording_stop()
  500. return self
  501. def shutdown(self):
  502. """
  503. Safely shuts down the audio recording by stopping the recording worker and closing the audio stream.
  504. """
  505. # Force wait_audio() and text() to exit
  506. self.is_shut_down = True
  507. self.start_recording_event.set()
  508. self.stop_recording_event.set()
  509. self.shutdown_event.set()
  510. self.is_recording = False
  511. self.is_running = False
  512. logging.debug('Finishing recording thread')
  513. if self.recording_thread:
  514. self.recording_thread.join()
  515. logging.debug('Terminating reader process')
  516. # Give it some time to finish the loop and cleanup.
  517. self.reader_process.join(timeout=10)
  518. if self.reader_process.is_alive():
  519. logging.warning("Reader process did not terminate in time. Terminating forcefully.")
  520. self.reader_process.terminate()
  521. logging.debug('Terminating transcription process')
  522. self.transcript_process.join(timeout=10)
  523. if self.transcript_process.is_alive():
  524. logging.warning("Transcript process did not terminate in time. Terminating forcefully.")
  525. self.transcript_process.terminate()
  526. self.parent_transcription_pipe.close()
  527. logging.debug('Finishing realtime thread')
  528. if self.realtime_thread:
  529. self.realtime_thread.join()
  530. def _recording_worker(self):
  531. """
  532. The main worker method which constantly monitors the audio input for voice activity and accordingly starts/stops the recording.
  533. """
  534. logging.debug('Starting recording worker')
  535. try:
  536. was_recording = False
  537. delay_was_passed = False
  538. # Continuously monitor audio for voice activity
  539. while self.is_running:
  540. try:
  541. data = self.audio_queue.get()
  542. # Handle queue overflow
  543. queue_overflow_logged = False
  544. while self.audio_queue.qsize() > self.allowed_latency_limit:
  545. if not queue_overflow_logged:
  546. logging.warning(f"Audio queue size exceeds latency limit. Current size: {self.audio_queue.qsize()}. Discarding old audio chunks.")
  547. queue_overflow_logged = True
  548. data = self.audio_queue.get()
  549. except BrokenPipeError:
  550. print ("BrokenPipeError _recording_worker")
  551. self.is_running = False
  552. break
  553. if not self.is_recording:
  554. # Handle not recording state
  555. time_since_listen_start = time.time() - self.listen_start if self.listen_start else 0
  556. wake_word_activation_delay_passed = (time_since_listen_start > self.wake_word_activation_delay)
  557. # Handle wake-word timeout callback
  558. if wake_word_activation_delay_passed and not delay_was_passed:
  559. if self.wake_words and self.wake_word_activation_delay:
  560. if self.on_wakeword_timeout:
  561. self.on_wakeword_timeout()
  562. delay_was_passed = wake_word_activation_delay_passed
  563. # Set state and spinner text
  564. if not self.recording_stop_time:
  565. if self.wake_words and wake_word_activation_delay_passed and not self.wakeword_detected:
  566. self._set_state("wakeword")
  567. else:
  568. if self.listen_start:
  569. self._set_state("listening")
  570. else:
  571. self._set_state("inactive")
  572. # Detect wake words if applicable
  573. if self.wake_words and wake_word_activation_delay_passed:
  574. try:
  575. pcm = struct.unpack_from("h" * self.buffer_size, data)
  576. wakeword_index = self.porcupine.process(pcm)
  577. except struct.error:
  578. logging.error("Error unpacking audio data for wake word processing.")
  579. continue
  580. except Exception as e:
  581. logging.error(f"Wake word processing error: {e}")
  582. continue
  583. # If a wake word is detected
  584. if wakeword_index >= 0:
  585. # Removing the wake word from the recording
  586. samples_for_0_1_sec = int(self.sample_rate * 0.1)
  587. start_index = max(0, len(self.audio_buffer) - samples_for_0_1_sec)
  588. temp_samples = collections.deque(itertools.islice(self.audio_buffer, start_index, None))
  589. self.audio_buffer.clear()
  590. self.audio_buffer.extend(temp_samples)
  591. self.wake_word_detect_time = time.time()
  592. self.wakeword_detected = True
  593. if self.on_wakeword_detected:
  594. self.on_wakeword_detected()
  595. # Check for voice activity to trigger the start of recording
  596. if ((not self.wake_words or not wake_word_activation_delay_passed) and self.start_recording_on_voice_activity) or self.wakeword_detected:
  597. if self._is_voice_active():
  598. logging.info("voice activity detected")
  599. self.start()
  600. if self.is_recording:
  601. self.start_recording_on_voice_activity = False
  602. # Add the buffered audio to the recording frames
  603. self.frames.extend(list(self.audio_buffer))
  604. self.audio_buffer.clear()
  605. self.silero_vad_model.reset_states()
  606. else:
  607. data_copy = data[:]
  608. self._check_voice_activity(data_copy)
  609. self.speech_end_silence_start = 0
  610. else:
  611. # If we are currently recording
  612. # Stop the recording if silence is detected after speech
  613. if self.stop_recording_on_voice_deactivity:
  614. if not self._is_webrtc_speech(data, True):
  615. # Voice deactivity was detected, so we start measuring silence time before stopping recording
  616. if self.speech_end_silence_start == 0:
  617. self.speech_end_silence_start = time.time()
  618. else:
  619. self.speech_end_silence_start = 0
  620. # Wait for silence to stop recording after speech
  621. if self.speech_end_silence_start and time.time() - self.speech_end_silence_start > self.post_speech_silence_duration:
  622. logging.info("voice deactivity detected")
  623. self.stop()
  624. if not self.is_recording and was_recording:
  625. # Reset after stopping recording to ensure clean state
  626. self.stop_recording_on_voice_deactivity = False
  627. if time.time() - self.silero_check_time > 0.1:
  628. self.silero_check_time = 0
  629. # Handle wake word timeout (waited to long initiating speech after wake word detection)
  630. if self.wake_word_detect_time and time.time() - self.wake_word_detect_time > self.wake_word_timeout:
  631. self.wake_word_detect_time = 0
  632. if self.wakeword_detected and self.on_wakeword_timeout:
  633. self.on_wakeword_timeout()
  634. self.wakeword_detected = False
  635. was_recording = self.is_recording
  636. if self.is_recording:
  637. self.frames.append(data)
  638. if not self.is_recording or self.speech_end_silence_start:
  639. self.audio_buffer.append(data)
  640. except Exception as e:
  641. if not self.interrupt_stop_event.is_set():
  642. logging.error(f"Unhandled exeption in _recording_worker: {e}")
  643. raise
  644. def _realtime_worker(self):
  645. """
  646. Performs real-time transcription if the feature is enabled.
  647. The method is responsible transcribing recorded audio frames in real-time
  648. based on the specified resolution interval.
  649. The transcribed text is stored in `self.realtime_transcription_text` and a callback
  650. function is invoked with this text if specified.
  651. """
  652. try:
  653. logging.debug('Starting realtime worker')
  654. # Return immediately if real-time transcription is not enabled
  655. if not self.enable_realtime_transcription:
  656. return
  657. # Continue running as long as the main process is active
  658. while self.is_running:
  659. # Check if the recording is active
  660. if self.is_recording:
  661. # Sleep for the duration of the transcription resolution
  662. time.sleep(self.realtime_processing_pause)
  663. # Convert the buffer frames to a NumPy array
  664. audio_array = np.frombuffer(b''.join(self.frames), dtype=np.int16)
  665. # Normalize the array to a [-1, 1] range
  666. audio_array = audio_array.astype(np.float32) / INT16_MAX_ABS_VALUE
  667. # Perform transcription and assemble the text
  668. segments = self.realtime_model_type.transcribe(
  669. audio_array,
  670. language=self.language if self.language else None
  671. )
  672. # double check recording state because it could have changed mid-transcription
  673. if self.is_recording and time.time() - self.recording_start_time > 0.5:
  674. logging.debug('Starting realtime transcription')
  675. self.realtime_transcription_text = " ".join(seg.text for seg in segments[0]).strip()
  676. self.text_storage.append(self.realtime_transcription_text)
  677. # Take the last two texts in storage, if they exist
  678. if len(self.text_storage) >= 2:
  679. last_two_texts = self.text_storage[-2:]
  680. # Find the longest common prefix between the two texts
  681. prefix = os.path.commonprefix([last_two_texts[0], last_two_texts[1]])
  682. # This prefix is the text that was transcripted two times in the same way
  683. # Store as "safely detected text"
  684. if len(prefix) >= len(self.realtime_stabilized_safetext):
  685. # Only store when longer than the previous as additional security
  686. self.realtime_stabilized_safetext = prefix
  687. # Find parts of the stabilized text in the freshly transscripted text
  688. matching_position = self._find_tail_match_in_text(self.realtime_stabilized_safetext, self.realtime_transcription_text)
  689. if matching_position < 0:
  690. if self.realtime_stabilized_safetext:
  691. self._on_realtime_transcription_stabilized(self._preprocess_output(self.realtime_stabilized_safetext, True))
  692. else:
  693. self._on_realtime_transcription_stabilized(self._preprocess_output(self.realtime_transcription_text, True))
  694. else:
  695. # We found parts of the stabilized text in the transcripted text
  696. # We now take the stabilized text and add only the freshly transcripted part to it
  697. output_text = self.realtime_stabilized_safetext + self.realtime_transcription_text[matching_position:]
  698. # This yields us the "left" text part as stabilized AND at the same time delivers fresh detected parts
  699. # on the first run without the need for two transcriptions
  700. self._on_realtime_transcription_stabilized(self._preprocess_output(output_text, True))
  701. # Invoke the callback with the transcribed text
  702. self._on_realtime_transcription_update(self._preprocess_output(self.realtime_transcription_text, True))
  703. # If not recording, sleep briefly before checking again
  704. else:
  705. time.sleep(TIME_SLEEP)
  706. except Exception as e:
  707. logging.error(f"Unhandled exeption in _realtime_worker: {e}")
  708. raise
  709. def _is_silero_speech(self, data):
  710. """
  711. Returns true if speech is detected in the provided audio data
  712. Args:
  713. data (bytes): raw bytes of audio data (1024 raw bytes with 16000 sample rate and 16 bits per sample)
  714. """
  715. self.silero_working = True
  716. audio_chunk = np.frombuffer(data, dtype=np.int16)
  717. audio_chunk = audio_chunk.astype(np.float32) / INT16_MAX_ABS_VALUE # Convert to float and normalize
  718. vad_prob = self.silero_vad_model(torch.from_numpy(audio_chunk), SAMPLE_RATE).item()
  719. is_silero_speech_active = vad_prob > (1 - self.silero_sensitivity)
  720. if is_silero_speech_active:
  721. self.is_silero_speech_active = True
  722. self.silero_working = False
  723. return is_silero_speech_active
  724. def _is_webrtc_speech(self, data, all_frames_must_be_true=False):
  725. """
  726. Returns true if speech is detected in the provided audio data
  727. Args:
  728. data (bytes): raw bytes of audio data (1024 raw bytes with 16000 sample rate and 16 bits per sample)
  729. """
  730. # Number of audio frames per millisecond
  731. frame_length = int(self.sample_rate * 0.01) # for 10ms frame
  732. num_frames = int(len(data) / (2 * frame_length))
  733. speech_frames = 0
  734. for i in range(num_frames):
  735. start_byte = i * frame_length * 2
  736. end_byte = start_byte + frame_length * 2
  737. frame = data[start_byte:end_byte]
  738. if self.webrtc_vad_model.is_speech(frame, self.sample_rate):
  739. speech_frames += 1
  740. if not all_frames_must_be_true:
  741. return True
  742. if all_frames_must_be_true:
  743. return speech_frames == num_frames
  744. else:
  745. return False
  746. def _check_voice_activity(self, data):
  747. """
  748. Initiate check if voice is active based on the provided data.
  749. Args:
  750. data: The audio data to be checked for voice activity.
  751. """
  752. self.is_webrtc_speech_active = self._is_webrtc_speech(data)
  753. # First quick performing check for voice activity using WebRTC
  754. if self.is_webrtc_speech_active:
  755. if not self.silero_working:
  756. self.silero_working = True
  757. # Run the intensive check in a separate thread
  758. threading.Thread(target=self._is_silero_speech, args=(data,)).start()
  759. def _is_voice_active(self):
  760. """
  761. Determine if voice is active.
  762. Returns:
  763. bool: True if voice is active, False otherwise.
  764. """
  765. return self.is_webrtc_speech_active and self.is_silero_speech_active
  766. def _set_state(self, new_state):
  767. """
  768. Update the current state of the recorder and execute corresponding state-change callbacks.
  769. Args:
  770. new_state (str): The new state to set.
  771. """
  772. # Check if the state has actually changed
  773. if new_state == self.state:
  774. return
  775. # Store the current state for later comparison
  776. old_state = self.state
  777. # Update to the new state
  778. self.state = new_state
  779. # Execute callbacks based on transitioning FROM a particular state
  780. if old_state == "listening":
  781. if self.on_vad_detect_stop:
  782. self.on_vad_detect_stop()
  783. elif old_state == "wakeword":
  784. if self.on_wakeword_detection_end:
  785. self.on_wakeword_detection_end()
  786. # Execute callbacks based on transitioning TO a particular state
  787. if new_state == "listening":
  788. if self.on_vad_detect_start:
  789. self.on_vad_detect_start()
  790. self._set_spinner("speak now")
  791. if self.spinner and self.halo:
  792. self.halo._interval = 250
  793. elif new_state == "wakeword":
  794. if self.on_wakeword_detection_start:
  795. self.on_wakeword_detection_start()
  796. self._set_spinner(f"say {self.wake_words}")
  797. if self.spinner and self.halo:
  798. self.halo._interval = 500
  799. elif new_state == "transcribing":
  800. if self.on_transcription_start:
  801. self.on_transcription_start()
  802. self._set_spinner("transcribing")
  803. if self.spinner and self.halo:
  804. self.halo._interval = 50
  805. elif new_state == "recording":
  806. self._set_spinner("recording")
  807. if self.spinner and self.halo:
  808. self.halo._interval = 100
  809. elif new_state == "inactive":
  810. if self.spinner and self.halo:
  811. self.halo.stop()
  812. self.halo = None
  813. def _set_spinner(self, text):
  814. """
  815. Update the spinner's text or create a new spinner with the provided text.
  816. Args:
  817. text (str): The text to be displayed alongside the spinner.
  818. """
  819. if self.spinner:
  820. # If the Halo spinner doesn't exist, create and start it
  821. if self.halo is None:
  822. self.halo = halo.Halo(text=text)
  823. self.halo.start()
  824. # If the Halo spinner already exists, just update the text
  825. else:
  826. self.halo.text = text
  827. def _preprocess_output(self, text, preview=False):
  828. """
  829. Preprocesses the output text by removing any leading or trailing whitespace,
  830. converting all whitespace sequences to a single space character, and capitalizing
  831. the first character of the text.
  832. Args:
  833. text (str): The text to be preprocessed.
  834. Returns:
  835. str: The preprocessed text.
  836. """
  837. text = re.sub(r'\s+', ' ', text.strip())
  838. if self.ensure_sentence_starting_uppercase:
  839. if text:
  840. text = text[0].upper() + text[1:]
  841. # Ensure the text ends with a proper punctuation if it ends with an alphanumeric character
  842. if not preview:
  843. if self.ensure_sentence_ends_with_period:
  844. if text and text[-1].isalnum():
  845. text += '.'
  846. return text
  847. def _find_tail_match_in_text(self, text1, text2, length_of_match=10):
  848. """
  849. Find the position where the last 'n' characters of text1 match with a substring in text2.
  850. This method takes two texts, extracts the last 'n' characters from text1 (where 'n' is determined
  851. by the variable 'length_of_match'), and searches for an occurrence of this substring in text2,
  852. starting from the end of text2 and moving towards the beginning.
  853. Parameters:
  854. - text1 (str): The text containing the substring that we want to find in text2.
  855. - text2 (str): The text in which we want to find the matching substring.
  856. - length_of_match(int): The length of the matching string that we are looking for
  857. Returns:
  858. int: The position (0-based index) in text2 where the matching substring starts.
  859. If no match is found or either of the texts is too short, returns -1.
  860. """
  861. # Check if either of the texts is too short
  862. if len(text1) < length_of_match or len(text2) < length_of_match:
  863. return -1
  864. # The end portion of the first text that we want to compare
  865. target_substring = text1[-length_of_match:]
  866. # Loop through text2 from right to left
  867. for i in range(len(text2) - length_of_match + 1):
  868. # Extract the substring from text2 to compare with the target_substring
  869. current_substring = text2[len(text2) - i - length_of_match:len(text2) - i]
  870. # Compare the current_substring with the target_substring
  871. if current_substring == target_substring:
  872. return len(text2) - i # Position in text2 where the match starts
  873. return -1
  874. def _on_realtime_transcription_stabilized(self, text):
  875. """
  876. Callback method invoked when the real-time transcription stabilizes.
  877. This method is called internally when the transcription text is considered "stable"
  878. meaning it's less likely to change significantly with additional audio input. It
  879. notifies any registered external listener about the stabilized text if recording is
  880. still ongoing. This is particularly useful for applications that need to display
  881. live transcription results to users and want to highlight parts of the transcription
  882. that are less likely to change.
  883. Args:
  884. text (str): The stabilized transcription text.
  885. """
  886. if self.on_realtime_transcription_stabilized:
  887. if self.is_recording:
  888. self.on_realtime_transcription_stabilized(text)
  889. def _on_realtime_transcription_update(self, text):
  890. """
  891. Callback method invoked when there's an update in the real-time transcription.
  892. This method is called internally whenever there's a change in the transcription text,
  893. notifying any registered external listener about the update if recording is still
  894. ongoing. This provides a mechanism for applications to receive and possibly display
  895. live transcription updates, which could be partial and still subject to change.
  896. Args:
  897. text (str): The updated transcription text.
  898. """
  899. if self.on_realtime_transcription_update:
  900. if self.is_recording:
  901. self.on_realtime_transcription_update(text)
  902. def __enter__(self):
  903. """
  904. Method to setup the context manager protocol.
  905. This enables the instance to be used in a `with` statement, ensuring proper
  906. resource management. When the `with` block is entered, this method is
  907. automatically called.
  908. Returns:
  909. self: The current instance of the class.
  910. """
  911. return self
  912. def __exit__(self, exc_type, exc_value, traceback):
  913. """
  914. Method to define behavior when the context manager protocol exits.
  915. This is called when exiting the `with` block and ensures that any necessary
  916. cleanup or resource release processes are executed, such as shutting down
  917. the system properly.
  918. Args:
  919. exc_type (Exception or None): The type of the exception that caused the context to be exited, if any.
  920. exc_value (Exception or None): The exception instance that caused the context to be exited, if any.
  921. traceback (Traceback or None): The traceback corresponding to the exception, if any.
  922. """
  923. self.shutdown()