File size: 14,983 Bytes
3569cbd
 
 
 
 
 
b5d8a79
3569cbd
 
a4dee07
b5d8a79
 
 
ee7230e
3569cbd
 
 
b5d8a79
 
3569cbd
 
e303d11
b5d8a79
dac8f9a
 
 
 
 
3569cbd
 
ee7230e
dac8f9a
a4dee07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b5d8a79
 
ee7230e
 
 
 
 
 
b5d8a79
 
 
 
 
 
 
a4dee07
 
 
 
 
 
 
b5d8a79
a4dee07
 
 
b5d8a79
 
a4dee07
 
 
 
5df3ca5
b5d8a79
a4dee07
b5d8a79
 
a4dee07
2bb7b57
 
a4dee07
5df3ca5
3569cbd
5df3ca5
a4dee07
b5d8a79
 
3569cbd
5b9ecd0
b5d8a79
5b9ecd0
 
2bb7b57
5b9ecd0
a4dee07
b5d8a79
 
 
 
 
 
 
 
 
a4dee07
 
 
 
2bb7b57
a4dee07
b5d8a79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4dee07
 
5b9ecd0
 
 
5cb1ef7
2bb7b57
a4dee07
5cb1ef7
a4dee07
 
b5d8a79
2bb7b57
a4dee07
5cb1ef7
 
b5d8a79
 
 
 
 
5b9ecd0
2bb7b57
5b9ecd0
a4dee07
 
b5d8a79
a4dee07
 
 
 
 
 
 
b5d8a79
a4dee07
 
 
b5d8a79
a4dee07
 
b5d8a79
 
 
 
 
ee7230e
 
b0c3f88
5b9ecd0
 
819a8c6
b5d8a79
 
 
5df3ca5
5b9ecd0
 
 
b5d8a79
5b9ecd0
 
 
 
 
2bb7b57
 
 
 
 
5b9ecd0
 
 
b5d8a79
 
 
5df3ca5
b5d8a79
 
 
5b9ecd0
b5d8a79
5b9ecd0
 
a4dee07
ee7230e
5b9ecd0
 
819a8c6
2bb7b57
5b9ecd0
b5d8a79
 
 
 
 
 
5b9ecd0
5cb1ef7
5b9ecd0
b5d8a79
5b9ecd0
2bb7b57
 
 
5b9ecd0
 
 
b5d8a79
 
 
 
 
5b9ecd0
 
b5d8a79
2bb7b57
 
5b9ecd0
 
 
 
2bb7b57
 
3569cbd
 
 
b5d8a79
 
 
 
 
 
 
2bb7b57
 
819a8c6
 
2bb7b57
 
819a8c6
 
 
 
b5d8a79
 
 
819a8c6
 
2bb7b57
 
 
 
 
 
5b9ecd0
5cb1ef7
b5d8a79
 
 
5b9ecd0
b5d8a79
 
 
819a8c6
5b9ecd0
b5d8a79
 
 
 
 
5cb1ef7
b5d8a79
 
 
e303d11
b5d8a79
5b9ecd0
b5d8a79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4dee07
b5d8a79
 
 
 
a4dee07
 
 
 
 
 
b5d8a79
a4dee07
3569cbd
b5d8a79
a4dee07
 
 
b5d8a79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
use std::{
    collections::VecDeque,
    fmt::{Debug, Display, Formatter},
    thread::sleep,
    time::Duration,
};
use fvad::SampleRate;

use once_cell::sync::Lazy;
use tokio::sync::{broadcast, mpsc, oneshot};
use tokio::time::Instant;
use tracing::{debug, trace, warn};
use whisper_rs::{convert_integer_to_float_audio, WhisperContext, WhisperState, WhisperToken, WhisperTokenData};

use crate::config::{Settings, SETTINGS};
use crate::{config::WhisperConfig, group::GroupedWithin};

const WHISPER_SAMPLE_RATE: usize = whisper_rs_sys::WHISPER_SAMPLE_RATE as usize;

static WHISPER_CONTEXT: Lazy<WhisperContext> = Lazy::new(|| {
    let settings = Settings::new().expect("Failed to initialize settings.");
    if tracing::enabled!(tracing::Level::DEBUG) {
        let info = whisper_rs::print_system_info();
        debug!("system_info: n_threads = {} / {} | {}\n",
            settings.whisper.params.n_threads.unwrap_or(0),
            std::thread::available_parallelism().map(|c| c.get()).unwrap_or(0),
            info);
    }
    WhisperContext::new(&settings.whisper.model).expect("failed to create WhisperContext")
});


