use serde::{Deserialize, Serialize};
use crate::error::{MediaError, Result};
use crate::pcm::Join;
pub const UNSET_LIMIT_REFUSAL: usize = 4000;
pub const DEFAULT_CROSSFADE_MS: u64 = 10;
pub const DEFAULT_PAUSE_MS: u64 = 300;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ScriptTurn {
pub speaker: u8,
pub text: String,
}
impl ScriptTurn {
pub fn new(speaker: u8, text: impl Into<String>) -> Self {
ScriptTurn { speaker, text: text.into() }
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum SpeechText {
Text(String),
Script(Vec<ScriptTurn>),
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct TextLimits {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_input_chars: Option<usize>,
}
impl TextLimits {
pub fn new(max_input_chars: Option<usize>) -> Self {
TextLimits { max_input_chars }
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TextPiece {
pub index: usize,
pub text: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub speaker: Option<u8>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub turn: Option<usize>,
pub paragraph: usize,
pub starts_paragraph: bool,
pub chars: usize,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TextPlan {
pub pieces: Vec<TextPiece>,
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, '"' | '\'' | '”' | '’' | ')' | ']' | '»' | '」' | '』')
}
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()
}
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 {
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 {
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 })
}
pub fn text(text: &str, max_input_chars: Option<usize>) -> Result<TextPlan> {
TextPlan::new(&SpeechText::Text(text.to_string()), TextLimits::new(max_input_chars))
}
pub fn script(turns: &[ScriptTurn], max_input_chars: Option<usize>) -> Result<TextPlan> {
TextPlan::new(&SpeechText::Script(turns.to_vec()), TextLimits::new(max_input_chars))
}
pub fn total_chars(&self) -> usize {
self.pieces.iter().map(|p| p.chars).sum()
}
pub fn chars_done(&self, done: usize) -> usize {
self.pieces.iter().take(done).map(|p| p.chars).sum()
}
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()
}
pub fn default_joins(&self) -> Vec<Join> {
self.joins(DEFAULT_CROSSFADE_MS, DEFAULT_PAUSE_MS)
}
}