yum-slop/TaSTT

Free self-hosted STT for VRChat.

git clone https://git.yummers.dev/yum-slop/TaSTT

yumBump CUDNN to v8.9.74fec36c

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