weirdnet-media 0.2.0

Weirdnet media processing for clients and nodes: WAV probing and PCM in pure Rust, 16 kHz resampling, silence-aware chunking, long-audio transcription plans, long-text speech plans, SRT/VTT, video frame planning, and a hardened ffmpeg runner with a test fake.
Documentation
//! Long-text speech: [`TextPlan`] splits narration or a script into pieces that each fit the
//! model's `max_input_chars`, and says how to join the synthesized pieces.
//!
//! The plan is pure and deterministic. It splits at paragraphs, then sentences, then clauses, then
//! words, packing consecutive units into each piece, and never splits inside a word. A script
//! keeps its turns: a piece never mixes speakers, and a turn over the limit splits at sentences and
//! keeps its speaker. Without `max_input_chars` the plan refuses text over
//! [`UNSET_LIMIT_REFUSAL`] characters and says to set it (a refusal threshold of the client, not a
//! limit claimed for any model).

use serde::{Deserialize, Serialize};

use crate::error::{MediaError, Result};
use crate::pcm::Join;

/// With no `max_input_chars`, text longer than this is refused.
pub const UNSET_LIMIT_REFUSAL: usize = 4000;

/// The crossfade inside a paragraph, in milliseconds.
pub const DEFAULT_CROSSFADE_MS: u64 = 10;

/// The pause between paragraphs and speaker turns, in milliseconds.
pub const DEFAULT_PAUSE_MS: u64 = 300;

/// One turn of a script.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ScriptTurn {
    pub speaker: u8,
    pub text: String,
}

impl ScriptTurn {
    /// A turn.
    pub fn new(speaker: u8, text: impl Into<String>) -> Self {
        ScriptTurn { speaker, text: text.into() }
    }
}

/// What to speak.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum SpeechText {
    /// Narration; paragraphs are separated by blank lines.
    Text(String),
    /// Turns by numbered speakers.
    Script(Vec<ScriptTurn>),
}

/// What bounds one speech request. Absent when unknown.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct TextLimits {
    /// The most characters one request takes (the speech profile's `max_input_chars`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_input_chars: Option<usize>,
}

impl TextLimits {
    /// Limits with `max_input_chars`.
    pub fn new(max_input_chars: Option<usize>) -> Self {
        TextLimits { max_input_chars }
    }
}

/// One request's worth of text.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TextPiece {
    pub index: usize,
    pub text: String,
    /// The script speaker; `None` for narration.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub speaker: Option<u8>,
    /// The script turn it comes from.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub turn: Option<usize>,
    /// The paragraph it starts in (counted across the whole input).
    pub paragraph: usize,
    /// Whether it starts a paragraph or a turn (so a pause, not a crossfade, comes before it).
    pub starts_paragraph: bool,
    /// Its length in characters.
    pub chars: usize,
}

/// The plan. See the [module docs](self).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TextPlan {
    pub pieces: Vec<TextPiece>,
    /// The limit the plan packed to.
    pub max_chars: usize,
}

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Level {
    Sentence,
    Clause,
    Word,
}

fn is_sentence_end(c: char) -> bool {
    matches!(c, '.' | '!' | '?' | '…' | '。' | '!' | '?')
}

fn is_cjk_end(c: char) -> bool {
    matches!(c, '。' | '!' | '?' | '、' | ',' | ';' | ':')
}

fn is_clause_end(c: char) -> bool {
    matches!(c, ',' | ';' | ':' | '—' | '–' | '、' | ',' | ';' | ':')
}

fn is_closer(c: char) -> bool {
    matches!(c, '"' | '\'' | '”' | '’' | ')' | ']' | '»' | '」' | '』')
}

