asr-core 0.0.3

Unified streaming, offline, and cloud speech-to-text engine for Rust
Documentation
//! Snapshot → delta conversion for the SSE wire: the engine reports
//! whole-transcript snapshots, the OpenAI streaming protocol travels
//! append-only deltas (`transcript.text.delta` accumulates by appending;
//! `transcript.text.done` carries the authoritative full text).

/// Converts consecutive whole-transcript snapshots into append-only
/// deltas.
///
/// The client side of this protocol accumulates by appending, so a
/// snapshot can only travel as a delta when it strictly extends what was
/// already **sent**. A snapshot that rewrites sent text — a mid-utterance
/// rollback or revision, which ASR partials produce routinely — yields no
/// delta: emitting one would corrupt the client's accumulated text (the
/// append-only wire has no replace event), so the builder keeps waiting on
/// the last *sent* text and resyncs as soon as a snapshot re-extends it.
/// The final `transcript.text.done` frame is authoritative either way.
pub struct TextDeltaBuilder {
    /// What the client has accumulated so far — deliberately not the
    /// latest snapshot, so a rollback cannot desynchronize the delta
    /// stream from the client's view.
    sent: String,
}

impl TextDeltaBuilder {
    pub fn new() -> Self {
        Self {
            sent: String::new(),
        }
    }

    /// Feeds one snapshot; returns the delta the client should append, or
    /// `None` when the snapshot adds nothing expressible (no change, or a
    /// revision of already-sent text).
    pub fn update(&mut self, snapshot: &str) -> Option<String> {
        if !snapshot.starts_with(self.sent.as_str()) || snapshot == self.sent {
            return None;
        }
        let delta = snapshot[self.sent.len()..].to_string();
        self.sent = snapshot.to_string();
        Some(delta)
    }

    /// What the client has accumulated so far.
    pub fn sent(&self) -> &str {
        &self.sent
    }
}

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

#[cfg(test)]
mod tests;