aurum-core 0.0.17

On-device speech I/O core: whisper.cpp STT, ONNX TTS, cleanup, providers
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
//! Transcription provider abstraction.

pub mod local;
pub mod openrouter;

use crate::audio::AudioInput;
use crate::error::Result;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};

/// How a backend produces transcripts — affects timestamp trust and UX.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BackendKind {
    /// Dedicated ASR (e.g. whisper.cpp). Timestamps are engine-derived.
    Asr,
    /// Multimodal LLM asked to transcribe. Text may paraphrase; timestamps are unreliable.
    LlmAssisted,
}

/// Options controlling a single transcription request.
#[derive(Debug, Clone)]
pub struct TranscriptionOptions {
    /// Model name (local ggml name or remote model id).
    pub model: String,
    /// BCP-47 / ISO language code, or `"auto"`.
    pub language: String,
    /// Request segment-level timestamps when the provider supports them.
    pub timestamps: bool,
    /// Optional cooperative cancel flag (honoured by local whisper decode).
    pub cancel: Option<crate::cancel::CancelFlag>,
}

impl Default for TranscriptionOptions {
    fn default() -> Self {
        Self {
            model: crate::config::DEFAULT_LOCAL_MODEL.to_string(),
            language: crate::config::DEFAULT_LANGUAGE.to_string(),
            timestamps: false,
            cancel: None,
        }
    }
}

impl TranscriptionOptions {
    pub fn with_cancel(mut self, flag: crate::cancel::CancelFlag) -> Self {
        self.cancel = Some(flag);
        self
    }
}

/// A single timed segment of transcript text.
///
/// Fields are **private** (JOE-1786). Construct with [`Segment::try_new`] (fail closed)
/// or deserialize then [`Segment::validate`]. Prefer accessors over free mutation.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Segment {
    /// Start time in seconds.
    start: f64,
    /// End time in seconds.
    end: f64,
    text: String,
}

impl Segment {
    /// Construct a segment, rejecting NaN/Inf, negatives, and inverted ranges (JOE-1781).
    pub fn try_new(start: f64, end: f64, text: impl Into<String>) -> Result<Self> {
        let s = Self {
            start,
            end,
            text: text.into(),
        };
        s.validate()?;
        Ok(s)
    }

    /// Construct without validation (trusted provider/postprocess paths and tests).
    ///
    /// Prefer [`Segment::try_new`] for host-facing construction. Callers that
    /// skip validation must treat the segment as untrusted until [`Segment::validate`].
    pub fn from_parts_unchecked(start: f64, end: f64, text: impl Into<String>) -> Self {
        Self {
            start,
            end,
            text: text.into(),
        }
    }

    pub fn start(&self) -> f64 {
        self.start
    }

    pub fn end(&self) -> f64 {
        self.end
    }

    pub fn text(&self) -> &str {
        &self.text
    }

    pub fn set_start(&mut self, start: f64) {
        self.start = start;
    }

    pub fn set_end(&mut self, end: f64) {
        self.end = end;
    }

    pub fn set_text(&mut self, text: impl Into<String>) {
        self.text = text.into();
    }

    /// Validate timestamp finite-ness and ordering.
    pub fn validate(&self) -> Result<()> {
        if !self.start.is_finite() || !self.end.is_finite() {
            return Err(crate::error::UserError::Other {
                message: format!(
                    "segment timestamps must be finite (start={}, end={})",
                    self.start, self.end
                ),
            }
            .into());
        }
        if self.start < 0.0 || self.end < 0.0 {
            return Err(crate::error::UserError::Other {
                message: format!(
                    "segment timestamps must be non-negative (start={}, end={})",
                    self.start, self.end
                ),
            }
            .into());
        }
        if self.end < self.start {
            return Err(crate::error::UserError::Other {
                message: format!(
                    "segment end before start (start={}, end={})",
                    self.start, self.end
                ),
            }
            .into());
        }
        Ok(())
    }
}

