audio_recorder.py 107 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385
  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 openwakeword.model import Model
  29. from scipy.signal import resample
  30. from scipy import signal
  31. import signal as system_signal
  32. import faster_whisper
  33. import openwakeword
  34. import collections
  35. import numpy as np
  36. import pvporcupine
  37. import traceback
  38. import threading
  39. import webrtcvad
  40. import itertools
  41. import datetime
  42. import platform
  43. import pyaudio
  44. import logging
  45. import struct
  46. import queue
  47. import halo
  48. import time
  49. import copy
  50. import os
  51. import re
  52. import gc
  53. # Set OpenMP runtime duplicate library handling to OK (Use only for development!)
  54. os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'
  55. INIT_MODEL_TRANSCRIPTION = "tiny"
  56. INIT_MODEL_TRANSCRIPTION_REALTIME = "tiny"
  57. INIT_REALTIME_PROCESSING_PAUSE = 0.2
  58. INIT_SILERO_SENSITIVITY = 0.4
  59. INIT_WEBRTC_SENSITIVITY = 3
  60. INIT_POST_SPEECH_SILENCE_DURATION = 0.6
  61. INIT_MIN_LENGTH_OF_RECORDING = 0.5
  62. INIT_MIN_GAP_BETWEEN_RECORDINGS = 0
  63. INIT_WAKE_WORDS_SENSITIVITY = 0.6
  64. INIT_PRE_RECORDING_BUFFER_DURATION = 1.0
  65. INIT_WAKE_WORD_ACTIVATION_DELAY = 0.0
  66. INIT_WAKE_WORD_TIMEOUT = 5.0
  67. INIT_WAKE_WORD_BUFFER_DURATION = 0.1
  68. ALLOWED_LATENCY_LIMIT = 100
  69. TIME_SLEEP = 0.02
  70. SAMPLE_RATE = 16000
  71. BUFFER_SIZE = 512
  72. INT16_MAX_ABS_VALUE = 32768.0
  73. INIT_HANDLE_BUFFER_OVERFLOW = False
  74. if platform.system() != 'Darwin':
  75. INIT_HANDLE_BUFFER_OVERFLOW = True
  76. class TranscriptionWorker:
  77. def __init__(self, conn, stdout_pipe, model_path, compute_type, gpu_device_index, device,
  78. ready_event, shutdown_event, interrupt_stop_event, beam_size, initial_prompt, suppress_tokens):
  79. self.conn = conn
  80. self.stdout_pipe = stdout_pipe
  81. self.model_path = model_path
  82. self.compute_type = compute_type
  83. self.gpu_device_index = gpu_device_index
  84. self.device = device
  85. self.ready_event = ready_event
  86. self.shutdown_event = shutdown_event
  87. self.interrupt_stop_event = interrupt_stop_event
  88. self.beam_size = beam_size
  89. self.initial_prompt = initial_prompt
  90. self.suppress_tokens = suppress_tokens
  91. self.queue = queue.Queue()
  92. def custom_print(self, *args, **kwargs):
  93. message = ' '.join(map(str, args))
  94. try:
  95. self.stdout_pipe.send(message)
  96. except (BrokenPipeError, EOFError, OSError):
  97. pass
  98. def poll_connection(self):
  99. while not self.shutdown_event.is_set():
  100. if self.conn.poll(0.01):
  101. try:
  102. data = self.conn.recv()
  103. self.queue.put(data)
  104. except Exception as e:
  105. logging.error(f"Error receiving data from connection: {e}")
  106. else:
  107. time.sleep(TIME_SLEEP)
  108. def run(self):
  109. system_signal.signal(system_signal.SIGINT, system_signal.SIG_IGN)
  110. __builtins__['print'] = self.custom_print
  111. logging.info(f"Initializing faster_whisper main transcription model {self.model_path}")
  112. try:
  113. model = faster_whisper.WhisperModel(
  114. model_size_or_path=self.model_path,
  115. device=self.device,
  116. compute_type=self.compute_type,
  117. device_index=self.gpu_device_index,
  118. )
  119. except Exception as e:
  120. logging.exception(f"Error initializing main faster_whisper transcription model: {e}")
  121. raise
  122. self.ready_event.set()
  123. logging.debug("Faster_whisper main speech to text transcription model initialized successfully")
  124. # Start the polling thread
  125. polling_thread = threading.Thread(target=self.poll_connection)
  126. polling_thread.start()
  127. try:
  128. while not self.shutdown_event.is_set():
  129. try:
  130. audio, language = self.queue.get(timeout=0.1)
  131. try:
  132. segments, info = model.transcribe(
  133. audio,
  134. language=language if language else None,
  135. beam_size=self.beam_size,
  136. initial_prompt=self.initial_prompt,
  137. suppress_tokens=self.suppress_tokens
  138. )
  139. transcription = " ".join(seg.text for seg in segments).strip()
  140. logging.debug(f"Final text detected with main model: {transcription}")
  141. self.conn.send(('success', (transcription, info)))
  142. except Exception as e:
  143. logging.error(f"General error in transcription: {e}")
  144. self.conn.send(('error', str(e)))
  145. except queue.Empty:
  146. continue
  147. except KeyboardInterrupt:
  148. self.interrupt_stop_event.set()
  149. logging.debug("Transcription worker process finished due to KeyboardInterrupt")
  150. break
  151. except Exception as e:
  152. logging.error(f"General error in processing queue item: {e}")
  153. finally:
  154. __builtins__['print'] = print # Restore the original print function
  155. self.conn.close()
  156. self.stdout_pipe.close()
  157. self.shutdown_event.set() # Ensure the polling thread will stop
  158. polling_thread.join() # Wait for the polling thread to finish
  159. class AudioToTextRecorder:
  160. """
  161. A class responsible for capturing audio from the microphone, detecting
  162. voice activity, and then transcribing the captured audio using the
  163. `faster_whisper` model.
  164. """
  165. def __init__(self,
  166. model: str = INIT_MODEL_TRANSCRIPTION,
  167. language: str = "",
  168. compute_type: str = "default",
  169. input_device_index: int = None,
  170. gpu_device_index: Union[int, List[int]] = 0,
  171. device: str = "cuda",
  172. on_recording_start=None,
  173. on_recording_stop=None,
  174. on_transcription_start=None,
  175. ensure_sentence_starting_uppercase=True,
  176. ensure_sentence_ends_with_period=True,
  177. use_microphone=True,
  178. spinner=True,
  179. level=logging.WARNING,
  180. # Realtime transcription parameters
  181. enable_realtime_transcription=False,
  182. use_main_model_for_realtime=False,
  183. realtime_model_type=INIT_MODEL_TRANSCRIPTION_REALTIME,
  184. realtime_processing_pause=INIT_REALTIME_PROCESSING_PAUSE,
  185. on_realtime_transcription_update=None,
  186. on_realtime_transcription_stabilized=None,
  187. # Voice activation parameters
  188. silero_sensitivity: float = INIT_SILERO_SENSITIVITY,
  189. silero_use_onnx: bool = False,
  190. silero_deactivity_detection: bool = False,
  191. webrtc_sensitivity: int = INIT_WEBRTC_SENSITIVITY,
  192. post_speech_silence_duration: float = (
  193. INIT_POST_SPEECH_SILENCE_DURATION
  194. ),
  195. min_length_of_recording: float = (
  196. INIT_MIN_LENGTH_OF_RECORDING
  197. ),
  198. min_gap_between_recordings: float = (
  199. INIT_MIN_GAP_BETWEEN_RECORDINGS
  200. ),
  201. pre_recording_buffer_duration: float = (
  202. INIT_PRE_RECORDING_BUFFER_DURATION
  203. ),
  204. on_vad_detect_start=None,
  205. on_vad_detect_stop=None,
  206. # Wake word parameters
  207. wakeword_backend: str = "pvporcupine",
  208. openwakeword_model_paths: str = None,
  209. openwakeword_inference_framework: str = "onnx",
  210. wake_words: str = "",
  211. wake_words_sensitivity: float = INIT_WAKE_WORDS_SENSITIVITY,
  212. wake_word_activation_delay: float = (
  213. INIT_WAKE_WORD_ACTIVATION_DELAY
  214. ),
  215. wake_word_timeout: float = INIT_WAKE_WORD_TIMEOUT,
  216. wake_word_buffer_duration: float = INIT_WAKE_WORD_BUFFER_DURATION,
  217. on_wakeword_detected=None,
  218. on_wakeword_timeout=None,
  219. on_wakeword_detection_start=None,
  220. on_wakeword_detection_end=None,
  221. on_recorded_chunk=None,
  222. debug_mode=False,
  223. handle_buffer_overflow: bool = INIT_HANDLE_BUFFER_OVERFLOW,
  224. beam_size: int = 5,
  225. beam_size_realtime: int = 3,
  226. buffer_size: int = BUFFER_SIZE,
  227. sample_rate: int = SAMPLE_RATE,
  228. initial_prompt: Optional[Union[str, Iterable[int]]] = None,
  229. suppress_tokens: Optional[List[int]] = [-1],
  230. print_transcription_time: bool = False,
  231. early_transcription_on_silence: int = 0,
  232. allowed_latency_limit: int = ALLOWED_LATENCY_LIMIT,
  233. no_log_file: bool = False,
  234. use_extended_logging: bool = False,
  235. ):
  236. """
  237. Initializes an audio recorder and transcription
  238. and wake word detection.
  239. Args:
  240. - model (str, default="tiny"): Specifies the size of the transcription
  241. model to use or the path to a converted model directory.
  242. Valid options are 'tiny', 'tiny.en', 'base', 'base.en',
  243. 'small', 'small.en', 'medium', 'medium.en', 'large-v1',
  244. 'large-v2'.
  245. If a specific size is provided, the model is downloaded
  246. from the Hugging Face Hub.
  247. - language (str, default=""): Language code for speech-to-text engine.
  248. If not specified, the model will attempt to detect the language
  249. automatically.
  250. - compute_type (str, default="default"): Specifies the type of
  251. computation to be used for transcription.
  252. See https://opennmt.net/CTranslate2/quantization.html.
  253. - input_device_index (int, default=0): The index of the audio input
  254. device to use.
  255. - gpu_device_index (int, default=0): Device ID to use.
  256. The model can also be loaded on multiple GPUs by passing a list of
  257. IDs (e.g. [0, 1, 2, 3]). In that case, multiple transcriptions can
  258. run in parallel when transcribe() is called from multiple Python
  259. threads
  260. - device (str, default="cuda"): Device for model to use. Can either be
  261. "cuda" or "cpu".
  262. - on_recording_start (callable, default=None): Callback function to be
  263. called when recording of audio to be transcripted starts.
  264. - on_recording_stop (callable, default=None): Callback function to be
  265. called when recording of audio to be transcripted stops.
  266. - on_transcription_start (callable, default=None): Callback function
  267. to be called when transcription of audio to text starts.
  268. - ensure_sentence_starting_uppercase (bool, default=True): Ensures
  269. that every sentence detected by the algorithm starts with an
  270. uppercase letter.
  271. - ensure_sentence_ends_with_period (bool, default=True): Ensures that
  272. every sentence that doesn't end with punctuation such as "?", "!"
  273. ends with a period
  274. - use_microphone (bool, default=True): Specifies whether to use the
  275. microphone as the audio input source. If set to False, the
  276. audio input source will be the audio data sent through the
  277. feed_audio() method.
  278. - spinner (bool, default=True): Show spinner animation with current
  279. state.
  280. - level (int, default=logging.WARNING): Logging level.
  281. - enable_realtime_transcription (bool, default=False): Enables or
  282. disables real-time transcription of audio. When set to True, the
  283. audio will be transcribed continuously as it is being recorded.
  284. - use_main_model_for_realtime (str, default=False):
  285. If True, use the main transcription model for both regular and
  286. real-time transcription. If False, use a separate model specified
  287. by realtime_model_type for real-time transcription.
  288. Using a single model can save memory and potentially improve
  289. performance, but may not be optimized for real-time processing.
  290. Using separate models allows for a smaller, faster model for
  291. real-time transcription while keeping a more accurate model for
  292. final transcription.
  293. - realtime_model_type (str, default="tiny"): Specifies the machine
  294. learning model to be used for real-time transcription. Valid
  295. options include 'tiny', 'tiny.en', 'base', 'base.en', 'small',
  296. 'small.en', 'medium', 'medium.en', 'large-v1', 'large-v2'.
  297. - realtime_processing_pause (float, default=0.1): Specifies the time
  298. interval in seconds after a chunk of audio gets transcribed. Lower
  299. values will result in more "real-time" (frequent) transcription
  300. updates but may increase computational load.
  301. - on_realtime_transcription_update = A callback function that is
  302. triggered whenever there's an update in the real-time
  303. transcription. The function is called with the newly transcribed
  304. text as its argument.
  305. - on_realtime_transcription_stabilized = A callback function that is
  306. triggered when the transcribed text stabilizes in quality. The
  307. stabilized text is generally more accurate but may arrive with a
  308. slight delay compared to the regular real-time updates.
  309. - silero_sensitivity (float, default=SILERO_SENSITIVITY): Sensitivity
  310. for the Silero Voice Activity Detection model ranging from 0
  311. (least sensitive) to 1 (most sensitive). Default is 0.5.
  312. - silero_use_onnx (bool, default=False): Enables usage of the
  313. pre-trained model from Silero in the ONNX (Open Neural Network
  314. Exchange) format instead of the PyTorch format. This is
  315. recommended for faster performance.
  316. - silero_deactivity_detection (bool, default=False): Enables the Silero
  317. model for end-of-speech detection. More robust against background
  318. noise. Utilizes additional GPU resources but improves accuracy in
  319. noisy environments. When False, uses the default WebRTC VAD,
  320. which is more sensitive but may continue recording longer due
  321. to background sounds.
  322. - webrtc_sensitivity (int, default=WEBRTC_SENSITIVITY): Sensitivity
  323. for the WebRTC Voice Activity Detection engine ranging from 0
  324. (least aggressive / most sensitive) to 3 (most aggressive,
  325. least sensitive). Default is 3.
  326. - post_speech_silence_duration (float, default=0.2): Duration in
  327. seconds of silence that must follow speech before the recording
  328. is considered to be completed. This ensures that any brief
  329. pauses during speech don't prematurely end the recording.
  330. - min_gap_between_recordings (float, default=1.0): Specifies the
  331. minimum time interval in seconds that should exist between the
  332. end of one recording session and the beginning of another to
  333. prevent rapid consecutive recordings.
  334. - min_length_of_recording (float, default=1.0): Specifies the minimum
  335. duration in seconds that a recording session should last to ensure
  336. meaningful audio capture, preventing excessively short or
  337. fragmented recordings.
  338. - pre_recording_buffer_duration (float, default=0.2): Duration in
  339. seconds for the audio buffer to maintain pre-roll audio
  340. (compensates speech activity detection latency)
  341. - on_vad_detect_start (callable, default=None): Callback function to
  342. be called when the system listens for voice activity.
  343. - on_vad_detect_stop (callable, default=None): Callback function to be
  344. called when the system stops listening for voice activity.
  345. - wakeword_backend (str, default="pvporcupine"): Specifies the backend
  346. library to use for wake word detection. Supported options include
  347. 'pvporcupine' for using the Porcupine wake word engine or 'oww' for
  348. using the OpenWakeWord engine.
  349. - openwakeword_model_paths (str, default=None): Comma-separated paths
  350. to model files for the openwakeword library. These paths point to
  351. custom models that can be used for wake word detection when the
  352. openwakeword library is selected as the wakeword_backend.
  353. - openwakeword_inference_framework (str, default="onnx"): Specifies
  354. the inference framework to use with the openwakeword library.
  355. Can be either 'onnx' for Open Neural Network Exchange format
  356. or 'tflite' for TensorFlow Lite.
  357. - wake_words (str, default=""): Comma-separated string of wake words to
  358. initiate recording when using the 'pvporcupine' wakeword backend.
  359. Supported wake words include: 'alexa', 'americano', 'blueberry',
  360. 'bumblebee', 'computer', 'grapefruits', 'grasshopper', 'hey google',
  361. 'hey siri', 'jarvis', 'ok google', 'picovoice', 'porcupine',
  362. 'terminator'. For the 'openwakeword' backend, wake words are
  363. automatically extracted from the provided model files, so specifying
  364. them here is not necessary.
  365. - wake_words_sensitivity (float, default=0.5): Sensitivity for wake
  366. word detection, ranging from 0 (least sensitive) to 1 (most
  367. sensitive). Default is 0.5.
  368. - wake_word_activation_delay (float, default=0): Duration in seconds
  369. after the start of monitoring before the system switches to wake
  370. word activation if no voice is initially detected. If set to
  371. zero, the system uses wake word activation immediately.
  372. - wake_word_timeout (float, default=5): Duration in seconds after a
  373. wake word is recognized. If no subsequent voice activity is
  374. detected within this window, the system transitions back to an
  375. inactive state, awaiting the next wake word or voice activation.
  376. - wake_word_buffer_duration (float, default=0.1): Duration in seconds
  377. to buffer audio data during wake word detection. This helps in
  378. cutting out the wake word from the recording buffer so it does not
  379. falsely get detected along with the following spoken text, ensuring
  380. cleaner and more accurate transcription start triggers.
  381. Increase this if parts of the wake word get detected as text.
  382. - on_wakeword_detected (callable, default=None): Callback function to
  383. be called when a wake word is detected.
  384. - on_wakeword_timeout (callable, default=None): Callback function to
  385. be called when the system goes back to an inactive state after when
  386. no speech was detected after wake word activation
  387. - on_wakeword_detection_start (callable, default=None): Callback
  388. function to be called when the system starts to listen for wake
  389. words
  390. - on_wakeword_detection_end (callable, default=None): Callback
  391. function to be called when the system stops to listen for
  392. wake words (e.g. because of timeout or wake word detected)
  393. - on_recorded_chunk (callable, default=None): Callback function to be
  394. called when a chunk of audio is recorded. The function is called
  395. with the recorded audio chunk as its argument.
  396. - debug_mode (bool, default=False): If set to True, the system will
  397. print additional debug information to the console.
  398. - handle_buffer_overflow (bool, default=True): If set to True, the system
  399. will log a warning when an input overflow occurs during recording and
  400. remove the data from the buffer.
  401. - beam_size (int, default=5): The beam size to use for beam search
  402. decoding.
  403. - beam_size_realtime (int, default=3): The beam size to use for beam
  404. search decoding in the real-time transcription model.
  405. - buffer_size (int, default=512): The buffer size to use for audio
  406. recording. Changing this may break functionality.
  407. - sample_rate (int, default=16000): The sample rate to use for audio
  408. recording. Changing this will very probably functionality (as the
  409. WebRTC VAD model is very sensitive towards the sample rate).
  410. - initial_prompt (str or iterable of int, default=None): Initial
  411. prompt to be fed to the transcription models.
  412. - suppress_tokens (list of int, default=[-1]): Tokens to be suppressed
  413. from the transcription output.
  414. - print_transcription_time (bool, default=False): Logs processing time
  415. of main model transcription
  416. - early_transcription_on_silence (int, default=0): If set, the
  417. system will transcribe audio faster when silence is detected.
  418. Transcription will start after the specified milliseconds, so
  419. keep this value lower than post_speech_silence_duration.
  420. Ideally around post_speech_silence_duration minus the estimated
  421. transcription time with the main model.
  422. If silence lasts longer than post_speech_silence_duration, the
  423. recording is stopped, and the transcription is submitted. If
  424. voice activity resumes within this period, the transcription
  425. is discarded. Results in faster final transcriptions to the cost
  426. of additional GPU load due to some unnecessary final transcriptions.
  427. - allowed_latency_limit (int, default=100): Maximal amount of chunks
  428. that can be unprocessed in queue before discarding chunks.
  429. - no_log_file (bool, default=False): Skips writing of debug log file.
  430. - use_extended_logging (bool, default=False): Writes extensive
  431. log messages for the recording worker, that processes the audio
  432. chunks.
  433. Raises:
  434. Exception: Errors related to initializing transcription
  435. model, wake word detection, or audio recording.
  436. """
  437. self.language = language
  438. self.compute_type = compute_type
  439. self.input_device_index = input_device_index
  440. self.gpu_device_index = gpu_device_index
  441. self.device = device
  442. self.wake_words = wake_words
  443. self.wake_word_activation_delay = wake_word_activation_delay
  444. self.wake_word_timeout = wake_word_timeout
  445. self.wake_word_buffer_duration = wake_word_buffer_duration
  446. self.ensure_sentence_starting_uppercase = (
  447. ensure_sentence_starting_uppercase
  448. )
  449. self.ensure_sentence_ends_with_period = (
  450. ensure_sentence_ends_with_period
  451. )
  452. self.use_microphone = mp.Value(c_bool, use_microphone)
  453. self.min_gap_between_recordings = min_gap_between_recordings
  454. self.min_length_of_recording = min_length_of_recording
  455. self.pre_recording_buffer_duration = pre_recording_buffer_duration
  456. self.post_speech_silence_duration = post_speech_silence_duration
  457. self.on_recording_start = on_recording_start
  458. self.on_recording_stop = on_recording_stop
  459. self.on_wakeword_detected = on_wakeword_detected
  460. self.on_wakeword_timeout = on_wakeword_timeout
  461. self.on_vad_detect_start = on_vad_detect_start
  462. self.on_vad_detect_stop = on_vad_detect_stop
  463. self.on_wakeword_detection_start = on_wakeword_detection_start
  464. self.on_wakeword_detection_end = on_wakeword_detection_end
  465. self.on_recorded_chunk = on_recorded_chunk
  466. self.on_transcription_start = on_transcription_start
  467. self.enable_realtime_transcription = enable_realtime_transcription
  468. self.use_main_model_for_realtime = use_main_model_for_realtime
  469. self.main_model_type = model
  470. self.realtime_model_type = realtime_model_type
  471. self.realtime_processing_pause = realtime_processing_pause
  472. self.on_realtime_transcription_update = (
  473. on_realtime_transcription_update
  474. )
  475. self.on_realtime_transcription_stabilized = (
  476. on_realtime_transcription_stabilized
  477. )
  478. self.debug_mode = debug_mode
  479. self.handle_buffer_overflow = handle_buffer_overflow
  480. self.beam_size = beam_size
  481. self.beam_size_realtime = beam_size_realtime
  482. self.allowed_latency_limit = allowed_latency_limit
  483. self.level = level
  484. self.audio_queue = mp.Queue()
  485. self.buffer_size = buffer_size
  486. self.sample_rate = sample_rate
  487. self.recording_start_time = 0
  488. self.recording_stop_time = 0
  489. self.wake_word_detect_time = 0
  490. self.silero_check_time = 0
  491. self.silero_working = False
  492. self.speech_end_silence_start = 0
  493. self.silero_sensitivity = silero_sensitivity
  494. self.silero_deactivity_detection = silero_deactivity_detection
  495. self.listen_start = 0
  496. self.spinner = spinner
  497. self.halo = None
  498. self.state = "inactive"
  499. self.wakeword_detected = False
  500. self.text_storage = []
  501. self.realtime_stabilized_text = ""
  502. self.realtime_stabilized_safetext = ""
  503. self.is_webrtc_speech_active = False
  504. self.is_silero_speech_active = False
  505. self.recording_thread = None
  506. self.realtime_thread = None
  507. self.audio_interface = None
  508. self.audio = None
  509. self.stream = None
  510. self.start_recording_event = threading.Event()
  511. self.stop_recording_event = threading.Event()
  512. self.last_transcription_bytes = None
  513. self.initial_prompt = initial_prompt
  514. self.suppress_tokens = suppress_tokens
  515. self.use_wake_words = wake_words or wakeword_backend in {'oww', 'openwakeword', 'openwakewords'}
  516. self.detected_language = None
  517. self.detected_language_probability = 0
  518. self.detected_realtime_language = None
  519. self.detected_realtime_language_probability = 0
  520. self.transcription_lock = threading.Lock()
  521. self.shutdown_lock = threading.Lock()
  522. self.transcribe_count = 0
  523. self.print_transcription_time = print_transcription_time
  524. self.early_transcription_on_silence = early_transcription_on_silence
  525. self.use_extended_logging = use_extended_logging
  526. # Initialize the logging configuration with the specified level
  527. log_format = 'RealTimeSTT: %(name)s - %(levelname)s - %(message)s'
  528. # Adjust file_log_format to include milliseconds
  529. file_log_format = '%(asctime)s.%(msecs)03d - ' + log_format
  530. # Get the root logger
  531. logger = logging.getLogger()
  532. logger.setLevel(logging.DEBUG) # Set the root logger's level to DEBUG
  533. # Remove any existing handlers
  534. logger.handlers = []
  535. # Create a console handler and set its level
  536. console_handler = logging.StreamHandler()
  537. console_handler.setLevel(level)
  538. console_handler.setFormatter(logging.Formatter(log_format))
  539. # Add the handlers to the logger
  540. if not no_log_file:
  541. # Create a file handler and set its level
  542. file_handler = logging.FileHandler('realtimesst.log')
  543. file_handler.setLevel(logging.DEBUG)
  544. file_handler.setFormatter(logging.Formatter(
  545. file_log_format,
  546. datefmt='%Y-%m-%d %H:%M:%S'
  547. ))
  548. logger.addHandler(file_handler)
  549. logger.addHandler(console_handler)
  550. self.is_shut_down = False
  551. self.shutdown_event = mp.Event()
  552. try:
  553. # Only set the start method if it hasn't been set already
  554. if mp.get_start_method(allow_none=True) is None:
  555. mp.set_start_method("spawn")
  556. except RuntimeError as e:
  557. logging.info(f"Start method has already been set. Details: {e}")
  558. logging.info("Starting RealTimeSTT")
  559. self.interrupt_stop_event = mp.Event()
  560. self.was_interrupted = mp.Event()
  561. self.main_transcription_ready_event = mp.Event()
  562. self.parent_transcription_pipe, child_transcription_pipe = mp.Pipe()
  563. self.parent_stdout_pipe, child_stdout_pipe = mp.Pipe()
  564. # Set device for model
  565. self.device = "cuda" if self.device == "cuda" and torch.cuda.is_available() else "cpu"
  566. self.transcript_process = self._start_thread(
  567. target=AudioToTextRecorder._transcription_worker,
  568. args=(
  569. child_transcription_pipe,
  570. child_stdout_pipe,
  571. model,
  572. self.compute_type,
  573. self.gpu_device_index,
  574. self.device,
  575. self.main_transcription_ready_event,
  576. self.shutdown_event,
  577. self.interrupt_stop_event,
  578. self.beam_size,
  579. self.initial_prompt,
  580. self.suppress_tokens
  581. )
  582. )
  583. # Start audio data reading process
  584. if self.use_microphone.value:
  585. logging.info("Initializing audio recording"
  586. " (creating pyAudio input stream,"
  587. f" sample rate: {self.sample_rate}"
  588. f" buffer size: {self.buffer_size}"
  589. )
  590. self.reader_process = self._start_thread(
  591. target=AudioToTextRecorder._audio_data_worker,
  592. args=(
  593. self.audio_queue,
  594. self.sample_rate,
  595. self.buffer_size,
  596. self.input_device_index,
  597. self.shutdown_event,
  598. self.interrupt_stop_event,
  599. self.use_microphone
  600. )
  601. )
  602. # Initialize the realtime transcription model
  603. if self.enable_realtime_transcription and not self.use_main_model_for_realtime:
  604. try:
  605. logging.info("Initializing faster_whisper realtime "
  606. f"transcription model {self.realtime_model_type}"
  607. )
  608. self.realtime_model_type = faster_whisper.WhisperModel(
  609. model_size_or_path=self.realtime_model_type,
  610. device=self.device,
  611. compute_type=self.compute_type,
  612. device_index=self.gpu_device_index
  613. )
  614. except Exception as e:
  615. logging.exception("Error initializing faster_whisper "
  616. f"realtime transcription model: {e}"
  617. )
  618. raise
  619. logging.debug("Faster_whisper realtime speech to text "
  620. "transcription model initialized successfully")
  621. # Setup wake word detection
  622. if wake_words or wakeword_backend in {'oww', 'openwakeword', 'openwakewords'}:
  623. self.wakeword_backend = wakeword_backend
  624. self.wake_words_list = [
  625. word.strip() for word in wake_words.lower().split(',')
  626. ]
  627. self.wake_words_sensitivity = wake_words_sensitivity
  628. self.wake_words_sensitivities = [
  629. float(wake_words_sensitivity)
  630. for _ in range(len(self.wake_words_list))
  631. ]
  632. if self.wakeword_backend in {'pvp', 'pvporcupine'}:
  633. try:
  634. self.porcupine = pvporcupine.create(
  635. keywords=self.wake_words_list,
  636. sensitivities=self.wake_words_sensitivities
  637. )
  638. self.buffer_size = self.porcupine.frame_length
  639. self.sample_rate = self.porcupine.sample_rate
  640. except Exception as e:
  641. logging.exception(
  642. "Error initializing porcupine "
  643. f"wake word detection engine: {e}"
  644. )
  645. raise
  646. logging.debug(
  647. "Porcupine wake word detection engine initialized successfully"
  648. )
  649. elif self.wakeword_backend in {'oww', 'openwakeword', 'openwakewords'}:
  650. openwakeword.utils.download_models()
  651. try:
  652. if openwakeword_model_paths:
  653. model_paths = openwakeword_model_paths.split(',')
  654. self.owwModel = Model(
  655. wakeword_models=model_paths,
  656. inference_framework=openwakeword_inference_framework
  657. )
  658. logging.info(
  659. "Successfully loaded wakeword model(s): "
  660. f"{openwakeword_model_paths}"
  661. )
  662. else:
  663. self.owwModel = Model(
  664. inference_framework=openwakeword_inference_framework)
  665. self.oww_n_models = len(self.owwModel.models.keys())
  666. if not self.oww_n_models:
  667. logging.error(
  668. "No wake word models loaded."
  669. )
  670. for model_key in self.owwModel.models.keys():
  671. logging.info(
  672. "Successfully loaded openwakeword model: "
  673. f"{model_key}"
  674. )
  675. except Exception as e:
  676. logging.exception(
  677. "Error initializing openwakeword "
  678. f"wake word detection engine: {e}"
  679. )
  680. raise
  681. logging.debug(
  682. "Open wake word detection engine initialized successfully"
  683. )
  684. else:
  685. logging.exception(f"Wakeword engine {self.wakeword_backend} unknown/unsupported. Please specify one of: pvporcupine, openwakeword.")
  686. # Setup voice activity detection model WebRTC
  687. try:
  688. logging.info("Initializing WebRTC voice with "
  689. f"Sensitivity {webrtc_sensitivity}"
  690. )
  691. self.webrtc_vad_model = webrtcvad.Vad()
  692. self.webrtc_vad_model.set_mode(webrtc_sensitivity)
  693. except Exception as e:
  694. logging.exception("Error initializing WebRTC voice "
  695. f"activity detection engine: {e}"
  696. )
  697. raise
  698. logging.debug("WebRTC VAD voice activity detection "
  699. "engine initialized successfully"
  700. )
  701. # Setup voice activity detection model Silero VAD
  702. try:
  703. self.silero_vad_model, _ = torch.hub.load(
  704. repo_or_dir="snakers4/silero-vad",
  705. model="silero_vad",
  706. verbose=False,
  707. onnx=silero_use_onnx
  708. )
  709. except Exception as e:
  710. logging.exception(f"Error initializing Silero VAD "
  711. f"voice activity detection engine: {e}"
  712. )
  713. raise
  714. logging.debug("Silero VAD voice activity detection "
  715. "engine initialized successfully"
  716. )
  717. self.audio_buffer = collections.deque(
  718. maxlen=int((self.sample_rate // self.buffer_size) *
  719. self.pre_recording_buffer_duration)
  720. )
  721. self.frames = []
  722. # Recording control flags
  723. self.is_recording = False
  724. self.is_running = True
  725. self.start_recording_on_voice_activity = False
  726. self.stop_recording_on_voice_deactivity = False
  727. # Start the recording worker thread
  728. self.recording_thread = threading.Thread(target=self._recording_worker)
  729. self.recording_thread.daemon = True
  730. self.recording_thread.start()
  731. # Start the realtime transcription worker thread
  732. self.realtime_thread = threading.Thread(target=self._realtime_worker)
  733. self.realtime_thread.daemon = True
  734. self.realtime_thread.start()
  735. # Wait for transcription models to start
  736. logging.debug('Waiting for main transcription model to start')
  737. self.main_transcription_ready_event.wait()
  738. logging.debug('Main transcription model ready')
  739. self.stdout_thread = threading.Thread(target=self._read_stdout)
  740. self.stdout_thread.daemon = True
  741. self.stdout_thread.start()
  742. logging.debug('RealtimeSTT initialization completed successfully')
  743. def _start_thread(self, target=None, args=()):
  744. """
  745. Implement a consistent threading model across the library.
  746. This method is used to start any thread in this library. It uses the
  747. standard threading. Thread for Linux and for all others uses the pytorch
  748. MultiProcessing library 'Process'.
  749. Args:
  750. target (callable object): is the callable object to be invoked by
  751. the run() method. Defaults to None, meaning nothing is called.
  752. args (tuple): is a list or tuple of arguments for the target
  753. invocation. Defaults to ().
  754. """
  755. if (platform.system() == 'Linux'):
  756. thread = threading.Thread(target=target, args=args)
  757. thread.deamon = True
  758. thread.start()
  759. return thread
  760. else:
  761. thread = mp.Process(target=target, args=args)
  762. thread.start()
  763. return thread
  764. def _read_stdout(self):
  765. while not self.shutdown_event.is_set():
  766. try:
  767. if self.parent_stdout_pipe.poll(0.1):
  768. logging.debug("Receive from stdout pipe")
  769. message = self.parent_stdout_pipe.recv()
  770. logging.info(message)
  771. except (BrokenPipeError, EOFError, OSError):
  772. # The pipe probably has been closed, so we ignore the error
  773. pass
  774. except KeyboardInterrupt: # handle manual interruption (Ctrl+C)
  775. logging.info("KeyboardInterrupt in read from stdout detected, exiting...")
  776. break
  777. except Exception as e:
  778. logging.error(f"Unexpected error in read from stdout: {e}")
  779. logging.error(traceback.format_exc()) # Log the full traceback here
  780. break
  781. time.sleep(0.1)
  782. def _transcription_worker(*args, **kwargs):
  783. worker = TranscriptionWorker(*args, **kwargs)
  784. worker.run()
  785. @staticmethod
  786. def _audio_data_worker(audio_queue,
  787. target_sample_rate,
  788. buffer_size,
  789. input_device_index,
  790. shutdown_event,
  791. interrupt_stop_event,
  792. use_microphone):
  793. """
  794. Worker method that handles the audio recording process.
  795. This method runs in a separate process and is responsible for:
  796. - Setting up the audio input stream for recording at the highest possible sample rate.
  797. - Continuously reading audio data from the input stream, resampling if necessary,
  798. preprocessing the data, and placing complete chunks in a queue.
  799. - Handling errors during the recording process.
  800. - Gracefully terminating the recording process when a shutdown event is set.
  801. Args:
  802. audio_queue (queue.Queue): A queue where recorded audio data is placed.
  803. target_sample_rate (int): The desired sample rate for the output audio (for Silero VAD).
  804. buffer_size (int): The number of samples expected by the Silero VAD model.
  805. input_device_index (int): The index of the audio input device.
  806. shutdown_event (threading.Event): An event that, when set, signals this worker method to terminate.
  807. interrupt_stop_event (threading.Event): An event to signal keyboard interrupt.
  808. use_microphone (multiprocessing.Value): A shared value indicating whether to use the microphone.
  809. Raises:
  810. Exception: If there is an error while initializing the audio recording.
  811. """
  812. import pyaudio
  813. import numpy as np
  814. from scipy import signal
  815. system_signal.signal(system_signal.SIGINT, system_signal.SIG_IGN)
  816. def get_highest_sample_rate(audio_interface, device_index):
  817. """Get the highest supported sample rate for the specified device."""
  818. try:
  819. device_info = audio_interface.get_device_info_by_index(device_index)
  820. max_rate = int(device_info['defaultSampleRate'])
  821. if 'supportedSampleRates' in device_info:
  822. supported_rates = [int(rate) for rate in device_info['supportedSampleRates']]
  823. if supported_rates:
  824. max_rate = max(supported_rates)
  825. return max_rate
  826. except Exception as e:
  827. logging.warning(f"Failed to get highest sample rate: {e}")
  828. return 48000 # Fallback to a common high sample rate
  829. def initialize_audio_stream(audio_interface, device_index, sample_rate, chunk_size):
  830. """Initialize the audio stream with error handling."""
  831. try:
  832. stream = audio_interface.open(
  833. format=pyaudio.paInt16,
  834. channels=1,
  835. rate=sample_rate,
  836. input=True,
  837. frames_per_buffer=chunk_size,
  838. input_device_index=device_index,
  839. )
  840. return stream
  841. except Exception as e:
  842. logging.error(f"Error initializing audio stream: {e}")
  843. raise
  844. def preprocess_audio(chunk, original_sample_rate, target_sample_rate):
  845. """Preprocess audio chunk similar to feed_audio method."""
  846. if isinstance(chunk, np.ndarray):
  847. # Handle stereo to mono conversion if necessary
  848. if chunk.ndim == 2:
  849. chunk = np.mean(chunk, axis=1)
  850. # Resample to target_sample_rate if necessary
  851. if original_sample_rate != target_sample_rate:
  852. num_samples = int(len(chunk) * target_sample_rate / original_sample_rate)
  853. chunk = signal.resample(chunk, num_samples)
  854. # Ensure data type is int16
  855. chunk = chunk.astype(np.int16)
  856. else:
  857. # If chunk is bytes, convert to numpy array
  858. chunk = np.frombuffer(chunk, dtype=np.int16)
  859. # Resample if necessary
  860. if original_sample_rate != target_sample_rate:
  861. num_samples = int(len(chunk) * target_sample_rate / original_sample_rate)
  862. chunk = signal.resample(chunk, num_samples)
  863. chunk = chunk.astype(np.int16)
  864. return chunk.tobytes()
  865. audio_interface = None
  866. stream = None
  867. device_sample_rate = None
  868. chunk_size = 1024 # Increased chunk size for better performance
  869. def setup_audio():
  870. nonlocal audio_interface, stream, device_sample_rate, input_device_index
  871. try:
  872. audio_interface = pyaudio.PyAudio()
  873. if input_device_index is None:
  874. try:
  875. default_device = audio_interface.get_default_input_device_info()
  876. input_device_index = default_device['index']
  877. except OSError as e:
  878. input_device_index = None
  879. sample_rates_to_try = [16000] # Try 16000 Hz first
  880. if input_device_index is not None:
  881. highest_rate = get_highest_sample_rate(audio_interface, input_device_index)
  882. if highest_rate != 16000:
  883. sample_rates_to_try.append(highest_rate)
  884. else:
  885. sample_rates_to_try.append(48000) # Fallback sample rate
  886. for rate in sample_rates_to_try:
  887. try:
  888. device_sample_rate = rate
  889. stream = initialize_audio_stream(audio_interface, input_device_index, device_sample_rate, chunk_size)
  890. if stream is not None:
  891. logging.debug(f"Audio recording initialized successfully at {device_sample_rate} Hz, reading {chunk_size} frames at a time")
  892. return True
  893. except Exception as e:
  894. logging.warning(f"Failed to initialize audio stream at {device_sample_rate} Hz: {e}")
  895. continue
  896. # If we reach here, none of the sample rates worked
  897. raise Exception("Failed to initialize audio stream with all sample rates.")
  898. except Exception as e:
  899. logging.exception(f"Error initializing pyaudio audio recording: {e}")
  900. if audio_interface:
  901. audio_interface.terminate()
  902. return False
  903. if not setup_audio():
  904. raise Exception("Failed to set up audio recording.")
  905. buffer = bytearray()
  906. silero_buffer_size = 2 * buffer_size # silero complains if too short
  907. time_since_last_buffer_message = 0
  908. try:
  909. while not shutdown_event.is_set():
  910. try:
  911. data = stream.read(chunk_size, exception_on_overflow=False)
  912. if use_microphone.value:
  913. processed_data = preprocess_audio(data, device_sample_rate, target_sample_rate)
  914. buffer += processed_data
  915. # Check if the buffer has reached or exceeded the silero_buffer_size
  916. while len(buffer) >= silero_buffer_size:
  917. # Extract silero_buffer_size amount of data from the buffer
  918. to_process = buffer[:silero_buffer_size]
  919. buffer = buffer[silero_buffer_size:]
  920. # Feed the extracted data to the audio_queue
  921. if time_since_last_buffer_message:
  922. time_passed = time.time() - time_since_last_buffer_message
  923. if time_passed > 1:
  924. logging.debug("_audio_data_worker writing audio data into queue.")
  925. time_since_last_buffer_message = time.time()
  926. else:
  927. time_since_last_buffer_message = time.time()
  928. audio_queue.put(to_process)
  929. except OSError as e:
  930. if e.errno == pyaudio.paInputOverflowed:
  931. logging.warning("Input overflowed. Frame dropped.")
  932. else:
  933. logging.error(f"Error during recording: {e}")
  934. # Attempt to reinitialize the stream
  935. logging.info("Attempting to reinitialize the audio stream...")
  936. if stream:
  937. stream.stop_stream()
  938. stream.close()
  939. if audio_interface:
  940. audio_interface.terminate()
  941. # Wait a bit before trying to reinitialize
  942. time.sleep(1)
  943. if not setup_audio():
  944. logging.error("Failed to reinitialize audio stream. Exiting.")
  945. break
  946. else:
  947. logging.info("Audio stream reinitialized successfully.")
  948. continue
  949. except Exception as e:
  950. logging.error(f"Error during recording: {e}")
  951. tb_str = traceback.format_exc()
  952. logging.error(f"Traceback: {tb_str}")
  953. logging.error(f"Error: {e}")
  954. # Attempt to reinitialize the stream
  955. logging.info("Attempting to reinitialize the audio stream...")
  956. if stream:
  957. stream.stop_stream()
  958. stream.close()
  959. if audio_interface:
  960. audio_interface.terminate()
  961. # Wait a bit before trying to reinitialize
  962. time.sleep(0.5)
  963. if not setup_audio():
  964. logging.error("Failed to reinitialize audio stream. Exiting.")
  965. break
  966. else:
  967. logging.info("Audio stream reinitialized successfully.")
  968. continue
  969. except KeyboardInterrupt:
  970. interrupt_stop_event.set()
  971. logging.debug("Audio data worker process finished due to KeyboardInterrupt")
  972. finally:
  973. # After recording stops, feed any remaining audio data
  974. if buffer:
  975. audio_queue.put(bytes(buffer))
  976. if stream:
  977. stream.stop_stream()
  978. stream.close()
  979. if audio_interface:
  980. audio_interface.terminate()
  981. def wakeup(self):
  982. """
  983. If in wake work modus, wake up as if a wake word was spoken.
  984. """
  985. self.listen_start = time.time()
  986. def abort(self):
  987. self.start_recording_on_voice_activity = False
  988. self.stop_recording_on_voice_deactivity = False
  989. self._set_state("inactive")
  990. self.interrupt_stop_event.set()
  991. self.was_interrupted.wait()
  992. self.was_interrupted.clear()
  993. def wait_audio(self):
  994. """
  995. Waits for the start and completion of the audio recording process.
  996. This method is responsible for:
  997. - Waiting for voice activity to begin recording if not yet started.
  998. - Waiting for voice inactivity to complete the recording.
  999. - Setting the audio buffer from the recorded frames.
  1000. - Resetting recording-related attributes.
  1001. Side effects:
  1002. - Updates the state of the instance.
  1003. - Modifies the audio attribute to contain the processed audio data.
  1004. """
  1005. try:
  1006. logging.info("Setting listen time")
  1007. if self.listen_start == 0:
  1008. self.listen_start = time.time()
  1009. # If not yet started recording, wait for voice activity to initiate.
  1010. if not self.is_recording and not self.frames:
  1011. self._set_state("listening")
  1012. self.start_recording_on_voice_activity = True
  1013. # Wait until recording starts
  1014. logging.debug('Waiting for recording start')
  1015. while not self.interrupt_stop_event.is_set():
  1016. if self.start_recording_event.wait(timeout=0.02):
  1017. break
  1018. # If recording is ongoing, wait for voice inactivity
  1019. # to finish recording.
  1020. if self.is_recording:
  1021. self.stop_recording_on_voice_deactivity = True
  1022. # Wait until recording stops
  1023. logging.debug('Waiting for recording stop')
  1024. while not self.interrupt_stop_event.is_set():
  1025. if (self.stop_recording_event.wait(timeout=0.02)):
  1026. break
  1027. # Convert recorded frames to the appropriate audio format.
  1028. audio_array = np.frombuffer(b''.join(self.frames), dtype=np.int16)
  1029. self.audio = audio_array.astype(np.float32) / INT16_MAX_ABS_VALUE
  1030. self.frames.clear()
  1031. # Reset recording-related timestamps
  1032. self.recording_stop_time = 0
  1033. self.listen_start = 0
  1034. self._set_state("inactive")
  1035. except KeyboardInterrupt:
  1036. logging.info("KeyboardInterrupt in wait_audio, shutting down")
  1037. self.shutdown()
  1038. raise # Re-raise the exception after cleanup
  1039. def transcribe(self):
  1040. """
  1041. Transcribes audio captured by this class instance using the
  1042. `faster_whisper` model.
  1043. Automatically starts recording upon voice activity if not manually
  1044. started using `recorder.start()`.
  1045. Automatically stops recording upon voice deactivity if not manually
  1046. stopped with `recorder.stop()`.
  1047. Processes the recorded audio to generate transcription.
  1048. Args:
  1049. on_transcription_finished (callable, optional): Callback function
  1050. to be executed when transcription is ready.
  1051. If provided, transcription will be performed asynchronously,
  1052. and the callback will receive the transcription as its argument.
  1053. If omitted, the transcription will be performed synchronously,
  1054. and the result will be returned.
  1055. Returns (if no callback is set):
  1056. str: The transcription of the recorded audio.
  1057. Raises:
  1058. Exception: If there is an error during the transcription process.
  1059. """
  1060. self._set_state("transcribing")
  1061. audio_copy = copy.deepcopy(self.audio)
  1062. start_time = 0
  1063. with self.transcription_lock:
  1064. try:
  1065. if self.transcribe_count == 0:
  1066. logging.debug("Adding transcription request, no early transcription started")
  1067. start_time = time.time() # Start timing
  1068. self.parent_transcription_pipe.send((self.audio, self.language))
  1069. self.transcribe_count += 1
  1070. while self.transcribe_count > 0:
  1071. logging.debug(F"Receive from parent_transcription_pipe after sendiung transcription request, transcribe_count: {self.transcribe_count}")
  1072. status, result = self.parent_transcription_pipe.recv()
  1073. self.transcribe_count -= 1
  1074. self.allowed_to_early_transcribe = True
  1075. self._set_state("inactive")
  1076. if status == 'success':
  1077. segments, info = result
  1078. self.detected_language = info.language if info.language_probability > 0 else None
  1079. self.detected_language_probability = info.language_probability
  1080. self.last_transcription_bytes = audio_copy
  1081. transcription = self._preprocess_output(segments)
  1082. end_time = time.time() # End timing
  1083. transcription_time = end_time - start_time
  1084. if start_time:
  1085. if self.print_transcription_time:
  1086. print(f"Model {self.main_model_type} completed transcription in {transcription_time:.2f} seconds")
  1087. else:
  1088. logging.debug(f"Model {self.main_model_type} completed transcription in {transcription_time:.2f} seconds")
  1089. return transcription
  1090. else:
  1091. logging.error(f"Transcription error: {result}")
  1092. raise Exception(result)
  1093. except Exception as e:
  1094. logging.error(f"Error during transcription: {str(e)}")
  1095. raise e
  1096. def _process_wakeword(self, data):
  1097. """
  1098. Processes audio data to detect wake words.
  1099. """
  1100. if self.wakeword_backend in {'pvp', 'pvporcupine'}:
  1101. pcm = struct.unpack_from(
  1102. "h" * self.buffer_size,
  1103. data
  1104. )
  1105. porcupine_index = self.porcupine.process(pcm)
  1106. if self.debug_mode:
  1107. logging.info(f"wake words porcupine_index: {porcupine_index}")
  1108. return self.porcupine.process(pcm)
  1109. elif self.wakeword_backend in {'oww', 'openwakeword', 'openwakewords'}:
  1110. pcm = np.frombuffer(data, dtype=np.int16)
  1111. prediction = self.owwModel.predict(pcm)
  1112. max_score = -1
  1113. max_index = -1
  1114. wake_words_in_prediction = len(self.owwModel.prediction_buffer.keys())
  1115. self.wake_words_sensitivities
  1116. if wake_words_in_prediction:
  1117. for idx, mdl in enumerate(self.owwModel.prediction_buffer.keys()):
  1118. scores = list(self.owwModel.prediction_buffer[mdl])
  1119. if scores[-1] >= self.wake_words_sensitivity and scores[-1] > max_score:
  1120. max_score = scores[-1]
  1121. max_index = idx
  1122. if self.debug_mode:
  1123. logging.info(f"wake words oww max_index, max_score: {max_index} {max_score}")
  1124. return max_index
  1125. else:
  1126. if self.debug_mode:
  1127. logging.info(f"wake words oww_index: -1")
  1128. return -1
  1129. if self.debug_mode:
  1130. logging.info("wake words no match")
  1131. return -1
  1132. def text(self,
  1133. on_transcription_finished=None,
  1134. ):
  1135. """
  1136. Transcribes audio captured by this class instance
  1137. using the `faster_whisper` model.
  1138. - Automatically starts recording upon voice activity if not manually
  1139. started using `recorder.start()`.
  1140. - Automatically stops recording upon voice deactivity if not manually
  1141. stopped with `recorder.stop()`.
  1142. - Processes the recorded audio to generate transcription.
  1143. Args:
  1144. on_transcription_finished (callable, optional): Callback function
  1145. to be executed when transcription is ready.
  1146. If provided, transcription will be performed asynchronously, and
  1147. the callback will receive the transcription as its argument.
  1148. If omitted, the transcription will be performed synchronously,
  1149. and the result will be returned.
  1150. Returns (if not callback is set):
  1151. str: The transcription of the recorded audio
  1152. """
  1153. self.interrupt_stop_event.clear()
  1154. self.was_interrupted.clear()
  1155. try:
  1156. self.wait_audio()
  1157. except KeyboardInterrupt:
  1158. logging.info("KeyboardInterrupt in text() method")
  1159. self.shutdown()
  1160. raise # Re-raise the exception after cleanup
  1161. if self.is_shut_down or self.interrupt_stop_event.is_set():
  1162. if self.interrupt_stop_event.is_set():
  1163. self.was_interrupted.set()
  1164. return ""
  1165. if on_transcription_finished:
  1166. threading.Thread(target=on_transcription_finished,
  1167. args=(self.transcribe(),)).start()
  1168. else:
  1169. return self.transcribe()
  1170. def start(self):
  1171. """
  1172. Starts recording audio directly without waiting for voice activity.
  1173. """
  1174. # Ensure there's a minimum interval
  1175. # between stopping and starting recording
  1176. if (time.time() - self.recording_stop_time
  1177. < self.min_gap_between_recordings):
  1178. logging.info("Attempted to start recording "
  1179. "too soon after stopping."
  1180. )
  1181. return self
  1182. logging.info("recording started")
  1183. self._set_state("recording")
  1184. self.text_storage = []
  1185. self.realtime_stabilized_text = ""
  1186. self.realtime_stabilized_safetext = ""
  1187. self.wakeword_detected = False
  1188. self.wake_word_detect_time = 0
  1189. self.frames = []
  1190. self.is_recording = True
  1191. self.recording_start_time = time.time()
  1192. self.is_silero_speech_active = False
  1193. self.is_webrtc_speech_active = False
  1194. self.stop_recording_event.clear()
  1195. self.start_recording_event.set()
  1196. if self.on_recording_start:
  1197. self.on_recording_start()
  1198. return self
  1199. def stop(self):
  1200. """
  1201. Stops recording audio.
  1202. """
  1203. # Ensure there's a minimum interval
  1204. # between starting and stopping recording
  1205. if (time.time() - self.recording_start_time
  1206. < self.min_length_of_recording):
  1207. logging.info("Attempted to stop recording "
  1208. "too soon after starting."
  1209. )
  1210. return self
  1211. logging.info("recording stopped")
  1212. self.is_recording = False
  1213. self.recording_stop_time = time.time()
  1214. self.is_silero_speech_active = False
  1215. self.is_webrtc_speech_active = False
  1216. self.silero_check_time = 0
  1217. self.start_recording_event.clear()
  1218. self.stop_recording_event.set()
  1219. if self.on_recording_stop:
  1220. self.on_recording_stop()
  1221. return self
  1222. def listen(self):
  1223. """
  1224. Puts recorder in immediate "listen" state.
  1225. This is the state after a wake word detection, for example.
  1226. The recorder now "listens" for voice activation.
  1227. Once voice is detected we enter "recording" state.
  1228. """
  1229. self.listen_start = time.time()
  1230. self._set_state("listening")
  1231. self.start_recording_on_voice_activity = True
  1232. def feed_audio(self, chunk, original_sample_rate=16000):
  1233. """
  1234. Feed an audio chunk into the processing pipeline. Chunks are
  1235. accumulated until the buffer size is reached, and then the accumulated
  1236. data is fed into the audio_queue.
  1237. """
  1238. # Check if the buffer attribute exists, if not, initialize it
  1239. if not hasattr(self, 'buffer'):
  1240. self.buffer = bytearray()
  1241. # Check if input is a NumPy array
  1242. if isinstance(chunk, np.ndarray):
  1243. # Handle stereo to mono conversion if necessary
  1244. if chunk.ndim == 2:
  1245. chunk = np.mean(chunk, axis=1)
  1246. # Resample to 16000 Hz if necessary
  1247. if original_sample_rate != 16000:
  1248. num_samples = int(len(chunk) * 16000 / original_sample_rate)
  1249. chunk = resample(chunk, num_samples)
  1250. # Ensure data type is int16
  1251. chunk = chunk.astype(np.int16)
  1252. # Convert the NumPy array to bytes
  1253. chunk = chunk.tobytes()
  1254. # Append the chunk to the buffer
  1255. self.buffer += chunk
  1256. buf_size = 2 * self.buffer_size # silero complains if too short
  1257. # Check if the buffer has reached or exceeded the buffer_size
  1258. while len(self.buffer) >= buf_size:
  1259. # Extract self.buffer_size amount of data from the buffer
  1260. to_process = self.buffer[:buf_size]
  1261. self.buffer = self.buffer[buf_size:]
  1262. # Feed the extracted data to the audio_queue
  1263. self.audio_queue.put(to_process)
  1264. def set_microphone(self, microphone_on=True):
  1265. """
  1266. Set the microphone on or off.
  1267. """
  1268. logging.info("Setting microphone to: " + str(microphone_on))
  1269. self.use_microphone.value = microphone_on
  1270. def shutdown(self):
  1271. """
  1272. Safely shuts down the audio recording by stopping the
  1273. recording worker and closing the audio stream.
  1274. """
  1275. with self.shutdown_lock:
  1276. if self.is_shut_down:
  1277. return
  1278. print("\033[91mRealtimeSTT shutting down\033[0m")
  1279. # logging.debug("RealtimeSTT shutting down")
  1280. # Force wait_audio() and text() to exit
  1281. self.is_shut_down = True
  1282. self.start_recording_event.set()
  1283. self.stop_recording_event.set()
  1284. self.shutdown_event.set()
  1285. self.is_recording = False
  1286. self.is_running = False
  1287. logging.debug('Finishing recording thread')
  1288. if self.recording_thread:
  1289. self.recording_thread.join()
  1290. logging.debug('Terminating reader process')
  1291. # Give it some time to finish the loop and cleanup.
  1292. if self.use_microphone.value:
  1293. self.reader_process.join(timeout=10)
  1294. if self.reader_process.is_alive():
  1295. logging.warning("Reader process did not terminate "
  1296. "in time. Terminating forcefully."
  1297. )
  1298. self.reader_process.terminate()
  1299. logging.debug('Terminating transcription process')
  1300. self.transcript_process.join(timeout=10)
  1301. if self.transcript_process.is_alive():
  1302. logging.warning("Transcript process did not terminate "
  1303. "in time. Terminating forcefully."
  1304. )
  1305. self.transcript_process.terminate()
  1306. self.parent_transcription_pipe.close()
  1307. logging.debug('Finishing realtime thread')
  1308. if self.realtime_thread:
  1309. self.realtime_thread.join()
  1310. if self.enable_realtime_transcription:
  1311. if self.realtime_model_type:
  1312. del self.realtime_model_type
  1313. self.realtime_model_type = None
  1314. gc.collect()
  1315. def _recording_worker(self):
  1316. """
  1317. The main worker method which constantly monitors the audio
  1318. input for voice activity and accordingly starts/stops the recording.
  1319. """
  1320. if self.use_extended_logging:
  1321. logging.debug('Debug: Entering try block')
  1322. last_inner_try_time = 0
  1323. try:
  1324. if self.use_extended_logging:
  1325. logging.debug('Debug: Initializing variables')
  1326. time_since_last_buffer_message = 0
  1327. was_recording = False
  1328. delay_was_passed = False
  1329. wakeword_detected_time = None
  1330. wakeword_samples_to_remove = None
  1331. self.allowed_to_early_transcribe = True
  1332. if self.use_extended_logging:
  1333. logging.debug('Debug: Starting main loop')
  1334. # Continuously monitor audio for voice activity
  1335. while self.is_running:
  1336. if self.use_extended_logging:
  1337. logging.debug('Debug: Entering inner try block')
  1338. if last_inner_try_time:
  1339. last_processing_time = time.time() - last_inner_try_time
  1340. if last_processing_time > 0.1:
  1341. if self.use_extended_logging:
  1342. logging.warning('### WARNING: PROCESSING TOOK TOO LONG')
  1343. last_inner_try_time = time.time()
  1344. try:
  1345. if self.use_extended_logging:
  1346. logging.debug('Debug: Trying to get data from audio queue')
  1347. try:
  1348. data = self.audio_queue.get(timeout=0.01)
  1349. except queue.Empty:
  1350. if self.use_extended_logging:
  1351. logging.debug('Debug: Queue is empty, checking if still running')
  1352. if not self.is_running:
  1353. if self.use_extended_logging:
  1354. logging.debug('Debug: Not running, breaking loop')
  1355. break
  1356. if self.use_extended_logging:
  1357. logging.debug('Debug: Continuing to next iteration')
  1358. continue
  1359. if self.use_extended_logging:
  1360. logging.debug('Debug: Checking for on_recorded_chunk callback')
  1361. if self.on_recorded_chunk:
  1362. if self.use_extended_logging:
  1363. logging.debug('Debug: Calling on_recorded_chunk')
  1364. self.on_recorded_chunk(data)
  1365. if self.use_extended_logging:
  1366. logging.debug('Debug: Checking if handle_buffer_overflow is True')
  1367. if self.handle_buffer_overflow:
  1368. if self.use_extended_logging:
  1369. logging.debug('Debug: Handling buffer overflow')
  1370. # Handle queue overflow
  1371. if (self.audio_queue.qsize() >
  1372. self.allowed_latency_limit):
  1373. if self.use_extended_logging:
  1374. logging.debug('Debug: Queue size exceeds limit, logging warnings')
  1375. logging.warning("Audio queue size exceeds "
  1376. "latency limit. Current size: "
  1377. f"{self.audio_queue.qsize()}. "
  1378. "Discarding old audio chunks."
  1379. )
  1380. if self.use_extended_logging:
  1381. logging.debug('Debug: Discarding old chunks if necessary')
  1382. while (self.audio_queue.qsize() >
  1383. self.allowed_latency_limit):
  1384. data = self.audio_queue.get()
  1385. except BrokenPipeError:
  1386. logging.error("BrokenPipeError _recording_worker")
  1387. self.is_running = False
  1388. break
  1389. if self.use_extended_logging:
  1390. logging.debug('Debug: Updating time_since_last_buffer_message')
  1391. # Feed the extracted data to the audio_queue
  1392. if time_since_last_buffer_message:
  1393. time_passed = time.time() - time_since_last_buffer_message
  1394. if time_passed > 1:
  1395. if self.use_extended_logging:
  1396. logging.debug("_recording_worker processing audio data")
  1397. time_since_last_buffer_message = time.time()
  1398. else:
  1399. time_since_last_buffer_message = time.time()
  1400. if self.use_extended_logging:
  1401. logging.debug('Debug: Initializing failed_stop_attempt')
  1402. failed_stop_attempt = False
  1403. if self.use_extended_logging:
  1404. logging.debug('Debug: Checking if not recording')
  1405. if not self.is_recording:
  1406. if self.use_extended_logging:
  1407. logging.debug('Debug: Handling not recording state')
  1408. # Handle not recording state
  1409. time_since_listen_start = (time.time() - self.listen_start
  1410. if self.listen_start else 0)
  1411. wake_word_activation_delay_passed = (
  1412. time_since_listen_start >
  1413. self.wake_word_activation_delay
  1414. )
  1415. if self.use_extended_logging:
  1416. logging.debug('Debug: Handling wake-word timeout callback')
  1417. # Handle wake-word timeout callback
  1418. if wake_word_activation_delay_passed \
  1419. and not delay_was_passed:
  1420. if self.use_wake_words and self.wake_word_activation_delay:
  1421. if self.on_wakeword_timeout:
  1422. if self.use_extended_logging:
  1423. logging.debug('Debug: Calling on_wakeword_timeout')
  1424. self.on_wakeword_timeout()
  1425. delay_was_passed = wake_word_activation_delay_passed
  1426. if self.use_extended_logging:
  1427. logging.debug('Debug: Setting state and spinner text')
  1428. # Set state and spinner text
  1429. if not self.recording_stop_time:
  1430. if self.use_wake_words \
  1431. and wake_word_activation_delay_passed \
  1432. and not self.wakeword_detected:
  1433. if self.use_extended_logging:
  1434. logging.debug('Debug: Setting state to "wakeword"')
  1435. self._set_state("wakeword")
  1436. else:
  1437. if self.listen_start:
  1438. if self.use_extended_logging:
  1439. logging.debug('Debug: Setting state to "listening"')
  1440. self._set_state("listening")
  1441. else:
  1442. if self.use_extended_logging:
  1443. logging.debug('Debug: Setting state to "inactive"')
  1444. self._set_state("inactive")
  1445. if self.use_extended_logging:
  1446. logging.debug('Debug: Checking wake word conditions')
  1447. if self.use_wake_words and wake_word_activation_delay_passed:
  1448. try:
  1449. if self.use_extended_logging:
  1450. logging.debug('Debug: Processing wakeword')
  1451. wakeword_index = self._process_wakeword(data)
  1452. except struct.error:
  1453. logging.error("Error unpacking audio data "
  1454. "for wake word processing.")
  1455. continue
  1456. except Exception as e:
  1457. logging.error(f"Wake word processing error: {e}")
  1458. continue
  1459. if self.use_extended_logging:
  1460. logging.debug('Debug: Checking if wake word detected')
  1461. # If a wake word is detected
  1462. if wakeword_index >= 0:
  1463. if self.use_extended_logging:
  1464. logging.debug('Debug: Wake word detected, updating variables')
  1465. self.wake_word_detect_time = time.time()
  1466. wakeword_detected_time = time.time()
  1467. wakeword_samples_to_remove = int(self.sample_rate * self.wake_word_buffer_duration)
  1468. self.wakeword_detected = True
  1469. if self.on_wakeword_detected:
  1470. if self.use_extended_logging:
  1471. logging.debug('Debug: Calling on_wakeword_detected')
  1472. self.on_wakeword_detected()
  1473. if self.use_extended_logging:
  1474. logging.debug('Debug: Checking voice activity conditions')
  1475. # Check for voice activity to
  1476. # trigger the start of recording
  1477. if ((not self.use_wake_words
  1478. or not wake_word_activation_delay_passed)
  1479. and self.start_recording_on_voice_activity) \
  1480. or self.wakeword_detected:
  1481. if self.use_extended_logging:
  1482. logging.debug('Debug: Checking if voice is active')
  1483. if self._is_voice_active():
  1484. if self.use_extended_logging:
  1485. logging.debug('Debug: Voice activity detected')
  1486. logging.info("voice activity detected")
  1487. if self.use_extended_logging:
  1488. logging.debug('Debug: Starting recording')
  1489. self.start()
  1490. self.start_recording_on_voice_activity = False
  1491. if self.use_extended_logging:
  1492. logging.debug('Debug: Adding buffered audio to frames')
  1493. # Add the buffered audio
  1494. # to the recording frames
  1495. self.frames.extend(list(self.audio_buffer))
  1496. self.audio_buffer.clear()
  1497. if self.use_extended_logging:
  1498. logging.debug('Debug: Resetting Silero VAD model states')
  1499. self.silero_vad_model.reset_states()
  1500. else:
  1501. if self.use_extended_logging:
  1502. logging.debug('Debug: Checking voice activity')
  1503. data_copy = data[:]
  1504. self._check_voice_activity(data_copy)
  1505. if self.use_extended_logging:
  1506. logging.debug('Debug: Resetting speech_end_silence_start')
  1507. self.speech_end_silence_start = 0
  1508. else:
  1509. if self.use_extended_logging:
  1510. logging.debug('Debug: Handling recording state')
  1511. # If we are currently recording
  1512. if wakeword_samples_to_remove and wakeword_samples_to_remove > 0:
  1513. if self.use_extended_logging:
  1514. logging.debug('Debug: Removing wakeword samples')
  1515. # Remove samples from the beginning of self.frames
  1516. samples_removed = 0
  1517. while wakeword_samples_to_remove > 0 and self.frames:
  1518. frame = self.frames[0]
  1519. frame_samples = len(frame) // 2 # Assuming 16-bit audio
  1520. if wakeword_samples_to_remove >= frame_samples:
  1521. self.frames.pop(0)
  1522. samples_removed += frame_samples
  1523. wakeword_samples_to_remove -= frame_samples
  1524. else:
  1525. self.frames[0] = frame[wakeword_samples_to_remove * 2:]
  1526. samples_removed += wakeword_samples_to_remove
  1527. samples_to_remove = 0
  1528. wakeword_samples_to_remove = 0
  1529. if self.use_extended_logging:
  1530. logging.debug('Debug: Checking if stop_recording_on_voice_deactivity is True')
  1531. # Stop the recording if silence is detected after speech
  1532. if self.stop_recording_on_voice_deactivity:
  1533. if self.use_extended_logging:
  1534. logging.debug('Debug: Determining if speech is detected')
  1535. is_speech = (
  1536. self._is_silero_speech(data) if self.silero_deactivity_detection
  1537. else self._is_webrtc_speech(data, True)
  1538. )
  1539. if self.use_extended_logging:
  1540. logging.debug('Debug: Formatting speech_end_silence_start')
  1541. if not self.speech_end_silence_start:
  1542. str_speech_end_silence_start = "0"
  1543. else:
  1544. str_speech_end_silence_start = datetime.datetime.fromtimestamp(self.speech_end_silence_start).strftime('%H:%M:%S.%f')[:-3]
  1545. if self.use_extended_logging:
  1546. logging.debug(f"is_speech: {is_speech}, str_speech_end_silence_start: {str_speech_end_silence_start}")
  1547. if self.use_extended_logging:
  1548. logging.debug('Debug: Checking if speech is not detected')
  1549. if not is_speech:
  1550. if self.use_extended_logging:
  1551. logging.debug('Debug: Handling voice deactivity')
  1552. # Voice deactivity was detected, so we start
  1553. # measuring silence time before stopping recording
  1554. if self.speech_end_silence_start == 0 and \
  1555. (time.time() - self.recording_start_time > self.min_length_of_recording):
  1556. self.speech_end_silence_start = time.time()
  1557. if self.use_extended_logging:
  1558. logging.debug('Debug: Checking early transcription conditions')
  1559. if self.speech_end_silence_start and self.early_transcription_on_silence and len(self.frames) > 0 and \
  1560. (time.time() - self.speech_end_silence_start > self.early_transcription_on_silence) and \
  1561. self.allowed_to_early_transcribe:
  1562. if self.use_extended_logging:
  1563. logging.debug("Debug:Adding early transcription request")
  1564. self.transcribe_count += 1
  1565. audio_array = np.frombuffer(b''.join(self.frames), dtype=np.int16)
  1566. audio = audio_array.astype(np.float32) / INT16_MAX_ABS_VALUE
  1567. if self.use_extended_logging:
  1568. logging.debug("Debug: early transcription request pipe send")
  1569. self.parent_transcription_pipe.send((audio, self.language))
  1570. if self.use_extended_logging:
  1571. logging.debug("Debug: early transcription request pipe send return")
  1572. self.allowed_to_early_transcribe = False
  1573. else:
  1574. if self.use_extended_logging:
  1575. logging.debug('Debug: Handling speech detection')
  1576. if self.speech_end_silence_start:
  1577. if self.use_extended_logging:
  1578. logging.info("Resetting self.speech_end_silence_start")
  1579. self.speech_end_silence_start = 0
  1580. self.allowed_to_early_transcribe = True
  1581. if self.use_extended_logging:
  1582. logging.debug('Debug: Checking if silence duration exceeds threshold')
  1583. # Wait for silence to stop recording after speech
  1584. if self.speech_end_silence_start and time.time() - \
  1585. self.speech_end_silence_start >= \
  1586. self.post_speech_silence_duration:
  1587. if self.use_extended_logging:
  1588. logging.debug('Debug: Formatting silence start time')
  1589. # Get time in desired format (HH:MM:SS.nnn)
  1590. silence_start_time = datetime.datetime.fromtimestamp(self.speech_end_silence_start).strftime('%H:%M:%S.%f')[:-3]
  1591. if self.use_extended_logging:
  1592. logging.debug('Debug: Calculating time difference')
  1593. # Calculate time difference
  1594. time_diff = time.time() - self.speech_end_silence_start
  1595. if self.use_extended_logging:
  1596. logging.debug('Debug: Logging voice deactivity detection')
  1597. logging.info(f"voice deactivity detected at {silence_start_time}, "
  1598. f"time since silence start: {time_diff:.3f} seconds")
  1599. logging.debug('Debug: Appending data to frames and stopping recording')
  1600. self.frames.append(data)
  1601. self.stop()
  1602. if not self.is_recording:
  1603. if self.use_extended_logging:
  1604. logging.debug('Debug: Resetting speech_end_silence_start')
  1605. self.speech_end_silence_start = 0
  1606. if self.use_extended_logging:
  1607. logging.debug('Debug: Handling non-wake word scenario')
  1608. if not self.use_wake_words:
  1609. self.listen()
  1610. else:
  1611. if self.use_extended_logging:
  1612. logging.debug('Debug: Setting failed_stop_attempt to True')
  1613. failed_stop_attempt = True
  1614. if self.use_extended_logging:
  1615. logging.debug('Debug: Checking if recording stopped')
  1616. if not self.is_recording and was_recording:
  1617. if self.use_extended_logging:
  1618. logging.debug('Debug: Resetting after stopping recording')
  1619. # Reset after stopping recording to ensure clean state
  1620. self.stop_recording_on_voice_deactivity = False
  1621. if self.use_extended_logging:
  1622. logging.debug('Debug: Checking Silero time')
  1623. if time.time() - self.silero_check_time > 0.1:
  1624. self.silero_check_time = 0
  1625. if self.use_extended_logging:
  1626. logging.debug('Debug: Handling wake word timeout')
  1627. # Handle wake word timeout (waited to long initiating
  1628. # speech after wake word detection)
  1629. if self.wake_word_detect_time and time.time() - \
  1630. self.wake_word_detect_time > self.wake_word_timeout:
  1631. self.wake_word_detect_time = 0
  1632. if self.wakeword_detected and self.on_wakeword_timeout:
  1633. if self.use_extended_logging:
  1634. logging.debug('Debug: Calling on_wakeword_timeout')
  1635. self.on_wakeword_timeout()
  1636. self.wakeword_detected = False
  1637. if self.use_extended_logging:
  1638. logging.debug('Debug: Updating was_recording')
  1639. was_recording = self.is_recording
  1640. if self.use_extended_logging:
  1641. logging.debug('Debug: Checking if recording and not failed stop attempt')
  1642. if self.is_recording and not failed_stop_attempt:
  1643. if self.use_extended_logging:
  1644. logging.debug('Debug: Appending data to frames')
  1645. self.frames.append(data)
  1646. if self.use_extended_logging:
  1647. logging.debug('Debug: Checking if not recording or speech end silence start')
  1648. if not self.is_recording or self.speech_end_silence_start:
  1649. if self.use_extended_logging:
  1650. logging.debug('Debug: Appending data to audio buffer')
  1651. self.audio_buffer.append(data)
  1652. except Exception as e:
  1653. logging.debug('Debug: Caught exception in main try block')
  1654. if not self.interrupt_stop_event.is_set():
  1655. logging.error(f"Unhandled exeption in _recording_worker: {e}")
  1656. raise
  1657. if self.use_extended_logging:
  1658. logging.debug('Debug: Exiting _recording_worker method')
  1659. def _realtime_worker(self):
  1660. """
  1661. Performs real-time transcription if the feature is enabled.
  1662. The method is responsible transcribing recorded audio frames
  1663. in real-time based on the specified resolution interval.
  1664. The transcribed text is stored in `self.realtime_transcription_text`
  1665. and a callback
  1666. function is invoked with this text if specified.
  1667. """
  1668. try:
  1669. logging.debug('Starting realtime worker')
  1670. # Return immediately if real-time transcription is not enabled
  1671. if not self.enable_realtime_transcription:
  1672. return
  1673. # Continue running as long as the main process is active
  1674. while self.is_running:
  1675. # Check if the recording is active
  1676. if self.is_recording:
  1677. # Sleep for the duration of the transcription resolution
  1678. time.sleep(self.realtime_processing_pause)
  1679. # Convert the buffer frames to a NumPy array
  1680. audio_array = np.frombuffer(
  1681. b''.join(self.frames),
  1682. dtype=np.int16
  1683. )
  1684. logging.debug(f"Current realtime buffer size: {len(audio_array)}")
  1685. # Normalize the array to a [-1, 1] range
  1686. audio_array = audio_array.astype(np.float32) / \
  1687. INT16_MAX_ABS_VALUE
  1688. if self.use_main_model_for_realtime:
  1689. with self.transcription_lock:
  1690. try:
  1691. self.parent_transcription_pipe.send((audio_array, self.language))
  1692. if self.parent_transcription_pipe.poll(timeout=5): # Wait for 5 seconds
  1693. logging.debug("Receive from realtime worker after transcription request to main model")
  1694. status, result = self.parent_transcription_pipe.recv()
  1695. if status == 'success':
  1696. segments, info = result
  1697. self.detected_realtime_language = info.language if info.language_probability > 0 else None
  1698. self.detected_realtime_language_probability = info.language_probability
  1699. realtime_text = segments
  1700. logging.debug(f"Realtime text detected with main model: {realtime_text}")
  1701. else:
  1702. logging.error(f"Realtime transcription error: {result}")
  1703. continue
  1704. else:
  1705. logging.warning("Realtime transcription timed out")
  1706. continue
  1707. except Exception as e:
  1708. logging.error(f"Error in realtime transcription: {str(e)}")
  1709. continue
  1710. else:
  1711. # Perform transcription and assemble the text
  1712. segments, info = self.realtime_model_type.transcribe(
  1713. audio_array,
  1714. language=self.language if self.language else None,
  1715. beam_size=self.beam_size_realtime,
  1716. initial_prompt=self.initial_prompt,
  1717. suppress_tokens=self.suppress_tokens,
  1718. )
  1719. self.detected_realtime_language = info.language if info.language_probability > 0 else None
  1720. self.detected_realtime_language_probability = info.language_probability
  1721. realtime_text = " ".join(
  1722. seg.text for seg in segments
  1723. )
  1724. logging.debug(f"Realtime text detected: {realtime_text}")
  1725. # double check recording state
  1726. # because it could have changed mid-transcription
  1727. if self.is_recording and time.time() - \
  1728. self.recording_start_time > 0.5:
  1729. # logging.debug('Starting realtime transcription')
  1730. self.realtime_transcription_text = realtime_text
  1731. self.realtime_transcription_text = \
  1732. self.realtime_transcription_text.strip()
  1733. self.text_storage.append(
  1734. self.realtime_transcription_text
  1735. )
  1736. # Take the last two texts in storage, if they exist
  1737. if len(self.text_storage) >= 2:
  1738. last_two_texts = self.text_storage[-2:]
  1739. # Find the longest common prefix
  1740. # between the two texts
  1741. prefix = os.path.commonprefix(
  1742. [last_two_texts[0], last_two_texts[1]]
  1743. )
  1744. # This prefix is the text that was transcripted
  1745. # two times in the same way
  1746. # Store as "safely detected text"
  1747. if len(prefix) >= \
  1748. len(self.realtime_stabilized_safetext):
  1749. # Only store when longer than the previous
  1750. # as additional security
  1751. self.realtime_stabilized_safetext = prefix
  1752. # Find parts of the stabilized text
  1753. # in the freshly transcripted text
  1754. matching_pos = self._find_tail_match_in_text(
  1755. self.realtime_stabilized_safetext,
  1756. self.realtime_transcription_text
  1757. )
  1758. if matching_pos < 0:
  1759. if self.realtime_stabilized_safetext:
  1760. self._on_realtime_transcription_stabilized(
  1761. self._preprocess_output(
  1762. self.realtime_stabilized_safetext,
  1763. True
  1764. )
  1765. )
  1766. else:
  1767. self._on_realtime_transcription_stabilized(
  1768. self._preprocess_output(
  1769. self.realtime_transcription_text,
  1770. True
  1771. )
  1772. )
  1773. else:
  1774. # We found parts of the stabilized text
  1775. # in the transcripted text
  1776. # We now take the stabilized text
  1777. # and add only the freshly transcripted part to it
  1778. output_text = self.realtime_stabilized_safetext + \
  1779. self.realtime_transcription_text[matching_pos:]
  1780. # This yields us the "left" text part as stabilized
  1781. # AND at the same time delivers fresh detected
  1782. # parts on the first run without the need for
  1783. # two transcriptions
  1784. self._on_realtime_transcription_stabilized(
  1785. self._preprocess_output(output_text, True)
  1786. )
  1787. # Invoke the callback with the transcribed text
  1788. self._on_realtime_transcription_update(
  1789. self._preprocess_output(
  1790. self.realtime_transcription_text,
  1791. True
  1792. )
  1793. )
  1794. # If not recording, sleep briefly before checking again
  1795. else:
  1796. time.sleep(TIME_SLEEP)
  1797. except Exception as e:
  1798. logging.error(f"Unhandled exeption in _realtime_worker: {e}")
  1799. raise
  1800. def _is_silero_speech(self, chunk):
  1801. """
  1802. Returns true if speech is detected in the provided audio data
  1803. Args:
  1804. data (bytes): raw bytes of audio data (1024 raw bytes with
  1805. 16000 sample rate and 16 bits per sample)
  1806. """
  1807. if self.sample_rate != 16000:
  1808. pcm_data = np.frombuffer(chunk, dtype=np.int16)
  1809. data_16000 = signal.resample_poly(
  1810. pcm_data, 16000, self.sample_rate)
  1811. chunk = data_16000.astype(np.int16).tobytes()
  1812. self.silero_working = True
  1813. audio_chunk = np.frombuffer(chunk, dtype=np.int16)
  1814. audio_chunk = audio_chunk.astype(np.float32) / INT16_MAX_ABS_VALUE
  1815. vad_prob = self.silero_vad_model(
  1816. torch.from_numpy(audio_chunk),
  1817. SAMPLE_RATE).item()
  1818. is_silero_speech_active = vad_prob > (1 - self.silero_sensitivity)
  1819. if is_silero_speech_active:
  1820. self.is_silero_speech_active = True
  1821. self.silero_working = False
  1822. return is_silero_speech_active
  1823. def _is_webrtc_speech(self, chunk, all_frames_must_be_true=False):
  1824. """
  1825. Returns true if speech is detected in the provided audio data
  1826. Args:
  1827. data (bytes): raw bytes of audio data (1024 raw bytes with
  1828. 16000 sample rate and 16 bits per sample)
  1829. """
  1830. if self.sample_rate != 16000:
  1831. pcm_data = np.frombuffer(chunk, dtype=np.int16)
  1832. data_16000 = signal.resample_poly(
  1833. pcm_data, 16000, self.sample_rate)
  1834. chunk = data_16000.astype(np.int16).tobytes()
  1835. # Number of audio frames per millisecond
  1836. frame_length = int(16000 * 0.01) # for 10ms frame
  1837. num_frames = int(len(chunk) / (2 * frame_length))
  1838. speech_frames = 0
  1839. for i in range(num_frames):
  1840. start_byte = i * frame_length * 2
  1841. end_byte = start_byte + frame_length * 2
  1842. frame = chunk[start_byte:end_byte]
  1843. if self.webrtc_vad_model.is_speech(frame, 16000):
  1844. speech_frames += 1
  1845. if not all_frames_must_be_true:
  1846. if self.debug_mode:
  1847. logging.info(f"Speech detected in frame {i + 1}"
  1848. f" of {num_frames}")
  1849. return True
  1850. if all_frames_must_be_true:
  1851. if self.debug_mode and speech_frames == num_frames:
  1852. logging.info(f"Speech detected in {speech_frames} of "
  1853. f"{num_frames} frames")
  1854. elif self.debug_mode:
  1855. logging.info(f"Speech not detected in all {num_frames} frames")
  1856. return speech_frames == num_frames
  1857. else:
  1858. if self.debug_mode:
  1859. logging.info(f"Speech not detected in any of {num_frames} frames")
  1860. return False
  1861. def _check_voice_activity(self, data):
  1862. """
  1863. Initiate check if voice is active based on the provided data.
  1864. Args:
  1865. data: The audio data to be checked for voice activity.
  1866. """
  1867. self.is_webrtc_speech_active = self._is_webrtc_speech(data)
  1868. # First quick performing check for voice activity using WebRTC
  1869. if self.is_webrtc_speech_active:
  1870. if not self.silero_working:
  1871. self.silero_working = True
  1872. # Run the intensive check in a separate thread
  1873. threading.Thread(
  1874. target=self._is_silero_speech,
  1875. args=(data,)).start()
  1876. def clear_audio_queue(self):
  1877. """
  1878. Safely empties the audio queue to ensure no remaining audio
  1879. fragments get processed e.g. after waking up the recorder.
  1880. """
  1881. self.audio_buffer.clear()
  1882. try:
  1883. while True:
  1884. self.audio_queue.get_nowait()
  1885. except:
  1886. # PyTorch's mp.Queue doesn't have a specific Empty exception
  1887. # so we catch any exception that might occur when the queue is empty
  1888. pass
  1889. def _is_voice_active(self):
  1890. """
  1891. Determine if voice is active.
  1892. Returns:
  1893. bool: True if voice is active, False otherwise.
  1894. """
  1895. return self.is_webrtc_speech_active and self.is_silero_speech_active
  1896. def _set_state(self, new_state):
  1897. """
  1898. Update the current state of the recorder and execute
  1899. corresponding state-change callbacks.
  1900. Args:
  1901. new_state (str): The new state to set.
  1902. """
  1903. # Check if the state has actually changed
  1904. if new_state == self.state:
  1905. return
  1906. # Store the current state for later comparison
  1907. old_state = self.state
  1908. # Update to the new state
  1909. self.state = new_state
  1910. # Log the state change
  1911. logging.info(f"State changed from '{old_state}' to '{new_state}'")
  1912. # Execute callbacks based on transitioning FROM a particular state
  1913. if old_state == "listening":
  1914. if self.on_vad_detect_stop:
  1915. self.on_vad_detect_stop()
  1916. elif old_state == "wakeword":
  1917. if self.on_wakeword_detection_end:
  1918. self.on_wakeword_detection_end()
  1919. # Execute callbacks based on transitioning TO a particular state
  1920. if new_state == "listening":
  1921. if self.on_vad_detect_start:
  1922. self.on_vad_detect_start()
  1923. self._set_spinner("speak now")
  1924. if self.spinner and self.halo:
  1925. self.halo._interval = 250
  1926. elif new_state == "wakeword":
  1927. if self.on_wakeword_detection_start:
  1928. self.on_wakeword_detection_start()
  1929. self._set_spinner(f"say {self.wake_words}")
  1930. if self.spinner and self.halo:
  1931. self.halo._interval = 500
  1932. elif new_state == "transcribing":
  1933. if self.on_transcription_start:
  1934. self.on_transcription_start()
  1935. self._set_spinner("transcribing")
  1936. if self.spinner and self.halo:
  1937. self.halo._interval = 50
  1938. elif new_state == "recording":
  1939. self._set_spinner("recording")
  1940. if self.spinner and self.halo:
  1941. self.halo._interval = 100
  1942. elif new_state == "inactive":
  1943. if self.spinner and self.halo:
  1944. self.halo.stop()
  1945. self.halo = None
  1946. def _set_spinner(self, text):
  1947. """
  1948. Update the spinner's text or create a new
  1949. spinner with the provided text.
  1950. Args:
  1951. text (str): The text to be displayed alongside the spinner.
  1952. """
  1953. if self.spinner:
  1954. # If the Halo spinner doesn't exist, create and start it
  1955. if self.halo is None:
  1956. self.halo = halo.Halo(text=text)
  1957. self.halo.start()
  1958. # If the Halo spinner already exists, just update the text
  1959. else:
  1960. self.halo.text = text
  1961. def _preprocess_output(self, text, preview=False):
  1962. """
  1963. Preprocesses the output text by removing any leading or trailing
  1964. whitespace, converting all whitespace sequences to a single space
  1965. character, and capitalizing the first character of the text.
  1966. Args:
  1967. text (str): The text to be preprocessed.
  1968. Returns:
  1969. str: The preprocessed text.
  1970. """
  1971. text = re.sub(r'\s+', ' ', text.strip())
  1972. if self.ensure_sentence_starting_uppercase:
  1973. if text:
  1974. text = text[0].upper() + text[1:]
  1975. # Ensure the text ends with a proper punctuation
  1976. # if it ends with an alphanumeric character
  1977. if not preview:
  1978. if self.ensure_sentence_ends_with_period:
  1979. if text and text[-1].isalnum():
  1980. text += '.'
  1981. return text
  1982. def _find_tail_match_in_text(self, text1, text2, length_of_match=10):
  1983. """
  1984. Find the position where the last 'n' characters of text1
  1985. match with a substring in text2.
  1986. This method takes two texts, extracts the last 'n' characters from
  1987. text1 (where 'n' is determined by the variable 'length_of_match'), and
  1988. searches for an occurrence of this substring in text2, starting from
  1989. the end of text2 and moving towards the beginning.
  1990. Parameters:
  1991. - text1 (str): The text containing the substring that we want to find
  1992. in text2.
  1993. - text2 (str): The text in which we want to find the matching
  1994. substring.
  1995. - length_of_match(int): The length of the matching string that we are
  1996. looking for
  1997. Returns:
  1998. int: The position (0-based index) in text2 where the matching
  1999. substring starts. If no match is found or either of the texts is
  2000. too short, returns -1.
  2001. """
  2002. # Check if either of the texts is too short
  2003. if len(text1) < length_of_match or len(text2) < length_of_match:
  2004. return -1
  2005. # The end portion of the first text that we want to compare
  2006. target_substring = text1[-length_of_match:]
  2007. # Loop through text2 from right to left
  2008. for i in range(len(text2) - length_of_match + 1):
  2009. # Extract the substring from text2
  2010. # to compare with the target_substring
  2011. current_substring = text2[len(text2) - i - length_of_match:
  2012. len(text2) - i]
  2013. # Compare the current_substring with the target_substring
  2014. if current_substring == target_substring:
  2015. # Position in text2 where the match starts
  2016. return len(text2) - i
  2017. return -1
  2018. def _on_realtime_transcription_stabilized(self, text):
  2019. """
  2020. Callback method invoked when the real-time transcription stabilizes.
  2021. This method is called internally when the transcription text is
  2022. considered "stable" meaning it's less likely to change significantly
  2023. with additional audio input. It notifies any registered external
  2024. listener about the stabilized text if recording is still ongoing.
  2025. This is particularly useful for applications that need to display
  2026. live transcription results to users and want to highlight parts of the
  2027. transcription that are less likely to change.
  2028. Args:
  2029. text (str): The stabilized transcription text.
  2030. """
  2031. if self.on_realtime_transcription_stabilized:
  2032. if self.is_recording:
  2033. self.on_realtime_transcription_stabilized(text)
  2034. def _on_realtime_transcription_update(self, text):
  2035. """
  2036. Callback method invoked when there's an update in the real-time
  2037. transcription.
  2038. This method is called internally whenever there's a change in the
  2039. transcription text, notifying any registered external listener about
  2040. the update if recording is still ongoing. This provides a mechanism
  2041. for applications to receive and possibly display live transcription
  2042. updates, which could be partial and still subject to change.
  2043. Args:
  2044. text (str): The updated transcription text.
  2045. """
  2046. if self.on_realtime_transcription_update:
  2047. if self.is_recording:
  2048. self.on_realtime_transcription_update(text)
  2049. def __enter__(self):
  2050. """
  2051. Method to setup the context manager protocol.
  2052. This enables the instance to be used in a `with` statement, ensuring
  2053. proper resource management. When the `with` block is entered, this
  2054. method is automatically called.
  2055. Returns:
  2056. self: The current instance of the class.
  2057. """
  2058. return self
  2059. def __exit__(self, exc_type, exc_value, traceback):
  2060. """
  2061. Method to define behavior when the context manager protocol exits.
  2062. This is called when exiting the `with` block and ensures that any
  2063. necessary cleanup or resource release processes are executed, such as
  2064. shutting down the system properly.
  2065. Args:
  2066. exc_type (Exception or None): The type of the exception that
  2067. caused the context to be exited, if any.
  2068. exc_value (Exception or None): The exception instance that caused
  2069. the context to be exited, if any.
  2070. traceback (Traceback or None): The traceback corresponding to the
  2071. exception, if any.
  2072. """
  2073. self.shutdown()