#[derive(Debug)]
pub(crate) enum Error {
    WhisperError {
        description: String,
        error: whisper_rs::WhisperError,
    },
}

impl Error {
    fn whisper_error(description: &str, error: whisper_rs::WhisperError) -> Self {
        Self::WhisperError {
            description: description.to_string(),
            error,
        }
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::WhisperError { description, error } => {
                write!(f, "WhisperError: {}: {}", description, error)
            }
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::WhisperError { error, .. } => Some(error),
        }
    }
}

fn u8_to_i16(input: &[u8]) -> Vec<i16> {
    input
        .chunks_exact(2)
        .map(|chunk| {
            let mut buf = [0u8; 2];
            buf.copy_from_slice(chunk);
            i16::from_le_bytes(buf)
        })
        .collect::<Vec<i16>>()
}

#[derive(Clone, Debug)]
pub enum Output {
    Unstable(Segment),
    Stable(Segment),
}

#[derive(Clone, Debug)]
pub struct Segment {
    pub start_timestamp: i64,
    pub end_timestamp: i64,
    pub text: String,
    tokens: Vec<WhisperTokenData>,
}

pub struct WhisperHandler {
    tx: mpsc::Sender<Vec<i16>>,
    transcription_tx: broadcast::Sender<Vec<Output>>,
    stop_handle: Option<oneshot::Sender<()>>,
}

impl WhisperHandler {
    pub(crate) fn new(config: WhisperConfig, prompt: String) -> Result<Self, Error> {
        let vad_slice_size = WHISPER_SAMPLE_RATE / 100 * 3;
        let (stop_handle, mut stop_signal) = oneshot::channel();
        let (pcm_tx, pcm_rx) = mpsc::channel::<Vec<i16>>(128);
        let (transcription_tx, _) = broadcast::channel::<Vec<Output>>(128);
        let shared_transcription_tx = transcription_tx.clone();
        let state = WHISPER_CONTEXT
            .create_state()
            .map_err(|e| Error::whisper_error("failed to create WhisperState", e))?;
        let preset_prompt_tokens = WHISPER_CONTEXT
            .tokenize(prompt.as_str(), SETTINGS.whisper.max_prompt_tokens)
            .map_err(|e| Error::whisper_error("failed to tokenize prompt", e))?;
        tokio::task::spawn_blocking(move || {
            let mut vad = fvad::Fvad::new().expect("failed to create VAD")
                .set_sample_rate(SampleRate::Rate16kHz);
            let mut detector = Detector::new(state, &SETTINGS.whisper, preset_prompt_tokens);
            let mut grouped = GroupedWithin::new(
                detector.n_samples_step,
                Duration::from_millis(config.step_ms as u64),
                pcm_rx,
                u16::MAX as usize,
            );
            while let Err(oneshot::error::TryRecvError::Empty) = stop_signal.try_recv() {
                if detector.has_crossed_next_line() {
                    if let Some(segment) = detector.next_line() {
                        let segments = vec![Output::Stable(segment)];
                        if let Err(e) = shared_transcription_tx.send(segments) {
                            tracing::error!("failed to send transcription: {}", e);
                            break;
                        };
                    }
                }
                let new_pcm_f32 = match grouped.next() {
                    Err(mpsc::error::TryRecvError::Disconnected) => break,
                    Err(mpsc::error::TryRecvError::Empty) => {
                        sleep(Duration::from_millis(10));
                        continue;
                    }
                    Ok(data) => {
                        let active_voice = data
                            .chunks(vad_slice_size)
                            .filter(|frame| {
                                if frame.len() != vad_slice_size {
                                    true
                                } else {
                                    vad.is_voice_frame(frame).unwrap_or(true)
                                }
                                // true
                            })
                            .collect::<Vec<_>>()
                            .concat();
                        convert_integer_to_float_audio(&active_voice)
                    },
                };

                detector.feed(new_pcm_f32);
                let segments = match detector.inference() {
                    Ok(result) => {
                        if result.is_empty() {
                            continue;
                        }
                        result
                    }
                    Err(err) => {
                        warn!("failed to inference: {}", err);
                        continue;
                    }
                };

                let outputs = segments
                    .iter()
                    .map(|segment| Output::Unstable(segment.clone()))
                    .collect::<Vec<_>>();
                if let Err(e) = shared_transcription_tx.send(outputs) {
                    tracing::error!("failed to send transcription: {}", e);
                    break;
                };
            }
        });

        Ok(Self {
            tx: pcm_tx,
            transcription_tx,
            stop_handle: Some(stop_handle),
        })
    }