/// Splits `s` (whitespace already collapsed) into units at `level`, as byte ranges that cover it.
fn units(s: &str, level: Level) -> Vec<(usize, usize)> {
    let chars: Vec<(usize, char)> = s.char_indices().collect();
    let mut out = Vec::new();
    let mut start = 0usize;
    let mut i = 0usize;
    while i < chars.len() {
        let (at, c) = chars[i];
        let boundary_char = match level {
            Level::Sentence => is_sentence_end(c),
            Level::Clause => is_sentence_end(c) || is_clause_end(c),
            Level::Word => c.is_whitespace(),
        };
        if boundary_char {
            let mut j = i + 1;
            if level != Level::Word {
                while j < chars.len() && (is_closer(chars[j].1) || (level == Level::Sentence && is_sentence_end(chars[j].1))) {
                    j += 1;
                }
            }
            let end_byte = chars.get(j).map(|x| x.0).unwrap_or(s.len());
            let next_ws = chars.get(j).is_none_or(|x| x.1.is_whitespace());
            if level == Level::Word || next_ws || is_cjk_end(c) {
                let end = if level == Level::Word { at } else { end_byte };
                if end > start {
                    out.push((start, end));
                }
                start = end;
                i = j;
                continue;
            }
        }
        i += 1;
    }
    if start < s.len() {
        out.push((start, s.len()));
    }
    out.into_iter().filter(|(a, b)| !s[*a..*b].trim().is_empty()).collect()
}

fn count(s: &str) -> usize {
    s.chars().count()
}

/// Packs `s` into pieces of at most `max` characters, splitting at the coarsest level that fits.
fn pack(s: &str, max: usize, level: Level, out: &mut Vec<String>) -> Result<()> {
    if count(s) <= max {
        out.push(s.to_string());
        return Ok(());
    }
    let parts = units(s, level);
    let finer = match level {
        Level::Sentence => Some(Level::Clause),
        Level::Clause => Some(Level::Word),
        Level::Word => None,
    };
    let mut current: Option<(usize, usize)> = None;
    let flush = |cur: &mut Option<(usize, usize)>, out: &mut Vec<String>| {
        if let Some((a, b)) = cur.take() {
            out.push(s[a..b].trim().to_string());
        }
    };
    for (a, b) in parts {
        let unit = s[a..b].trim();
        if count(unit) > max {
            flush(&mut current, out);
            match finer {
                Some(f) => pack(unit, max, f, out)?,
                None => {
                    return Err(MediaError::limit(format!("a word of {} characters is longer than the {max}-character limit", count(unit))));
                }
            }
            continue;
        }
        current = match current {
            Some((ca, _)) if count(s[ca..b].trim()) <= max => Some((ca, b)),
            Some(_) => {
                flush(&mut current, out);
                Some((a, b))
            }
            None => Some((a, b)),
        };
    }
    flush(&mut current, out);
    Ok(())
}

fn paragraphs(text: &str) -> Vec<String> {
    let mut out = Vec::new();
    let mut cur: Vec<&str> = Vec::new();
    for line in text.lines() {
        if line.trim().is_empty() {
            if !cur.is_empty() {
                out.push(cur.join(" "));
                cur.clear();
            }
        } else {
            cur.push(line);
        }
    }
    if !cur.is_empty() {
        out.push(cur.join(" "));
    }
    out.into_iter().map(|p| p.split_whitespace().collect::<Vec<_>>().join(" ")).filter(|p| !p.is_empty()).collect()
}

