audio_recorder.py 107 KB

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