audio_recorder.py 69 KB

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