    pub fn subscribe(&self) -> broadcast::Receiver<Vec<Output>> {
        self.transcription_tx.subscribe()
    }

    pub async fn send_i16(&mut self, data: Vec<i16>) -> Result<(), mpsc::error::SendError<Vec<i16>>> {
        self.tx.send(data).await
    }

    pub async fn send_bytes(&mut self, data: Vec<u8>) -> Result<(), mpsc::error::SendError<Vec<i16>>> {
        let i16_data = u8_to_i16(&data);
        self.send_i16(i16_data).await
    }
}

#[allow(dead_code)]
struct Detector {
    state: WhisperState<'static>,
    config: &'static WhisperConfig,
    start_time: Instant,
    segment: Option<Segment>,
    line_num: usize,
    preset_prompt_tokens: Vec<WhisperToken>,
    n_samples_keep: usize,
    n_samples_step: usize,
    n_samples_len: usize,
    prompt_tokens: Vec<WhisperToken>,
    pcm_f32: VecDeque<f32>,
    offset: usize,
}

impl Detector {
    fn new(
        state: WhisperState<'static>,
        config: &'static WhisperConfig,
        preset_prompt_tokens: Vec<WhisperToken>,
    ) -> Self {
        Detector {
            state,
            config,
            start_time: Instant::now(),
            segment: None,
            line_num: 0,
            preset_prompt_tokens,
            n_samples_keep: config.keep_ms * WHISPER_SAMPLE_RATE / 1000,
            n_samples_step: config.step_ms * WHISPER_SAMPLE_RATE / 1000,
            n_samples_len: config.length_ms * WHISPER_SAMPLE_RATE / 1000,
            prompt_tokens: Default::default(),
            pcm_f32: VecDeque::with_capacity(config.length_ms * WHISPER_SAMPLE_RATE / 1000),
            offset: 0,
        }
    }

    fn feed(&mut self, new_pcm_f32: Vec<f32>) {
        self.pcm_f32.extend(new_pcm_f32);
        if self.pcm_f32.len() < self.n_samples_len {
            return;
        }
        // let len_to_drain = self
        //     .pcm_f32
        //     .drain(0..(self.pcm_f32.len() - self.n_samples_len))
        //     .len();
        // warn!("ASR too slow, drain {} samples", len_to_drain);
        // self.offset += len_to_drain;
    }

    fn inference(&mut self) -> Result<Vec<Segment>, Error> {
        let params = self.config.params.to_full_params(self.prompt_tokens.as_slice());
        let start = std::time::Instant::now();
        let _ = self
            .state
            .full(params, self.pcm_f32.make_contiguous())
            .map_err(|e| Error::whisper_error("failed to initialize WhisperState", e))?;
        let end = std::time::Instant::now();
        if end - start > Duration::from_millis(self.config.step_ms as u64) {
            // warn!(
            //     "full([{}]) took {} ms too slow",
            //     self.pcm_f32.len(),
            //     (end - start).as_millis()
            // );
        }

        let timestamp_offset: i64 = (self.offset * 1000 / WHISPER_SAMPLE_RATE) as i64;
        let num_segments = self
            .state
            .full_n_segments()
            .map_err(|e| Error::whisper_error("failed to get number of segments", e))?;
        let mut segments: Vec<Segment> = Vec::with_capacity(num_segments as usize);
        for i in 0..num_segments {
            let start_timestamp: i64 = timestamp_offset
                + 10 * self
                    .state
                    .full_get_segment_t0(i)
                    .map_err(|e| Error::whisper_error("failed to get start timestamp", e))?;

            let end_timestamp: i64 = timestamp_offset
                + 10 * self
                .state
                .full_get_segment_t1(i)
                .map_err(|e| Error::whisper_error("failed to get end timestamp", e))?;

            let segment = self
                .state
                .full_get_segment_text(i)
                .map_err(|e| Error::whisper_error("failed to get segment", e))?;
            let num_tokens = self
                .state
                .full_n_tokens(i)
                .map_err(|e| Error::whisper_error("failed to get segment tokens", e))?;
            let mut segment_tokens = Vec::with_capacity(num_tokens as usize);
            for j in 0..num_tokens {
                let token_data = self.state.full_get_token_data(i, j)
                    .map_err(|e| Error::whisper_error("failed to get token data", e))?;
                segment_tokens.push(token_data);
            }

            segments.push(Segment {
                start_timestamp,
                end_timestamp,
                text: segment.trim().to_string(),
                tokens: segment_tokens,
            });
        }

        self.segment = segments.first().cloned();
        Ok(segments.to_vec())
    }

