audio_recorder.py 69 KB

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