/// Normalized result returned by every provider.
///
/// Fields are **private** (JOE-1809). Prefer builders
/// [`TranscriptionResult::local`] / [`TranscriptionResult::openrouter`] and
/// accessors. `Deserialize` is untrusted — use [`TranscriptionResult::try_from_dto`]
/// or [`TranscriptionResult::validate_segments`] before relying on timings.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TranscriptionResult {
    text: String,
    segments: Vec<Segment>,
    language: Option<String>,
    model: String,
    provider: String,
    duration_secs: f64,
    /// Backend class — consumers should treat LLM timestamps as best-effort.
    #[serde(default = "default_backend_kind")]
    backend_kind: BackendKind,
    /// Whether segment timestamps are considered reliable.
    #[serde(default = "default_true")]
    timestamps_reliable: bool,
    /// Post-ASR cleanup style applied to [`Self::text`] (default: raw).
    #[serde(default)]
    cleanup_style: crate::cleanup::CleanupStyle,
    /// Cleanup backend used, if any cleanup beyond raw was applied.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    cleanup_provider: Option<crate::cleanup::CleanupProviderKind>,
    /// Pre-cleanup ASR text when cleanup rewrote [`Self::text`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    original_text: Option<String>,
    /// Pre-cleanup ASR segments when cleanup rewrote or cleared timings.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    original_segments: Option<Vec<Segment>>,
    /// Segment policy that was applied during cleanup (when not raw).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    cleanup_segment_policy: Option<crate::cleanup::SegmentCleanupPolicy>,
}

fn default_backend_kind() -> BackendKind {
    BackendKind::Asr
}
fn default_true() -> bool {
    true
}

impl TranscriptionResult {
    pub fn text(&self) -> &str {
        &self.text
    }

    pub fn set_text(&mut self, text: impl Into<String>) {
        self.text = text.into();
    }

    pub fn segments(&self) -> &[Segment] {
        &self.segments
    }

    pub fn segments_mut(&mut self) -> &mut Vec<Segment> {
        &mut self.segments
    }

    pub fn set_segments(&mut self, segments: Vec<Segment>) {
        self.segments = segments;
    }

    pub fn language(&self) -> Option<&str> {
        self.language.as_deref()
    }

    pub fn set_language(&mut self, language: Option<String>) {
        self.language = language;
    }

    pub fn model(&self) -> &str {
        &self.model
    }

    pub fn set_model(&mut self, model: impl Into<String>) {
        self.model = model.into();
    }

    pub fn provider(&self) -> &str {
        &self.provider
    }

    pub fn set_provider(&mut self, provider: impl Into<String>) {
        self.provider = provider.into();
    }

    pub fn duration_secs(&self) -> f64 {
        self.duration_secs
    }

    pub fn set_duration_secs(&mut self, duration_secs: f64) {
        self.duration_secs = duration_secs;
    }

    pub fn backend_kind(&self) -> BackendKind {
        self.backend_kind
    }

    pub fn set_backend_kind(&mut self, kind: BackendKind) {
        self.backend_kind = kind;
    }

    pub fn timestamps_reliable(&self) -> bool {
        self.timestamps_reliable
    }

    pub fn set_timestamps_reliable(&mut self, reliable: bool) {
        self.timestamps_reliable = reliable;
    }

    pub fn cleanup_style(&self) -> crate::cleanup::CleanupStyle {
        self.cleanup_style
    }

    pub fn set_cleanup_style(&mut self, style: crate::cleanup::CleanupStyle) {
        self.cleanup_style = style;
    }

    pub fn cleanup_provider(&self) -> Option<crate::cleanup::CleanupProviderKind> {
        self.cleanup_provider
    }

    pub fn set_cleanup_provider(&mut self, provider: Option<crate::cleanup::CleanupProviderKind>) {
        self.cleanup_provider = provider;
    }

    pub fn original_text(&self) -> Option<&str> {
        self.original_text.as_deref()
    }

    pub fn set_original_text(&mut self, text: Option<String>) {
        self.original_text = text;
    }

    pub fn original_segments(&self) -> Option<&[Segment]> {
        self.original_segments.as_deref()
    }

    pub fn set_original_segments(&mut self, segments: Option<Vec<Segment>>) {
        self.original_segments = segments;
    }

    pub fn cleanup_segment_policy(&self) -> Option<crate::cleanup::SegmentCleanupPolicy> {
        self.cleanup_segment_policy
    }

