yum-archive/yapBox
A black box for your yapping
git clone https://git.yummers.dev/yum-archive/yapBox
c8ae984
v1.0.0
1from datetime import datetime 2from pydub import AudioSegment 3 4import gradio as gr 5import math 6import numpy as np 7import os 8import pyaudio 9import sys 10import time 11import typing 12import vad 13import wave 14 15class Logger : 16def __init__ ( self , filename ) : 17self . terminal = sys . stdout 18self . log = open ( filename , "w" ) 19 20def write ( self , message ) : 21self . terminal . write ( message ) 22self . log . write ( message ) 23 24def flush ( self ) : 25self . terminal . flush () 26self . log . flush () 27 28def isatty ( self ) : 29return False 30 31class AudioStream () : 32FORMAT = pyaudio . paInt16 33# Size of each frame (audio sample), in bytes. If you change FORMAT, make 34# sure this stays up to date! 35FRAME_SZ = 2 36# Frames per second. 37FPS = 16000 38CHANNELS = 1 39def __init__ ( self ) : 40pass 41 42def getSamples ( self ) -> bytes : 43raise NotImplementedError ( "getSamples is not implemented!" ) 44 45class MicStream ( AudioStream ) : 46CHUNK_SZ = 1024 47 48def __init__ ( self , which_mic : str , fps : int = AudioStream . FPS ) : 49self . p = pyaudio . PyAudio () 50self . stream = None 51self . sample_rate = None 52# Each time pyaudio gives us audio data, it's in the form of a chunk of 53# samples. We keep these in a list to keep the audio callback as light 54# as possible. Whenever downstream layers want data, we collapse the 55# list into a single array of data (a bytes object). 56self . chunks = [] 57# If set, incoming frames are simply discarded. 58self . paused = False 59self . fps = fps 60 61( f"Finding mic { which_mic } " , file = sys . stderr ) 62self . dumpMicDevices () 63 64got_match = False 65device_index = - 1 66focusrite_str = "Focusrite" 67index_str = "Digital Audio Interface" 68if which_mic == "index" : 69target_str = index_str 70elif which_mic == "focusrite" : 71target_str = focusrite_str 72else : 73( f"Mic { which_mic } requested, treating it as a numerical " + 74"device ID" , file = sys . stderr ) 75device_index = int ( which_mic ) 76got_match = True 77if not got_match : 78info = self . p . get_host_api_info_by_index ( 0 ) 79numdevices = info . get ( 'deviceCount' ) 80for i in range ( 0 , numdevices ) : 81if ( self . p . get_device_info_by_host_api_device_index ( 0 , i ) . get ( 'maxInputChannels' )) > 0 : 82device_name = self . p . get_device_info_by_host_api_device_index ( 0 , i ) . get ( 'name' ) 83if target_str in device_name : 84( f"Got matching mic: { device_name } " , 85file = sys . stderr ) 86device_index = i 87got_match = True 88break 89if not got_match : 90raise KeyError ( f"Mic { which_mic } not found" ) 91 92info = self . p . get_device_info_by_host_api_device_index ( 0 , device_index ) 93( f"Found mic { which_mic } : { info [ 'name' ] } " , file = sys . stderr ) 94self . sample_rate = int ( info [ 'defaultSampleRate' ]) 95( f"Mic sample rate: { self . sample_rate } " , file = sys . stderr ) 96 97self . stream = self . p . open ( 98rate = self . sample_rate , 99channels = self . CHANNELS , 100format = self . FORMAT , 101input = True , 102frames_per_buffer = MicStream . CHUNK_SZ , 103input_device_index = device_index , 104stream_callback = self . onAudioFramesAvailable ) 105 106self . stream . start_stream () 107 108AudioStream . __init__ ( self ) 109 110def pause ( self , state : bool = True ) : 111self . paused = state 112 113def dumpMicDevices ( self ) : 114info = self . p . get_host_api_info_by_index ( 0 ) 115numdevices = info . get ( 'deviceCount' ) 116 117for i in range ( 0 , numdevices ) : 118if ( self . p . get_device_info_by_host_api_device_index ( 0 , i ) . get ( 'maxInputChannels' )) > 0 : 119device_name = self . p . get_device_info_by_host_api_device_index ( 0 , i ) . get ( 'name' ) 120( "Input Device id " , i , " - " , device_name ) 121 122def getMicDevices () -> str : 123p = pyaudio . PyAudio () 124info = p . get_host_api_info_by_index ( 0 ) 125numdevices = info . get ( 'deviceCount' ) 126 127result = [] 128for i in range ( 0 , numdevices ) : 129if ( p . get_device_info_by_host_api_device_index ( 0 , i ) . get ( 'maxInputChannels' )) > 0 : 130device_name = p . get_device_info_by_host_api_device_index ( 0 , i ) . get ( 'name' ) 131result . append ( f"Input Device id { i } - { device_name } " ) 132return ' \n ' . join ( result ) 133 134def onAudioFramesAvailable ( self , 135frames , 136frame_count , 137time_info , 138status_flags ) : 139if self . paused : 140# Don't literally pause, just start returning silence. This allows 141# the `min_segment_age_s` check to work while paused. 142n_frames = int ( frame_count * self . fps / 143float ( self . sample_rate )) 144self . chunks . append ( np . zeros ( n_frames , 145dtype = np . int16 ) . tobytes ()) 146return ( frames , pyaudio . paContinue ) 147 148decimated = b'' 149# In pyaudio, a `frame` is a single sample of audio data. 150frame_len = self . FRAME_SZ 151next_frame = 0.0 152# The mic probably has a higher sample rate than Whisper wants, so 153# decrease the sample rate by dropping samples. Note that this 154# algorithm only works if the mic's rate is higher than whisper's 155# expected rate. 156keep_every = float ( self . sample_rate ) / self . fps 157for i in range ( frame_count ) : 158if i >= next_frame : 159decimated += frames [ i * frame_len : ( i + 1 ) * frame_len ] 160next_frame += keep_every 161self . chunks . append ( decimated ) 162 163return ( frames , pyaudio . paContinue ) 164 165# Get audio data and the corresponding timestamp. 166def getSamples ( self ) -> bytes : 167chunks = self . chunks 168self . chunks = [] 169result = b'' . join ( chunks ) 170return result 171 172class AudioCollector : 173def __init__ ( self , stream : AudioStream ) : 174self . stream = stream 175self . frames = b'' 176# Note: by design, this is the only spot where we anchor our timestamps 177# against the real world. This is done to make it possible to profile 178# test cases which read from disk (at much faster than real speed) in 179# the same way that we profile real-time data. 180self . wall_ts = time . time () 181 182def getAudio ( self ) -> bytes : 183frames = self . stream . getSamples () 184if frames : 185self . frames += frames 186return self . frames 187 188def dropAudioPrefix ( self , dur_s : float ) -> bytes : 189n_bytes = int ( dur_s * self . stream . fps ) * self . stream . FRAME_SZ 190n_bytes = min ( n_bytes , len ( self . frames )) 191cut_portion = self . frames [ : n_bytes ] 192self . frames = self . frames [ n_bytes : ] 193self . wall_ts += float ( n_bytes / self . stream . FRAME_SZ ) / self . stream . fps 194return cut_portion 195 196def dropAudioPrefixByFrames ( self , dur_frames : int ) -> bytes : 197n_bytes = dur_frames * self . stream . FRAME_SZ 198n_bytes = min ( n_bytes , len ( self . frames )) 199cut_portion = self . frames [ : n_bytes ] 200self . frames = self . frames [ n_bytes : ] 201self . wall_ts += float ( n_bytes / self . stream . FRAME_SZ ) / self . stream . fps 202return cut_portion 203 204def keepLast ( self , dur_s : float ) -> bytes : 205drop_len = max ( 0 , self . duration () - dur_s ) 206return self . dropAudioPrefix ( drop_len ) 207 208def dropAudio ( self ) : 209self . wall_ts += self . duration () 210cut_portion = self . frames 211self . frames = b'' 212return cut_portion 213 214def duration ( self ) : 215return len ( self . frames ) / ( self . stream . fps * self . stream . FRAME_SZ ) 216 217def begin ( self ) : 218return self . wall_ts 219 220def now ( self ) : 221return self . begin () + self . duration () 222 223class AudioCollectorFilter : 224def __init__ ( self , parent : AudioCollector ) : 225self . parent = parent 226self . stream = self . parent . stream 227 228def getAudio ( self ) -> bytes : 229return self . parent . getAudio () 230def dropAudioPrefix ( self , dur_s : float ) : 231return self . parent . dropAudioPrefix ( dur_s ) 232def dropAudioPrefixByFrames ( self , dur_frames : int ) : 233return self . parent . dropAudioPrefixByFrames ( dur_frames ) 234def keepLast ( self , dur_s ) : 235return self . parent . keepLast ( dur_s ) 236def dropAudio ( self ) : 237return self . parent . dropAudio () 238def duration ( self ) : 239return self . parent . duration () 240def begin ( self ) : 241return self . parent . begin () 242def now ( self ) : 243return self . parent . now () 244 245class NormalizingAudioCollector ( AudioCollectorFilter ) : 246def __init__ ( self , parent : AudioCollector ) : 247AudioCollectorFilter . __init__ ( self , parent ) 248 249def getAudio ( self ) -> bytes : 250audio = self . parent . getAudio () 251 252audio = AudioSegment ( audio , sample_width = self . stream . FRAME_SZ , 253frame_rate = self . stream . fps , channels = self . stream . CHANNELS ) 254audio = audio . normalize () 255 256frames = np . array ( audio . get_array_of_samples ()) 257frames = np . int16 ( frames ) . tobytes () 258 259return frames 260 261class CompressingAudioCollector ( AudioCollectorFilter ) : 262def __init__ ( self , parent : AudioCollector ) : 263AudioCollectorFilter . __init__ ( self , parent ) 264 265def getAudio ( self ) -> bytes : 266audio = self . parent . getAudio () 267 268audio = AudioSegment ( audio , 269sample_width = self . stream . FRAME_SZ , 270frame_rate = self . stream . fps , 271channels = self . stream . CHANNELS ) 272# subtle compression has a slight positive effect on my benchmark 273audio = audio . compress_dynamic_range ( threshold =- 10 , ratio = 2.0 ) 274 275frames = np . array ( audio . get_array_of_samples ()) 276frames = np . int16 ( frames ) . tobytes () 277 278return frames 279 280class AudioSegmenter : 281def __init__ ( self , 282min_silence_ms = 250 , 283max_speech_s = 5 , 284stream : AudioStream = None ) : 285self . vad_options = vad . VadOptions ( 286min_silence_duration_ms = min_silence_ms , 287max_speech_duration_s = max_speech_s ) 288self . stream = stream 289pass 290 291def segmentAudio ( self , audio : bytes ) : 292audio = np . frombuffer ( audio , 293dtype = np . int16 ) . flatten () . astype ( np . float32 ) / 32768.0 294return vad . get_speech_timestamps ( audio , vad_options = self . vad_options ) 295 296# Returns the stable cutoff (if any) and whether there are any segments. 297def getStableCutoff ( self , audio : bytes ) -> typing . Tuple [ int , bool ] : 298min_delta_frames = int (( self . vad_options . min_silence_duration_ms * 299self . stream . fps ) / 1000 ) 300cutoff = None 301 302last_end = None 303segments = self . segmentAudio ( audio ) 304 305for i in range ( len ( segments )) : 306s = segments [ i ] 307#print(f"s: {s}") 308#print(f"last_end: {last_end}") 309 310if last_end : 311delta_frames = s [ 'start' ] - last_end 312#print(f"delta frames: {delta_frames}") 313if delta_frames > min_delta_frames : 314cutoff = s [ 'start' ] 315else : 316last_end = s [ 'end' ] 317 318if i == len ( segments ) - 1 : 319now = int ( len ( audio ) / self . stream . FRAME_SZ ) 320delta_frames = now - s [ 'end' ] 321if delta_frames > min_delta_frames : 322cutoff = now - int ( min_delta_frames / 2 ) 323 324return ( cutoff , len ( segments ) > 0 ) 325 326def install_in_venv ( pkgs : typing . List [ str ]) -> bool : 327pkgs_str = " " . join ( pkgs ) 328( f"Installing { pkgs_str } " ) 329pip_proc = subprocess . Popen ( 330f"Resources/Python/python.exe -m pip install { pkgs_str } --no-warn-script-location" . split () , 331stdout = subprocess . PIPE , 332stderr = subprocess . PIPE ) 333pip_stdout , pip_stderr = pip_proc . communicate () 334pip_stdout = pip_stdout . decode ( "utf-8" ) 335pip_stderr = pip_stderr . decode ( "utf-8" ) 336( pip_stdout , file = sys . stderr ) 337( pip_stderr , file = sys . stderr ) 338if pip_proc . returncode != 0 : 339( f"`pip install { pkgs_str } ` exited with { pip_proc . returncode } " , 340file = sys . stderr ) 341return False 342return True 343 344def saveAudio ( audio : bytes , path : str , stream : AudioStream ) : 345with wave . open ( path , 'wb' ) as wf : 346( f"Saving audio to { path } " , file = sys . stderr ) 347wf . setnchannels ( stream . CHANNELS ) 348wf . setsampwidth ( stream . FRAME_SZ ) 349wf . setframerate ( stream . fps ) 350wf . writeframes ( audio ) 351 352def concatenateWavFiles ( output_path ) : 353# List all .wav files in the CWD 354wav_files = [ f for f in os . listdir ( '.' ) if f . endswith ( '.wav' )] 355 356# Initialize parameters for wave file 357params = None 358 359# Open the output file 360with wave . open ( output_path , 'wb' ) as output_wav : 361for wav_file in wav_files : 362if os . path . abspath ( wav_file ) == os . path . abspath ( output_path ) : 363( f"Skip adding output file ( { wav_file } ) to itself" ) 364continue 365( f"Processing { wav_file } " ) 366with wave . open ( wav_file , 'rb' ) as input_wav : 367# Check if parameters are the same for each file 368if params is None : 369params = input_wav . getparams () 370output_wav . setparams ( params ) 371 372# Read and write frames 373frames = input_wav . readframes ( input_wav . getnframes ()) 374output_wav . writeframes ( frames ) 375 376class AppControl : 377run = True 378app_ctrl = AppControl () 379 380def recordMeDaddy ( 381mic_index : int , 382min_volume : float = - 1.3 , 383max_volume : float = - 0.8 384) : 385app_ctrl . run = True 386 387stream = MicStream ( str ( mic_index )) 388stream_hd = MicStream ( str ( mic_index ) , fps = 44100 ) 389 390collector = AudioCollector ( stream ) 391#collector = NormalizingAudioCollector(collector) 392collector = CompressingAudioCollector ( collector ) 393 394collector_hd = AudioCollector ( stream_hd ) 395#collector_hd = NormalizingAudioCollector(collector_hd) 396collector_hd = CompressingAudioCollector ( collector_hd ) 397 398min_silence_ms = 1000 399max_speech_s = 30 400segmenter = AudioSegmenter ( 401min_silence_ms = min_silence_ms , 402max_speech_s = max_speech_s , 403stream = stream ) 404 405while app_ctrl . run : 406audio = collector . getAudio () 407collector_hd . getAudio () 408stable_cutoff , has_audio = segmenter . getStableCutoff ( audio ) 409 410#print(f"has audio: {has_audio}") 411#print(f"stable cutoff: {stable_cutoff}") 412 413if has_audio and stable_cutoff : 414commit_audio = collector . dropAudioPrefixByFrames ( stable_cutoff ) 415( f"stable cutoff: { stable_cutoff } " ) 416hd_cutoff = int ( math . floor ( stable_cutoff * stream_hd . fps / 417stream . fps )) 418( f"hd cutoff: { hd_cutoff } " ) 419commit_audio_hd = collector_hd . dropAudioPrefixByFrames ( hd_cutoff ) 420( f"hd audio len: { len ( commit_audio_hd ) } " ) 421 422# Calculate naive measure of volume 423audio_v = AudioSegment ( commit_audio_hd , 424sample_width = stream_hd . FRAME_SZ , 425frame_rate = stream_hd . fps , 426channels = stream_hd . CHANNELS ) 427audio_v = np . array ( audio_v . get_array_of_samples ()) 428audio_v = np . int16 ( audio_v ) 429audio_v = np . sqrt ( np . mean ( np . square ( audio_v ))) 430audio_v /= np . sqrt ( len ( commit_audio_hd ) / stream_hd . FRAME_SZ ) 431audio_v = math . log ( audio_v , 10 ) 432( f"volume: { audio_v } " ) 433# cutoff is a fine-tuned value based on volumes seen while in vr 434# (index mic) 435if audio_v < min_volume or audio_v > max_volume : 436# Discard sample 437( "Discarding too-quiet/too-loud segment" ) 438collector . keepLast ( 1.0 ) 439collector_hd . keepLast ( 1.0 ) 440continue 441 442 443ts = datetime . fromtimestamp ( time . time ()) 444filename = str ( ts . strftime ( '%Y_%m_%d__%H-%M-%S' )) + ".wav" 445saveAudio ( commit_audio_hd , filename , stream_hd ) 446 447if not has_audio : 448#print("VAD detects no audio, skip transcription", file=sys.stderr) 449collector . keepLast ( 1.0 ) 450collector_hd . keepLast ( 1.0 ) 451( "Stopped recording" ) 452 453def getOutput () -> str : 454sys . stdout . flush () 455with open ( "output.log" , "r" ) as f : 456return f . read () 457 458def stopApp () : 459( "Requesting app stop" ) 460app_ctrl . run = False 461 462if __name__ == "__main__" : 463abspath = os . path . abspath ( __file__ ) 464dname = os . path . dirname ( abspath ) 465os . chdir ( dname ) 466 467sys . stdout = Logger ( "output.log" ) 468 469( f"Set cwd to { os . getcwd () } " , file = sys . stderr ) 470 471with gr . Blocks () as demo : 472dump_mics = gr . Button ( "Dump mics" ) 473mics_output = gr . Text ( label = "Microphones" ) 474 475mic_device = gr . Number ( label = "Mic device" ) 476min_volume = gr . Number ( label = "Minimum volume" , value =- 1.3 ) 477max_volume = gr . Number ( label = "Maximum volume" , value =- 0.8 ) 478record_audio = gr . Button ( "Record audio" ) 479stop_recording = gr . Button ( "Stop recording" ) 480concatenated_path = gr . Text ( label = "Combined audio filename" , value = "combined.wav" ) 481concatenate_audio = gr . Button ( "Combine audio files" ) 482 483dbg_output = gr . Text ( label = "Output" ) 484 485dump_mics . click ( MicStream . getMicDevices , [] , mics_output ) 486 487record_audio . click ( recordMeDaddy , [ mic_device , min_volume , max_volume ] , 488dbg_output ) 489stop_recording . click ( stopApp , [] , dbg_output ) 490concatenate_audio . click ( concatenateWavFiles , [ concatenated_path ] , 491dbg_output ) 492 493demo . load ( getOutput , None , dbg_output , every = 0.5 ) 494demo . launch () 495sys . exit ( 0 ) 496 497concatenateWavFiles ( "concatenated.wav" ) 498sys . exit ( 0 ) 499