Skip to main content

adk_audio/traits/
stt.rs

1//! Speech-to-text provider trait and response types.
2
3use std::pin::Pin;
4
5use async_trait::async_trait;
6use futures::Stream;
7
8use crate::error::{AudioError, AudioResult};
9use crate::frame::AudioFrame;
10use crate::metering::AudioBilling;
11
12/// Options for speech-to-text transcription.
13///
14/// # Example
15///
16/// ```
17/// use adk_audio::SttOptions;
18///
19/// let options = SttOptions::default()
20///     .with_language("en-US")
21///     .with_keywords(["Muse", "ADK-Rust"])
22///     .with_language_bias(["en", "sw"])
23///     .with_diarize(true);
24/// assert_eq!(options.keywords, ["Muse", "ADK-Rust"]);
25/// assert!(options.diarize);
26/// ```
27#[derive(Debug, Clone, Default)]
28#[non_exhaustive]
29pub struct SttOptions {
30    /// Optional BCP-47 language hint.
31    pub language: Option<String>,
32    /// Enable speaker diarization.
33    pub diarize: bool,
34    /// Include per-word timestamps.
35    pub word_timestamps: bool,
36    /// Apply smart formatting (punctuation, casing).
37    pub smart_format: bool,
38    /// Optional model hint for the provider.
39    pub model_hint: Option<String>,
40    /// Domain vocabulary the provider should favour, for providers that take keyword hints.
41    pub keywords: Vec<String>,
42    /// BCP-47 languages the audio is likely in, for providers that take several.
43    pub language_bias: Vec<String>,
44}
45
46impl SttOptions {
47    /// Sets the language hint.
48    #[must_use]
49    pub fn with_language(mut self, language: impl Into<String>) -> Self {
50        self.language = Some(language.into());
51        self
52    }
53
54    /// Turns speaker diarization on or off.
55    #[must_use]
56    pub fn with_diarize(mut self, diarize: bool) -> Self {
57        self.diarize = diarize;
58        self
59    }
60
61    /// Turns per-word timestamps on or off.
62    #[must_use]
63    pub fn with_word_timestamps(mut self, word_timestamps: bool) -> Self {
64        self.word_timestamps = word_timestamps;
65        self
66    }
67
68    /// Turns smart formatting on or off.
69    #[must_use]
70    pub fn with_smart_format(mut self, smart_format: bool) -> Self {
71        self.smart_format = smart_format;
72        self
73    }
74
75    /// Sets the model hint.
76    #[must_use]
77    pub fn with_model_hint(mut self, model: impl Into<String>) -> Self {
78        self.model_hint = Some(model.into());
79        self
80    }
81
82    /// Sets the keyword hints.
83    #[must_use]
84    pub fn with_keywords(mut self, keywords: impl IntoIterator<Item = impl Into<String>>) -> Self {
85        self.keywords = keywords.into_iter().map(Into::into).collect();
86        self
87    }
88
89    /// Sets the languages the audio is likely in.
90    #[must_use]
91    pub fn with_language_bias(
92        mut self,
93        languages: impl IntoIterator<Item = impl Into<String>>,
94    ) -> Self {
95        self.language_bias = languages.into_iter().map(Into::into).collect();
96        self
97    }
98}
99
100/// One event of a live transcription ([`SttProvider::transcribe_stream`]).
101///
102/// | Event | Meaning |
103/// |-------|---------|
104/// | [`Started`](Self::Started) | The provider accepted the session |
105/// | [`SpeechStarted`](Self::SpeechStarted) | Speech began; later events with the same `turn_id` belong to it |
106/// | [`Partial`](Self::Partial) | The current hypothesis for the turn, in full; a later `Partial` or the `Final` replaces it |
107/// | [`Final`](Self::Final) | Text the provider will not revise; at most one per turn for providers that number turns |
108/// | [`SpeechEnded`](Self::SpeechEnded) | Speech stopped |
109/// | [`Speaker`](Self::Speaker) | The speaker changed (diarization) |
110/// | [`Progress`](Self::Progress) | How much audio the provider has processed |
111/// | [`Usage`](Self::Usage) | The audio the session is billed for, its billing basis |
112///
113/// A provider that streams deltas reports them as cumulative `Partial` text, so a consumer
114/// always replaces the displayed hypothesis rather than appending to it.
115///
116/// # Example
117///
118/// ```
119/// use adk_audio::{Transcript, TranscriptEvent};
120///
121/// let events = [
122///     TranscriptEvent::Partial { turn_id: Some(1), text: "hello wor".into() },
123///     TranscriptEvent::Final {
124///         turn_id: Some(1),
125///         transcript: Transcript { text: "hello world".into(), ..Default::default() },
126///     },
127/// ];
128/// let finals: Vec<&str> = events
129///     .iter()
130///     .filter_map(|event| match event {
131///         TranscriptEvent::Final { transcript, .. } => Some(transcript.text.as_str()),
132///         _ => None,
133///     })
134///     .collect();
135/// assert_eq!(finals, ["hello world"]);
136/// ```
137#[derive(Debug, Clone)]
138#[non_exhaustive]
139pub enum TranscriptEvent {
140    /// The provider accepted the session.
141    Started {
142        /// The provider's session id, when it reports one.
143        session_id: Option<String>,
144    },
145    /// Speech began.
146    SpeechStarted {
147        /// The turn the speech opens, when the provider numbers turns.
148        turn_id: Option<u32>,
149        /// Where in the audio it began, in milliseconds, when reported.
150        offset_ms: Option<u64>,
151    },
152    /// The current hypothesis for a turn, in full.
153    Partial {
154        /// The turn, when the provider numbers turns.
155        turn_id: Option<u32>,
156        /// The hypothesis.
157        text: String,
158    },
159    /// Text the provider will not revise.
160    Final {
161        /// The turn, when the provider numbers turns.
162        turn_id: Option<u32>,
163        /// The transcript.
164        transcript: Transcript,
165    },
166    /// Speech stopped.
167    SpeechEnded {
168        /// The turn the silence closes, when the provider numbers turns.
169        turn_id: Option<u32>,
170        /// Where in the audio it stopped, in milliseconds, when reported.
171        offset_ms: Option<u64>,
172    },
173    /// The speaker changed.
174    Speaker {
175        /// The provider's label for the speaker.
176        label: String,
177        /// Where in the audio the change happened, in milliseconds, when reported.
178        offset_ms: Option<u64>,
179    },
180    /// Audio the provider has processed so far, in milliseconds.
181    Progress {
182        /// Milliseconds processed.
183        processed_ms: u64,
184    },
185    /// The audio the session is billed for, in milliseconds.
186    Usage {
187        /// Milliseconds billed.
188        audio_ms: u64,
189    },
190}
191
192/// A live transcription: the events of [`SttProvider::transcribe_stream`].
193pub type TranscriptStream = Pin<Box<dyn Stream<Item = AudioResult<TranscriptEvent>> + Send>>;
194
195/// A transcription result.
196#[derive(Debug, Clone, Default)]
197pub struct Transcript {
198    /// Full transcribed text.
199    pub text: String,
200    /// Per-word details with timestamps.
201    pub words: Vec<Word>,
202    /// Identified speakers.
203    pub speakers: Vec<Speaker>,
204    /// Overall confidence score (0.0–1.0).
205    pub confidence: f32,
206    /// Detected language (BCP-47).
207    pub language_detected: Option<String>,
208}
209
210/// A single word with timing and confidence.
211#[derive(Debug, Clone)]
212pub struct Word {
213    /// The word text.
214    pub text: String,
215    /// Start time in milliseconds.
216    pub start_ms: u32,
217    /// End time in milliseconds.
218    pub end_ms: u32,
219    /// Word-level confidence (0.0–1.0).
220    pub confidence: f32,
221    /// Speaker ID if diarization is enabled.
222    pub speaker: Option<u32>,
223}
224
225/// An identified speaker.
226#[derive(Debug, Clone)]
227pub struct Speaker {
228    /// Numeric speaker identifier.
229    pub id: u32,
230    /// Optional human-readable label.
231    pub label: Option<String>,
232}
233
234/// Unified trait for speech-to-text providers.
235///
236/// Implementors include cloud services (Whisper API, Deepgram, AssemblyAI)
237/// and local models (MLX Whisper).
238#[async_trait]
239pub trait SttProvider: Send + Sync {
240    /// Transcribe a single audio frame (batch mode).
241    async fn transcribe(&self, audio: &AudioFrame, opts: &SttOptions) -> AudioResult<Transcript>;
242
243    /// Transcribes a stream of audio frames as they arrive, yielding [`TranscriptEvent`]s.
244    ///
245    /// The default, for a provider without streaming support, returns
246    /// [`AudioError::Stt`] instead of an empty stream. Dropping the returned stream stops the
247    /// provider's work for it, including any task that forwards `audio`, and releases
248    /// `audio`.
249    ///
250    /// # Errors
251    ///
252    /// Returns [`AudioError::Stt`] when the provider does not support streaming or cannot
253    /// open the stream.
254    async fn transcribe_stream(
255        &self,
256        audio: Pin<Box<dyn Stream<Item = AudioFrame> + Send>>,
257        opts: &SttOptions,
258    ) -> AudioResult<TranscriptStream> {
259        let _ = (audio, opts);
260        Err(AudioError::Stt {
261            provider: "stt".into(),
262            message: "this provider does not support streaming transcription; use transcribe"
263                .into(),
264        })
265    }
266
267    /// The vendor and model this provider's calls are billed under, for metering them
268    /// against the current run ([`crate::metering`]). `None`, the default, for a provider
269    /// that bills nothing, such as a local model.
270    fn billing(&self) -> Option<AudioBilling> {
271        None
272    }
273}