audio_recorder.py 100 KB

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