yum-slop/TaSTT
Free self-hosted STT for VRChat.
git clone https://git.yummers.dev/yum-slop/TaSTT
953c03d
v0.21.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" 426 427already_downloaded = os . path . exists ( model_root ) 428 429self . model = WhisperModel ( model_str , 430device = model_device , 431device_index = cfg [ "gpu_idx" ] , 432compute_type = cfg [ "compute_type" ] , 433download_root = model_root , 434local_files_only = already_downloaded ) 435 436def transcribe ( self , frames : bytes = None ) -> typing . List [ Segment ] : 437if frames is None : 438frames = self . collector . getAudio () 439# Convert from signed 16-bit int [-32768, 32767] to signed 32-bit float on 440# [-1, 1]. 441audio = np . frombuffer ( frames , 442dtype = np . int16 ) . flatten () . astype ( np . float32 ) / 32768.0 443 444t0 = time . time () 445segments , info = self . model . transcribe ( 446audio , 447language = langcodes . find ( self . cfg [ "language" ]) . language , 448vad_filter = True , 449temperature = 0.0 , 450without_timestamps = False ) 451res = [] 452for s in segments : 453# Manual touchup. I see a decent number of hallucinations sneaking 454# in with high `no_speech_prob` and modest `avg_logprob`. 455if s . no_speech_prob > 0.6 and s . avg_logprob < - 0.5 : 456if cfg [ "enable_debug_mode" ] : 457( f"Drop probable hallucination (case 1) " + 458f"(text=' { s . text } ', " + 459f"no_speech_prob= { s . no_speech_prob } , " + 460f"avg_logprob= { s . avg_logprob } )" , file = sys . stderr ) 461continue 462# Another touchup targeted at the vexatious "thanks for watching!" 463# hallucination. This triggers a lot when listening to 464# instrumental/electronic music. 465if s . no_speech_prob > 0.15 and s . avg_logprob < - 0.7 : 466if cfg [ "enable_debug_mode" ] : 467( f"Drop probable hallucination (case 2) " + 468f"(text=' { s . text } ', " + 469f"no_speech_prob= { s . no_speech_prob } , " + 470f"avg_logprob= { s . avg_logprob } )" , file = sys . stderr ) 471continue 472if cfg [ "enable_debug_mode" ] : 473( f"s get: { s } " ) 474if s . avg_logprob < - 1.0 : 475continue 476if s . compression_ratio > 2.4 : 477continue 478res . append ( Segment ( s . text , s . start , s . end , 479self . collector . begin () , 480s . avg_logprob , s . no_speech_prob , s . compression_ratio )) 481t1 = time . time () 482if cfg [ "enable_debug_mode" ] : 483( f"Transcription latency (s): { t1 - t0 } " ) 484return res 485 486def saveAudio ( audio : bytes , path : str ) : 487with wave . open ( path , 'wb' ) as wf : 488( f"Saving audio to { path } " , file = sys . stderr ) 489wf . setnchannels ( AudioStream . CHANNELS ) 490wf . setsampwidth ( AudioStream . FRAME_SZ ) 491wf . setframerate ( AudioStream . FPS ) 492wf . writeframes ( audio ) 493 494class VadCommitter : 495def __init__ ( self , 496cfg : typing . Dict , 497collector : AudioCollector , 498whisper : Whisper , 499segmenter : AudioSegmenter ) : 500self . cfg = cfg 501self . collector = collector 502self . whisper = whisper 503self . segmenter = segmenter 504 505def getDelta ( self ) -> TranscriptCommit : 506audio = self . collector . getAudio () 507stable_cutoff , has_audio = self . segmenter . getStableCutoff ( audio ) 508 509delta = "" 510commit_audio = None 511latency_s = None 512duration_s = self . collector . duration () 513start_ts = self . collector . begin () 514 515if has_audio and stable_cutoff : 516#print(f"stable cutoff get: {stable_cutoff}", file=sys.stderr) 517latency_s = self . collector . now () - self . collector . begin () 518duration_s = stable_cutoff / AudioStream . FPS 519start_ts = self . collector . begin () 520commit_audio = self . collector . dropAudioPrefixByFrames ( stable_cutoff ) 521 522segments = self . whisper . transcribe ( commit_audio ) 523delta = '' . join ( s . transcript for s in segments ) 524audio = self . collector . getAudio () 525if cfg [ "enable_debug_mode" ] : 526for s in segments : 527( f"commit segment: { s } " , file = sys . stderr ) 528( f"delta get: { delta } " , file = sys . stderr ) 529 530if False : 531ts = datetime . fromtimestamp ( self . collector . now () - latency_s ) 532filename = str ( ts . strftime ( '%Y_%m_%d__%H-%M-%S' )) + ".wav" 533saveAudio ( commit_audio , filename ) 534 535preview = "" 536if self . cfg [ "enable_previews" ] and has_audio : 537segments = self . whisper . transcribe ( audio ) 538preview = "" . join ( s . transcript for s in segments ) 539 540if not has_audio : 541#print("VAD detects no audio, skip transcription", file=sys.stderr) 542self . collector . keepLast ( 1.0 ) 543 544return TranscriptCommit ( 545delta . strip () , 546preview . strip () , 547latency_s , 548audio = audio , 549duration_s = duration_s , 550start_ts = start_ts ) 551 552def install_in_venv ( pkgs : typing . List [ str ]) -> bool : 553pkgs_str = " " . join ( pkgs ) 554( f"Installing { pkgs_str } " ) 555pip_proc = subprocess . Popen ( 556f"Resources/Python/python.exe -m pip install { pkgs_str } --no-warn-script-location" . split () , 557stdout = subprocess . PIPE , 558stderr = subprocess . PIPE ) 559pip_stdout , pip_stderr = pip_proc . communicate () 560pip_stdout = pip_stdout . decode ( "utf-8" ) 561pip_stderr = pip_stderr . decode ( "utf-8" ) 562( pip_stdout , file = sys . stderr ) 563( pip_stderr , file = sys . stderr ) 564if pip_proc . returncode != 0 : 565( f"`pip install { pkgs_str } ` exited with { pip_proc . returncode } " , 566file = sys . stderr ) 567return False 568return True 569 570class TranslationPlugin ( StreamingPlugin ) : 571def __init__ ( self , cfg ) : 572lang_bits = cfg [ "language_target" ] . split ( " | " ) 573self . cfg = cfg 574self . language_target = None 575self . translator = None 576self . tokenizer = None 577if len ( lang_bits ) != 2 : 578return 579self . language_target = lang_bits [ 1 ] 580 581( "Translation requested" , file = sys . stderr ) 582# The ctranslate2 model converter needs torch. Grr. 583if not install_in_venv ([ "torch==2.2.2" ]) : 584return 585 586output_dir = "Resources/" + cfg [ "model_translation" ] 587# Provided by ctranslate2 Python package 588cmd = "ct2-transformers-converter.exe --model facebook/" + \ 589cfg [ "model_translation" ] + " --output_dir " + output_dir 590 591( f"Fetching translation algorithm ( { cfg [ 'model_translation' ] } )" , 592file = sys . stderr ) 593if not os . path . exists ( output_dir ) : 594ct2_proc = subprocess . Popen ( 595cmd . split () , 596stdout = subprocess . PIPE , 597stderr = subprocess . PIPE ) 598ct2_stdout , ct2_stderr = ct2_proc . communicate () 599ct2_stdout = ct2_stdout . decode ( "utf-8" ) 600ct2_stderr = ct2_stderr . decode ( "utf-8" ) 601( ct2_stdout , file = sys . stderr ) 602( ct2_stderr , file = sys . stderr ) 603if ct2_proc . returncode != 0 : 604( f"Failed to get NLLB model: ct2 process exited with " 605"{ct2_proc.returncode}" , file = sys . stderr ) 606( f"Using model at { output_dir } " , file = sys . stderr ) 607 608model_device = "cuda" 609if cfg [ "use_cpu" ] : 610model_device = "cpu" 611 612self . translator = ctranslate2 . Translator ( output_dir , 613device = model_device , 614device_index = cfg [ "gpu_idx" ] , 615compute_type = cfg [ "compute_type" ]) 616 617whisper_lang = cfg [ "language" ] 618nllb_lang = lang_compat . whisper_to_nllb [ whisper_lang ] 619 620self . tokenizer = transformers . AutoTokenizer . from_pretrained ( 621"facebook/" + cfg [ "model_translation" ] , 622src_lang = nllb_lang ) 623 624( f"Translation ready to go" , file = sys . stderr ) 625 626def transform ( self , commit : TranscriptCommit ) -> TranscriptCommit : 627if not self . language_target : 628return commit 629 630def _translate_text ( text : str ) -> str : 631 632whisper_lang = self . cfg [ "language" ] 633nllb_lang = lang_compat . whisper_to_nllb [ whisper_lang ] 634ss_lang = lang_compat . nllb_to_ss [ nllb_lang ] 635sentences = split_text_into_sentences ( text , language = ss_lang ) 636 637translated_sentences = [] 638for sentence in sentences : 639source = self . tokenizer . convert_ids_to_tokens ( self . tokenizer . encode ( sentence )) 640target_prefix = [ self . language_target ] 641results = self . translator . translate_batch ([ source ] , target_prefix = [ target_prefix ]) 642target = results [ 0 ] . hypotheses [ 0 ][ 1 : ] 643translated_sentence = self . tokenizer . decode ( self . tokenizer . convert_tokens_to_ids ( target )) 644translated_sentences . append ( translated_sentence ) 645translated = " " . join ( translated_sentences ) 646if cfg [ "enable_orig_lang" ] and len ( sentences ) > 0 : 647translated += f" ( { text } )" 648return translated 649 650commit . delta = _translate_text ( commit . delta ) 651commit . preview = _translate_text ( commit . preview ) 652return commit 653 654class LowercasePlugin ( StreamingPlugin ) : 655def __init__ ( self , cfg ) : 656self . cfg = cfg 657 658def transform ( self , commit : TranscriptCommit ) -> TranscriptCommit : 659if self . cfg [ "enable_lowercase_filter" ] : 660commit . delta = commit . delta . lower () 661commit . preview = commit . preview . lower () 662return commit 663 664class UppercasePlugin ( StreamingPlugin ) : 665def __init__ ( self , cfg ) : 666self . cfg = cfg 667 668def transform ( self , commit : TranscriptCommit ) -> TranscriptCommit : 669if self . cfg [ "enable_uppercase_filter" ] : 670commit . delta = commit . delta . upper () 671commit . preview = commit . preview . upper () 672return commit 673 674class UwuPlugin ( StreamingPlugin ) : 675def __init__ ( self , cfg ) : 676self . cfg = cfg 677 678def transform ( self , commit : TranscriptCommit ) -> TranscriptCommit : 679if self . cfg [ "enable_uwu_filter" ] : 680def _to_uwu ( s : str ) -> str : 681uwu_proc = subprocess . Popen ([ "Resources/Uwu/Uwwwu.exe" , s ] , 682stdout = subprocess . PIPE , 683stderr = subprocess . PIPE ) 684uwu_stdout , uwu_stderr = uwu_proc . communicate () 685uwu_text = uwu_stdout . decode ( "utf-8" ) 686uwu_text = uwu_text . replace ( " \n " , "" ) 687uwu_text = uwu_text . replace ( " \r " , "" ) 688if uwu_text . isspace () : 689return "" 690# Guarantee that the segment starts with a single space and 691# doesn't end with whitespace. 692uwu_text = " " + uwu_text . lstrip () . rstrip () 693return uwu_text 694commit . delta = _to_uwu ( commit . delta ) 695commit . preview = _to_uwu ( commit . preview ) 696return commit 697 698class ProfanityPlugin ( StreamingPlugin ) : 699def __init__ ( self , cfg ) : 700self . cfg = cfg 701en_profanity_path = os . path . abspath ( "Resources/Profanity/en" ) 702self . filter = ProfanityFilter ( en_profanity_path ) 703if cfg [ "enable_profanity_filter" ] : 704self . filter . load () 705 706def transform ( self , commit : TranscriptCommit ) -> TranscriptCommit : 707if self . cfg [ "enable_profanity_filter" ] : 708commit . delta = self . filter . filter ( commit . delta ) 709commit . preview = self . filter . filter ( commit . preview ) 710return commit 711 712class PresentationFilter : 713def __init__ ( self ) : 714pass 715 716def transform ( self , transcript : str , preview : str ) -> typing . Tuple [ str , str ] : 717return transcript , preview 718 719def stop ( self ) : 720pass 721 722class TrailingPeriodFilter ( PresentationFilter ) : 723def __init__ ( self , cfg ) : 724self . cfg = cfg 725 726def transform ( self , transcript : str , preview : str ) -> typing . Tuple [ str , str ] : 727if self . cfg [ "remove_trailing_period" ] : 728def _remove_trailing_period ( s : str ) -> str : 729if len ( s ) > 0 and s [ - 1 ] == '.' and not s . endswith ( "..." ) : 730s = s [ 0 : len ( s ) - 1 ] 731return s 732if len ( preview ) == 0 : 733( "here" ) 734transcript = _remove_trailing_period ( transcript ) 735else : 736( "there" ) 737preview = _remove_trailing_period ( preview ) 738return transcript , preview 739 740class OscPager : 741def __init__ ( self , cfg ) : 742self . osc_state = osc_ctrl . OscState ( cfg [ "chars_per_sync" ] , 743cfg [ "rows" ] , 744cfg [ "cols" ] , 745cfg [ "bytes_per_char" ]) 746self . cfg = cfg 747self . next_sync_window = time . time () 748 749def page ( self , text ) : 750if self . cfg [ "use_builtin" ] : 751osc_ctrl . pageMessageBuiltin ( self . cfg , self . osc_state , text ) 752self . bumpSyncWindow ( amount_s = 1.5 ) 753else : 754osc_ctrl . pageMessage ( self . cfg , self . osc_state , text , EmotesState ()) 755self . bumpSyncWindow () 756 757def bumpSyncWindow ( self , amount_s = osc_ctrl . SYNC_DELAY_S ) : 758self . next_sync_window = time . time () + amount_s 759 760def getSyncWindow ( self ) : 761while time . time () < self . next_sync_window : 762time . sleep ( 0.01 ) 763 764def clear ( self ) : 765osc_ctrl . clear ( self . osc_state ) 766self . bumpSyncWindow () 767 768def toggleBoard ( self , state : bool ) : 769osc_ctrl . toggleBoard ( self . osc_state . client , state ) 770self . bumpSyncWindow () 771 772def lockWorld ( self , state : bool ) : 773osc_ctrl . lockWorld ( self . osc_state . client , state ) 774self . bumpSyncWindow () 775 776def ellipsis ( self , state : bool ) : 777osc_ctrl . ellipsis ( self . osc_state . client , state ) 778self . bumpSyncWindow () 779 780def transcriptionThread ( ctrl : ThreadControl ) : 781last_stable_commit = None 782 783while ctrl . run_app : 784time . sleep ( ctrl . cfg [ "transcription_loop_delay_ms" ] / 1000.0 ) ; 785 786op = None 787 788commit = ctrl . committer . getDelta () 789 790for plugin in ctrl . plugins : 791commit = plugin . transform ( commit ) 792 793if len ( commit . delta ) > 0 or len ( commit . preview ) > 0 : 794# Avoid re-sending text after long pauses. User controls the length 795# of the pause in the UI. 796if ctrl . cfg [ "reset_after_silence_s" ] > 0 : 797silence_duration = 0 798if last_stable_commit : 799last_commit_end_ts = \ 800last_stable_commit . start_ts + \ 801last_stable_commit . duration_s 802silence_duration = commit . start_ts - last_commit_end_ts 803if silence_duration > ctrl . cfg [ "reset_after_silence_s" ] : 804( f"Resetting transcript after { silence_duration } -second " 805"silence" , file = sys . stderr ) 806ctrl . transcript = "" 807ctrl . preview = "" 808if commit . delta : 809last_stable_commit = commit 810 811# Hard-cap displayed transcript length at 4k characters to prevent 812# runaway memory use in UI. Keep the full transcript to avoid 813# breaking OSC pager. 814transcript = ctrl . transcript [ - 4096 : ] + commit . delta 815preview = commit . preview 816 817for filt in ctrl . filters : 818transcript , preview = filt . transform ( transcript , preview ) 819 820try : 821( f"Transcript: { transcript } " ) 822except UnicodeEncodeError : 823( "Failed to encode transcript - discarding delta" , 824file = sys . stderr ) 825continue 826try : 827( f"Preview: { preview } " ) 828except UnicodeEncodeError : 829( "Failed to encode preview - discarding" , file = sys . stderr ) 830 831if cfg [ "enable_debug_mode" ] : 832( f"commit latency: { commit . latency_s } " , file = sys . stderr ) 833( f"commit thresh: { commit . thresh_at_commit } " , 834file = sys . stderr ) 835 836if len ( ctrl . transcript ) > 0 and \ 837( not ctrl . transcript . endswith ( ' ' )) and \ 838( not commit . delta . startswith ( ' ' )) : 839commit . delta = ' ' + commit . delta 840if len ( commit . delta ) > 0 and \ 841( not commit . delta . endswith ( ' ' )) and \ 842( not commit . preview . startswith ( ' ' )) : 843commit . preview = ' ' + commit . preview 844 845ctrl . transcript += commit . delta 846ctrl . preview = ctrl . transcript + commit . preview 847for plugin in ctrl . plugins : 848plugin . stop () 849for filt in ctrl . filters : 850filt . stop () 851 852def vrInputThread ( ctrl : ThreadControl ) : 853RECORD_STATE = 0 854PAUSE_STATE = 1 855state = PAUSE_STATE 856 857hand_id = ctrl . cfg [ "button" ] . split ()[ 0 ] 858button_id = ctrl . cfg [ "button" ] . split ()[ 1 ] 859 860# Rough description of state machine: 861# Single short press: toggle transcription 862# Medium press: dismiss custom chatbox 863# Long press: update chatbox in place 864# Medium press + long press: type transcription 865 866last_rising = time . time () 867last_medium_press_end = 0 868 869waveform0 = os . path . abspath ( "Resources/Sounds/Noise_On_Quiet.wav" ) 870waveform1 = os . path . abspath ( "Resources/Sounds/Noise_Off_Quiet.wav" ) 871waveform2 = os . path . abspath ( "Resources/Sounds/Dismiss_Noise_Quiet.wav" ) 872waveform3 = os . path . abspath ( "Resources/Sounds/KB_Noise_Off_Quiet.wav" ) 873 874button_generator = steamvr . pollButtonPress ( hand = hand_id , button = button_id , 875ctrl = ctrl ) 876while ctrl . run_app : 877time . sleep ( 0.01 ) 878try : 879event = next ( button_generator ) 880except StopIteration : 881break 882 883if event . opcode == steamvr . EVENT_RISING_EDGE : 884last_rising = time . time () 885 886if state == PAUSE_STATE : 887ctrl . stream . pause ( False ) 888ctrl . stream . getSamples () 889 890elif event . opcode == steamvr . EVENT_FALLING_EDGE : 891now = time . time () 892if now - last_rising > 1.5 : 893# Long press: treat as the end of transcription. 894state = PAUSE_STATE 895 896ctrl . stream . pause ( True ) 897 898if last_rising - last_medium_press_end < 1.0 : 899# Type transcription 900if ctrl . cfg [ "enable_local_beep" ] : 901winsound . PlaySound ( waveform3 , winsound . SND_FILENAME | winsound . SND_ASYNC ) 902pass 903# TODO(yum) this is broken! Audio is not being collected 904# while paused anymore. 905#keyboard.write(ctrl.preview) 906else : 907if ctrl . cfg [ "enable_local_beep" ] : 908winsound . PlaySound ( waveform1 , winsound . SND_FILENAME | winsound . SND_ASYNC ) 909pass 910 911elif now - last_rising > 0.5 : 912# Medium press 913( "CLEARING" , file = sys . stderr ) 914last_medium_press_end = now 915state = PAUSE_STATE 916 917if ctrl . cfg [ "enable_local_beep" ] : 918winsound . PlaySound ( waveform2 , winsound . SND_FILENAME | winsound . SND_ASYNC ) 919pass 920 921if not ctrl . cfg [ "use_builtin" ] : 922ctrl . pager . getSyncWindow () 923ctrl . pager . toggleBoard ( False ) 924 925# Flush the *entire* pipeline. 926ctrl . stream . pause ( True ) 927ctrl . stream . getSamples () 928ctrl . collector . dropAudio () 929ctrl . pager . clear () 930if ctrl . cfg [ "enable_lock_at_spawn" ] : 931# Give the board 0.5 seconds to disappear before unlocking from 932# world space. 933time . sleep ( 0.5 ) 934ctrl . pager . lockWorld ( False ) 935else : 936# Short hold 937if state == RECORD_STATE : 938( "PAUSED" , file = sys . stderr ) 939state = PAUSE_STATE 940if not ctrl . cfg [ "use_builtin" ] and not ctrl . cfg [ "enable_lock_at_spawn" ] : 941ctrl . pager . getSyncWindow () 942ctrl . pager . lockWorld ( True ) 943 944ctrl . stream . pause ( True ) 945 946if ctrl . cfg [ "enable_local_beep" ] : 947winsound . PlaySound ( waveform1 , winsound . SND_FILENAME | winsound . SND_ASYNC ) 948pass 949elif state == PAUSE_STATE : 950( "RECORDING" , file = sys . stderr ) 951state = RECORD_STATE 952if not ctrl . cfg [ "use_builtin" ] : 953ctrl . pager . getSyncWindow () 954ctrl . pager . toggleBoard ( True ) 955ctrl . pager . lockWorld ( ctrl . cfg [ "enable_lock_at_spawn" ]) 956ctrl . pager . ellipsis ( True ) 957if ctrl . cfg [ "reset_on_toggle" ] : 958if ctrl . cfg [ "enable_debug_mode" ] : 959( "Toggle detected, dropping transcript (3)" , 960file = sys . stderr ) 961ctrl . transcript = "" 962ctrl . preview = "" 963#audio_state.drop_transcription = True 964else : 965if ctrl . cfg [ "enable_debug_mode" ] : 966( "Toggle detected, committing preview text (3)" , file = sys . stderr ) 967#audio_state.text += audio_state.preview_text 968 969ctrl . stream . pause ( False ) 970ctrl . pager . clear () 971 972if ctrl . cfg [ "enable_local_beep" ] : 973winsound . PlaySound ( waveform0 , winsound . SND_FILENAME | winsound . SND_ASYNC ) 974pass 975 976def kbInputThread ( ctrl : ThreadControl ) : 977machine = keybind_event_machine . KeybindEventMachine ( ctrl . cfg [ "keybind" ]) 978last_press_time = 0 979 980# double pressing the keybind 981double_press_timeout = 0.5 982 983RECORD_STATE = 0 984PAUSE_STATE = 1 985state = PAUSE_STATE 986 987waveform0 = os . path . abspath ( "Resources/Sounds/Noise_On_Quiet.wav" ) 988waveform1 = os . path . abspath ( "Resources/Sounds/Noise_Off_Quiet.wav" ) 989waveform2 = os . path . abspath ( "Resources/Sounds/Dismiss_Noise_Quiet.wav" ) 990waveform3 = os . path . abspath ( "Resources/Sounds/KB_Noise_Off_Quiet.wav" ) 991 992while ctrl . run_app : 993time . sleep ( 0.01 ) 994 995cur_press_time = machine . getNextPressTime () 996if cur_press_time == 0 : 997continue 998 999EVENT_SINGLE_PRESS = 0 1000EVENT_DOUBLE_PRESS = 1 1001if last_press_time == 0 : 1002event = EVENT_SINGLE_PRESS 1003elif cur_press_time - last_press_time < double_press_timeout : 1004event = EVENT_DOUBLE_PRESS 1005else : 1006event = EVENT_SINGLE_PRESS 1007last_press_time = cur_press_time 1008 1009if event == EVENT_DOUBLE_PRESS : 1010( "CLEARING" , file = sys . stderr ) 1011state = PAUSE_STATE 1012 1013if ctrl . cfg [ "enable_local_beep" ] : 1014winsound . PlaySound ( waveform2 , winsound . SND_FILENAME | winsound . SND_ASYNC ) 1015pass 1016 1017if not ctrl . cfg [ "use_builtin" ] : 1018ctrl . pager . getSyncWindow () 1019ctrl . pager . toggleBoard ( False ) 1020 1021# Flush the *entire* pipeline. 1022ctrl . stream . pause ( True ) 1023ctrl . stream . getSamples () 1024ctrl . collector . dropAudio () 1025ctrl . pager . clear () 1026if ctrl . cfg [ "enable_lock_at_spawn" ] : 1027# Give the board 0.5 seconds to disappear before unlocking from 1028# world space. 1029time . sleep ( 0.5 ) 1030ctrl . pager . lockWorld ( False ) 1031continue 1032 1033# Short hold 1034if state == RECORD_STATE : 1035( "PAUSED" , file = sys . stderr ) 1036state = PAUSE_STATE 1037if not ctrl . cfg [ "use_builtin" ] and not ctrl . cfg [ "enable_lock_at_spawn" ] : 1038ctrl . pager . getSyncWindow () 1039ctrl . pager . lockWorld ( True ) 1040 1041ctrl . stream . pause ( True ) 1042 1043if ctrl . cfg [ "enable_local_beep" ] : 1044winsound . PlaySound ( waveform1 , winsound . SND_FILENAME | winsound . SND_ASYNC ) 1045pass 1046elif state == PAUSE_STATE : 1047( "RECORDING" , file = sys . stderr ) 1048state = RECORD_STATE 1049if not ctrl . cfg [ "use_builtin" ] : 1050ctrl . pager . getSyncWindow () 1051ctrl . pager . toggleBoard ( True ) 1052ctrl . pager . lockWorld ( ctrl . cfg [ "enable_lock_at_spawn" ]) 1053ctrl . pager . ellipsis ( True ) 1054if ctrl . cfg [ "reset_on_toggle" ] : 1055if ctrl . cfg [ "enable_debug_mode" ] : 1056( "Toggle detected, dropping transcript (2)" , 1057file = sys . stderr ) 1058ctrl . transcript = "" 1059ctrl . preview = "" 1060else : 1061if ctrl . cfg [ "enable_debug_mode" ] : 1062( "Toggle detected, committing preview text (2)" , 1063file = sys . stderr ) 1064#audio_state.text += audio_state.preview_text 1065 1066ctrl . stream . pause ( False ) 1067ctrl . pager . clear () 1068 1069if ctrl . cfg [ "enable_local_beep" ] : 1070winsound . PlaySound ( waveform0 , winsound . SND_FILENAME | winsound . SND_ASYNC ) 1071pass 1072 1073def oscThread ( ctrl : ThreadControl ) : 1074while ctrl . run_app : 1075ctrl . pager . getSyncWindow () 1076ctrl . pager . page ( ctrl . preview ) 1077time . sleep ( 0.01 ) 1078 1079def run ( cfg ) : 1080stream = MicStream ( cfg [ "microphone" ]) 1081 1082collector = AudioCollector ( stream ) 1083#collector = LengthEnforcingAudioCollector(collector, 5.0) 1084collector = NormalizingAudioCollector ( collector ) 1085collector = CompressingAudioCollector ( collector ) 1086whisper = Whisper ( collector , cfg ) 1087segmenter = AudioSegmenter ( min_silence_ms = cfg [ "min_silence_duration_ms" ] , 1088max_speech_s = cfg [ "max_speech_duration_s" ]) 1089committer = VadCommitter ( cfg , collector , whisper , segmenter ) 1090pager = OscPager ( cfg ) 1091 1092ctrl = ThreadControl ( cfg ) 1093ctrl . stream = stream 1094ctrl . collector = collector 1095ctrl . whisper = whisper 1096ctrl . committer = committer 1097 1098ctrl . plugins = [] 1099ctrl . plugins . append ( TranslationPlugin ( cfg )) 1100ctrl . plugins . append ( UppercasePlugin ( cfg )) 1101ctrl . plugins . append ( LowercasePlugin ( cfg )) 1102ctrl . plugins . append ( ProfanityPlugin ( cfg )) 1103ctrl . plugins . append ( UwuPlugin ( cfg )) 1104ctrl . plugins . append ( BrowserSource ( cfg )) 1105 1106ctrl . filters = [] 1107ctrl . filters . append ( TrailingPeriodFilter ( cfg )) 1108 1109ctrl . pager = pager 1110ctrl . transcript = "" 1111ctrl . preview = "" 1112 1113transcribe_audio_thd = threading . Thread ( target = transcriptionThread , args = [ ctrl ]) 1114transcribe_audio_thd . daemon = True 1115transcribe_audio_thd . start () 1116 1117vr_input_thd = threading . Thread ( target = vrInputThread , args = [ ctrl ]) 1118vr_input_thd . daemon = True 1119vr_input_thd . start () 1120 1121kb_input_thd = threading . Thread ( target = kbInputThread , args = [ ctrl ]) 1122kb_input_thd . daemon = True 1123kb_input_thd . start () 1124 1125osc_thd = threading . Thread ( target = oscThread , args = [ ctrl ]) 1126osc_thd . daemon = True 1127osc_thd . start () 1128 1129for line in sys . stdin : 1130if "exit" in line or "quit" in line : 1131( "Exit requested" , file = sys . stderr ) 1132break 1133 1134ctrl . run_app = False 1135( "Join transcription thread" , file = sys . stderr ) 1136transcribe_audio_thd . join () 1137( "Join vr input thread" , file = sys . stderr ) 1138vr_input_thd . join () 1139( "Join kb input thread" , file = sys . stderr ) 1140kb_input_thd . join () 1141( "Join osc thread" , file = sys . stderr ) 1142osc_thd . join () 1143( "Done" , file = sys . stderr ) 1144 1145if __name__ == "__main__" : 1146sys . stdout . reconfigure ( encoding = "utf-8" ) 1147 1148parser = argparse . ArgumentParser () 1149parser . add_argument ( "--config" , type = str , help = "Path to app config YAML file." ) 1150args = parser . parse_args () 1151 1152cfg = app_config . getConfig ( args . config ) 1153 1154experiments = [ 1155( "Evaluate/declaration_short/audio.mp3" , 1156"Evaluate/declaration_short/control.txt" ) , 1157( "Evaluate/moist/audio.mp3" , 1158"Evaluate/moist/control.txt" ) , 1159( "Evaluate/vei/audio.mp3" , 1160"Evaluate/vei/control.txt" ) , 1161] 1162 1163if False : 1164sum = 0 1165for audio , control in experiments : 1166( f"Run experiment { audio } :: { control } " , file = sys . stderr ) 1167sum += evaluate ( cfg , audio , control ) 1168( f"Total score: { sum } " , file = sys . stderr ) 1169else : 1170#optimize(cfg, experiments) 1171run ( cfg ) 1172