yum-slop/TaSTT
Free self-hosted STT for VRChat.
git clone https://git.yummers.dev/yum-slop/TaSTT
4fec36c
v0.19.2
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 , 550preview , 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 ) 586if not install_in_venv ([ "torch" , "sentencepiece" ]) : 587return 588 589output_dir = "Resources/" + cfg [ "model_translation" ] 590# Provided by ctranslate2 Python package 591cmd = "ct2-transformers-converter.exe --model facebook/" + \ 592cfg [ "model_translation" ] + " --output_dir " + output_dir 593 594( f"Fetching translation algorithm ( { cfg [ 'model_translation' ] } )" , 595file = sys . stderr ) 596if not os . path . exists ( output_dir ) : 597ct2_proc = subprocess . Popen ( 598cmd . split () , 599stdout = subprocess . PIPE , 600stderr = subprocess . PIPE ) 601ct2_stdout , ct2_stderr = ct2_proc . communicate () 602ct2_stdout = ct2_stdout . decode ( "utf-8" ) 603ct2_stderr = ct2_stderr . decode ( "utf-8" ) 604( ct2_stdout , file = sys . stderr ) 605( ct2_stderr , file = sys . stderr ) 606if ct2_proc . returncode != 0 : 607( f"Failed to get NLLB model: ct2 process exited with " 608"{ct2_proc.returncode}" , file = sys . stderr ) 609( f"Using model at { output_dir } " , file = sys . stderr ) 610 611self . translator = ctranslate2 . Translator ( output_dir ) 612 613whisper_lang = cfg [ "language" ] 614nllb_lang = lang_compat . whisper_to_nllb [ whisper_lang ] 615 616self . tokenizer = transformers . AutoTokenizer . from_pretrained ( 617"facebook/" + cfg [ "model_translation" ] , 618src_lang = nllb_lang ) 619 620( f"Translation ready to go" , file = sys . stderr ) 621 622def transform ( self , commit : TranscriptCommit ) -> TranscriptCommit : 623if not self . language_target : 624return commit 625 626def _translate_text ( text : str ) -> str : 627 628whisper_lang = self . cfg [ "language" ] 629nllb_lang = lang_compat . whisper_to_nllb [ whisper_lang ] 630ss_lang = lang_compat . nllb_to_ss [ nllb_lang ] 631sentences = split_text_into_sentences ( text , language = ss_lang ) 632 633translated_sentences = [] 634for sentence in sentences : 635source = self . tokenizer . convert_ids_to_tokens ( self . tokenizer . encode ( sentence )) 636target_prefix = [ self . language_target ] 637results = self . translator . translate_batch ([ source ] , target_prefix = [ target_prefix ]) 638target = results [ 0 ] . hypotheses [ 0 ][ 1 : ] 639translated_sentence = self . tokenizer . decode ( self . tokenizer . convert_tokens_to_ids ( target )) 640translated_sentences . append ( translated_sentence ) 641translated = " " . join ( translated_sentences ) 642return translated 643 644commit . delta = _translate_text ( commit . delta ) 645commit . preview = _translate_text ( commit . preview ) 646return commit 647 648class LowercasePlugin ( StreamingPlugin ) : 649def __init__ ( self , cfg ) : 650self . cfg = cfg 651 652def transform ( self , commit : TranscriptCommit ) -> TranscriptCommit : 653if self . cfg [ "enable_lowercase_filter" ] : 654commit . delta = commit . delta . lower () 655commit . preview = commit . preview . lower () 656return commit 657 658class UppercasePlugin ( StreamingPlugin ) : 659def __init__ ( self , cfg ) : 660self . cfg = cfg 661 662def transform ( self , commit : TranscriptCommit ) -> TranscriptCommit : 663if self . cfg [ "enable_uppercase_filter" ] : 664commit . delta = commit . delta . upper () 665commit . preview = commit . preview . upper () 666return commit 667 668class UwuPlugin ( StreamingPlugin ) : 669def __init__ ( self , cfg ) : 670self . cfg = cfg 671 672def transform ( self , commit : TranscriptCommit ) -> TranscriptCommit : 673if self . cfg [ "enable_uwu_filter" ] : 674def _to_uwu ( s : str ) -> str : 675uwu_proc = subprocess . Popen ([ "Resources/Uwu/Uwwwu.exe" , s ] , 676stdout = subprocess . PIPE , 677stderr = subprocess . PIPE ) 678uwu_stdout , uwu_stderr = uwu_proc . communicate () 679uwu_text = uwu_stdout . decode ( "utf-8" ) 680uwu_text = uwu_text . replace ( " \n " , "" ) 681uwu_text = uwu_text . replace ( " \r " , "" ) 682if uwu_text . isspace () : 683return "" 684# Guarantee that the segment starts with a single space and 685# doesn't end with whitespace. 686uwu_text = " " + uwu_text . lstrip () . rstrip () 687return uwu_text 688commit . delta = _to_uwu ( commit . delta ) 689commit . preview = _to_uwu ( commit . preview ) 690return commit 691 692class ProfanityPlugin ( StreamingPlugin ) : 693def __init__ ( self , cfg ) : 694self . cfg = cfg 695en_profanity_path = os . path . abspath ( "Resources/Profanity/en" ) 696self . filter = ProfanityFilter ( en_profanity_path ) 697if cfg [ "enable_profanity_filter" ] : 698self . filter . load () 699 700def transform ( self , commit : TranscriptCommit ) -> TranscriptCommit : 701if self . cfg [ "enable_profanity_filter" ] : 702commit . delta = self . filter . filter ( commit . delta ) 703commit . preview = self . filter . filter ( commit . preview ) 704return commit 705 706class PresentationFilter : 707def __init__ ( self ) : 708pass 709 710def transform ( self , transcript : str , preview : str ) -> typing . Tuple [ str , str ] : 711return transcript , preview 712 713def stop ( self ) : 714pass 715 716class TrailingPeriodFilter ( PresentationFilter ) : 717def __init__ ( self , cfg ) : 718self . cfg = cfg 719 720def transform ( self , transcript : str , preview : str ) -> typing . Tuple [ str , str ] : 721if self . cfg [ "remove_trailing_period" ] : 722def _remove_trailing_period ( s : str ) -> str : 723if len ( s ) > 0 and s [ - 1 ] == '.' and not s . endswith ( "..." ) : 724s = s [ 0 : len ( s ) - 1 ] 725return s 726if len ( preview ) == 0 : 727( "here" ) 728transcript = _remove_trailing_period ( transcript ) 729else : 730( "there" ) 731preview = _remove_trailing_period ( preview ) 732return transcript , preview 733 734class OscPager : 735def __init__ ( self , cfg ) : 736self . osc_state = osc_ctrl . OscState ( cfg [ "chars_per_sync" ] , 737cfg [ "rows" ] , 738cfg [ "cols" ] , 739cfg [ "bytes_per_char" ]) 740self . cfg = cfg 741self . next_sync_window = time . time () 742 743def page ( self , text ) : 744if self . cfg [ "use_builtin" ] : 745osc_ctrl . pageMessageBuiltin ( self . cfg , self . osc_state , text ) 746self . bumpSyncWindow ( amount_s = 1.5 ) 747else : 748osc_ctrl . pageMessage ( self . cfg , self . osc_state , text , EmotesState ()) 749self . bumpSyncWindow () 750 751def bumpSyncWindow ( self , amount_s = osc_ctrl . SYNC_DELAY_S ) : 752self . next_sync_window = time . time () + amount_s 753 754def getSyncWindow ( self ) : 755while time . time () < self . next_sync_window : 756time . sleep ( 0.01 ) 757 758def clear ( self ) : 759osc_ctrl . clear ( self . osc_state ) 760self . bumpSyncWindow () 761 762def toggleBoard ( self , state : bool ) : 763osc_ctrl . toggleBoard ( self . osc_state . client , state ) 764self . bumpSyncWindow () 765 766def lockWorld ( self , state : bool ) : 767osc_ctrl . lockWorld ( self . osc_state . client , state ) 768self . bumpSyncWindow () 769 770def ellipsis ( self , state : bool ) : 771osc_ctrl . ellipsis ( self . osc_state . client , state ) 772self . bumpSyncWindow () 773 774def evaluate ( cfg , 775audio_path : str , 776control_path : str ) : 777stream = DiskStream ( audio_path ) 778 779collector = AudioCollector ( stream ) 780collector = CompressingAudioCollector ( collector ) 781whisper = Whisper ( collector , cfg ) 782segmenter = AudioSegmenter ( min_silence_ms = 250 ) 783committer = VadCommitter ( cfg , collector , whisper , segmenter ) 784transcript = "" 785commits = [] 786last_commit_ts = None 787 788while True : 789time . sleep ( .005 ) 790 791commit = committer . getDelta () 792 793if last_commit_ts != None and collector . now () - last_commit_ts > 30 : 794break 795 796if len ( commit . delta ) > 0 : 797( f"Commit latency: { commit . latency_s } " , file = sys . stderr ) 798commits . append ( commit ) 799last_commit_ts = collector . now () 800 801transcript += commit . delta 802preview = commit . preview 803 804if False and len ( commit . delta ) : 805( f"transcript: { transcript } " , file = sys . stderr ) 806( f"commit latency: { commit . latency_s } " , file = sys . stderr ) 807( f"commit thresh: { commit . thresh_at_commit } " , file = sys . stderr ) 808 809with open ( control_path , "r" ) as f : 810control = f . read () 811normalizer = EnglishTextNormalizer () 812control = normalizer ( control ) 813experiment = normalizer ( transcript ) 814 815sum_latency = 0 816for commit in commits : 817sum_latency += commit . latency_s 818avg_latency = sum_latency / len ( commits ) 819 820dist = editdistance . eval ( control , experiment ) 821 822( f"RESULTS" , file = sys . stderr ) 823( f"edit distance: { dist } " , file = sys . stderr ) 824( f"avg latency: { avg_latency } " , file = sys . stderr ) 825( f"num commits: { len ( commits ) } " , file = sys . stderr ) 826( f"final transcript: { transcript } " , file = sys . stderr ) 827 828score = ( 3 + ( dist / len ( control )) * 100 ) * avg_latency 829( f"score: { score } " , file = sys . stderr ) 830return score 831 832def optimize ( cfg , 833experiments : typing . List [ typing . Tuple [ str , str ]]) : 834 835install_in_venv ([ "git+https://github.com/openai/whisper.git" , 836"scipy" ]) 837 838from scipy . optimize import minimize 839from whisper . normalizers import EnglishTextNormalizer 840 841def wrapper_to_optimize ( x ) : 842s = 0 843for audio_path , control_path in experiments : 844s += evaluate ( 845cfg , 846audio_path , 847control_path , 848int ( x [ 0 ]) , # last_n_must_match 8492 ** x [ 1 ] , # edit_thresh_min 850( 2 ** x [ 2 ]) - 1 , # edit_thresh_grow_begin_s 851x [ 3 ] , # edit_thresh_grow_halflife_s 852x [ 4 ] # min_segment_age_s 853) 854return s 855 856initial_guess = [ 2.3 , 1 , 1.75 , 1.5 , 0.5 ] 857bounds = [ 858( 2 , 3 ) , # last_n_must_match 859( 1 , 4 ) , # edit_thresh_min 860( 0 , 2.5 ) , # edit_thresh_grow_begin_s 861( 0.1 , 2 ) , # edit_thresh_grow_halflife_s 862( 0 , 3 ) # min_segment_age_s 863] 864 865result = minimize ( 866wrapper_to_optimize , 867initial_guess , 868bounds = bounds , 869method = 'L-BFGS-B' , 870options = { "maxfun" : int (( 60 / .5 ) * 12 ) , 871"eps" : 0.2 } , 872) 873 874optimized_params = result . x 875 876( "Optimized Parameters:" , file = sys . stderr ) 877( f"last_n_must_match: { int ( optimized_params [ 0 ]) } " , file = sys . stderr ) 878( f"edit_thresh_min: { optimized_params [ 1 ] } " , file = sys . stderr ) 879( f"edit_thresh_grow_begin_s: { optimized_params [ 2 ] } " , file = sys . stderr ) 880( f"edit_thresh_grow_halflife_s: { optimized_params [ 3 ] } " , 881file = sys . stderr ) 882( f"min_segment_age_s: { optimized_params [ 4 ] } " , file = sys . stderr ) 883 884return optimized_params 885 886def transcriptionThread ( ctrl : ThreadControl ) : 887last_stable_commit = None 888 889while ctrl . run_app : 890time . sleep ( ctrl . cfg [ "transcription_loop_delay_ms" ] / 1000.0 ) ; 891 892op = None 893 894commit = ctrl . committer . getDelta () 895 896for plugin in ctrl . plugins : 897commit = plugin . transform ( commit ) 898 899if len ( commit . delta ) > 0 or len ( commit . preview ) > 0 : 900# Avoid re-sending text after long pauses. User controls the length 901# of the pause in the UI. 902if ctrl . cfg [ "reset_after_silence_s" ] > 0 : 903silence_duration = 0 904if last_stable_commit : 905last_commit_end_ts = \ 906last_stable_commit . start_ts + \ 907last_stable_commit . duration_s 908silence_duration = commit . start_ts - last_commit_end_ts 909if silence_duration > ctrl . cfg [ "reset_after_silence_s" ] : 910( f"Resetting transcript after { silence_duration } -second " 911"silence" , file = sys . stderr ) 912ctrl . transcript = "" 913ctrl . preview = "" 914if commit . delta : 915last_stable_commit = commit 916 917# Hard-cap displayed transcript length at 4k characters to prevent 918# runaway memory use in UI. Keep the full transcript to avoid 919# breaking OSC pager. 920transcript = ctrl . transcript [ - 4096 : ] + commit . delta 921preview = commit . preview 922 923for filt in ctrl . filters : 924transcript , preview = filt . transform ( transcript , preview ) 925 926try : 927( f"Transcript: { transcript } " ) 928except UnicodeEncodeError : 929( "Failed to encode transcript - discarding delta" , 930file = sys . stderr ) 931continue 932try : 933( f"Preview: { preview } " ) 934except UnicodeEncodeError : 935( "Failed to encode preview - discarding" , file = sys . stderr ) 936 937if cfg [ "enable_debug_mode" ] : 938( f"commit latency: { commit . latency_s } " , file = sys . stderr ) 939( f"commit thresh: { commit . thresh_at_commit } " , 940file = sys . stderr ) 941 942ctrl . transcript += commit . delta 943ctrl . preview = ctrl . transcript + commit . preview 944for plugin in ctrl . plugins : 945plugin . stop () 946for filt in ctrl . filters : 947filt . stop () 948 949def vrInputThread ( ctrl : ThreadControl ) : 950RECORD_STATE = 0 951PAUSE_STATE = 1 952state = PAUSE_STATE 953 954hand_id = ctrl . cfg [ "button" ] . split ()[ 0 ] 955button_id = ctrl . cfg [ "button" ] . split ()[ 1 ] 956 957# Rough description of state machine: 958# Single short press: toggle transcription 959# Medium press: dismiss custom chatbox 960# Long press: update chatbox in place 961# Medium press + long press: type transcription 962 963last_rising = time . time () 964last_medium_press_end = 0 965 966waveform0 = os . path . abspath ( "Resources/Sounds/Noise_On_Quiet.wav" ) 967waveform1 = os . path . abspath ( "Resources/Sounds/Noise_Off_Quiet.wav" ) 968waveform2 = os . path . abspath ( "Resources/Sounds/Dismiss_Noise_Quiet.wav" ) 969waveform3 = os . path . abspath ( "Resources/Sounds/KB_Noise_Off_Quiet.wav" ) 970 971button_generator = steamvr . pollButtonPress ( hand = hand_id , button = button_id , 972ctrl = ctrl ) 973while ctrl . run_app : 974time . sleep ( 0.01 ) 975try : 976event = next ( button_generator ) 977except StopIteration : 978break 979 980if event . opcode == steamvr . EVENT_RISING_EDGE : 981last_rising = time . time () 982 983if state == PAUSE_STATE : 984ctrl . stream . pause ( False ) 985ctrl . stream . getSamples () 986 987elif event . opcode == steamvr . EVENT_FALLING_EDGE : 988now = time . time () 989if now - last_rising > 1.5 : 990# Long press: treat as the end of transcription. 991state = PAUSE_STATE 992 993ctrl . stream . pause ( True ) 994 995if last_rising - last_medium_press_end < 1.0 : 996# Type transcription 997if ctrl . cfg [ "enable_local_beep" ] : 998winsound . PlaySound ( waveform3 , winsound . SND_FILENAME | winsound . SND_ASYNC ) 999pass 1000# TODO(yum) this is broken! Audio is not being collected 1001# while paused anymore. 1002#keyboard.write(ctrl.preview) 1003else : 1004if ctrl . cfg [ "enable_local_beep" ] : 1005winsound . PlaySound ( waveform1 , winsound . SND_FILENAME | winsound . SND_ASYNC ) 1006pass 1007 1008elif now - last_rising > 0.5 : 1009# Medium press 1010( "CLEARING" , file = sys . stderr ) 1011last_medium_press_end = now 1012state = PAUSE_STATE 1013 1014if ctrl . cfg [ "enable_local_beep" ] : 1015winsound . PlaySound ( waveform2 , winsound . SND_FILENAME | winsound . SND_ASYNC ) 1016pass 1017 1018if not ctrl . cfg [ "use_builtin" ] : 1019ctrl . pager . getSyncWindow () 1020ctrl . pager . toggleBoard ( False ) 1021 1022# Flush the *entire* pipeline. 1023ctrl . stream . pause ( True ) 1024ctrl . stream . getSamples () 1025ctrl . collector . dropAudio () 1026ctrl . pager . clear () 1027if ctrl . cfg [ "enable_lock_at_spawn" ] : 1028# Give the board 0.5 seconds to disappear before unlocking from 1029# world space. 1030time . sleep ( 0.5 ) 1031ctrl . pager . lockWorld ( False ) 1032else : 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 (3)" , 1057file = sys . stderr ) 1058ctrl . transcript = "" 1059ctrl . preview = "" 1060#audio_state.drop_transcription = True 1061else : 1062if ctrl . cfg [ "enable_debug_mode" ] : 1063( "Toggle detected, committing preview text (3)" , file = 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 kbInputThread ( ctrl : ThreadControl ) : 1074machine = keybind_event_machine . KeybindEventMachine ( ctrl . cfg [ "keybind" ]) 1075last_press_time = 0 1076 1077# double pressing the keybind 1078double_press_timeout = 0.5 1079 1080RECORD_STATE = 0 1081PAUSE_STATE = 1 1082state = PAUSE_STATE 1083 1084waveform0 = os . path . abspath ( "Resources/Sounds/Noise_On_Quiet.wav" ) 1085waveform1 = os . path . abspath ( "Resources/Sounds/Noise_Off_Quiet.wav" ) 1086waveform2 = os . path . abspath ( "Resources/Sounds/Dismiss_Noise_Quiet.wav" ) 1087waveform3 = os . path . abspath ( "Resources/Sounds/KB_Noise_Off_Quiet.wav" ) 1088 1089while ctrl . run_app : 1090time . sleep ( 0.01 ) 1091 1092cur_press_time = machine . getNextPressTime () 1093if cur_press_time == 0 : 1094continue 1095 1096EVENT_SINGLE_PRESS = 0 1097EVENT_DOUBLE_PRESS = 1 1098if last_press_time == 0 : 1099event = EVENT_SINGLE_PRESS 1100elif cur_press_time - last_press_time < double_press_timeout : 1101event = EVENT_DOUBLE_PRESS 1102else : 1103event = EVENT_SINGLE_PRESS 1104last_press_time = cur_press_time 1105 1106if event == EVENT_DOUBLE_PRESS : 1107( "CLEARING" , file = sys . stderr ) 1108state = PAUSE_STATE 1109 1110if ctrl . cfg [ "enable_local_beep" ] : 1111winsound . PlaySound ( waveform2 , winsound . SND_FILENAME | winsound . SND_ASYNC ) 1112pass 1113 1114if not ctrl . cfg [ "use_builtin" ] : 1115ctrl . pager . getSyncWindow () 1116ctrl . pager . toggleBoard ( False ) 1117 1118# Flush the *entire* pipeline. 1119ctrl . stream . pause ( True ) 1120ctrl . stream . getSamples () 1121ctrl . collector . dropAudio () 1122ctrl . pager . clear () 1123if ctrl . cfg [ "enable_lock_at_spawn" ] : 1124# Give the board 0.5 seconds to disappear before unlocking from 1125# world space. 1126time . sleep ( 0.5 ) 1127ctrl . pager . lockWorld ( False ) 1128continue 1129 1130# Short hold 1131if state == RECORD_STATE : 1132( "PAUSED" , file = sys . stderr ) 1133state = PAUSE_STATE 1134if not ctrl . cfg [ "use_builtin" ] and not ctrl . cfg [ "enable_lock_at_spawn" ] : 1135ctrl . pager . getSyncWindow () 1136ctrl . pager . lockWorld ( True ) 1137 1138ctrl . stream . pause ( True ) 1139 1140if ctrl . cfg [ "enable_local_beep" ] : 1141winsound . PlaySound ( waveform1 , winsound . SND_FILENAME | winsound . SND_ASYNC ) 1142pass 1143elif state == PAUSE_STATE : 1144( "RECORDING" , file = sys . stderr ) 1145state = RECORD_STATE 1146if not ctrl . cfg [ "use_builtin" ] : 1147ctrl . pager . getSyncWindow () 1148ctrl . pager . toggleBoard ( True ) 1149ctrl . pager . lockWorld ( ctrl . cfg [ "enable_lock_at_spawn" ]) 1150ctrl . pager . ellipsis ( True ) 1151if ctrl . cfg [ "reset_on_toggle" ] : 1152if ctrl . cfg [ "enable_debug_mode" ] : 1153( "Toggle detected, dropping transcript (2)" , 1154file = sys . stderr ) 1155ctrl . transcript = "" 1156ctrl . preview = "" 1157else : 1158if ctrl . cfg [ "enable_debug_mode" ] : 1159( "Toggle detected, committing preview text (2)" , 1160file = sys . stderr ) 1161#audio_state.text += audio_state.preview_text 1162 1163ctrl . stream . pause ( False ) 1164ctrl . pager . clear () 1165 1166if ctrl . cfg [ "enable_local_beep" ] : 1167winsound . PlaySound ( waveform0 , winsound . SND_FILENAME | winsound . SND_ASYNC ) 1168pass 1169 1170def oscThread ( ctrl : ThreadControl ) : 1171while ctrl . run_app : 1172ctrl . pager . getSyncWindow () 1173ctrl . pager . page ( ctrl . preview ) 1174time . sleep ( 0.01 ) 1175 1176def run ( cfg ) : 1177stream = MicStream ( cfg [ "microphone" ]) 1178 1179collector = AudioCollector ( stream ) 1180#collector = LengthEnforcingAudioCollector(collector, 5.0) 1181collector = NormalizingAudioCollector ( collector ) 1182collector = CompressingAudioCollector ( collector ) 1183whisper = Whisper ( collector , cfg ) 1184segmenter = AudioSegmenter ( min_silence_ms = cfg [ "min_silence_duration_ms" ] , 1185max_speech_s = cfg [ "max_speech_duration_s" ]) 1186committer = VadCommitter ( cfg , collector , whisper , segmenter ) 1187pager = OscPager ( cfg ) 1188 1189ctrl = ThreadControl ( cfg ) 1190ctrl . stream = stream 1191ctrl . collector = collector 1192ctrl . whisper = whisper 1193ctrl . committer = committer 1194 1195ctrl . plugins = [] 1196ctrl . plugins . append ( TranslationPlugin ( cfg )) 1197ctrl . plugins . append ( UppercasePlugin ( cfg )) 1198ctrl . plugins . append ( LowercasePlugin ( cfg )) 1199ctrl . plugins . append ( ProfanityPlugin ( cfg )) 1200ctrl . plugins . append ( UwuPlugin ( cfg )) 1201ctrl . plugins . append ( BrowserSource ( cfg )) 1202 1203ctrl . filters = [] 1204ctrl . filters . append ( TrailingPeriodFilter ( cfg )) 1205 1206ctrl . pager = pager 1207ctrl . transcript = "" 1208ctrl . preview = "" 1209 1210transcribe_audio_thd = threading . Thread ( target = transcriptionThread , args = [ ctrl ]) 1211transcribe_audio_thd . daemon = True 1212transcribe_audio_thd . start () 1213 1214vr_input_thd = threading . Thread ( target = vrInputThread , args = [ ctrl ]) 1215vr_input_thd . daemon = True 1216vr_input_thd . start () 1217 1218kb_input_thd = threading . Thread ( target = kbInputThread , args = [ ctrl ]) 1219kb_input_thd . daemon = True 1220kb_input_thd . start () 1221 1222osc_thd = threading . Thread ( target = oscThread , args = [ ctrl ]) 1223osc_thd . daemon = True 1224osc_thd . start () 1225 1226for line in sys . stdin : 1227if "exit" in line or "quit" in line : 1228( "Exit requested" , file = sys . stderr ) 1229break 1230 1231ctrl . run_app = False 1232( "Join transcription thread" , file = sys . stderr ) 1233transcribe_audio_thd . join () 1234( "Join vr input thread" , file = sys . stderr ) 1235vr_input_thd . join () 1236( "Join kb input thread" , file = sys . stderr ) 1237kb_input_thd . join () 1238( "Join osc thread" , file = sys . stderr ) 1239osc_thd . join () 1240( "Done" , file = sys . stderr ) 1241 1242if __name__ == "__main__" : 1243sys . stdout . reconfigure ( encoding = "utf-8" ) 1244 1245parser = argparse . ArgumentParser () 1246parser . add_argument ( "--config" , type = str , help = "Path to app config YAML file." ) 1247args = parser . parse_args () 1248 1249cfg = app_config . getConfig ( args . config ) 1250 1251experiments = [ 1252( "Evaluate/declaration_short/audio.mp3" , 1253"Evaluate/declaration_short/control.txt" ) , 1254( "Evaluate/moist/audio.mp3" , 1255"Evaluate/moist/control.txt" ) , 1256( "Evaluate/vei/audio.mp3" , 1257"Evaluate/vei/control.txt" ) , 1258] 1259 1260if False : 1261sum = 0 1262for audio , control in experiments : 1263( f"Run experiment { audio } :: { control } " , file = sys . stderr ) 1264sum += evaluate ( cfg , audio , control ) 1265( f"Total score: { sum } " , file = sys . stderr ) 1266else : 1267#optimize(cfg, experiments) 1268run ( cfg ) 1269