whisper-apr 0.3.1

WASM-first automatic speech recognition engine implementing OpenAI Whisper
Documentation
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
//! Timestamp interpolation for sub-word tokens (WAPR-162)
//!
//! Interpolates timestamps for BPE sub-word tokens within words.
//!
//! # Overview
//!
//! Whisper uses BPE tokenization, so words are often split into multiple tokens.
//! This module provides methods to:
//! 1. Interpolate timestamps within words
//! 2. Handle special tokens (punctuation, etc.)
//! 3. Smooth timestamp sequences

#[cfg(test)]
mod tests;

use crate::error::WhisperResult;

/// Interpolation configuration
#[derive(Debug, Clone)]
pub struct InterpolationConfig {
    /// Interpolation method
    pub method: InterpolationMethod,
    /// Smoothing window size (0 = no smoothing)
    pub smoothing_window: usize,
    /// Weight for character-length proportional timing
    pub char_weight: f32,
    /// Weight for uniform timing
    pub uniform_weight: f32,
}

/// Interpolation method
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InterpolationMethod {
    /// Linear interpolation based on token position
    Linear,
    /// Character-length proportional
    CharacterProportional,
    /// Weighted combination
    Weighted,
    /// Attention-guided (requires attention weights)
    AttentionGuided,
}

impl Default for InterpolationConfig {
    fn default() -> Self {
        Self {
            method: InterpolationMethod::Weighted,
            smoothing_window: 3,
            char_weight: 0.7,
            uniform_weight: 0.3,
        }
    }
}

impl InterpolationConfig {
    /// Create config for linear interpolation
    #[must_use]
    pub fn linear() -> Self {
        Self {
            method: InterpolationMethod::Linear,
            smoothing_window: 0,
            char_weight: 0.0,
            uniform_weight: 1.0,
        }
    }

    /// Create config for character-proportional interpolation
    #[must_use]
    pub fn character_proportional() -> Self {
        Self {
            method: InterpolationMethod::CharacterProportional,
            smoothing_window: 0,
            char_weight: 1.0,
            uniform_weight: 0.0,
        }
    }

    /// Set smoothing window
    #[must_use]
    pub fn with_smoothing(mut self, window: usize) -> Self {
        self.smoothing_window = window;
        self
    }

    /// Set interpolation method
    #[must_use]
    pub fn with_method(mut self, method: InterpolationMethod) -> Self {
        self.method = method;
        self
    }
}

/// Token timestamp information
#[derive(Debug, Clone)]
pub struct TokenTimestamp {
    /// Token index
    pub index: usize,
    /// Token text
    pub text: String,
    /// Start time in seconds
    pub start: f32,
    /// End time in seconds
    pub end: f32,
    /// Whether this timestamp was interpolated
    pub interpolated: bool,
    /// Confidence (lower for interpolated)
    pub confidence: f32,
}

impl TokenTimestamp {
    /// Create new token timestamp
    #[must_use]
    pub fn new(index: usize, text: String, start: f32, end: f32) -> Self {
        Self {
            index,
            text,
            start,
            end,
            interpolated: false,
            confidence: 1.0,
        }
    }

    /// Get duration
    #[must_use]
    pub fn duration(&self) -> f32 {
        self.end - self.start
    }

    /// Mark as interpolated
    pub fn mark_interpolated(&mut self, confidence: f32) {
        self.interpolated = true;
        self.confidence = confidence;
    }

    /// Create interpolated timestamp
    #[must_use]
    pub fn interpolated(index: usize, text: String, start: f32, end: f32, confidence: f32) -> Self {
        Self {
            index,
            text,
            start,
            end,
            interpolated: true,
            confidence,
        }
    }
}

/// Timestamp interpolator
#[derive(Debug, Clone)]
pub struct TimestampInterpolator {
    /// Configuration
    config: InterpolationConfig,
}

impl TimestampInterpolator {
    /// Create new interpolator
    #[must_use]
    pub fn new(config: InterpolationConfig) -> Self {
        Self { config }
    }