    fn remember_prompt(&mut self) {
        let Some(segment) = self.segment.as_ref() else {
            return
        };

        let tokens = segment
            .tokens
            .iter()
            .map(|td| td.tid)
            .collect::<Vec<WhisperToken>>();

        self.prompt_tokens.extend(tokens);
        if self.prompt_tokens.len() > self.config.max_prompt_tokens {
            let _ = self.prompt_tokens.drain(0..(self.prompt_tokens.len() - self.config.max_prompt_tokens)).len();
        }
    }

    fn has_crossed_next_line(&self) -> bool {
        let now = Instant::now();
        let elapsed = now - self.start_time;
        let line_number: usize = (elapsed.as_millis() / self.config.length_ms as u128) as usize;
        line_number > self.line_num
    }

    fn next_line(&mut self) -> Option<Segment> {
        if self.pcm_f32.len() > self.n_samples_keep {
            let drain_size = self.pcm_f32.drain(0..(self.pcm_f32.len() - self.n_samples_keep)).len();
            self.offset += drain_size;
        } else {
            let size_will_clear = self.pcm_f32.len();
            self.pcm_f32.clear();
            self.offset += size_will_clear;
        }

        self.line_num += 1;
        self.remember_prompt();
        self.segment.take()
    }
}

impl Drop for WhisperHandler {
    fn drop(&mut self) {
        let Some(stop_handle) = self.stop_handle.take() else {
            return warn!("WhisperHandler::drop() called without stop_handle");
        };
        if stop_handle.send(()).is_err() {
            warn!("WhisperHandler::drop() failed to send stop signal");
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use std::io::{stdout, Write};
    use hound;
    use tracing_test;
    use tracing::info;

    async fn print_output(output: Output) {
        match output {
            Output::Stable(stable) => {
                print!("\x1b[2K\r");
                print!("{}\n", stable.text);
            },
            Output::Unstable(unstable) => {
                // back to previous line of console
                print!("\x1b[2K\r");
                print!("{}", " ".repeat(100));
                print!("\x1b[2K\r");
                print!("{} ...", unstable.text);
            }
        }
        stdout().flush().unwrap();
    }
    #[tokio::test]
    #[tracing_test::traced_test]
    async fn test_whisper_handler() {
        let mut whisper_handler = WhisperHandler::new(
            SETTINGS.whisper.clone(),
            "Harry Potter and the Philosopher's Stone".to_string(),
        ).expect("failed to create WhisperHandler");

        let wav = hound::WavReader::open("samples/ADHD_1A.wav")
            .expect("failed to open wav");
        let spec = wav.spec();
        println!("{:?}", spec);
        let samples = wav
            .into_samples::<i16>()
            .map(|s| s.unwrap())
            .collect::<Vec<i16>>();
        let chunks = samples.chunks(1600)
            .map(|chunk| chunk.to_vec())
            .into_iter();

        let mut rx = whisper_handler.subscribe();
        let send_fut = async {
            // tokio::time::sleep(Duration::from_secs(5)).await;
            for chunk in chunks {
                let _ = whisper_handler.send_i16(chunk).await.expect("failed to send sample");
                tokio::time::sleep(Duration::from_millis(100)).await;
            }
        };

        let recv_fut = async {
            while let Ok(outputs) = rx.recv().await {
                let Some(output) = outputs.first() else {
                    continue
                };

                match output {
                    Output::Stable(stable) => {
                        println!("{}", stable.text);
                    },
                    Output::Unstable(unstable) => {

                    }
                }

            }
        };

        tokio::join!(send_fut, recv_fut);
    }
}