yum-archive/yapBox

A black box for your yapping

git clone https://git.yummers.dev/yum-archive/yapBox

yumAdd gradio webuic8ae984

v1.0.0
17.4 KiB499 linesraw
1from datetime import datetime
2from pydub import AudioSegment
3
4import gradio as gr
5import math
6import numpy as np
7import os
8import pyaudio
9import sys
10import time
11import typing
12import vad
13import wave
14
15class Logger:
16    def __init__(self, filename):
17        self.terminal = sys.stdout
18        self.log = open(filename, "w")
19
20    def write(self, message):
21        self.terminal.write(message)
22        self.log.write(message)
23
24    def flush(self):
25        self.terminal.flush()
26        self.log.flush()
27
28    def isatty(self):
29        return False    
30
31class AudioStream():
32    FORMAT = pyaudio.paInt16
33    # Size of each frame (audio sample), in bytes. If you change FORMAT, make
34    # sure this stays up to date!
35    FRAME_SZ = 2
36    # Frames per second.
37    FPS = 16000
38    CHANNELS = 1
39    def __init__(self):
40        pass
41
42    def getSamples(self) -> bytes:
43        raise NotImplementedError("getSamples is not implemented!")
44
45class MicStream(AudioStream):
46    CHUNK_SZ = 1024
47
48    def __init__(self, which_mic: str, fps: int = AudioStream.FPS):
49        self.p = pyaudio.PyAudio()
50        self.stream = None
51        self.sample_rate = None
52        # Each time pyaudio gives us audio data, it's in the form of a chunk of
53        # samples. We keep these in a list to keep the audio callback as light
54        # as possible. Whenever downstream layers want data, we collapse the
55        # list into a single array of data (a bytes object).
56        self.chunks = []
57        # If set, incoming frames are simply discarded.
58        self.paused = False
59        self.fps = fps
60
61        print(f"Finding mic {which_mic}", file=sys.stderr)
62        self.dumpMicDevices()
63
64        got_match = False
65        device_index = -1
66        focusrite_str = "Focusrite"
67        index_str = "Digital Audio Interface"
68        if which_mic == "index":
69            target_str = index_str
70        elif which_mic == "focusrite":
71            target_str = focusrite_str
72        else:
73            print(f"Mic {which_mic} requested, treating it as a numerical " +
74                    "device ID", file=sys.stderr)
75            device_index = int(which_mic)
76            got_match = True
77        if not got_match:
78            info = self.p.get_host_api_info_by_index(0)
79            numdevices = info.get('deviceCount')
80            for i in range(0, numdevices):
81                if (self.p.get_device_info_by_host_api_device_index(0, i).get('maxInputChannels')) > 0:
82                    device_name = self.p.get_device_info_by_host_api_device_index(0, i).get('name')
83                    if target_str in device_name:
84                        print(f"Got matching mic: {device_name}",
85                                file=sys.stderr)
86                        device_index = i
87                        got_match = True
88                        break
89        if not got_match:
90            raise KeyError(f"Mic {which_mic} not found")
91
92        info = self.p.get_device_info_by_host_api_device_index(0, device_index)
93        print(f"Found mic {which_mic}: {info['name']}", file=sys.stderr)
94        self.sample_rate = int(info['defaultSampleRate'])
95        print(f"Mic sample rate: {self.sample_rate}", file=sys.stderr)
96
97        self.stream = self.p.open(
98                rate=self.sample_rate,
99                channels=self.CHANNELS,
100                format=self.FORMAT,
101                input=True,
102                frames_per_buffer=MicStream.CHUNK_SZ,
103                input_device_index=device_index,
104                stream_callback=self.onAudioFramesAvailable)
105
106        self.stream.start_stream()
107
108        AudioStream.__init__(self)
109
110    def pause(self, state: bool = True):
111        self.paused = state
112
113    def dumpMicDevices(self):
114        info = self.p.get_host_api_info_by_index(0)
115        numdevices = info.get('deviceCount')
116
117        for i in range(0, numdevices):
118            if (self.p.get_device_info_by_host_api_device_index(0, i).get('maxInputChannels')) > 0:
119                device_name = self.p.get_device_info_by_host_api_device_index(0, i).get('name')
120                print("Input Device id ", i, " - ", device_name)
121
122    def getMicDevices() -> str:
123        p = pyaudio.PyAudio()
124        info = p.get_host_api_info_by_index(0)
125        numdevices = info.get('deviceCount')
126
127        result = []
128        for i in range(0, numdevices):
129            if (p.get_device_info_by_host_api_device_index(0, i).get('maxInputChannels')) > 0:
130                device_name = p.get_device_info_by_host_api_device_index(0, i).get('name')
131                result.append(f"Input Device id {i} - {device_name}")
132        return '\n'.join(result)
133
134    def onAudioFramesAvailable(self,
135            frames,
136            frame_count,
137            time_info,
138            status_flags):
139        if self.paused:
140            # Don't literally pause, just start returning silence. This allows
141            # the `min_segment_age_s` check to work while paused.
142            n_frames = int(frame_count * self.fps /
143                    float(self.sample_rate))
144            self.chunks.append(np.zeros(n_frames,
145                dtype=np.int16).tobytes())
146            return (frames, pyaudio.paContinue)
147
148        decimated = b''
149        # In pyaudio, a `frame` is a single sample of audio data.
150        frame_len = self.FRAME_SZ
151        next_frame = 0.0
152        # The mic probably has a higher sample rate than Whisper wants, so
153        # decrease the sample rate by dropping samples. Note that this
154        # algorithm only works if the mic's rate is higher than whisper's
155        # expected rate.
156        keep_every = float(self.sample_rate) / self.fps
157        for i in range(frame_count):
158            if i >= next_frame:
159                decimated += frames[i*frame_len:(i+1)*frame_len]
160                next_frame += keep_every
161        self.chunks.append(decimated)
162
163        return (frames, pyaudio.paContinue)
164
165    # Get audio data and the corresponding timestamp.
166    def getSamples(self) -> bytes:
167        chunks = self.chunks
168        self.chunks = []
169        result = b''.join(chunks)
170        return result
171
172class AudioCollector:
173    def __init__(self, stream: AudioStream):
174        self.stream = stream
175        self.frames = b''
176        # Note: by design, this is the only spot where we anchor our timestamps
177        # against the real world. This is done to make it possible to profile
178        # test cases which read from disk (at much faster than real speed) in
179        # the same way that we profile real-time data.
180        self.wall_ts = time.time()
181
182    def getAudio(self) -> bytes:
183        frames = self.stream.getSamples()
184        if frames:
185            self.frames += frames
186        return self.frames
187
188    def dropAudioPrefix(self, dur_s: float) -> bytes:
189        n_bytes = int(dur_s * self.stream.fps) * self.stream.FRAME_SZ
190        n_bytes = min(n_bytes, len(self.frames))
191        cut_portion = self.frames[:n_bytes]
192        self.frames = self.frames[n_bytes:]
193        self.wall_ts += float(n_bytes / self.stream.FRAME_SZ) / self.stream.fps
194        return cut_portion
195
196    def dropAudioPrefixByFrames(self, dur_frames: int) -> bytes:
197        n_bytes = dur_frames * self.stream.FRAME_SZ
198        n_bytes = min(n_bytes, len(self.frames))
199        cut_portion = self.frames[:n_bytes]
200        self.frames = self.frames[n_bytes:]
201        self.wall_ts += float(n_bytes / self.stream.FRAME_SZ) / self.stream.fps
202        return cut_portion
203
204    def keepLast(self, dur_s: float) -> bytes:
205        drop_len = max(0, self.duration() - dur_s)
206        return self.dropAudioPrefix(drop_len)
207
208    def dropAudio(self):
209        self.wall_ts += self.duration()
210        cut_portion = self.frames
211        self.frames = b''
212        return cut_portion
213
214    def duration(self):
215        return len(self.frames) / (self.stream.fps * self.stream.FRAME_SZ)
216
217    def begin(self):
218        return self.wall_ts
219
220    def now(self):
221        return self.begin() + self.duration()
222
223class AudioCollectorFilter:
224    def __init__(self, parent: AudioCollector):
225        self.parent = parent
226        self.stream = self.parent.stream
227
228    def getAudio(self) -> bytes:
229        return self.parent.getAudio()
230    def dropAudioPrefix(self, dur_s: float):
231        return self.parent.dropAudioPrefix(dur_s)
232    def dropAudioPrefixByFrames(self, dur_frames: int):
233        return self.parent.dropAudioPrefixByFrames(dur_frames)
234    def keepLast(self, dur_s):
235        return self.parent.keepLast(dur_s)
236    def dropAudio(self):
237        return self.parent.dropAudio()
238    def duration(self):
239        return self.parent.duration()
240    def begin(self):
241        return self.parent.begin()
242    def now(self):
243        return self.parent.now()
244
245class NormalizingAudioCollector(AudioCollectorFilter):
246    def __init__(self, parent: AudioCollector):
247        AudioCollectorFilter.__init__(self, parent)
248
249    def getAudio(self) -> bytes:
250        audio = self.parent.getAudio()
251
252        audio = AudioSegment(audio, sample_width=self.stream.FRAME_SZ,
253                frame_rate=self.stream.fps, channels=self.stream.CHANNELS)
254        audio = audio.normalize()
255
256        frames = np.array(audio.get_array_of_samples())
257        frames = np.int16(frames).tobytes()
258
259        return frames
260
261class CompressingAudioCollector(AudioCollectorFilter):
262    def __init__(self, parent: AudioCollector):
263        AudioCollectorFilter.__init__(self, parent)
264
265    def getAudio(self) -> bytes:
266        audio = self.parent.getAudio()
267
268        audio = AudioSegment(audio,
269                sample_width=self.stream.FRAME_SZ,
270                frame_rate=self.stream.fps,
271                channels=self.stream.CHANNELS)
272        # subtle compression has a slight positive effect on my benchmark
273        audio = audio.compress_dynamic_range(threshold=-10, ratio=2.0)
274
275        frames = np.array(audio.get_array_of_samples())
276        frames = np.int16(frames).tobytes()
277
278        return frames
279
280class AudioSegmenter:
281    def __init__(self,
282            min_silence_ms=250,
283            max_speech_s=5,
284            stream: AudioStream = None):
285        self.vad_options = vad.VadOptions(
286                min_silence_duration_ms=min_silence_ms,
287                max_speech_duration_s=max_speech_s)
288        self.stream = stream
289        pass
290
291    def segmentAudio(self, audio: bytes):
292        audio = np.frombuffer(audio,
293                dtype=np.int16).flatten().astype(np.float32) / 32768.0
294        return vad.get_speech_timestamps(audio, vad_options=self.vad_options)
295
296    # Returns the stable cutoff (if any) and whether there are any segments.
297    def getStableCutoff(self, audio: bytes) -> typing.Tuple[int, bool]:
298        min_delta_frames = int((self.vad_options.min_silence_duration_ms *
299                self.stream.fps) / 1000)
300        cutoff = None
301
302        last_end = None
303        segments = self.segmentAudio(audio)
304
305        for i in range(len(segments)):
306            s = segments[i]
307            #print(f"s: {s}")
308            #print(f"last_end: {last_end}")
309
310            if last_end:
311                delta_frames = s['start'] - last_end
312                #print(f"delta frames: {delta_frames}")
313                if delta_frames > min_delta_frames:
314                    cutoff = s['start']
315            else:
316                last_end = s['end']
317
318            if i == len(segments) - 1:
319                now = int(len(audio) / self.stream.FRAME_SZ)
320                delta_frames = now - s['end']
321                if delta_frames > min_delta_frames:
322                    cutoff = now - int(min_delta_frames / 2)
323
324        return (cutoff, len(segments) > 0)
325
326def install_in_venv(pkgs: typing.List[str]) -> bool:
327    pkgs_str = " ".join(pkgs)
328    print(f"Installing {pkgs_str}")
329    pip_proc = subprocess.Popen(
330            f"Resources/Python/python.exe -m pip install {pkgs_str} --no-warn-script-location".split(),
331            stdout=subprocess.PIPE,
332            stderr=subprocess.PIPE)
333    pip_stdout, pip_stderr = pip_proc.communicate()
334    pip_stdout = pip_stdout.decode("utf-8")
335    pip_stderr = pip_stderr.decode("utf-8")
336    print(pip_stdout, file=sys.stderr)
337    print(pip_stderr, file=sys.stderr)
338    if pip_proc.returncode != 0:
339        print(f"`pip install {pkgs_str}` exited with {pip_proc.returncode}",
340                file=sys.stderr)
341        return False
342    return True
343
344def saveAudio(audio: bytes, path: str, stream: AudioStream):
345    with wave.open(path, 'wb') as wf:
346        print(f"Saving audio to {path}", file=sys.stderr)
347        wf.setnchannels(stream.CHANNELS)
348        wf.setsampwidth(stream.FRAME_SZ)
349        wf.setframerate(stream.fps)
350        wf.writeframes(audio)
351
352def concatenateWavFiles(output_path):
353    # List all .wav files in the CWD
354    wav_files = [f for f in os.listdir('.') if f.endswith('.wav')]
355
356    # Initialize parameters for wave file
357    params = None
358
359    # Open the output file
360    with wave.open(output_path, 'wb') as output_wav:
361        for wav_file in wav_files:
362            if os.path.abspath(wav_file) == os.path.abspath(output_path):
363                print(f"Skip adding output file ({wav_file}) to itself")
364                continue
365            print(f"Processing {wav_file}")
366            with wave.open(wav_file, 'rb') as input_wav:
367                # Check if parameters are the same for each file
368                if params is None:
369                    params = input_wav.getparams()
370                    output_wav.setparams(params)
371
372                # Read and write frames
373                frames = input_wav.readframes(input_wav.getnframes())
374                output_wav.writeframes(frames)
375
376class AppControl:
377    run = True
378app_ctrl = AppControl()
379
380def recordMeDaddy(
381        mic_index: int,
382        min_volume: float = -1.3,
383        max_volume: float = -0.8
384        ):
385    app_ctrl.run = True
386
387    stream = MicStream(str(mic_index))
388    stream_hd = MicStream(str(mic_index), fps=44100)
389
390    collector = AudioCollector(stream)
391    #collector = NormalizingAudioCollector(collector)
392    collector = CompressingAudioCollector(collector)
393
394    collector_hd = AudioCollector(stream_hd)
395    #collector_hd = NormalizingAudioCollector(collector_hd)
396    collector_hd = CompressingAudioCollector(collector_hd)
397
398    min_silence_ms = 1000
399    max_speech_s = 30
400    segmenter = AudioSegmenter(
401            min_silence_ms=min_silence_ms,
402            max_speech_s=max_speech_s,
403            stream=stream)
404
405    while app_ctrl.run:
406        audio = collector.getAudio()
407        collector_hd.getAudio()
408        stable_cutoff, has_audio = segmenter.getStableCutoff(audio)
409
410        #print(f"has audio: {has_audio}")
411        #print(f"stable cutoff: {stable_cutoff}")
412
413        if has_audio and stable_cutoff:
414            commit_audio = collector.dropAudioPrefixByFrames(stable_cutoff)
415            print(f"stable cutoff: {stable_cutoff}")
416            hd_cutoff = int(math.floor(stable_cutoff * stream_hd.fps /
417                stream.fps))
418            print(f"hd cutoff: {hd_cutoff}")
419            commit_audio_hd = collector_hd.dropAudioPrefixByFrames(hd_cutoff)
420            print(f"hd audio len: {len(commit_audio_hd)}")
421
422            # Calculate naive measure of volume
423            audio_v = AudioSegment(commit_audio_hd,
424                    sample_width=stream_hd.FRAME_SZ,
425                    frame_rate=stream_hd.fps,
426                    channels=stream_hd.CHANNELS)
427            audio_v = np.array(audio_v.get_array_of_samples())
428            audio_v = np.int16(audio_v)
429            audio_v = np.sqrt(np.mean(np.square(audio_v)))
430            audio_v /= np.sqrt(len(commit_audio_hd) / stream_hd.FRAME_SZ)
431            audio_v = math.log(audio_v, 10)
432            print(f"volume: {audio_v}")
433            # cutoff is a fine-tuned value based on volumes seen while in vr
434            # (index mic)
435            if audio_v < min_volume or audio_v > max_volume:
436                # Discard sample
437                print("Discarding too-quiet/too-loud segment")
438                collector.keepLast(1.0)
439                collector_hd.keepLast(1.0)
440                continue
441
442
443            ts = datetime.fromtimestamp(time.time())
444            filename = str(ts.strftime('%Y_%m_%d__%H-%M-%S')) + ".wav"
445            saveAudio(commit_audio_hd, filename, stream_hd)
446
447        if not has_audio:
448            #print("VAD detects no audio, skip transcription", file=sys.stderr)
449            collector.keepLast(1.0)
450            collector_hd.keepLast(1.0)
451    print("Stopped recording")
452
453def getOutput() -> str:
454    sys.stdout.flush()
455    with open("output.log", "r") as f:
456        return f.read()
457
458def stopApp():
459    print("Requesting app stop")
460    app_ctrl.run = False
461
462if __name__ == "__main__":
463    abspath = os.path.abspath(__file__)
464    dname = os.path.dirname(abspath)
465    os.chdir(dname)
466
467    sys.stdout = Logger("output.log")
468
469    print(f"Set cwd to {os.getcwd()}", file=sys.stderr)
470
471    with gr.Blocks() as demo:
472        dump_mics = gr.Button("Dump mics")
473        mics_output = gr.Text(label="Microphones")
474
475        mic_device = gr.Number(label="Mic device")
476        min_volume = gr.Number(label="Minimum volume", value=-1.3)
477        max_volume = gr.Number(label="Maximum volume", value=-0.8)
478        record_audio = gr.Button("Record audio")
479        stop_recording = gr.Button("Stop recording")
480        concatenated_path = gr.Text(label="Combined audio filename", value="combined.wav")
481        concatenate_audio = gr.Button("Combine audio files")
482
483        dbg_output = gr.Text(label="Output")
484
485        dump_mics.click(MicStream.getMicDevices, [], mics_output)
486
487        record_audio.click(recordMeDaddy, [mic_device, min_volume, max_volume],
488                dbg_output)
489        stop_recording.click(stopApp, [], dbg_output)
490        concatenate_audio.click(concatenateWavFiles, [concatenated_path],
491                dbg_output)
492
493        demo.load(getOutput, None, dbg_output, every=0.5)
494    demo.launch()
495    sys.exit(0)
496
497    concatenateWavFiles("concatenated.wav")
498    sys.exit(0)
499