    /// Interpolate timestamps for tokens within a word
    ///
    /// # Arguments
    /// * `word_start` - Word start time
    /// * `word_end` - Word end time
    /// * `tokens` - Token texts within the word
    pub fn interpolate_word_tokens(
        &self,
        word_start: f32,
        word_end: f32,
        tokens: &[String],
        start_index: usize,
    ) -> WhisperResult<Vec<TokenTimestamp>> {
        if tokens.len() <= 1 {
            return Ok(tokens
                .iter()
                .enumerate()
                .map(|(i, t)| TokenTimestamp::new(start_index + i, t.clone(), word_start, word_end))
                .collect());
        }

        match self.config.method {
            InterpolationMethod::Linear => {
                self.interpolate_linear(word_start, word_end, tokens, start_index)
            }
            InterpolationMethod::CharacterProportional => {
                self.interpolate_char_proportional(word_start, word_end, tokens, start_index)
            }
            InterpolationMethod::Weighted => {
                self.interpolate_weighted(word_start, word_end, tokens, start_index)
            }
            InterpolationMethod::AttentionGuided => {
                // Falls back to weighted without attention weights
                self.interpolate_weighted(word_start, word_end, tokens, start_index)
            }
        }
    }

    /// Interpolate with attention guidance
    pub fn interpolate_with_attention(
        &self,
        word_start: f32,
        word_end: f32,
        tokens: &[String],
        attention_weights: &[Vec<f32>],
        start_index: usize,
        frame_rate: f32,
    ) -> WhisperResult<Vec<TokenTimestamp>> {
        if tokens.is_empty() {
            return Ok(Vec::new());
        }

        if attention_weights.len() != tokens.len() {
            return self.interpolate_word_tokens(word_start, word_end, tokens, start_index);
        }

        let duration = word_end - word_start;
        let mut timestamps = Vec::with_capacity(tokens.len());
        let mut current_time = word_start;

        for (i, (text, attention)) in tokens.iter().zip(attention_weights.iter()).enumerate() {
            // Find peak attention frame for this token
            let (peak_frame, _) = attention
                .iter()
                .enumerate()
                .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
                .unwrap_or((0, &0.0));

            let peak_time = peak_frame as f32 / frame_rate;

            // Constrain to word boundaries
            let token_center = peak_time.clamp(word_start, word_end);

            // Estimate token duration
            let token_duration = if i + 1 < tokens.len() {
                let next_peak = attention_weights[i + 1]
                    .iter()
                    .enumerate()
                    .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
                    .map_or(0, |(idx, _)| idx);
                let next_time = (next_peak as f32 / frame_rate).clamp(word_start, word_end);
                (next_time - token_center).max(duration / tokens.len() as f32 * 0.5)
            } else {
                word_end - token_center
            };

            let token_start = current_time;
            let token_end = (token_start + token_duration).min(word_end);

            timestamps.push(TokenTimestamp::interpolated(
                start_index + i,
                text.clone(),
                token_start,
                token_end,
                0.8, // Higher confidence with attention guidance
            ));

            current_time = token_end;
        }

        Ok(timestamps)
    }

    /// Linear interpolation
    #[allow(clippy::unnecessary_wraps)]
    fn interpolate_linear(
        &self,
        word_start: f32,
        word_end: f32,
        tokens: &[String],
        start_index: usize,
    ) -> WhisperResult<Vec<TokenTimestamp>> {
        let _ = self; // Method for consistency
        let duration = word_end - word_start;
        let token_duration = duration / tokens.len() as f32;

        let mut timestamps = Vec::with_capacity(tokens.len());
        let mut current_time = word_start;

        for (i, text) in tokens.iter().enumerate() {
            let token_end = current_time + token_duration;

            timestamps.push(TokenTimestamp::interpolated(
                start_index + i,
                text.clone(),
                current_time,
                token_end,
                0.5, // Low confidence for linear interpolation
            ));

            current_time = token_end;
        }

        Ok(timestamps)
    }