    pub fn set_cleanup_segment_policy(
        &mut self,
        policy: Option<crate::cleanup::SegmentCleanupPolicy>,
    ) {
        self.cleanup_segment_policy = policy;
    }

    /// Validate all segments (finite, ordered timestamps).
    pub fn validate_segments(&self) -> Result<()> {
        for (i, seg) in self.segments.iter().enumerate() {
            if let Err(e) = seg.validate() {
                return Err(crate::error::UserError::Other {
                    message: format!("segment[{i}]: {e}"),
                }
                .into());
            }
        }
        if !self.duration_secs.is_finite() || self.duration_secs < 0.0 {
            return Err(crate::error::UserError::Other {
                message: format!(
                    "duration_secs must be finite and non-negative (got {})",
                    self.duration_secs
                ),
            }
            .into());
        }
        Ok(())
    }

    /// Build a domain result from a public DTO **with validation** (JOE-1809).
    ///
    /// Deserializing JSON into [`crate::dto::SttResultDto`] alone does not create
    /// a trusted domain object — this path re-validates every segment and duration.
    pub fn try_from_dto(dto: &crate::dto::SttResultDto) -> Result<Self> {
        if dto.schema_version != crate::dto::STT_RESULT_SCHEMA_VERSION {
            return Err(crate::error::UserError::Other {
                message: format!(
                    "unsupported STT DTO schema_version {} (expected {})",
                    dto.schema_version,
                    crate::dto::STT_RESULT_SCHEMA_VERSION
                ),
            }
            .into());
        }
        let mut r = Self {
            text: dto.text.clone(),
            segments: dto.segments.clone(),
            language: dto.language.clone(),
            model: dto.model.clone(),
            provider: dto.provider.clone(),
            duration_secs: dto.duration_secs,
            backend_kind: dto.backend_kind,
            timestamps_reliable: dto.timestamps_reliable,
            cleanup_style: dto.cleanup_style,
            cleanup_provider: dto.cleanup_provider,
            original_text: dto.original_text.clone(),
            original_segments: dto.original_segments.clone(),
            cleanup_segment_policy: dto.cleanup_segment_policy,
        };
        // LLM-assisted paths cannot claim reliable timestamps through DTO injection.
        if matches!(r.backend_kind, BackendKind::LlmAssisted) {
            r.timestamps_reliable = false;
        }
        r.validate_segments()?;
        if let Some(ref segs) = r.original_segments {
            for (i, seg) in segs.iter().enumerate() {
                if let Err(e) = seg.validate() {
                    return Err(crate::error::UserError::Other {
                        message: format!("original_segments[{i}]: {e}"),
                    }
                    .into());
                }
            }
        }
        Ok(r)
    }

    pub fn local(
        text: String,
        segments: Vec<Segment>,
        language: Option<String>,
        model: String,
        duration_secs: f64,
    ) -> Self {
        Self {
            text,
            segments,
            language,
            model,
            provider: "local".into(),
            duration_secs,
            backend_kind: BackendKind::Asr,
            timestamps_reliable: true,
            cleanup_style: crate::cleanup::CleanupStyle::Raw,
            cleanup_provider: None,
            original_text: None,
            original_segments: None,
            cleanup_segment_policy: None,
        }
    }

    /// Like [`Self::local`] but fail-closed when segments/duration are invalid (JOE-1781).
    pub fn try_local(
        text: String,
        segments: Vec<Segment>,
        language: Option<String>,
        model: String,
        duration_secs: f64,
    ) -> Result<Self> {
        let r = Self::local(text, segments, language, model, duration_secs);
        r.validate_segments()?;
        Ok(r)
    }

    pub fn openrouter(
        text: String,
        segments: Vec<Segment>,
        language: Option<String>,
        model: String,
        duration_secs: f64,
        _timestamps_requested: bool,
    ) -> Self {
        Self {
            text,
            segments,
            language,
            model,
            provider: "openrouter".into(),
            duration_secs,
            backend_kind: BackendKind::LlmAssisted,
            // LLM timestamps are never treated as reliable ASR timing.
            timestamps_reliable: false,
            cleanup_style: crate::cleanup::CleanupStyle::Raw,
            cleanup_provider: None,
            original_text: None,
            original_segments: None,
            cleanup_segment_policy: None,
        }
    }

