audio_recorder.py 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  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, Queue
  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. TIME_SLEEP = 0.02
  48. SAMPLE_RATE = 16000
  49. BUFFER_SIZE = 512
  50. INT16_MAX_ABS_VALUE = 32768.0
  51. class AudioToTextRecorder:
  52. """
  53. A class responsible for capturing audio from the microphone, detecting voice activity, and then transcribing the captured audio using the `faster_whisper` model.
  54. """
  55. def __init__(self,
  56. model: str = INIT_MODEL_TRANSCRIPTION,
  57. language: str = "",
  58. on_recording_start = None,
  59. on_recording_stop = None,
  60. on_transcription_start = None,
  61. ensure_sentence_starting_uppercase = True,
  62. ensure_sentence_ends_with_period = True,
  63. spinner = True,
  64. level=logging.WARNING,
  65. # Realtime transcription parameters
  66. enable_realtime_transcription = False,
  67. realtime_model_type = INIT_MODEL_TRANSCRIPTION_REALTIME,
  68. realtime_processing_pause = INIT_REALTIME_PROCESSING_PAUSE,
  69. on_realtime_transcription_update = None,
  70. on_realtime_transcription_stabilized = None,
  71. # Voice activation parameters
  72. silero_sensitivity: float = INIT_SILERO_SENSITIVITY,
  73. silero_use_onnx: bool = True,
  74. webrtc_sensitivity: int = INIT_WEBRTC_SENSITIVITY,
  75. post_speech_silence_duration: float = INIT_POST_SPEECH_SILENCE_DURATION,
  76. min_length_of_recording: float = INIT_MIN_LENGTH_OF_RECORDING,
  77. min_gap_between_recordings: float = INIT_MIN_GAP_BETWEEN_RECORDINGS,
  78. pre_recording_buffer_duration: float = INIT_PRE_RECORDING_BUFFER_DURATION,
  79. on_vad_detect_start = None,
  80. on_vad_detect_stop = None,
  81. # Wake word parameters
  82. wake_words: str = "",
  83. wake_words_sensitivity: float = INIT_WAKE_WORDS_SENSITIVITY,
  84. wake_word_activation_delay: float = INIT_WAKE_WORD_ACTIVATION_DELAY,
  85. wake_word_timeout: float = INIT_WAKE_WORD_TIMEOUT,
  86. on_wakeword_detected = None,
  87. on_wakeword_timeout = None,
  88. on_wakeword_detection_start = None,
  89. on_wakeword_detection_end = None,
  90. ):
  91. """
  92. Initializes an audio recorder and transcription and wake word detection.
  93. Args:
  94. - model (str, default="tiny"): Specifies the size of the transcription model to use or the path to a converted model directory.
  95. Valid options are 'tiny', 'tiny.en', 'base', 'base.en', 'small', 'small.en', 'medium', 'medium.en', 'large-v1', 'large-v2'.
  96. If a specific size is provided, the model is downloaded from the Hugging Face Hub.
  97. - language (str, default=""): Language code for speech-to-text engine. If not specified, the model will attempt to detect the language automatically.
  98. - on_recording_start (callable, default=None): Callback function to be called when recording of audio to be transcripted starts.
  99. - on_recording_stop (callable, default=None): Callback function to be called when recording of audio to be transcripted stops.
  100. - on_transcription_start (callable, default=None): Callback function to be called when transcription of audio to text starts.
  101. - ensure_sentence_starting_uppercase (bool, default=True): Ensures that every sentence detected by the algorithm starts with an uppercase letter.
  102. - ensure_sentence_ends_with_period (bool, default=True): Ensures that every sentence that doesn't end with punctuation such as "?", "!" ends with a period
  103. - spinner (bool, default=True): Show spinner animation with current state.
  104. - level (int, default=logging.WARNING): Logging level.
  105. - 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.
  106. - 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'.
  107. - 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.
  108. - 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.
  109. - 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.
  110. - 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.
  111. - silero_use_onnx (bool, default=True): 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.
  112. - 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.
  113. - 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.
  114. - 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.
  115. - 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.
  116. - 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)
  117. - on_vad_detect_start (callable, default=None): Callback function to be called when the system listens for voice activity.
  118. - on_vad_detect_stop (callable, default=None): Callback function to be called when the system stops listening for voice activity.
  119. - wake_words (str, default=""): Comma-separated string of wake words to initiate recording. Supported wake words include:
  120. 'alexa', 'americano', 'blueberry', 'bumblebee', 'computer', 'grapefruits', 'grasshopper', 'hey google', 'hey siri', 'jarvis', 'ok google', 'picovoice', 'porcupine', 'terminator'.
  121. - 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.
  122. - 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.
  123. - 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.
  124. - on_wakeword_detected (callable, default=None): Callback function to be called when a wake word is detected.
  125. - 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
  126. - on_wakeword_detection_start (callable, default=None): Callback function to be called when the system starts to listen for wake words
  127. - 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)
  128. Raises:
  129. Exception: Errors related to initializing transcription model, wake word detection, or audio recording.
  130. """
  131. self.language = language
  132. self.wake_words = wake_words
  133. self.wake_word_activation_delay = wake_word_activation_delay
  134. self.wake_word_timeout = wake_word_timeout
  135. self.ensure_sentence_starting_uppercase = ensure_sentence_starting_uppercase
  136. self.ensure_sentence_ends_with_period = ensure_sentence_ends_with_period
  137. self.min_gap_between_recordings = min_gap_between_recordings
  138. self.min_length_of_recording = min_length_of_recording
  139. self.pre_recording_buffer_duration = pre_recording_buffer_duration
  140. self.post_speech_silence_duration = post_speech_silence_duration
  141. self.on_recording_start = on_recording_start
  142. self.on_recording_stop = on_recording_stop
  143. self.on_wakeword_detected = on_wakeword_detected
  144. self.on_wakeword_timeout = on_wakeword_timeout
  145. self.on_vad_detect_start = on_vad_detect_start
  146. self.on_vad_detect_stop = on_vad_detect_stop
  147. self.on_wakeword_detection_start = on_wakeword_detection_start
  148. self.on_wakeword_detection_end = on_wakeword_detection_end
  149. self.on_transcription_start = on_transcription_start
  150. self.enable_realtime_transcription = enable_realtime_transcription
  151. self.realtime_model_type = realtime_model_type
  152. self.realtime_processing_pause = realtime_processing_pause
  153. self.on_realtime_transcription_update = on_realtime_transcription_update
  154. self.on_realtime_transcription_stabilized = on_realtime_transcription_stabilized
  155. self.level = level
  156. self.audio_queue = Queue()
  157. self.buffer_size = BUFFER_SIZE
  158. self.sample_rate = SAMPLE_RATE
  159. self.recording_start_time = 0
  160. self.recording_stop_time = 0
  161. self.wake_word_detect_time = 0
  162. self.silero_check_time = 0
  163. self.silero_working = False
  164. self.speech_end_silence_start = 0
  165. self.silero_sensitivity = silero_sensitivity
  166. self.listen_start = 0
  167. self.spinner = spinner
  168. self.halo = None
  169. self.state = "inactive"
  170. self.wakeword_detected = False
  171. self.text_storage = []
  172. self.realtime_stabilized_text = ""
  173. self.realtime_stabilized_safetext = ""
  174. self.is_webrtc_speech_active = False
  175. self.is_silero_speech_active = False
  176. self.recording_thread = None
  177. self.realtime_thread = None
  178. self.audio_interface = None
  179. self.audio = None
  180. self.stream = None
  181. self.start_recording_event = threading.Event()
  182. self.stop_recording_event = threading.Event()
  183. # Initialize the logging configuration with the specified level
  184. log_format = 'RealTimeSTT: %(name)s - %(levelname)s - %(message)s'
  185. # Create a logger
  186. logger = logging.getLogger()
  187. logger.setLevel(level) # Set the root logger's level
  188. # Create a file handler and set its level
  189. file_handler = logging.FileHandler('audio_recorder.log')
  190. file_handler.setLevel(logging.DEBUG)
  191. file_handler.setFormatter(logging.Formatter(log_format))
  192. # Create a console handler and set its level
  193. console_handler = logging.StreamHandler()
  194. console_handler.setLevel(level)
  195. console_handler.setFormatter(logging.Formatter(log_format))
  196. # Add the handlers to the logger
  197. logger.addHandler(file_handler)
  198. logger.addHandler(console_handler)
  199. # start transcription process
  200. self.parent_transcription_pipe, child_transcription_pipe = Pipe()
  201. self.process = Process(target=AudioToTextRecorder._transcription_worker, args=(child_transcription_pipe, model))
  202. self.process.start()
  203. # start audio data reading process
  204. reader_process = Process(target=AudioToTextRecorder._audio_data_worker, args=(self.audio_queue, self.sample_rate, self.buffer_size))
  205. reader_process.start()
  206. # Initialize the realtime transcription model
  207. if self.enable_realtime_transcription:
  208. try:
  209. logging.info(f"Initializing faster_whisper realtime transcription model {self.realtime_model_type}")
  210. self.realtime_model_type = faster_whisper.WhisperModel(model_size_or_path=self.realtime_model_type, device='cuda' if torch.cuda.is_available() else 'cpu')
  211. except Exception as e:
  212. logging.exception(f"Error initializing faster_whisper realtime transcription model: {e}")
  213. raise
  214. logging.debug('Faster_whisper realtime speech to text transcription model initialized successfully')
  215. # Setup wake word detection
  216. if wake_words:
  217. self.wake_words_list = [word.strip() for word in wake_words.lower().split(',')]
  218. sensitivity_list = [float(wake_words_sensitivity) for _ in range(len(self.wake_words_list))]
  219. try:
  220. self.porcupine = pvporcupine.create(keywords=self.wake_words_list, sensitivities=sensitivity_list)
  221. self.buffer_size = self.porcupine.frame_length
  222. self.sample_rate = self.porcupine.sample_rate
  223. except Exception as e:
  224. logging.exception(f"Error initializing porcupine wake word detection engine: {e}")
  225. raise
  226. logging.debug('Porcupine wake word detection engine initialized successfully')
  227. # Setup voice activity detection model WebRTC
  228. try:
  229. logging.info(f"Initializing WebRTC voice with Sensitivity {webrtc_sensitivity}")
  230. self.webrtc_vad_model = webrtcvad.Vad()
  231. self.webrtc_vad_model.set_mode(webrtc_sensitivity)
  232. except Exception as e:
  233. logging.exception(f"Error initializing WebRTC voice activity detection engine: {e}")
  234. raise
  235. logging.debug('WebRTC VAD voice activity detection engine initialized successfully')
  236. # Setup voice activity detection model Silero VAD
  237. try:
  238. self.silero_vad_model, _ = torch.hub.load(
  239. repo_or_dir="snakers4/silero-vad",
  240. model="silero_vad",
  241. verbose=False,
  242. onnx=silero_use_onnx
  243. )
  244. except Exception as e:
  245. logging.exception(f"Error initializing Silero VAD voice activity detection engine: {e}")
  246. raise
  247. logging.debug('Silero VAD voice activity detection engine initialized successfully')
  248. self.audio_buffer = collections.deque(maxlen=int((self.sample_rate // self.buffer_size) * self.pre_recording_buffer_duration))
  249. self.frames = []
  250. # Recording control flags
  251. self.is_recording = False
  252. self.is_running = True
  253. self.start_recording_on_voice_activity = False
  254. self.stop_recording_on_voice_deactivity = False
  255. # Start the recording worker thread
  256. self.recording_thread = threading.Thread(target=self._recording_worker)
  257. self.recording_thread.daemon = True
  258. self.recording_thread.start()
  259. # Start the realtime transcription worker thread
  260. self.realtime_thread = threading.Thread(target=self._realtime_worker)
  261. self.realtime_thread.daemon = True
  262. self.realtime_thread.start()
  263. logging.debug('RealtimeSTT initialization completed successfully')
  264. @staticmethod
  265. def _transcription_worker(conn, model_path):
  266. logging.info(f"Initializing faster_whisper main transcription model {model_path}")
  267. try:
  268. model = faster_whisper.WhisperModel(
  269. model_size_or_path=model_path,
  270. device='cuda' if torch.cuda.is_available() else 'cpu'
  271. )
  272. except Exception as e:
  273. logging.exception(f"Error initializing main faster_whisper transcription model: {e}")
  274. raise
  275. logging.debug('Faster_whisper main speech to text transcription model initialized successfully')
  276. while True:
  277. audio, language = conn.recv()
  278. try:
  279. segments = model.transcribe(audio, language=language if language else None)[0]
  280. transcription = " ".join(seg.text for seg in segments).strip()
  281. conn.send(('success', transcription))
  282. except faster_whisper.WhisperError as e:
  283. logging.error(f"Whisper transcription error: {e}")
  284. conn.send(('error', str(e)))
  285. except Exception as e:
  286. logging.error(f"General transcription error: {e}")
  287. conn.send(('error', str(e)))
  288. @staticmethod
  289. def _audio_data_worker(audio_queue, sample_rate, buffer_size):
  290. logging.info("Initializing audio recording (creating pyAudio input stream)")
  291. try:
  292. audio_interface = pyaudio.PyAudio()
  293. stream = audio_interface.open(rate=sample_rate, format=pyaudio.paInt16, channels=1, input=True, frames_per_buffer=buffer_size)
  294. except Exception as e:
  295. logging.exception(f"Error initializing pyaudio audio recording: {e}")
  296. raise
  297. logging.debug('Audio recording (pyAudio input stream) initialized successfully')
  298. while True:
  299. try:
  300. data = stream.read(buffer_size)
  301. except OSError as e:
  302. if e.errno == pyaudio.paInputOverflowed:
  303. logging.warning("Input overflowed. Frame dropped.")
  304. else:
  305. logging.error(f"Error during recording: {e}")
  306. tb_str = traceback.format_exc()
  307. print (f"Traceback: {tb_str}")
  308. print (f"Error: {e}")
  309. continue
  310. except Exception as e:
  311. logging.error(f"Error during recording: {e}")
  312. time.sleep(1)
  313. tb_str = traceback.format_exc()
  314. print (f"Traceback: {tb_str}")
  315. print (f"Error: {e}")
  316. continue
  317. audio_queue.put(data)
  318. def wait_audio(self):
  319. """
  320. Waits for the start and completion of the audio recording process.
  321. This method is responsible for:
  322. - Waiting for voice activity to begin recording if not yet started.
  323. - Waiting for voice inactivity to complete the recording.
  324. - Setting the audio buffer from the recorded frames.
  325. - Resetting recording-related attributes.
  326. Side effects:
  327. - Updates the state of the instance.
  328. - Modifies the audio attribute to contain the processed audio data.
  329. """
  330. self.listen_start = time.time()
  331. # If not yet started recording, wait for voice activity to initiate.
  332. if not self.is_recording and not self.frames:
  333. self._set_state("listening")
  334. self.start_recording_on_voice_activity = True
  335. # wait until recording starts
  336. self.start_recording_event.wait()
  337. # If recording is ongoing, wait for voice inactivity to finish recording.
  338. if self.is_recording:
  339. self.stop_recording_on_voice_deactivity = True
  340. # wait until recording stops
  341. self.stop_recording_event.wait()
  342. # Convert recorded frames to the appropriate audio format.
  343. audio_array = np.frombuffer(b''.join(self.frames), dtype=np.int16)
  344. self.audio = audio_array.astype(np.float32) / INT16_MAX_ABS_VALUE
  345. self.frames.clear()
  346. # Reset recording-related timestamps
  347. self.recording_stop_time = 0
  348. self.listen_start = 0
  349. self._set_state("inactive")
  350. def transcribe(self):
  351. self._set_state("transcribing")
  352. self.parent_transcription_pipe.send((self.audio, self.language))
  353. status, result = self.parent_transcription_pipe.recv()
  354. self._set_state("inactive")
  355. if status == 'success':
  356. return self._preprocess_output(result)
  357. else:
  358. logging.error(result)
  359. raise Exception(result)
  360. def text(self,
  361. on_transcription_finished = None,
  362. ):
  363. """
  364. Transcribes audio captured by this class instance using the `faster_whisper` model.
  365. - Automatically starts recording upon voice activity if not manually started using `recorder.start()`.
  366. - Automatically stops recording upon voice deactivity if not manually stopped with `recorder.stop()`.
  367. - Processes the recorded audio to generate transcription.
  368. Args:
  369. on_transcription_finished (callable, optional): Callback function to be executed when transcription is ready.
  370. If provided, transcription will be performed asynchronously, and the callback will receive the transcription
  371. as its argument. If omitted, the transcription will be performed synchronously, and the result will be returned.
  372. Returns (if not callback is set):
  373. str: The transcription of the recorded audio
  374. """
  375. self.wait_audio()
  376. if on_transcription_finished:
  377. threading.Thread(target=on_transcription_finished, args=(self.transcribe(),)).start()
  378. else:
  379. return self.transcribe()
  380. def start(self):
  381. """
  382. Starts recording audio directly without waiting for voice activity.
  383. """
  384. # Ensure there's a minimum interval between stopping and starting recording
  385. if time.time() - self.recording_stop_time < self.min_gap_between_recordings:
  386. logging.info("Attempted to start recording too soon after stopping.")
  387. return self
  388. logging.info("recording started")
  389. self._set_state("recording")
  390. self.text_storage = []
  391. self.realtime_stabilized_text = ""
  392. self.realtime_stabilized_safetext = ""
  393. self.wakeword_detected = False
  394. self.wake_word_detect_time = 0
  395. self.frames = []
  396. self.is_recording = True
  397. self.recording_start_time = time.time()
  398. self.is_silero_speech_active = False
  399. self.is_webrtc_speech_active = False
  400. self.stop_recording_event.clear()
  401. self.start_recording_event.set()
  402. if self.on_recording_start:
  403. self.on_recording_start()
  404. return self
  405. def stop(self):
  406. """
  407. Stops recording audio.
  408. """
  409. # Ensure there's a minimum interval between starting and stopping recording
  410. if time.time() - self.recording_start_time < self.min_length_of_recording:
  411. logging.info("Attempted to stop recording too soon after starting.")
  412. return self
  413. logging.info("recording stopped")
  414. self.is_recording = False
  415. self.recording_stop_time = time.time()
  416. self.is_silero_speech_active = False
  417. self.is_webrtc_speech_active = False
  418. self.silero_check_time = 0
  419. self.start_recording_event.clear()
  420. self.stop_recording_event.set()
  421. if self.on_recording_stop:
  422. self.on_recording_stop()
  423. return self
  424. def shutdown(self):
  425. """
  426. Safely shuts down the audio recording by stopping the recording worker and closing the audio stream.
  427. """
  428. self.parent_transcription_pipe.close()
  429. self.process.terminate()
  430. self.is_recording = False
  431. self.is_running = False
  432. if self.recording_thread:
  433. self.recording_thread.join()
  434. if self.realtime_thread:
  435. self.realtime_thread.join()
  436. try:
  437. if self.stream:
  438. self.stream.stop_stream()
  439. self.stream.close()
  440. if self.audio_interface:
  441. self.audio_interface.terminate()
  442. except Exception as e:
  443. logging.error(f"Error closing the audio stream: {e}")
  444. def _is_silero_speech(self, data):
  445. """
  446. Returns true if speech is detected in the provided audio data
  447. Args:
  448. data (bytes): raw bytes of audio data (1024 raw bytes with 16000 sample rate and 16 bits per sample)
  449. """
  450. self.silero_working = True
  451. audio_chunk = np.frombuffer(data, dtype=np.int16)
  452. audio_chunk = audio_chunk.astype(np.float32) / INT16_MAX_ABS_VALUE # Convert to float and normalize
  453. vad_prob = self.silero_vad_model(torch.from_numpy(audio_chunk), SAMPLE_RATE).item()
  454. is_silero_speech_active = vad_prob > (1 - self.silero_sensitivity)
  455. if is_silero_speech_active:
  456. self.is_silero_speech_active = True
  457. self.silero_working = False
  458. return is_silero_speech_active
  459. def _is_webrtc_speech(self, data, all_frames_must_be_true=False):
  460. """
  461. Returns true if speech is detected in the provided audio data
  462. Args:
  463. data (bytes): raw bytes of audio data (1024 raw bytes with 16000 sample rate and 16 bits per sample)
  464. """
  465. # Number of audio frames per millisecond
  466. frame_length = int(self.sample_rate * 0.01) # for 10ms frame
  467. num_frames = int(len(data) / (2 * frame_length))
  468. speech_frames = 0
  469. for i in range(num_frames):
  470. start_byte = i * frame_length * 2
  471. end_byte = start_byte + frame_length * 2
  472. frame = data[start_byte:end_byte]
  473. if self.webrtc_vad_model.is_speech(frame, self.sample_rate):
  474. speech_frames += 1
  475. if not all_frames_must_be_true:
  476. return True
  477. if all_frames_must_be_true:
  478. return speech_frames == num_frames
  479. else:
  480. return False
  481. def _check_voice_activity(self, data):
  482. """
  483. Initiate check if voice is active based on the provided data.
  484. Args:
  485. data: The audio data to be checked for voice activity.
  486. """
  487. self.is_webrtc_speech_active = self._is_webrtc_speech(data)
  488. # First quick performing check for voice activity using WebRTC
  489. if self.is_webrtc_speech_active:
  490. if not self.silero_working:
  491. self.silero_working = True
  492. # Run the intensive check in a separate thread
  493. threading.Thread(target=self._is_silero_speech, args=(data,)).start()
  494. def _is_voice_active(self):
  495. """
  496. Determine if voice is active.
  497. Returns:
  498. bool: True if voice is active, False otherwise.
  499. """
  500. return self.is_webrtc_speech_active and self.is_silero_speech_active
  501. def _set_state(self, new_state):
  502. """
  503. Update the current state of the recorder and execute corresponding state-change callbacks.
  504. Args:
  505. new_state (str): The new state to set.
  506. """
  507. # Check if the state has actually changed
  508. if new_state == self.state:
  509. return
  510. # Store the current state for later comparison
  511. old_state = self.state
  512. # Update to the new state
  513. self.state = new_state
  514. # Execute callbacks based on transitioning FROM a particular state
  515. if old_state == "listening":
  516. if self.on_vad_detect_stop:
  517. self.on_vad_detect_stop()
  518. elif old_state == "wakeword":
  519. if self.on_wakeword_detection_end:
  520. self.on_wakeword_detection_end()
  521. # Execute callbacks based on transitioning TO a particular state
  522. if new_state == "listening":
  523. if self.on_vad_detect_start:
  524. self.on_vad_detect_start()
  525. self._set_spinner("speak now")
  526. if self.spinner:
  527. self.halo._interval = 250
  528. elif new_state == "wakeword":
  529. if self.on_wakeword_detection_start:
  530. self.on_wakeword_detection_start()
  531. self._set_spinner(f"say {self.wake_words}")
  532. if self.spinner:
  533. self.halo._interval = 500
  534. elif new_state == "transcribing":
  535. if self.on_transcription_start:
  536. self.on_transcription_start()
  537. self._set_spinner("transcribing")
  538. if self.spinner:
  539. self.halo._interval = 50
  540. elif new_state == "recording":
  541. self._set_spinner("recording")
  542. if self.spinner:
  543. self.halo._interval = 100
  544. elif new_state == "inactive":
  545. if self.spinner and self.halo:
  546. self.halo.stop()
  547. self.halo = None
  548. def _set_spinner(self, text):
  549. """
  550. Update the spinner's text or create a new spinner with the provided text.
  551. Args:
  552. text (str): The text to be displayed alongside the spinner.
  553. """
  554. if self.spinner:
  555. # If the Halo spinner doesn't exist, create and start it
  556. if self.halo is None:
  557. self.halo = halo.Halo(text=text)
  558. self.halo.start()
  559. # If the Halo spinner already exists, just update the text
  560. else:
  561. self.halo.text = text
  562. def _recording_worker(self):
  563. """
  564. The main worker method which constantly monitors the audio input for voice activity and accordingly starts/stops the recording.
  565. """
  566. logging.debug('Starting recording worker')
  567. try:
  568. was_recording = False
  569. delay_was_passed = False
  570. # Continuously monitor audio for voice activity
  571. while self.is_running:
  572. data = self.audio_queue.get()
  573. if not self.is_recording:
  574. # handle not recording state
  575. time_since_listen_start = time.time() - self.listen_start if self.listen_start else 0
  576. wake_word_activation_delay_passed = (time_since_listen_start > self.wake_word_activation_delay)
  577. # handle wake-word timeout callback
  578. if wake_word_activation_delay_passed and not delay_was_passed:
  579. if self.wake_words and self.wake_word_activation_delay:
  580. if self.on_wakeword_timeout:
  581. self.on_wakeword_timeout()
  582. delay_was_passed = wake_word_activation_delay_passed
  583. # Set state and spinner text
  584. if not self.recording_stop_time:
  585. if self.wake_words and wake_word_activation_delay_passed and not self.wakeword_detected:
  586. self._set_state("wakeword")
  587. else:
  588. if self.listen_start:
  589. self._set_state("listening")
  590. else:
  591. self._set_state("inactive")
  592. # Detect wake words if applicable
  593. if self.wake_words and wake_word_activation_delay_passed:
  594. try:
  595. pcm = struct.unpack_from("h" * self.buffer_size, data)
  596. wakeword_index = self.porcupine.process(pcm)
  597. except struct.error:
  598. logging.error("Error unpacking audio data for wake word processing.")
  599. continue
  600. except Exception as e:
  601. logging.error(f"Wake word processing error: {e}")
  602. continue
  603. # If a wake word is detected
  604. if wakeword_index >= 0:
  605. # Removing the wake word from the recording
  606. samples_for_0_1_sec = int(self.sample_rate * 0.1)
  607. start_index = max(0, len(self.audio_buffer) - samples_for_0_1_sec)
  608. temp_samples = collections.deque(itertools.islice(self.audio_buffer, start_index, None))
  609. self.audio_buffer.clear()
  610. self.audio_buffer.extend(temp_samples)
  611. self.wake_word_detect_time = time.time()
  612. self.wakeword_detected = True
  613. if self.on_wakeword_detected:
  614. self.on_wakeword_detected()
  615. # Check for voice activity to trigger the start of recording
  616. if ((not self.wake_words or not wake_word_activation_delay_passed) and self.start_recording_on_voice_activity) or self.wakeword_detected:
  617. if self._is_voice_active():
  618. logging.info("voice activity detected")
  619. self.start()
  620. if self.is_recording:
  621. self.start_recording_on_voice_activity = False
  622. # Add the buffered audio to the recording frames
  623. self.frames.extend(list(self.audio_buffer))
  624. self.audio_buffer.clear()
  625. self.silero_vad_model.reset_states()
  626. else:
  627. data_copy = data[:]
  628. self._check_voice_activity(data_copy)
  629. self.speech_end_silence_start = 0
  630. else:
  631. # If we are currently recording
  632. # Stop the recording if silence is detected after speech
  633. if self.stop_recording_on_voice_deactivity:
  634. if not self._is_webrtc_speech(data, True):
  635. # Voice deactivity was detected, so we start measuring silence time before stopping recording
  636. if self.speech_end_silence_start == 0:
  637. self.speech_end_silence_start = time.time()
  638. else:
  639. self.speech_end_silence_start = 0
  640. # Wait for silence to stop recording after speech
  641. if self.speech_end_silence_start and time.time() - self.speech_end_silence_start > self.post_speech_silence_duration:
  642. logging.info("voice deactivity detected")
  643. self.stop()
  644. if not self.is_recording and was_recording:
  645. # Reset after stopping recording to ensure clean state
  646. self.stop_recording_on_voice_deactivity = False
  647. if time.time() - self.silero_check_time > 0.1:
  648. self.silero_check_time = 0
  649. # handle wake word timeout (waited to long initiating speech after wake word detection)
  650. if self.wake_word_detect_time and time.time() - self.wake_word_detect_time > self.wake_word_timeout:
  651. self.wake_word_detect_time = 0
  652. if self.wakeword_detected and self.on_wakeword_timeout:
  653. self.on_wakeword_timeout()
  654. self.wakeword_detected = False
  655. if self.is_recording:
  656. self.frames.append(data)
  657. if not self.is_recording or self.speech_end_silence_start:
  658. self.audio_buffer.append(data)
  659. was_recording = self.is_recording
  660. except Exception as e:
  661. logging.error(f"Unhandled exeption in _recording_worker: {e}")
  662. raise
  663. def _preprocess_output(self, text, preview=False):
  664. """
  665. Preprocesses the output text by removing any leading or trailing whitespace,
  666. converting all whitespace sequences to a single space character, and capitalizing
  667. the first character of the text.
  668. Args:
  669. text (str): The text to be preprocessed.
  670. Returns:
  671. str: The preprocessed text.
  672. """
  673. text = re.sub(r'\s+', ' ', text.strip())
  674. if self.ensure_sentence_starting_uppercase:
  675. if text:
  676. text = text[0].upper() + text[1:]
  677. # Ensure the text ends with a proper punctuation if it ends with an alphanumeric character
  678. if not preview:
  679. if self.ensure_sentence_ends_with_period:
  680. if text and text[-1].isalnum():
  681. text += '.'
  682. return text
  683. def find_tail_match_in_text(self, text1, text2, length_of_match=10):
  684. """
  685. Find the position where the last 'n' characters of text1 match with a substring in text2.
  686. This method takes two texts, extracts the last 'n' characters from text1 (where 'n' is determined
  687. by the variable 'length_of_match'), and searches for an occurrence of this substring in text2,
  688. starting from the end of text2 and moving towards the beginning.
  689. Parameters:
  690. - text1 (str): The text containing the substring that we want to find in text2.
  691. - text2 (str): The text in which we want to find the matching substring.
  692. - length_of_match(int): The length of the matching string that we are looking for
  693. Returns:
  694. int: The position (0-based index) in text2 where the matching substring starts.
  695. If no match is found or either of the texts is too short, returns -1.
  696. """
  697. # Check if either of the texts is too short
  698. if len(text1) < length_of_match or len(text2) < length_of_match:
  699. return -1
  700. # The end portion of the first text that we want to compare
  701. target_substring = text1[-length_of_match:]
  702. # Loop through text2 from right to left
  703. for i in range(len(text2) - length_of_match + 1):
  704. # Extract the substring from text2 to compare with the target_substring
  705. current_substring = text2[len(text2) - i - length_of_match:len(text2) - i]
  706. # Compare the current_substring with the target_substring
  707. if current_substring == target_substring:
  708. return len(text2) - i # Position in text2 where the match starts
  709. return -1
  710. def _on_realtime_transcription_stabilized(self, text):
  711. if self.on_realtime_transcription_stabilized:
  712. if self.is_recording:
  713. self.on_realtime_transcription_stabilized(text)
  714. def _on_realtime_transcription_update(self, text):
  715. if self.on_realtime_transcription_update:
  716. if self.is_recording:
  717. self.on_realtime_transcription_update(text)
  718. def _realtime_worker(self):
  719. """
  720. Performs real-time transcription if the feature is enabled.
  721. The method is responsible transcribing recorded audio frames in real-time
  722. based on the specified resolution interval.
  723. The transcribed text is stored in `self.realtime_transcription_text` and a callback
  724. function is invoked with this text if specified.
  725. """
  726. try:
  727. logging.debug('Starting realtime worker')
  728. # Return immediately if real-time transcription is not enabled
  729. if not self.enable_realtime_transcription:
  730. return
  731. # Continue running as long as the main process is active
  732. while self.is_running:
  733. # Check if the recording is active
  734. if self.is_recording:
  735. # Sleep for the duration of the transcription resolution
  736. time.sleep(self.realtime_processing_pause)
  737. # Convert the buffer frames to a NumPy array
  738. audio_array = np.frombuffer(b''.join(self.frames), dtype=np.int16)
  739. # Normalize the array to a [-1, 1] range
  740. audio_array = audio_array.astype(np.float32) / INT16_MAX_ABS_VALUE
  741. # Perform transcription and assemble the text
  742. segments = self.realtime_model_type.transcribe(
  743. audio_array,
  744. language=self.language if self.language else None
  745. )
  746. # double check recording state because it could have changed mid-transcription
  747. if self.is_recording and time.time() - self.recording_start_time > 0.5:
  748. logging.debug('Starting realtime transcription')
  749. self.realtime_transcription_text = " ".join(seg.text for seg in segments[0]).strip()
  750. self.text_storage.append(self.realtime_transcription_text)
  751. # Take the last two texts in storage, if they exist
  752. if len(self.text_storage) >= 2:
  753. last_two_texts = self.text_storage[-2:]
  754. # Find the longest common prefix between the two texts
  755. prefix = os.path.commonprefix([last_two_texts[0], last_two_texts[1]])
  756. # This prefix is the text that was transcripted two times in the same way
  757. # Store as "safely detected text"
  758. if len(prefix) >= len(self.realtime_stabilized_safetext):
  759. # Only store when longer than the previous as additional security
  760. self.realtime_stabilized_safetext = prefix
  761. # Find parts of the stabilized text in the freshly transscripted text
  762. matching_position = self.find_tail_match_in_text(self.realtime_stabilized_safetext, self.realtime_transcription_text)
  763. if matching_position < 0:
  764. if self.realtime_stabilized_safetext:
  765. self._on_realtime_transcription_stabilized(self._preprocess_output(self.realtime_stabilized_safetext, True))
  766. else:
  767. self._on_realtime_transcription_stabilized(self._preprocess_output(self.realtime_transcription_text, True))
  768. else:
  769. # We found parts of the stabilized text in the transcripted text
  770. # We now take the stabilized text and add only the freshly transcripted part to it
  771. output_text = self.realtime_stabilized_safetext + self.realtime_transcription_text[matching_position:]
  772. # This yields us the "left" text part as stabilized AND at the same time delivers fresh detected parts
  773. # on the first run without the need for two transcriptions
  774. self._on_realtime_transcription_stabilized(self._preprocess_output(output_text, True))
  775. # Invoke the callback with the transcribed text
  776. self._on_realtime_transcription_update(self._preprocess_output(self.realtime_transcription_text, True))
  777. # If not recording, sleep briefly before checking again
  778. else:
  779. time.sleep(TIME_SLEEP)
  780. except Exception as e:
  781. logging.error(f"Unhandled exeption in _realtime_worker: {e}")
  782. raise
  783. def __del__(self):
  784. """
  785. Destructor method ensures safe shutdown of the recorder when the instance is destroyed.
  786. """
  787. self.shutdown()