yum-slop/TaSTT

Free self-hosted STT for VRChat.

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

yumRemove flash_attention toggle953c03d

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