1use crate::words::TimedWord;
10use serde::{Deserialize, Serialize};
11
12pub const SCHEMA: &str = "rightkit.transcript.v1";
13pub const LEGACY_SCHEMA: &str = "cutright.transcript.v1";
14
15#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
16pub struct Transcript {
17 pub schema: String,
18 #[serde(default)]
21 pub source_blake3: String,
22 #[serde(default)]
24 pub language: String,
25 pub duration_ms: u64,
27 pub words: Vec<Word>,
28 #[serde(default)]
30 pub vad: Vec<Span>,
31 #[serde(default)]
32 pub model: ModelRef,
33}
34
35#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
36pub struct Word {
37 pub text: String,
38 pub start_ms: u64,
39 pub end_ms: u64,
40 #[serde(default, skip_serializing_if = "Option::is_none")]
42 pub confidence: Option<f32>,
43 #[serde(default)]
44 pub end_source: EndSource,
45}
46
47#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
49#[serde(rename_all = "snake_case")]
50pub enum EndSource {
51 #[default]
52 Model,
53 NextTokenStart,
55 Vad,
56 Interpolated,
58}
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
61pub struct Span {
62 pub start_ms: u64,
63 pub end_ms: u64,
64}
65
66#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
67pub struct ModelRef {
68 #[serde(default)]
70 pub id: String,
71 #[serde(default)]
72 pub revision: String,
73 #[serde(default)]
75 pub backend: String,
76}
77
78#[derive(Debug, thiserror::Error, PartialEq, Eq)]
79pub enum TranscriptError {
80 #[error("unsupported schema {0:?}")]
81 Schema(String),
82 #[error("word {index} has start_ms >= end_ms")]
83 EmptyWord { index: usize },
84 #[error("word {index} overlaps or precedes the previous word")]
85 Unsorted { index: usize },
86 #[error("{kind} {index} ends after the source duration")]
87 PastEnd { kind: &'static str, index: usize },
88 #[error("vad span {index} is empty, unsorted or overlapping")]
89 BadVad { index: usize },
90 #[error("invalid transcript JSON: {0}")]
91 Json(String),
92}
93
94impl Transcript {
95 pub fn from_words(
97 words: &[TimedWord],
98 language: &str,
99 duration_ms: Option<u64>,
100 model: ModelRef,
101 end_source: EndSource,
102 ) -> Self {
103 let words: Vec<Word> = crate::segment::normalize_words(words)
104 .into_iter()
105 .map(|w| Word {
106 text: w.text,
107 start_ms: w.start_ms,
108 end_ms: w.end_ms,
109 confidence: None,
110 end_source,
111 })
112 .collect();
113 let end = words.last().map(|w| w.end_ms).unwrap_or(0);
114 Transcript {
115 schema: SCHEMA.into(),
116 source_blake3: String::new(),
117 language: language.into(),
118 duration_ms: duration_ms.unwrap_or(end).max(end),
119 words,
120 vad: Vec::new(),
121 model,
122 }
123 }
124
125 pub fn timed_words(&self) -> Vec<TimedWord> {
126 self.words
127 .iter()
128 .map(|w| TimedWord::new(w.text.clone(), w.start_ms, w.end_ms))
129 .collect()
130 }
131
132 pub fn text(&self) -> String {
134 self.words
135 .iter()
136 .map(|w| w.text.as_str())
137 .collect::<Vec<_>>()
138 .join(" ")
139 }
140
141 pub fn validate(&self) -> Result<(), TranscriptError> {
142 if self.schema != SCHEMA && self.schema != LEGACY_SCHEMA {
143 return Err(TranscriptError::Schema(self.schema.clone()));
144 }
145 let mut prev_end = 0;
146 for (index, w) in self.words.iter().enumerate() {
147 if w.start_ms >= w.end_ms {
148 return Err(TranscriptError::EmptyWord { index });
149 }
150 if w.start_ms < prev_end {
151 return Err(TranscriptError::Unsorted { index });
152 }
153 if w.end_ms > self.duration_ms {
154 return Err(TranscriptError::PastEnd {
155 kind: "word",
156 index,
157 });
158 }
159 prev_end = w.end_ms;
160 }
161 let mut prev_end = 0;
162 for (index, s) in self.vad.iter().enumerate() {
163 if s.start_ms >= s.end_ms || s.start_ms < prev_end {
164 return Err(TranscriptError::BadVad { index });
165 }
166 if s.end_ms > self.duration_ms {
167 return Err(TranscriptError::PastEnd {
168 kind: "vad span",
169 index,
170 });
171 }
172 prev_end = s.end_ms;
173 }
174 Ok(())
175 }
176
177 pub fn to_json(&self) -> String {
178 serde_json::to_string_pretty(self).expect("transcript serialises")
179 }
180
181 pub fn from_json(s: &str) -> Result<Self, TranscriptError> {
183 let t: Transcript =
184 serde_json::from_str(s).map_err(|e| TranscriptError::Json(e.to_string()))?;
185 t.validate()?;
186 Ok(t)
187 }
188}