audio_recorder.py 108 KB

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