yum-slop/TaSTT

Free self-hosted STT for VRChat.

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

yumAnother edge case: first commit should not get a leading space59578a6

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