Skip to main content

aurum_core/
dto.rs

1//! Versioned external JSON DTOs (JOE-1614).
2//!
3//! In-memory domain types are converted *to* these DTOs for CLI/embed JSON.
4//! Deserializing a DTO does **not** reconstruct native audio buffers.
5
6use crate::cleanup::{CleanupProviderKind, CleanupStyle, SegmentCleanupPolicy};
7use crate::error::TranscriptionError;
8use crate::providers::{BackendKind, Segment, TranscriptionResult};
9use serde::{Deserialize, Serialize};
10
11/// Current STT result schema version for `--emit-json` / library export.
12pub const STT_RESULT_SCHEMA_VERSION: u32 = 1;
13/// TTS metadata schema (PCM never included).
14pub const TTS_META_SCHEMA_VERSION: u32 = 1;
15/// Error envelope schema.
16pub const ERROR_SCHEMA_VERSION: u32 = 1;
17
18/// Versioned STT result DTO (public contract).
19#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
20pub struct SttResultDto {
21    pub schema_version: u32,
22    pub text: String,
23    pub language: Option<String>,
24    pub model: String,
25    pub provider: String,
26    pub duration_secs: f64,
27    pub backend_kind: BackendKind,
28    pub timestamps_reliable: bool,
29    pub cleanup_style: CleanupStyle,
30    #[serde(skip_serializing_if = "Option::is_none")]
31    pub cleanup_provider: Option<CleanupProviderKind>,
32    #[serde(skip_serializing_if = "Option::is_none")]
33    pub original_text: Option<String>,
34    #[serde(skip_serializing_if = "Option::is_none")]
35    pub original_segments: Option<Vec<Segment>>,
36    #[serde(skip_serializing_if = "Option::is_none")]
37    pub cleanup_segment_policy: Option<SegmentCleanupPolicy>,
38    pub segments: Vec<Segment>,
39    /// Normalization warnings (empty when none).
40    #[serde(default, skip_serializing_if = "Vec::is_empty")]
41    pub normalization_warnings: Vec<String>,
42    #[serde(default, skip_serializing_if = "Option::is_none")]
43    pub request_id: Option<u64>,
44}
45
46impl SttResultDto {
47    pub fn from_result(result: &TranscriptionResult) -> Self {
48        Self::from_result_with_warnings(result, &[])
49    }
50
51    pub fn from_result_with_warnings(result: &TranscriptionResult, warnings: &[String]) -> Self {
52        Self {
53            schema_version: STT_RESULT_SCHEMA_VERSION,
54            text: result.text().to_string(),
55            language: result.language().map(|s| s.to_string()),
56            model: result.model().to_string(),
57            provider: result.provider().to_string(),
58            duration_secs: finite_or_zero(result.duration_secs()),
59            backend_kind: result.backend_kind(),
60            timestamps_reliable: result.timestamps_reliable(),
61            cleanup_style: result.cleanup_style(),
62            cleanup_provider: result.cleanup_provider(),
63            original_text: result.original_text().map(|s| s.to_string()),
64            original_segments: result.original_segments().map(|s| s.to_vec()),
65            cleanup_segment_policy: result.cleanup_segment_policy(),
66            segments: result
67                .segments()
68                .iter()
69                .map(|s| {
70                    Segment::from_parts_unchecked(
71                        finite_or_zero(s.start()),
72                        finite_or_zero(s.end()),
73                        s.text().to_string(),
74                    )
75                })
76                .collect(),
77            normalization_warnings: warnings.to_vec(),
78            request_id: None,
79        }
80    }
81
82    /// Convert this DTO into a validated domain [`TranscriptionResult`] (JOE-1809).
83    pub fn into_domain(self) -> crate::error::Result<TranscriptionResult> {
84        TranscriptionResult::try_from_dto(&self)
85    }
86
87    /// Pretty JSON that never emits NaN/Inf.
88    pub fn to_json_pretty(&self) -> Result<String, TranscriptionError> {
89        serde_json::to_string_pretty(self)
90            .map_err(|e| TranscriptionError::internal(format!("STT DTO serialize failed: {e}")))
91    }
92}
93
94/// TTS metadata DTO — **no PCM bytes**.
95#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
96pub struct TtsMetaDto {
97    pub schema_version: u32,
98    pub sample_rate_hz: u32,
99    pub channels: u16,
100    pub backend_kind: String,
101    pub provider: String,
102    pub model: String,
103    pub voice: String,
104    pub language: String,
105    pub duration_ms: u64,
106    pub text_chars: usize,
107    pub text_truncated: bool,
108    pub chunk_count: usize,
109    pub synthesized_chars: usize,
110    /// Adapter id (JOE-1576); omitted when unknown.
111    #[serde(default, skip_serializing_if = "Option::is_none")]
112    pub adapter: Option<String>,
113    /// Trust mode: builtin | verified | local_unverified.
114    #[serde(default, skip_serializing_if = "Option::is_none")]
115    pub trust: Option<String>,
116    /// Provenance: builtin | custom | local_pack.
117    #[serde(default, skip_serializing_if = "Option::is_none")]
118    pub provenance: Option<String>,
119}
120
121#[cfg(feature = "tts")]
122impl TtsMetaDto {
123    pub fn from_result(r: &crate::tts::SynthesisResult) -> Self {
124        Self {
125            schema_version: TTS_META_SCHEMA_VERSION,
126            sample_rate_hz: r.sample_rate_hz,
127            channels: r.channels,
128            backend_kind: match r.backend_kind {
129                crate::tts::BackendKind::Local => "local".into(),
130            },
131            provider: r.provider.clone(),
132            model: r.model.clone(),
133            voice: r.voice.clone(),
134            language: r.language.clone(),
135            duration_ms: r.duration_ms,
136            text_chars: r.text_chars,
137            text_truncated: r.text_truncated,
138            chunk_count: r.chunk_count,
139            synthesized_chars: r.synthesized_chars,
140            adapter: r.adapter.clone(),
141            trust: r.trust.clone(),
142            provenance: r.provenance.clone(),
143        }
144    }
145}
146
147/// Stable error envelope for JSON/CLI.
148#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
149pub struct ErrorDto {
150    pub schema_version: u32,
151    pub category: String,
152    pub retryable: bool,
153    pub message: String,
154    pub exit_code: i32,
155    #[serde(skip_serializing_if = "Option::is_none")]
156    pub operation: Option<String>,
157}
158
159impl ErrorDto {
160    pub fn from_error(err: &TranscriptionError) -> Self {
161        Self {
162            schema_version: ERROR_SCHEMA_VERSION,
163            category: err.error_category().as_str().into(),
164            retryable: err.retryable(),
165            message: err.to_string(),
166            exit_code: err.exit_code(),
167            operation: None,
168        }
169    }
170}
171
172fn finite_or_zero(v: f64) -> f64 {
173    if v.is_finite() {
174        v
175    } else {
176        0.0
177    }
178}
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183
184    #[test]
185    fn stt_dto_roundtrip_fields() {
186        let r = TranscriptionResult::local(
187            "hi".into(),
188            vec![Segment::from_parts_unchecked(0.0, 1.0, "hi".to_string())],
189            Some("en".into()),
190            "base".into(),
191            1.0,
192        );
193        let dto = SttResultDto::from_result(&r);
194        let json = dto.to_json_pretty().unwrap();
195        assert!(json.contains("schema_version"));
196        assert!(!json.contains("NaN"));
197        let back: SttResultDto = serde_json::from_str(&json).unwrap();
198        assert_eq!(back.text, "hi");
199        assert_eq!(back.schema_version, 1);
200    }
201
202    #[test]
203    fn nan_duration_sanitized() {
204        let mut r = TranscriptionResult::local("x".into(), vec![], None, "m".into(), f64::NAN);
205        r.set_duration_secs(f64::NAN);
206        let dto = SttResultDto::from_result(&r);
207        assert_eq!(dto.duration_secs, 0.0);
208    }
209}