whisper-apr 0.3.0

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
427
428
429
430
431
432
433
434
//! TUI Panel Rendering
//!
//! Renders the whisper dashboard panels using ratatui.

use super::app::{WhisperApp, WhisperPanel, WhisperState};
use super::visualization::{render_attention_heatmap, render_mel_spectrogram, render_waveform};
use ratatui::{
    layout::{Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Cell, Paragraph, Row, Table, Tabs},
    Frame,
};

/// Render a data table with header row and fixed-width columns
fn render_data_table(
    f: &mut Frame<'_>,
    area: Rect,
    headers: &[&str],
    widths: &[u16],
    rows: Vec<Row<'_>>,
) {
    let header_cells: Vec<Cell<'_>> = headers.iter().map(|&h| Cell::from(h)).collect();
    let header = Row::new(header_cells)
        .style(Style::default().add_modifier(Modifier::BOLD))
        .bottom_margin(1);
    let constraints: Vec<Constraint> = widths.iter().map(|&w| Constraint::Length(w)).collect();
    let table = Table::new(rows, constraints)
        .header(header)
        .block(Block::default());
    f.render_widget(table, area);
}

/// Render an empty-state placeholder if the data slice is empty.
/// Returns `true` (and renders placeholder) if empty, `false` otherwise.
fn render_empty_placeholder<T>(f: &mut Frame<'_>, area: Rect, data: &[T], message: &str) -> bool {
    if data.is_empty() {
        let text = Paragraph::new(message).style(Style::default().fg(Color::DarkGray));
        f.render_widget(text, area);
        true
    } else {
        false
    }
}

/// Render the main whisper dashboard
pub fn render_whisper_dashboard(f: &mut Frame<'_>, app: &WhisperApp) {
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3), // Tabs
            Constraint::Min(10),   // Main content
            Constraint::Length(3), // Status bar
        ])
        .split(f.area());

    // Render tab bar
    render_tabs(f, app, chunks[0]);

    // Render main panel
    render_main_panel(f, app, chunks[1]);

    // Render status bar
    render_status_bar(f, app, chunks[2]);
}

/// Render tab navigation
fn render_tabs(f: &mut Frame<'_>, app: &WhisperApp, area: Rect) {
    let titles: Vec<Line<'_>> = WhisperPanel::titles()
        .iter()
        .map(|t| Line::from(*t))
        .collect();

    let tabs = Tabs::new(titles)
        .block(Block::default().borders(Borders::ALL).title("Navigation"))
        .highlight_style(
            Style::default()
                .fg(Color::Yellow)
                .add_modifier(Modifier::BOLD),
        )
        .select(app.current_panel.index());

    f.render_widget(tabs, area);
}

/// Render main content panel
fn render_main_panel(f: &mut Frame<'_>, app: &WhisperApp, area: Rect) {
    match app.current_panel {
        WhisperPanel::Waveform => render_waveform_panel(f, app, area),
        WhisperPanel::Mel => render_mel_panel(f, app, area),
        WhisperPanel::Encoder => render_encoder_panel(f, app, area),
        WhisperPanel::Decoder => render_decoder_panel(f, app, area),
        WhisperPanel::Attention => render_attention_panel(f, app, area),
        WhisperPanel::Transcription => render_transcription_panel(f, app, area),
        WhisperPanel::Metrics => render_metrics_panel(f, app, area),
        WhisperPanel::Help => render_help_panel(f, app, area),
    }
}

/// Render waveform visualization panel
fn render_waveform_panel(f: &mut Frame<'_>, app: &WhisperApp, area: Rect) {
    let block = Block::default()
        .borders(Borders::ALL)
        .title("WAVEFORM - Audio Signal");

    let inner = block.inner(area);
    f.render_widget(block, area);

    if render_empty_placeholder(
        f,
        inner,
        &app.audio_data,
        "No audio loaded. Load audio to visualize waveform.",
    ) {
        return;
    }

    // Render waveform ASCII art
    let waveform = render_waveform(&app.audio_data, inner.width as usize, inner.height as usize);
    let info = format!(
        "{} samples @ {}Hz ({:.2}s)",
        app.audio_data.len(),
        app.sample_rate,
        app.metrics.audio_duration_secs
    );

    let content = format!("{}\n\n{}", info, waveform);
    let paragraph = Paragraph::new(content);
    f.render_widget(paragraph, inner);
}