    /// Character-proportional interpolation
    #[allow(clippy::unnecessary_wraps)]
    fn interpolate_char_proportional(
        &self,
        word_start: f32,
        word_end: f32,
        tokens: &[String],
        start_index: usize,
    ) -> WhisperResult<Vec<TokenTimestamp>> {
        let _ = self; // Method for consistency
        let duration = word_end - word_start;
        let total_chars: usize = tokens.iter().map(|t| t.chars().count().max(1)).sum();

        let mut timestamps = Vec::with_capacity(tokens.len());
        let mut current_time = word_start;

        for (i, text) in tokens.iter().enumerate() {
            let char_count = text.chars().count().max(1);
            let token_duration = (char_count as f32 / total_chars as f32) * duration;
            let token_end = current_time + token_duration;

            timestamps.push(TokenTimestamp::interpolated(
                start_index + i,
                text.clone(),
                current_time,
                token_end,
                0.6, // Medium confidence
            ));

            current_time = token_end;
        }

        Ok(timestamps)
    }

    /// Weighted interpolation (combination of linear and character-proportional)
    #[allow(clippy::unnecessary_wraps)]
    fn interpolate_weighted(
        &self,
        word_start: f32,
        word_end: f32,
        tokens: &[String],
        start_index: usize,
    ) -> WhisperResult<Vec<TokenTimestamp>> {
        let duration = word_end - word_start;
        let total_chars: usize = tokens.iter().map(|t| t.chars().count().max(1)).sum();
        let uniform_duration = duration / tokens.len() as f32;

        let mut timestamps = Vec::with_capacity(tokens.len());
        let mut current_time = word_start;

        for (i, text) in tokens.iter().enumerate() {
            let char_count = text.chars().count().max(1);
            let char_duration = (char_count as f32 / total_chars as f32) * duration;

            let weighted_duration = self
                .config
                .char_weight
                .mul_add(char_duration, self.config.uniform_weight * uniform_duration);

            let token_end = (current_time + weighted_duration).min(word_end);

            timestamps.push(TokenTimestamp::interpolated(
                start_index + i,
                text.clone(),
                current_time,
                token_end,
                0.65, // Medium-high confidence for weighted
            ));

            current_time = token_end;
        }

        // Ensure last token ends at word_end
        if let Some(last) = timestamps.last_mut() {
            last.end = word_end;
        }

        Ok(timestamps)
    }

    /// Smooth timestamps using moving average
    pub fn smooth_timestamps(&self, timestamps: &mut [TokenTimestamp]) {
        if self.config.smoothing_window == 0 || timestamps.len() < 3 {
            return;
        }

        let window = self.config.smoothing_window;
        let mut smoothed_starts = Vec::with_capacity(timestamps.len());
        let mut smoothed_ends = Vec::with_capacity(timestamps.len());

        for i in 0..timestamps.len() {
            let start = i.saturating_sub(window / 2);
            let end = (i + window / 2 + 1).min(timestamps.len());

            let avg_start: f32 =
                timestamps[start..end].iter().map(|t| t.start).sum::<f32>() / (end - start) as f32;
            let avg_end: f32 =
                timestamps[start..end].iter().map(|t| t.end).sum::<f32>() / (end - start) as f32;

            smoothed_starts.push(avg_start);
            smoothed_ends.push(avg_end);
        }

        for (i, ts) in timestamps.iter_mut().enumerate() {
            if ts.interpolated {
                ts.start = smoothed_starts[i];
                ts.end = smoothed_ends[i];
            }
        }

        // Fix any overlaps
        for i in 1..timestamps.len() {
            if timestamps[i].start < timestamps[i - 1].end {
                let mid = (timestamps[i].start + timestamps[i - 1].end) / 2.0;
                timestamps[i - 1].end = mid;
                timestamps[i].start = mid;
            }
        }
    }
}

impl Default for TimestampInterpolator {
    fn default() -> Self {
        Self::new(InterpolationConfig::default())
    }
}