impl TextPlan {
    /// The plan for `input` under `limits`.
    pub fn new(input: &SpeechText, limits: TextLimits) -> Result<TextPlan> {
        let blocks: Vec<(Option<u8>, Option<usize>, &str)> = match input {
            SpeechText::Text(t) => vec![(None, None, t.as_str())],
            SpeechText::Script(turns) => turns.iter().enumerate().map(|(i, t)| (Some(t.speaker), Some(i), t.text.as_str())).collect(),
        };
        let paras: Vec<(Option<u8>, Option<usize>, Vec<String>)> = blocks.iter().map(|(s, t, text)| (*s, *t, paragraphs(text))).collect();
        let total: usize = paras.iter().flat_map(|(_, _, ps)| ps.iter().map(|p| count(p))).sum();
        if total == 0 {
            return Err(MediaError::invalid("there is no text to speak"));
        }
        let max = match limits.max_input_chars {
            Some(0) => return Err(MediaError::limit("max_input_chars is 0")),
            Some(m) => m,
            None if total > UNSET_LIMIT_REFUSAL => {
                return Err(MediaError::limit(format!(
                    "the text is {total} characters and the model reports no max_input_chars; set max_input_chars to plan pieces (the client refuses over {UNSET_LIMIT_REFUSAL} without it)"
                )));
            }
            None => UNSET_LIMIT_REFUSAL,
        };
        let mut pieces = Vec::new();
        let mut paragraph = 0usize;
        for (speaker, turn, ps) in paras {
            // Consecutive paragraphs of one block share a piece while they fit.
            let mut acc: Option<(String, usize)> = None;
            let push = |pieces: &mut Vec<TextPiece>, text: String, para: usize, starts: bool| {
                let chars = count(&text);
                pieces.push(TextPiece { index: pieces.len(), text, speaker, turn, paragraph: para, starts_paragraph: starts, chars });
            };
            for p in ps {
                if let Some((text, _)) = acc.as_mut()
                    && count(text) + 2 + count(&p) <= max
                {
                    text.push_str("\n\n");
                    text.push_str(&p);
                    paragraph += 1;
                    continue;
                }
                if let Some((text, para)) = acc.take() {
                    push(&mut pieces, text, para, true);
                }
                if count(&p) <= max {
                    acc = Some((p, paragraph));
                } else {
                    let mut parts = Vec::new();
                    pack(&p, max, Level::Sentence, &mut parts)?;
                    for (k, part) in parts.into_iter().enumerate() {
                        push(&mut pieces, part, paragraph, k == 0);
                    }
                }
                paragraph += 1;
            }
            if let Some((text, para)) = acc.take() {
                push(&mut pieces, text, para, true);
            }
        }
        Ok(TextPlan { pieces, max_chars: max })
    }

    /// The plan for narration `text`.
    pub fn text(text: &str, max_input_chars: Option<usize>) -> Result<TextPlan> {
        TextPlan::new(&SpeechText::Text(text.to_string()), TextLimits::new(max_input_chars))
    }

    /// The plan for a script.
    pub fn script(turns: &[ScriptTurn], max_input_chars: Option<usize>) -> Result<TextPlan> {
        TextPlan::new(&SpeechText::Script(turns.to_vec()), TextLimits::new(max_input_chars))
    }

    /// Characters in all pieces.
    pub fn total_chars(&self) -> usize {
        self.pieces.iter().map(|p| p.chars).sum()
    }

    /// Characters in the first `done` pieces, for "piece i of n" progress.
    pub fn chars_done(&self, done: usize) -> usize {
        self.pieces.iter().take(done).map(|p| p.chars).sum()
    }

    /// How to join the synthesized pieces: `crossfade_ms` inside a paragraph, `pause_ms` before a
    /// new paragraph or turn. One join between each pair, for [`crate::pcm::concat`].
    pub fn joins(&self, crossfade_ms: u64, pause_ms: u64) -> Vec<Join> {
        self.pieces
            .iter()
            .skip(1)
            .map(|p| if p.starts_paragraph { Join::Pause { ms: pause_ms } } else { Join::Crossfade { ms: crossfade_ms } })
            .collect()
    }

    /// [`TextPlan::joins`] with [`DEFAULT_CROSSFADE_MS`] and [`DEFAULT_PAUSE_MS`].
    pub fn default_joins(&self) -> Vec<Join> {
        self.joins(DEFAULT_CROSSFADE_MS, DEFAULT_PAUSE_MS)
    }
}