/// Render mel spectrogram panel
fn render_mel_panel(f: &mut Frame<'_>, app: &WhisperApp, area: Rect) {
    let block = Block::default()
        .borders(Borders::ALL)
        .title("MEL SPECTROGRAM - 80 Mel Bins");

    let inner = block.inner(area);
    f.render_widget(block, area);

    if render_empty_placeholder(
        f,
        inner,
        &app.mel_data,
        "No mel spectrogram computed. Compute mel to visualize.",
    ) {
        return;
    }

    // Render mel heatmap
    let heatmap = render_mel_spectrogram(
        &app.mel_data,
        80,
        app.mel_frames,
        inner.width as usize,
        inner.height as usize,
    );
    let info = format!("80 bins x {} frames", app.mel_frames);

    let content = format!("{}\n{}", info, heatmap);
    let paragraph = Paragraph::new(content);
    f.render_widget(paragraph, inner);
}

/// Render encoder panel
fn render_encoder_panel(f: &mut Frame<'_>, app: &WhisperApp, area: Rect) {
    let block = Block::default()
        .borders(Borders::ALL)
        .title("ENCODER - Layer Activations");

    let inner = block.inner(area);
    f.render_widget(block, area);

    if render_empty_placeholder(
        f,
        inner,
        &app.encoder_metrics,
        "No encoder data. Start encoding to see layer activations.",
    ) {
        return;
    }

    // Create table of layer metrics
    let rows: Vec<Row<'_>> = app
        .encoder_metrics
        .iter()
        .map(|m| {
            Row::new(vec![
                Cell::from(format!("Layer {}", m.layer)),
                Cell::from(format!("{:.3}", m.mean_activation)),
                Cell::from(format!("{:.3}", m.max_activation)),
                Cell::from(format!("{:.3}", m.attention_entropy)),
            ])
        })
        .collect();

    render_data_table(
        f,
        inner,
        &["Layer", "Mean Act.", "Max Act.", "Attn Entropy"],
        &[10, 12, 12, 14],
        rows,
    );
}

/// Render decoder panel
fn render_decoder_panel(f: &mut Frame<'_>, app: &WhisperApp, area: Rect) {
    let block = Block::default()
        .borders(Borders::ALL)
        .title("DECODER - Token Generation");

    let inner = block.inner(area);
    f.render_widget(block, area);

    if render_empty_placeholder(
        f,
        inner,
        &app.decoder_tokens,
        "No tokens generated. Start decoding to see tokens.",
    ) {
        return;
    }

    // Create table of tokens
    let rows: Vec<Row<'_>> = app
        .decoder_tokens
        .iter()
        .enumerate()
        .map(|(i, t)| {
            Row::new(vec![
                Cell::from(format!("{}", i)),
                Cell::from(format!("{}", t.id)),
                Cell::from(t.text.clone()),
                Cell::from(format!("{:.3}", t.log_prob)),
            ])
        })
        .collect();

    render_data_table(
        f,
        inner,
        &["Idx", "Token ID", "Text", "Log P"],
        &[5, 10, 20, 10],
        rows,
    );
}

/// Render attention panel
fn render_attention_panel(f: &mut Frame<'_>, app: &WhisperApp, area: Rect) {
    let block = Block::default()
        .borders(Borders::ALL)
        .title("ATTENTION - Cross-Attention Weights");

    let inner = block.inner(area);
    f.render_widget(block, area);

    if render_empty_placeholder(
        f,
        inner,
        &app.attention_weights,
        "No attention data. Decode to see cross-attention.",
    ) {
        return;
    }

    // Render attention heatmap
    let heatmap = render_attention_heatmap(
        &app.attention_weights,
        inner.width as usize,
        inner.height as usize,
    );

    let info = format!(
        "Cross-attention: {} tokens x {} frames",
        app.attention_weights.len(),
        app.attention_weights.first().map(|a| a.len()).unwrap_or(0)
    );

    let content = format!("{}\n{}", info, heatmap);
    let paragraph = Paragraph::new(content);
    f.render_widget(paragraph, inner);
}