    /// Like [`Self::openrouter`] but fail-closed on invalid segments/duration (JOE-1781).
    pub fn try_openrouter(
        text: String,
        segments: Vec<Segment>,
        language: Option<String>,
        model: String,
        duration_secs: f64,
        timestamps_requested: bool,
    ) -> Result<Self> {
        let r = Self::openrouter(
            text,
            segments,
            language,
            model,
            duration_secs,
            timestamps_requested,
        );
        r.validate_segments()?;
        Ok(r)
    }
}

/// Provider trait — the foundation for local and remote backends.
#[async_trait]
pub trait TranscriptionProvider: Send + Sync {
    /// Human-readable provider name (e.g. `"local"`, `"openrouter"`).
    fn name(&self) -> &'static str;

    /// Backend classification.
    fn backend_kind(&self) -> BackendKind;

    /// Whether this provider can emit trustworthy media timestamps.
    fn timestamps_reliable(&self) -> bool {
        matches!(self.backend_kind(), BackendKind::Asr)
    }

    /// Transcribe audio according to `options`.
    async fn transcribe(
        &self,
        input: &AudioInput,
        options: &TranscriptionOptions,
    ) -> Result<TranscriptionResult>;
}

pub use local::LocalWhisperProvider;
pub use openrouter::{OpenRouterProvider, OpenRouterSttMode, SttPath};

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn segment_try_new_accepts_valid() {
        let s = Segment::try_new(0.0, 1.5, "hello").unwrap();
        assert_eq!(s.start, 0.0);
        assert_eq!(s.end, 1.5);
        assert_eq!(s.text, "hello");
    }

    #[test]
    fn segment_try_new_rejects_nan() {
        assert!(Segment::try_new(f64::NAN, 1.0, "x").is_err());
        assert!(Segment::try_new(0.0, f64::INFINITY, "x").is_err());
    }

    #[test]
    fn segment_try_new_rejects_negative_and_inverted() {
        assert!(Segment::try_new(-0.1, 1.0, "x").is_err());
        assert!(Segment::try_new(2.0, 1.0, "x").is_err());
    }

    #[test]
    fn segment_validate_ok_on_zero_length() {
        // Zero-duration is allowed (start == end).
        Segment::try_new(1.0, 1.0, "").unwrap();
    }

    #[test]
    fn try_local_rejects_nan_segment() {
        let segs = vec![Segment::from_parts_unchecked(
            f64::NAN,
            1.0,
            "x".to_string(),
        )];
        assert!(TranscriptionResult::try_local("x".into(), segs, None, "m".into(), 1.0).is_err());
    }

    #[test]
    fn try_local_accepts_valid() {
        let segs = vec![Segment::try_new(0.0, 0.5, "hi").unwrap()];
        let r =
            TranscriptionResult::try_local("hi".into(), segs, Some("en".into()), "m".into(), 1.0)
                .unwrap();
        assert_eq!(r.provider(), "local");
    }

    #[test]
    fn try_from_dto_rejects_nan_segment() {
        let mut dto = crate::dto::SttResultDto::from_result(&TranscriptionResult::local(
            "x".into(),
            vec![Segment::try_new(0.0, 1.0, "x").unwrap()],
            None,
            "m".into(),
            1.0,
        ));
        dto.segments = vec![Segment::from_parts_unchecked(
            f64::NAN,
            1.0,
            "x".to_string(),
        )];
        assert!(TranscriptionResult::try_from_dto(&dto).is_err());
    }

    #[test]
    fn try_from_dto_forces_llm_timestamps_unreliable() {
        let mut dto = crate::dto::SttResultDto::from_result(&TranscriptionResult::openrouter(
            "hi".into(),
            vec![Segment::try_new(0.0, 1.0, "hi").unwrap()],
            None,
            "m".into(),
            1.0,
            true,
        ));
        dto.timestamps_reliable = true; // injection attempt
        let r = TranscriptionResult::try_from_dto(&dto).unwrap();
        assert!(!r.timestamps_reliable());
        assert_eq!(r.backend_kind(), BackendKind::LlmAssisted);
    }
}