yum-slop/TaSTT
Free self-hosted STT for VRChat.
git clone https://git.yummers.dev/yum-slop/TaSTT
59578a6
v0.20.0
1from browser_src import BrowserSource 2from datetime import datetime 3from emotes_v2 import EmotesState 4from faster_whisper import WhisperModel 5from functools import partial 6from huggingface_hub import hf_hub_download 7from profanity_filter import ProfanityFilter 8from pydub import AudioSegment 9from sentence_splitter import split_text_into_sentences 10from transcribe_pipeline import StreamingPlugin , TranscriptCommit 11 12import app_config 13import argparse 14import ctranslate2 15import editdistance 16import glob 17import keybind_event_machine 18import keyboard 19import langcodes 20import lang_compat 21import math 22import numpy as np 23import os 24import osc_ctrl 25import pyaudio 26import steamvr 27import subprocess 28import sys 29import threading 30import time 31import transformers 32import typing 33import vad 34import wave 35import winsound 36 37class ThreadControl : 38def __init__ ( self , cfg ) : 39self . cfg = cfg 40self . run_app = True 41 42class AudioStream () : 43FORMAT = pyaudio . paInt16 44# Size of each frame (audio sample), in bytes. If you change FORMAT, make 45# sure this stays up to date! 46FRAME_SZ = 2 47# Frames per second. 48FPS = 16000 49CHANNELS = 1 50def __init__ ( self ) : 51pass 52 53def getSamples ( self ) -> bytes : 54raise NotImplementedError ( "getSamples is not implemented!" ) 55 56class DiskStream ( AudioStream ) : 57def __init__ ( self , path : str ) : 58fmt = None 59if path . endswith ( ".mp3" ) : 60fmt = "mp3" 61elif path . endswith ( ".wav" ) : 62fmt = "wav" 63else : 64raise NotImplementedError ( f"Requested file type { path } " + \ 65"is not supported" ) 66( f"Loading audio data" , file = sys . stderr ) 67audio = AudioSegment . from_file ( path , format = fmt ) 68audio = audio . set_channels ( 1 ) 69# TODO(yum) replace manual decimation code with this! 70audio = audio . set_frame_rate ( 16000 ) 71frames = np . array ( audio . get_array_of_samples ()) 72frames = np . int16 ( frames ) . tobytes () 73 74self . frames = frames 75 76( f"Loaded data" , file = sys . stderr ) 77 78def getSamples ( self ) -> bytes : 79# Give out samples at a fixed rate to minimize 80# noise. 81give_s = 0.2 82nframes = int ( give_s * AudioStream . FPS ) 83frames = self . frames [ 0 : nframes * AudioStream . FRAME_SZ ] ; 84self . frames = self . frames [ nframes * AudioStream . FRAME_SZ : ] 85 86if len ( frames ) < nframes : 87frames += np . zeros ( nframes - len ( frames ) , dtype = np . int16 ) . tobytes () 88 89return frames 90 91class MicStream ( AudioStream ) : 92CHUNK_SZ = 1024 93 94def __init__ ( self , which_mic : str ) : 95self . p = pyaudio . PyAudio () 96self . stream = None 97self . sample_rate = None 98# Each time pyaudio gives us audio data, it's in the form of a chunk of 99# samples. We keep these in a list to keep the audio callback as light 100# as possible. Whenever downstream layers want data, we collapse the 101# list into a single array of data (a bytes object). 102self . chunks = [] 103# If set, incoming frames are simply discarded. 104self . paused = False 105 106( f"Finding mic { which_mic } " , file = sys . stderr ) 107self . dumpMicDevices () 108 109got_match = False 110device_index = - 1 111if which_mic == "index" : 112target_str = "Digital Audio Interface" 113elif which_mic == "focusrite" : 114target_str = "Focusrite" 115elif which_mic == "motu" : 116target_str = "In 1-2 (MOTU M Series)" 117elif which_mic == "beyond" : 118target_str = "Microphone (Beyond)" 119else : 120( f"Mic { which_mic } requested, treating it as a numerical " + 121"device ID" , file = sys . stderr ) 122device_index = int ( which_mic ) 123got_match = True 124if not got_match : 125info = self . p . get_host_api_info_by_index ( 0 ) 126numdevices = info . get ( 'deviceCount' ) 127for i in range ( 0 , numdevices ) : 128if ( self . p . get_device_info_by_host_api_device_index ( 0 , i ) . get ( 'maxInputChannels' )) > 0 : 129device_name = self . p . get_device_info_by_host_api_device_index ( 0 , i ) . get ( 'name' ) 130if target_str in device_name : 131( f"Got matching mic: { device_name } " , 132file = sys . stderr ) 133device_index = i 134got_match = True 135break 136if not got_match : 137raise KeyError ( f"Mic { which_mic } not found" ) 138 139info = self . p . get_device_info_by_host_api_device_index ( 0 , device_index ) 140( f"Found mic { which_mic } : { info [ 'name' ] } " , file = sys . stderr ) 141self . sample_rate = int ( info [ 'defaultSampleRate' ]) 142( f"Mic sample rate: { self . sample_rate } " , file = sys . stderr ) 143 144self . stream = self . p . open ( 145rate = self . sample_rate , 146channels = AudioStream . CHANNELS , 147format = AudioStream . FORMAT , 148input = True , 149frames_per_buffer = MicStream . CHUNK_SZ , 150input_device_index = device_index , 151stream_callback = self . onAudioFramesAvailable ) 152 153self . stream . start_stream () 154 155AudioStream . __init__ ( self ) 156 157def pause ( self , state : bool = True ) : 158self . paused = state 159 160def dumpMicDevices ( self ) : 161info = self . p . get_host_api_info_by_index ( 0 ) 162numdevices = info . get ( 'deviceCount' ) 163 164for i in range ( 0 , numdevices ) : 165if ( self . p . get_device_info_by_host_api_device_index ( 0 , i ) . get ( 'maxInputChannels' )) > 0 : 166device_name = self . p . get_device_info_by_host_api_device_index ( 0 , i ) . get ( 'name' ) 167( "Input Device id " , i , " - " , device_name ) 168 169def onAudioFramesAvailable ( self , 170frames , 171frame_count , 172time_info , 173status_flags ) : 174if self . paused : 175# Don't literally pause, just start returning silence. This allows 176# the `min_segment_age_s` check to work while paused. 177n_frames = int ( frame_count * AudioStream . FPS / 178float ( self . sample_rate )) 179self . chunks . append ( np . zeros ( n_frames , 180dtype = np . int16 ) . tobytes ()) 181return ( frames , pyaudio . paContinue ) 182 183decimated = b'' 184# In pyaudio, a `frame` is a single sample of audio data. 185frame_len = AudioStream . FRAME_SZ 186next_frame = 0.0 187# The mic probably has a higher sample rate than Whisper wants, so 188# decrease the sample rate by dropping samples. Note that this 189# algorithm only works if the mic's rate is higher than whisper's 190# expected rate. 191keep_every = float ( self . sample_rate ) / AudioStream . FPS 192for i in range ( frame_count ) : 193if i >= next_frame : 194decimated += frames [ i * frame_len : ( i + 1 ) * frame_len ] 195next_frame += keep_every 196self . chunks . append ( decimated ) 197 198return ( frames , pyaudio . paContinue ) 199 200# Get audio data and the corresponding timestamp. 201def getSamples ( self ) -> bytes : 202chunks = self . chunks 203self . chunks = [] 204result = b'' . join ( chunks ) 205return result 206 207class AudioCollector : 208def __init__ ( self , stream : AudioStream ) : 209self . stream = stream 210self . frames = b'' 211# Note: by design, this is the only spot where we anchor our timestamps 212# against the real world. This is done to make it possible to profile 213# test cases which read from disk (at much faster than real speed) in 214# the same way that we profile real-time data. 215self . wall_ts = time . time () 216 217def getAudio ( self ) -> bytes : 218frames = self . stream . getSamples () 219if frames : 220self . frames += frames 221return self . frames 222 223def dropAudioPrefix ( self , dur_s : float ) -> bytes : 224n_bytes = int ( dur_s * AudioStream . FPS ) * self . stream . FRAME_SZ 225n_bytes = min ( n_bytes , len ( self . frames )) 226cut_portion = self . frames [ : n_bytes ] 227self . frames = self . frames [ n_bytes : ] 228self . wall_ts += float ( n_bytes / self . stream . FRAME_SZ ) / self . stream . FPS 229return cut_portion 230 231def dropAudioPrefixByFrames ( self , dur_frames : int ) -> bytes : 232n_bytes = dur_frames * self . stream . FRAME_SZ 233n_bytes = min ( n_bytes , len ( self . frames )) 234cut_portion = self . frames [ : n_bytes ] 235self . frames = self . frames [ n_bytes : ] 236self . wall_ts += float ( n_bytes / self . stream . FRAME_SZ ) / self . stream . FPS 237return cut_portion 238 239def keepLast ( self , dur_s : float ) -> bytes : 240drop_len = max ( 0 , self . duration () - dur_s ) 241return self . dropAudioPrefix ( drop_len ) 242 243def dropAudio ( self ) : 244self . wall_ts += self . duration () 245cut_portion = self . frames 246self . frames = b'' 247return cut_portion 248 249def duration ( self ) : 250return len ( self . frames ) / ( AudioStream . FPS * self . stream . FRAME_SZ ) 251 252def begin ( self ) : 253return self . wall_ts 254 255def now ( self ) : 256return self . begin () + self . duration () 257 258class AudioCollectorFilter : 259def __init__ ( self , parent : AudioCollector ) : 260self . parent = parent 261 262def getAudio ( self ) -> bytes : 263return self . parent . getAudio () 264def dropAudioPrefix ( self , dur_s : float ) : 265return self . parent . dropAudioPrefix ( dur_s ) 266def dropAudioPrefixByFrames ( self , dur_frames : int ) : 267return self . parent . dropAudioPrefixByFrames ( dur_frames ) 268def keepLast ( self , dur_s ) : 269return self . parent . keepLast ( dur_s ) 270def dropAudio ( self ) : 271return self . parent . dropAudio () 272def duration ( self ) : 273return self . parent . duration () 274def begin ( self ) : 275return self . parent . begin () 276def now ( self ) : 277return self . parent . now () 278 279# Audio collector that enforces a minimum length on its audio data. 280class LengthEnforcingAudioCollector ( AudioCollectorFilter ) : 281def __init__ ( self , parent : AudioCollector , min_duration_s : float ) : 282AudioCollectorFilter . __init__ ( self , parent ) 283self . min_duration_s = min_duration_s 284 285def getAudio ( self ) -> bytes : 286audio = self . parent . getAudio () 287min_duration_frames = int ( self . min_duration_s * AudioStream . FPS ) 288pad_len_frames = max ( 0 , min_duration_frames - int ( len ( audio ) / 289AudioStream . FRAME_SZ )) 290pad = np . zeros ( pad_len_frames , dtype = np . int16 ) . tobytes () 291return pad + audio 292 293class NormalizingAudioCollector ( AudioCollectorFilter ) : 294def __init__ ( self , parent : AudioCollector ) : 295AudioCollectorFilter . __init__ ( self , parent ) 296 297def getAudio ( self ) -> bytes : 298audio = self . parent . getAudio () 299 300audio = AudioSegment ( audio , sample_width = AudioStream . FRAME_SZ , 301frame_rate = AudioStream . FPS , channels = AudioStream . CHANNELS ) 302audio = audio . normalize () 303 304frames = np . array ( audio . get_array_of_samples ()) 305frames = np . int16 ( frames ) . tobytes () 306 307return frames 308 309class CompressingAudioCollector ( AudioCollectorFilter ) : 310def __init__ ( self , parent : AudioCollector ) : 311AudioCollectorFilter . __init__ ( self , parent ) 312 313def getAudio ( self ) -> bytes : 314audio = self . parent . getAudio () 315 316audio = AudioSegment ( audio , sample_width = AudioStream . FRAME_SZ , 317frame_rate = AudioStream . FPS , channels = AudioStream . CHANNELS ) 318# subtle compression has a slight positive effect on my benchmark 319audio = audio . compress_dynamic_range ( threshold =- 10 , ratio = 2.0 ) 320 321frames = np . array ( audio . get_array_of_samples ()) 322frames = np . int16 ( frames ) . tobytes () 323 324return frames 325 326class AudioSegmenter : 327def __init__ ( self , 328min_silence_ms = 250 , 329max_speech_s = 5 ) : 330self . vad_options = vad . VadOptions ( 331min_silence_duration_ms = min_silence_ms , 332max_speech_duration_s = max_speech_s ) 333pass 334 335def segmentAudio ( self , audio : bytes ) : 336audio = np . frombuffer ( audio , 337dtype = np . int16 ) . flatten () . astype ( np . float32 ) / 32768.0 338return vad . get_speech_timestamps ( audio , vad_options = self . vad_options ) 339 340# Returns the stable cutoff (if any) and whether there are any segments. 341def getStableCutoff ( self , audio : bytes ) -> typing . Tuple [ int , bool ] : 342min_delta_frames = int (( self . vad_options . min_silence_duration_ms * 343AudioStream . FPS ) / 1000.0 ) 344cutoff = None 345 346last_end = None 347segments = self . segmentAudio ( audio ) 348 349for i in range ( len ( segments )) : 350s = segments [ i ] 351#print(f"s: {s}") 352#print(f"last_end: {last_end}") 353 354if last_end : 355delta_frames = s [ 'start' ] - last_end 356#print(f"delta frames: {delta_frames}") 357if delta_frames > min_delta_frames : 358cutoff = s [ 'start' ] 359else : 360last_end = s [ 'end' ] 361 362if i == len ( segments ) - 1 : 363now = int ( len ( audio ) / AudioStream . FRAME_SZ ) 364#print(f"now: {now}") 365#print(f"min d: {min_delta_frames}") 366delta_frames = now - s [ 'end' ] 367if delta_frames > min_delta_frames : 368cutoff = now - int ( min_delta_frames / 2 ) 369 370return ( cutoff , len ( segments ) > 0 ) 371 372# A segment of transcribed audio. `start_ts` and `end_ts` are floating point 373# number of seconds since the beginning of audio data. 374class Segment : 375def __init__ ( self , 376transcript : str , 377start_ts : float , 378end_ts : float , 379wall_ts : float , 380avg_logprob : float , 381no_speech_prob : float , 382compression_ratio : float ) : 383self . transcript = transcript 384# start_ts, end_ts are timestamps in seconds relative to `wall_ts`. 385self . start_ts = start_ts 386self . end_ts = end_ts 387# wall_ts is the time.time() at which the oldest audio sample leading 388# to this transcript was collected. 389self . wall_ts = wall_ts 390self . avg_logprob = avg_logprob 391self . no_speech_prob = no_speech_prob 392self . compression_ratio = compression_ratio 393 394def __str__ ( self ) : 395ts = f"(ts: { self . start_ts } - { self . end_ts } ) " 396 397wall_ts_start = datetime . utcfromtimestamp ( self . start_ts + self . wall_ts ) . strftime ( '%H:%M:%S' ) 398wall_ts_end = datetime . utcfromtimestamp ( self . end_ts + self . wall_ts ) . strftime ( '%H:%M:%S' ) 399wall_ts = f"(wall ts: { wall_ts_start } - { wall_ts_end } ) " 400 401no_speech = f"(no_speech: { self . no_speech_prob } ) " 402avg_logprob = f"(avg_logprob: { self . avg_logprob } ) " 403return f" { self . transcript } " + ts + wall_ts + no_speech + avg_logprob 404 405class Whisper : 406def __init__ ( self , 407collector : AudioCollector , 408cfg : typing . Dict ) : 409self . collector = collector 410self . model = None 411self . cfg = cfg 412 413abspath = os . path . abspath ( __file__ ) 414my_dir = os . path . dirname ( abspath ) 415parent_dir = os . path . dirname ( my_dir ) 416 417model_str = cfg [ "model" ] 418model_root = os . path . join ( parent_dir , "Models" , 419os . path . normpath ( model_str )) 420( f"Model { cfg [ 'model' ] } will be saved to { model_root } " , 421file = sys . stderr ) 422 423model_device = "cuda" 424if cfg [ "use_cpu" ] : 425model_device = "cpu" 426if cfg [ "use_flash_attention" ] : 427( f"Flash attention disabled on CPU" , file = sys . stderr ) 428cfg [ "use_flash_attention" ] = False 429 430already_downloaded = os . path . exists ( model_root ) 431 432self . model = WhisperModel ( model_str , 433device = model_device , 434device_index = cfg [ "gpu_idx" ] , 435compute_type = cfg [ "compute_type" ] , 436download_root = model_root , 437local_files_only = already_downloaded , 438flash_attention = cfg [ "use_flash_attention" ]) 439 440def transcribe ( self , frames : bytes = None ) -> typing . List [ Segment ] : 441if frames is None : 442frames = self . collector . getAudio () 443# Convert from signed 16-bit int [-32768, 32767] to signed 32-bit float on 444# [-1, 1]. 445audio = np . frombuffer ( frames , 446dtype = np . int16 ) . flatten () . astype ( np . float32 ) / 32768.0 447 448t0 = time . time () 449segments , info = self . model . transcribe ( 450audio , 451language = langcodes . find ( self . cfg [ "language" ]) . language , 452vad_filter = True , 453temperature = 0.0 , 454without_timestamps = False ) 455res = [] 456for s in segments : 457# Manual touchup. I see a decent number of hallucinations sneaking 458# in with high `no_speech_prob` and modest `avg_logprob`. 459if s . no_speech_prob > 0.6 and s . avg_logprob < - 0.5 : 460if cfg [ "enable_debug_mode" ] : 461( f"Drop probable hallucination (case 1) " + 462f"(text=' { s . text } ', " + 463f"no_speech_prob= { s . no_speech_prob } , " + 464f"avg_logprob= { s . avg_logprob } )" , file = sys . stderr ) 465continue 466# Another touchup targeted at the vexatious "thanks for watching!" 467# hallucination. This triggers a lot when listening to 468# instrumental/electronic music. 469if s . no_speech_prob > 0.15 and s . avg_logprob < - 0.7 : 470if cfg [ "enable_debug_mode" ] : 471( f"Drop probable hallucination (case 2) " + 472f"(text=' { s . text } ', " + 473f"no_speech_prob= { s . no_speech_prob } , " + 474f"avg_logprob= { s . avg_logprob } )" , file = sys . stderr ) 475continue 476if cfg [ "enable_debug_mode" ] : 477( f"s get: { s } " ) 478if s . avg_logprob < - 1.0 : 479continue 480if s . compression_ratio > 2.4 : 481continue 482res . append ( Segment ( s . text , s . start , s . end , 483self . collector . begin () , 484s . avg_logprob , s . no_speech_prob , s . compression_ratio )) 485t1 = time . time () 486if cfg [ "enable_debug_mode" ] : 487( f"Transcription latency (s): { t1 - t0 } " ) 488return res 489 490def saveAudio ( audio : bytes , path : str ) : 491with wave . open ( path , 'wb' ) as wf : 492( f"Saving audio to { path } " , file = sys . stderr ) 493wf . setnchannels ( AudioStream . CHANNELS ) 494wf . setsampwidth ( AudioStream . FRAME_SZ ) 495wf . setframerate ( AudioStream . FPS ) 496wf . writeframes ( audio ) 497 498class VadCommitter : 499def __init__ ( self , 500cfg : typing . Dict , 501collector : AudioCollector , 502whisper : Whisper , 503segmenter : AudioSegmenter ) : 504self . cfg = cfg 505self . collector = collector 506self . whisper = whisper 507self . segmenter = segmenter 508 509def getDelta ( self ) -> TranscriptCommit : 510audio = self . collector . getAudio () 511stable_cutoff , has_audio = self . segmenter . getStableCutoff ( audio ) 512 513delta = "" 514commit_audio = None 515latency_s = None 516duration_s = self . collector . duration () 517start_ts = self . collector . begin () 518 519if has_audio and stable_cutoff : 520#print(f"stable cutoff get: {stable_cutoff}", file=sys.stderr) 521latency_s = self . collector . now () - self . collector . begin () 522duration_s = stable_cutoff / AudioStream . FPS 523start_ts = self . collector . begin () 524commit_audio = self . collector . dropAudioPrefixByFrames ( stable_cutoff ) 525 526segments = self . whisper . transcribe ( commit_audio ) 527delta = '' . join ( s . transcript for s in segments ) 528audio = self . collector . getAudio () 529if cfg [ "enable_debug_mode" ] : 530for s in segments : 531( f"commit segment: { s } " , file = sys . stderr ) 532( f"delta get: { delta } " , file = sys . stderr ) 533 534if False : 535ts = datetime . fromtimestamp ( self . collector . now () - latency_s ) 536filename = str ( ts . strftime ( '%Y_%m_%d__%H-%M-%S' )) + ".wav" 537saveAudio ( commit_audio , filename ) 538 539preview = "" 540if self . cfg [ "enable_previews" ] and has_audio : 541segments = self . whisper . transcribe ( audio ) 542preview = "" . join ( s . transcript for s in segments ) 543 544if not has_audio : 545#print("VAD detects no audio, skip transcription", file=sys.stderr) 546self . collector . keepLast ( 1.0 ) 547 548return TranscriptCommit ( 549delta . strip () , 550preview . strip () , 551latency_s , 552audio = audio , 553duration_s = duration_s , 554start_ts = start_ts ) 555 556def install_in_venv ( pkgs : typing . List [ str ]) -> bool : 557pkgs_str = " " . join ( pkgs ) 558( f"Installing { pkgs_str } " ) 559pip_proc = subprocess . Popen ( 560f"Resources/Python/python.exe -m pip install { pkgs_str } --no-warn-script-location" . split () , 561stdout = subprocess . PIPE , 562stderr = subprocess . PIPE ) 563pip_stdout , pip_stderr = pip_proc . communicate () 564pip_stdout = pip_stdout . decode ( "utf-8" ) 565pip_stderr = pip_stderr . decode ( "utf-8" ) 566( pip_stdout , file = sys . stderr ) 567( pip_stderr , file = sys . stderr ) 568if pip_proc . returncode != 0 : 569( f"`pip install { pkgs_str } ` exited with { pip_proc . returncode } " , 570file = sys . stderr ) 571return False 572return True 573 574class TranslationPlugin ( StreamingPlugin ) : 575def __init__ ( self , cfg ) : 576lang_bits = cfg [ "language_target" ] . split ( " | " ) 577self . cfg = cfg 578self . language_target = None 579self . translator = None 580self . tokenizer = None 581if len ( lang_bits ) != 2 : 582return 583self . language_target = lang_bits [ 1 ] 584 585( "Translation requested" , file = sys . stderr ) 586# The ctranslate2 model converter needs torch. Grr. 587if not install_in_venv ([ "torch==2.2.2" ]) : 588return 589 590output_dir = "Resources/" + cfg [ "model_translation" ] 591# Provided by ctranslate2 Python package 592cmd = "ct2-transformers-converter.exe --model facebook/" + \ 593cfg [ "model_translation" ] + " --output_dir " + output_dir 594 595( f"Fetching translation algorithm ( { cfg [ 'model_translation' ] } )" , 596file = sys . stderr ) 597if not os . path . exists ( output_dir ) : 598ct2_proc = subprocess . Popen ( 599cmd . split () , 600stdout = subprocess . PIPE , 601stderr = subprocess . PIPE ) 602ct2_stdout , ct2_stderr = ct2_proc . communicate () 603ct2_stdout = ct2_stdout . decode ( "utf-8" ) 604ct2_stderr = ct2_stderr . decode ( "utf-8" ) 605( ct2_stdout , file = sys . stderr ) 606( ct2_stderr , file = sys . stderr ) 607if ct2_proc . returncode != 0 : 608( f"Failed to get NLLB model: ct2 process exited with " 609"{ct2_proc.returncode}" , file = sys . stderr ) 610( f"Using model at { output_dir } " , file = sys . stderr ) 611 612model_device = "cuda" 613if cfg [ "use_cpu" ] : 614model_device = "cpu" 615if cfg [ "use_flash_attention" ] : 616( f"Flash attention disabled on CPU" , file = sys . stderr ) 617cfg [ "use_flash_attention" ] = False 618 619self . translator = ctranslate2 . Translator ( output_dir , 620device = model_device , 621device_index = cfg [ "gpu_idx" ] , 622compute_type = cfg [ "compute_type" ] , 623flash_attention = cfg [ "use_flash_attention" ]) 624 625whisper_lang = cfg [ "language" ] 626nllb_lang = lang_compat . whisper_to_nllb [ whisper_lang ] 627 628self . tokenizer = transformers . AutoTokenizer . from_pretrained ( 629"facebook/" + cfg [ "model_translation" ] , 630src_lang = nllb_lang ) 631 632( f"Translation ready to go" , file = sys . stderr ) 633 634def transform ( self , commit : TranscriptCommit ) -> TranscriptCommit : 635if not self . language_target : 636return commit 637 638def _translate_text ( text : str ) -> str : 639 640whisper_lang = self . cfg [ "language" ] 641nllb_lang = lang_compat . whisper_to_nllb [ whisper_lang ] 642ss_lang = lang_compat . nllb_to_ss [ nllb_lang ] 643sentences = split_text_into_sentences ( text , language = ss_lang ) 644 645translated_sentences = [] 646for sentence in sentences : 647source = self . tokenizer . convert_ids_to_tokens ( self . tokenizer . encode ( sentence )) 648target_prefix = [ self . language_target ] 649results = self . translator . translate_batch ([ source ] , target_prefix = [ target_prefix ]) 650target = results [ 0 ] . hypotheses [ 0 ][ 1 : ] 651translated_sentence = self . tokenizer . decode ( self . tokenizer . convert_tokens_to_ids ( target )) 652translated_sentences . append ( translated_sentence ) 653translated = " " . join ( translated_sentences ) 654if cfg [ "enable_orig_lang" ] and len ( sentences ) > 0 : 655translated += f" ( { text } )" 656return translated 657 658commit . delta = _translate_text ( commit . delta ) 659commit . preview = _translate_text ( commit . preview ) 660return commit 661 662class LowercasePlugin ( StreamingPlugin ) : 663def __init__ ( self , cfg ) : 664self . cfg = cfg 665 666def transform ( self , commit : TranscriptCommit ) -> TranscriptCommit : 667if self . cfg [ "enable_lowercase_filter" ] : 668commit . delta = commit . delta . lower () 669commit . preview = commit . preview . lower () 670return commit 671 672class UppercasePlugin ( StreamingPlugin ) : 673def __init__ ( self , cfg ) : 674self . cfg = cfg 675 676def transform ( self , commit : TranscriptCommit ) -> TranscriptCommit : 677if self . cfg [ "enable_uppercase_filter" ] : 678commit . delta = commit . delta . upper () 679commit . preview = commit . preview . upper () 680return commit 681 682class UwuPlugin ( StreamingPlugin ) : 683def __init__ ( self , cfg ) : 684self . cfg = cfg 685 686def transform ( self , commit : TranscriptCommit ) -> TranscriptCommit : 687if self . cfg [ "enable_uwu_filter" ] : 688def _to_uwu ( s : str ) -> str : 689uwu_proc = subprocess . Popen ([ "Resources/Uwu/Uwwwu.exe" , s ] , 690stdout = subprocess . PIPE , 691stderr = subprocess . PIPE ) 692uwu_stdout , uwu_stderr = uwu_proc . communicate () 693uwu_text = uwu_stdout . decode ( "utf-8" ) 694uwu_text = uwu_text . replace ( " \n " , "" ) 695uwu_text = uwu_text . replace ( " \r " , "" ) 696if uwu_text . isspace () : 697return "" 698# Guarantee that the segment starts with a single space and 699# doesn't end with whitespace. 700uwu_text = " " + uwu_text . lstrip () . rstrip () 701return uwu_text 702commit . delta = _to_uwu ( commit . delta ) 703commit . preview = _to_uwu ( commit . preview ) 704return commit 705 706class ProfanityPlugin ( StreamingPlugin ) : 707def __init__ ( self , cfg ) : 708self . cfg = cfg 709en_profanity_path = os . path . abspath ( "Resources/Profanity/en" ) 710self . filter = ProfanityFilter ( en_profanity_path ) 711if cfg [ "enable_profanity_filter" ] : 712self . filter . load () 713 714def transform ( self , commit : TranscriptCommit ) -> TranscriptCommit : 715if self . cfg [ "enable_profanity_filter" ] : 716commit . delta = self . filter . filter ( commit . delta ) 717commit . preview = self . filter . filter ( commit . preview ) 718return commit 719 720class PresentationFilter : 721def __init__ ( self ) : 722pass 723 724def transform ( self , transcript : str , preview : str ) -> typing . Tuple [ str , str ] : 725return transcript , preview 726 727def stop ( self ) : 728pass 729 730class TrailingPeriodFilter ( PresentationFilter ) : 731def __init__ ( self , cfg ) : 732self . cfg = cfg 733 734def transform ( self , transcript : str , preview : str ) -> typing . Tuple [ str , str ] : 735if self . cfg [ "remove_trailing_period" ] : 736def _remove_trailing_period ( s : str ) -> str : 737if len ( s ) > 0 and s [ - 1 ] == '.' and not s . endswith ( "..." ) : 738s = s [ 0 : len ( s ) - 1 ] 739return s 740if len ( preview ) == 0 : 741( "here" ) 742transcript = _remove_trailing_period ( transcript ) 743else : 744( "there" ) 745preview = _remove_trailing_period ( preview ) 746return transcript , preview 747 748class OscPager : 749def __init__ ( self , cfg ) : 750self . osc_state = osc_ctrl . OscState ( cfg [ "chars_per_sync" ] , 751cfg [ "rows" ] , 752cfg [ "cols" ] , 753cfg [ "bytes_per_char" ]) 754self . cfg = cfg 755self . next_sync_window = time . time () 756 757def page ( self , text ) : 758if self . cfg [ "use_builtin" ] : 759osc_ctrl . pageMessageBuiltin ( self . cfg , self . osc_state , text ) 760self . bumpSyncWindow ( amount_s = 1.5 ) 761else : 762osc_ctrl . pageMessage ( self . cfg , self . osc_state , text , EmotesState ()) 763self . bumpSyncWindow () 764 765def bumpSyncWindow ( self , amount_s = osc_ctrl . SYNC_DELAY_S ) : 766self . next_sync_window = time . time () + amount_s 767 768def getSyncWindow ( self ) : 769while time . time () < self . next_sync_window : 770time . sleep ( 0.01 ) 771 772def clear ( self ) : 773osc_ctrl . clear ( self . osc_state ) 774self . bumpSyncWindow () 775 776def toggleBoard ( self , state : bool ) : 777osc_ctrl . toggleBoard ( self . osc_state . client , state ) 778self . bumpSyncWindow () 779 780def lockWorld ( self , state : bool ) : 781osc_ctrl . lockWorld ( self . osc_state . client , state ) 782self . bumpSyncWindow () 783 784def ellipsis ( self , state : bool ) : 785osc_ctrl . ellipsis ( self . osc_state . client , state ) 786self . bumpSyncWindow () 787 788def transcriptionThread ( ctrl : ThreadControl ) : 789last_stable_commit = None 790 791while ctrl . run_app : 792time . sleep ( ctrl . cfg [ "transcription_loop_delay_ms" ] / 1000.0 ) ; 793 794op = None 795 796commit = ctrl . committer . getDelta () 797 798for plugin in ctrl . plugins : 799commit = plugin . transform ( commit ) 800 801if len ( commit . delta ) > 0 or len ( commit . preview ) > 0 : 802# Avoid re-sending text after long pauses. User controls the length 803# of the pause in the UI. 804if ctrl . cfg [ "reset_after_silence_s" ] > 0 : 805silence_duration = 0 806if last_stable_commit : 807last_commit_end_ts = \ 808last_stable_commit . start_ts + \ 809last_stable_commit . duration_s 810silence_duration = commit . start_ts - last_commit_end_ts 811if silence_duration > ctrl . cfg [ "reset_after_silence_s" ] : 812( f"Resetting transcript after { silence_duration } -second " 813"silence" , file = sys . stderr ) 814ctrl . transcript = "" 815ctrl . preview = "" 816if commit . delta : 817last_stable_commit = commit 818 819# Hard-cap displayed transcript length at 4k characters to prevent 820# runaway memory use in UI. Keep the full transcript to avoid 821# breaking OSC pager. 822transcript = ctrl . transcript [ - 4096 : ] + commit . delta 823preview = commit . preview 824 825for filt in ctrl . filters : 826transcript , preview = filt . transform ( transcript , preview ) 827 828try : 829( f"Transcript: { transcript } " ) 830except UnicodeEncodeError : 831( "Failed to encode transcript - discarding delta" , 832file = sys . stderr ) 833continue 834try : 835( f"Preview: { preview } " ) 836except UnicodeEncodeError : 837( "Failed to encode preview - discarding" , file = sys . stderr ) 838 839if cfg [ "enable_debug_mode" ] : 840( f"commit latency: { commit . latency_s } " , file = sys . stderr ) 841( f"commit thresh: { commit . thresh_at_commit } " , 842file = sys . stderr ) 843 844if len ( ctrl . transcript ) > 0 and \ 845( not ctrl . transcript . endswith ( ' ' )) and \ 846( not commit . delta . startswith ( ' ' )) : 847commit . delta = ' ' + commit . delta 848if len ( commit . delta ) > 0 and \ 849( not commit . delta . endswith ( ' ' )) and \ 850( not commit . preview . startswith ( ' ' )) : 851commit . preview = ' ' + commit . preview 852 853ctrl . transcript += commit . delta 854ctrl . preview = ctrl . transcript + commit . preview 855for plugin in ctrl . plugins : 856plugin . stop () 857for filt in ctrl . filters : 858filt . stop () 859 860def vrInputThread ( ctrl : ThreadControl ) : 861RECORD_STATE = 0 862PAUSE_STATE = 1 863state = PAUSE_STATE 864 865hand_id = ctrl . cfg [ "button" ] . split ()[ 0 ] 866button_id = ctrl . cfg [ "button" ] . split ()[ 1 ] 867 868# Rough description of state machine: 869# Single short press: toggle transcription 870# Medium press: dismiss custom chatbox 871# Long press: update chatbox in place 872# Medium press + long press: type transcription 873 874last_rising = time . time () 875last_medium_press_end = 0 876 877waveform0 = os . path . abspath ( "Resources/Sounds/Noise_On_Quiet.wav" ) 878waveform1 = os . path . abspath ( "Resources/Sounds/Noise_Off_Quiet.wav" ) 879waveform2 = os . path . abspath ( "Resources/Sounds/Dismiss_Noise_Quiet.wav" ) 880waveform3 = os . path . abspath ( "Resources/Sounds/KB_Noise_Off_Quiet.wav" ) 881 882button_generator = steamvr . pollButtonPress ( hand = hand_id , button = button_id , 883ctrl = ctrl ) 884while ctrl . run_app : 885time . sleep ( 0.01 ) 886try : 887event = next ( button_generator ) 888except StopIteration : 889break 890 891if event . opcode == steamvr . EVENT_RISING_EDGE : 892last_rising = time . time () 893 894if state == PAUSE_STATE : 895ctrl . stream . pause ( False ) 896ctrl . stream . getSamples () 897 898elif event . opcode == steamvr . EVENT_FALLING_EDGE : 899now = time . time () 900if now - last_rising > 1.5 : 901# Long press: treat as the end of transcription. 902state = PAUSE_STATE 903 904ctrl . stream . pause ( True ) 905 906if last_rising - last_medium_press_end < 1.0 : 907# Type transcription 908if ctrl . cfg [ "enable_local_beep" ] : 909winsound . PlaySound ( waveform3 , winsound . SND_FILENAME | winsound . SND_ASYNC ) 910pass 911# TODO(yum) this is broken! Audio is not being collected 912# while paused anymore. 913#keyboard.write(ctrl.preview) 914else : 915if ctrl . cfg [ "enable_local_beep" ] : 916winsound . PlaySound ( waveform1 , winsound . SND_FILENAME | winsound . SND_ASYNC ) 917pass 918 919elif now - last_rising > 0.5 : 920# Medium press 921( "CLEARING" , file = sys . stderr ) 922last_medium_press_end = now 923state = PAUSE_STATE 924 925if ctrl . cfg [ "enable_local_beep" ] : 926winsound . PlaySound ( waveform2 , winsound . SND_FILENAME | winsound . SND_ASYNC ) 927pass 928 929if not ctrl . cfg [ "use_builtin" ] : 930ctrl . pager . getSyncWindow () 931ctrl . pager . toggleBoard ( False ) 932 933# Flush the *entire* pipeline. 934ctrl . stream . pause ( True ) 935ctrl . stream . getSamples () 936ctrl . collector . dropAudio () 937ctrl . pager . clear () 938if ctrl . cfg [ "enable_lock_at_spawn" ] : 939# Give the board 0.5 seconds to disappear before unlocking from 940# world space. 941time . sleep ( 0.5 ) 942ctrl . pager . lockWorld ( False ) 943else : 944# Short hold 945if state == RECORD_STATE : 946( "PAUSED" , file = sys . stderr ) 947state = PAUSE_STATE 948if not ctrl . cfg [ "use_builtin" ] and not ctrl . cfg [ "enable_lock_at_spawn" ] : 949ctrl . pager . getSyncWindow () 950ctrl . pager . lockWorld ( True ) 951 952ctrl . stream . pause ( True ) 953 954if ctrl . cfg [ "enable_local_beep" ] : 955winsound . PlaySound ( waveform1 , winsound . SND_FILENAME | winsound . SND_ASYNC ) 956pass 957elif state == PAUSE_STATE : 958( "RECORDING" , file = sys . stderr ) 959state = RECORD_STATE 960if not ctrl . cfg [ "use_builtin" ] : 961ctrl . pager . getSyncWindow () 962ctrl . pager . toggleBoard ( True ) 963ctrl . pager . lockWorld ( ctrl . cfg [ "enable_lock_at_spawn" ]) 964ctrl . pager . ellipsis ( True ) 965if ctrl . cfg [ "reset_on_toggle" ] : 966if ctrl . cfg [ "enable_debug_mode" ] : 967( "Toggle detected, dropping transcript (3)" , 968file = sys . stderr ) 969ctrl . transcript = "" 970ctrl . preview = "" 971#audio_state.drop_transcription = True 972else : 973if ctrl . cfg [ "enable_debug_mode" ] : 974( "Toggle detected, committing preview text (3)" , file = sys . stderr ) 975#audio_state.text += audio_state.preview_text 976 977ctrl . stream . pause ( False ) 978ctrl . pager . clear () 979 980if ctrl . cfg [ "enable_local_beep" ] : 981winsound . PlaySound ( waveform0 , winsound . SND_FILENAME | winsound . SND_ASYNC ) 982pass 983 984def kbInputThread ( ctrl : ThreadControl ) : 985machine = keybind_event_machine . KeybindEventMachine ( ctrl . cfg [ "keybind" ]) 986last_press_time = 0 987 988# double pressing the keybind 989double_press_timeout = 0.5 990 991RECORD_STATE = 0 992PAUSE_STATE = 1 993state = PAUSE_STATE 994 995waveform0 = os . path . abspath ( "Resources/Sounds/Noise_On_Quiet.wav" ) 996waveform1 = os . path . abspath ( "Resources/Sounds/Noise_Off_Quiet.wav" ) 997waveform2 = os . path . abspath ( "Resources/Sounds/Dismiss_Noise_Quiet.wav" ) 998waveform3 = os . path . abspath ( "Resources/Sounds/KB_Noise_Off_Quiet.wav" ) 999 1000while ctrl . run_app : 1001time . sleep ( 0.01 ) 1002 1003cur_press_time = machine . getNextPressTime () 1004if cur_press_time == 0 : 1005continue 1006 1007EVENT_SINGLE_PRESS = 0 1008EVENT_DOUBLE_PRESS = 1 1009if last_press_time == 0 : 1010event = EVENT_SINGLE_PRESS 1011elif cur_press_time - last_press_time < double_press_timeout : 1012event = EVENT_DOUBLE_PRESS 1013else : 1014event = EVENT_SINGLE_PRESS 1015last_press_time = cur_press_time 1016 1017if event == EVENT_DOUBLE_PRESS : 1018( "CLEARING" , file = sys . stderr ) 1019state = PAUSE_STATE 1020 1021if ctrl . cfg [ "enable_local_beep" ] : 1022winsound . PlaySound ( waveform2 , winsound . SND_FILENAME | winsound . SND_ASYNC ) 1023pass 1024 1025if not ctrl . cfg [ "use_builtin" ] : 1026ctrl . pager . getSyncWindow () 1027ctrl . pager . toggleBoard ( False ) 1028 1029# Flush the *entire* pipeline. 1030ctrl . stream . pause ( True ) 1031ctrl . stream . getSamples () 1032ctrl . collector . dropAudio () 1033ctrl . pager . clear () 1034if ctrl . cfg [ "enable_lock_at_spawn" ] : 1035# Give the board 0.5 seconds to disappear before unlocking from 1036# world space. 1037time . sleep ( 0.5 ) 1038ctrl . pager . lockWorld ( False ) 1039continue 1040 1041# Short hold 1042if state == RECORD_STATE : 1043( "PAUSED" , file = sys . stderr ) 1044state = PAUSE_STATE 1045if not ctrl . cfg [ "use_builtin" ] and not ctrl . cfg [ "enable_lock_at_spawn" ] : 1046ctrl . pager . getSyncWindow () 1047ctrl . pager . lockWorld ( True ) 1048 1049ctrl . stream . pause ( True ) 1050 1051if ctrl . cfg [ "enable_local_beep" ] : 1052winsound . PlaySound ( waveform1 , winsound . SND_FILENAME | winsound . SND_ASYNC ) 1053pass 1054elif state == PAUSE_STATE : 1055( "RECORDING" , file = sys . stderr ) 1056state = RECORD_STATE 1057if not ctrl . cfg [ "use_builtin" ] : 1058ctrl . pager . getSyncWindow () 1059ctrl . pager . toggleBoard ( True ) 1060ctrl . pager . lockWorld ( ctrl . cfg [ "enable_lock_at_spawn" ]) 1061ctrl . pager . ellipsis ( True ) 1062if ctrl . cfg [ "reset_on_toggle" ] : 1063if ctrl . cfg [ "enable_debug_mode" ] : 1064( "Toggle detected, dropping transcript (2)" , 1065file = sys . stderr ) 1066ctrl . transcript = "" 1067ctrl . preview = "" 1068else : 1069if ctrl . cfg [ "enable_debug_mode" ] : 1070( "Toggle detected, committing preview text (2)" , 1071file = sys . stderr ) 1072#audio_state.text += audio_state.preview_text 1073 1074ctrl . stream . pause ( False ) 1075ctrl . pager . clear () 1076 1077if ctrl . cfg [ "enable_local_beep" ] : 1078winsound . PlaySound ( waveform0 , winsound . SND_FILENAME | winsound . SND_ASYNC ) 1079pass 1080 1081def oscThread ( ctrl : ThreadControl ) : 1082while ctrl . run_app : 1083ctrl . pager . getSyncWindow () 1084ctrl . pager . page ( ctrl . preview ) 1085time . sleep ( 0.01 ) 1086 1087def run ( cfg ) : 1088stream = MicStream ( cfg [ "microphone" ]) 1089 1090collector = AudioCollector ( stream ) 1091#collector = LengthEnforcingAudioCollector(collector, 5.0) 1092collector = NormalizingAudioCollector ( collector ) 1093collector = CompressingAudioCollector ( collector ) 1094whisper = Whisper ( collector , cfg ) 1095segmenter = AudioSegmenter ( min_silence_ms = cfg [ "min_silence_duration_ms" ] , 1096max_speech_s = cfg [ "max_speech_duration_s" ]) 1097committer = VadCommitter ( cfg , collector , whisper , segmenter ) 1098pager = OscPager ( cfg ) 1099 1100ctrl = ThreadControl ( cfg ) 1101ctrl . stream = stream 1102ctrl . collector = collector 1103ctrl . whisper = whisper 1104ctrl . committer = committer 1105 1106ctrl . plugins = [] 1107ctrl . plugins . append ( TranslationPlugin ( cfg )) 1108ctrl . plugins . append ( UppercasePlugin ( cfg )) 1109ctrl . plugins . append ( LowercasePlugin ( cfg )) 1110ctrl . plugins . append ( ProfanityPlugin ( cfg )) 1111ctrl . plugins . append ( UwuPlugin ( cfg )) 1112ctrl . plugins . append ( BrowserSource ( cfg )) 1113 1114ctrl . filters = [] 1115ctrl . filters . append ( TrailingPeriodFilter ( cfg )) 1116 1117ctrl . pager = pager 1118ctrl . transcript = "" 1119ctrl . preview = "" 1120 1121transcribe_audio_thd = threading . Thread ( target = transcriptionThread , args = [ ctrl ]) 1122transcribe_audio_thd . daemon = True 1123transcribe_audio_thd . start () 1124 1125vr_input_thd = threading . Thread ( target = vrInputThread , args = [ ctrl ]) 1126vr_input_thd . daemon = True 1127vr_input_thd . start () 1128 1129kb_input_thd = threading . Thread ( target = kbInputThread , args = [ ctrl ]) 1130kb_input_thd . daemon = True 1131kb_input_thd . start () 1132 1133osc_thd = threading . Thread ( target = oscThread , args = [ ctrl ]) 1134osc_thd . daemon = True 1135osc_thd . start () 1136 1137for line in sys . stdin : 1138if "exit" in line or "quit" in line : 1139( "Exit requested" , file = sys . stderr ) 1140break 1141 1142ctrl . run_app = False 1143( "Join transcription thread" , file = sys . stderr ) 1144transcribe_audio_thd . join () 1145( "Join vr input thread" , file = sys . stderr ) 1146vr_input_thd . join () 1147( "Join kb input thread" , file = sys . stderr ) 1148kb_input_thd . join () 1149( "Join osc thread" , file = sys . stderr ) 1150osc_thd . join () 1151( "Done" , file = sys . stderr ) 1152 1153if __name__ == "__main__" : 1154sys . stdout . reconfigure ( encoding = "utf-8" ) 1155 1156parser = argparse . ArgumentParser () 1157parser . add_argument ( "--config" , type = str , help = "Path to app config YAML file." ) 1158args = parser . parse_args () 1159 1160cfg = app_config . getConfig ( args . config ) 1161 1162experiments = [ 1163( "Evaluate/declaration_short/audio.mp3" , 1164"Evaluate/declaration_short/control.txt" ) , 1165( "Evaluate/moist/audio.mp3" , 1166"Evaluate/moist/control.txt" ) , 1167( "Evaluate/vei/audio.mp3" , 1168"Evaluate/vei/control.txt" ) , 1169] 1170 1171if False : 1172sum = 0 1173for audio , control in experiments : 1174( f"Run experiment { audio } :: { control } " , file = sys . stderr ) 1175sum += evaluate ( cfg , audio , control ) 1176( f"Total score: { sum } " , file = sys . stderr ) 1177else : 1178#optimize(cfg, experiments) 1179run ( cfg ) 1180