/// Render transcription panel
fn render_transcription_panel(f: &mut Frame<'_>, app: &WhisperApp, area: Rect) {
    let block = Block::default()
        .borders(Borders::ALL)
        .title("TRANSCRIPTION - Final Output");

    let inner = block.inner(area);
    f.render_widget(block, area);

    let content = if app.transcription.is_empty() {
        "No transcription yet. Complete pipeline to see result.".to_string()
    } else {
        let mut text = String::new();
        text.push_str(&format!("Result: {}\n\n", app.transcription));
        text.push_str("Token Details:\n");

        for (i, token) in app.decoder_tokens.iter().enumerate() {
            text.push_str(&format!(
                "  [{}] {} (p={:.3})\n",
                i,
                token.text,
                token.log_prob.exp()
            ));
        }

        text
    };

    let paragraph = Paragraph::new(content);
    f.render_widget(paragraph, inner);
}

/// Render metrics panel
fn render_metrics_panel(f: &mut Frame<'_>, app: &WhisperApp, area: Rect) {
    let block = Block::default()
        .borders(Borders::ALL)
        .title("METRICS - Performance Data");

    let inner = block.inner(area);
    f.render_widget(block, area);

    let m = &app.metrics;

    let content = format!(
        r#"Pipeline Performance Metrics

Audio Duration:    {:.2} seconds
Sample Rate:       {} Hz
Mel Frames:        {}

Timing Breakdown:
  Mel Compute:     {:.2} ms
  Encoder:         {:.2} ms
  Decoder:         {:.2} ms
  ─────────────────────
  Total:           {:.2} ms

RTF (Real-Time Factor): {:.3}x
  (< 1.0 = faster than real-time)

Tokens Generated:  {}
Tokens/Second:     {:.1}
"#,
        m.audio_duration_secs,
        app.sample_rate,
        app.mel_frames,
        m.mel_time_ms,
        m.encoder_time_ms,
        m.decoder_time_ms,
        m.total_time_ms,
        m.rtf,
        m.tokens_generated,
        if m.total_time_ms > 0.0 {
            m.tokens_generated as f32 / (m.total_time_ms / 1000.0)
        } else {
            0.0
        }
    );

    let paragraph = Paragraph::new(content);
    f.render_widget(paragraph, inner);
}

/// Render help panel
fn render_help_panel(f: &mut Frame<'_>, _app: &WhisperApp, area: Rect) {
    let block = Block::default()
        .borders(Borders::ALL)
        .title("HELP - Keyboard Shortcuts");

    let inner = block.inner(area);
    f.render_widget(block, area);

    let content = r#"Keyboard Bindings

Panel Navigation:
  1  Waveform panel
  2  Mel spectrogram panel
  3  Encoder panel
  4  Decoder panel
  5  Attention panel
  6  Transcription panel
  7  Metrics panel
  ?  This help panel

Controls:
  Space  Pause/Resume
  r      Reset pipeline
  q      Quit

Scroll (where applicable):
  ←/→    Scroll horizontally
  ↑/↓    Scroll vertically

References:
  Radford et al. (2022) - Whisper architecture
  Davis & Mermelstein (1980) - Mel filterbank
  Vaswani et al. (2017) - Transformer attention
"#;

    let paragraph = Paragraph::new(content);
    f.render_widget(paragraph, inner);
}

/// Render status bar
fn render_status_bar(f: &mut Frame<'_>, app: &WhisperApp, area: Rect) {
    let state_color = match app.state {
        WhisperState::Idle => Color::DarkGray,
        WhisperState::WaveformReady => Color::Blue,
        WhisperState::MelReady => Color::Cyan,
        WhisperState::Encoding => Color::Yellow,
        WhisperState::Decoding => Color::Magenta,
        WhisperState::Complete => Color::Green,
        WhisperState::Error => Color::Red,
    };

    let state_text = app.state_description();
    let status = app.status_message.as_deref().unwrap_or("");
    let paused = if app.paused { " [PAUSED]" } else { "" };

    let spans = vec![
        Span::styled(
            format!(" {} ", state_text),
            Style::default().fg(Color::Black).bg(state_color),
        ),
        Span::raw(format!(" {} {}", status, paused)),
    ];

    let paragraph = Paragraph::new(Line::from(spans)).block(Block::default().borders(Borders::ALL));

    f.render_widget(paragraph, area);
}