1#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4pub enum Level { None, Light, Medium, High }
5
6const FILLERS: &[&str] = &["um", "uh", "er", "ah", "like", "you", "know", "so", "well", "i", "mean"];
16
17const LEADING_DISFLUENCIES: &[&str] = &["um", "uh", "er", "ah", "mm", "hmm", "uhm", "erm", "hm"];
24
25fn content_words(text: &str) -> Vec<String> {
26 text.to_lowercase()
27 .split(|c: char| !c.is_alphanumeric())
28 .filter(|w| !w.is_empty())
29 .filter(|w| !FILLERS.contains(w))
30 .map(|w| w.to_string())
31 .collect()
32}
33
34pub fn guard_accepts(input: &str, output: &str) -> bool {
38 content_words(input) == content_words(output)
39}
40
41pub fn apply_spoken_commands(text: &str) -> String {
46 format!(" {} ", text)
47 .replace(" new paragraph ", "\n\n")
48 .replace(" new line ", "\n")
49 .replace(" period ", ". ")
50 .replace(" comma ", ", ")
51 .trim()
52 .to_string()
53}
54
55fn find_word_bounded(hay: &str, needle_lower: &str) -> Option<usize> {
60 let hb = hay.as_bytes();
61 let nb = needle_lower.as_bytes();
62 let nlen = nb.len();
63 if nlen == 0 || hb.len() < nlen { return None; }
64 let mut i = 0;
65 while i + nlen <= hb.len() {
66 if (0..nlen).all(|k| hb[i + k].to_ascii_lowercase() == nb[k]) {
69 let before_ok = i == 0 || !hb[i - 1].is_ascii_alphanumeric();
70 let after = i + nlen;
71 let after_ok = after == hb.len() || !hb[after].is_ascii_alphanumeric();
72 if before_ok && after_ok { return Some(i); }
73 }
74 i += 1;
75 }
76 None
77}
78
79pub fn apply_backtrack(text: &str) -> String {
84 const TRIGGERS: &[&str] = &["scratch that", "actually no"];
85 let mut result = text.to_string();
86 for trigger in TRIGGERS {
87 while let Some(pos) = find_word_bounded(&result, trigger) {
88 let before = result[..pos].trim_end();
89 let after = &result[pos + trigger.len()..];
90 let kept: Vec<&str> = before.split_whitespace().collect();
91 if kept.len() >= 3 {
92 let cut = before.rfind(['.', '\n']).map(|i| i + 1).unwrap_or(0);
94 result = format!("{}{}", &before[..cut], after);
95 } else {
96 result = format!("{} {}", before, after.trim_start());
98 }
99 }
100 }
101 result.split_whitespace().collect::<Vec<_>>().join(" ")
102}
103
104const CONTINUATIONS: &[&str] = &[
108 "and", "but", "so", "or", "the", "a", "an", "it", "that", "this", "these",
109 "those", "all", "then", "because", "which", "who",
110];
111
112pub fn decapitalize_continuation(text: &str, prev_clean: Option<&str>) -> String {
118 let continues = prev_clean.is_some_and(|p| {
119 let tail = p.trim_end().trim_end_matches(['"', '\'', ')', ']', '”', '’']);
122 !matches!(tail.chars().last(), Some('.' | '!' | '?' | '…') | None)
123 });
124 if !continues {
125 return text.to_string();
126 }
127 let first = text.split_whitespace().next().unwrap_or("");
128 let bare = first.trim_matches(|c: char| !c.is_alphanumeric()).to_lowercase();
129 if !CONTINUATIONS.contains(&bare.as_str()) {
130 return text.to_string();
131 }
132 let mut chars = text.chars();
133 match chars.next() {
134 Some(c) if c.is_uppercase() => c.to_lowercase().collect::<String>() + chars.as_str(),
135 _ => text.to_string(),
136 }
137}
138
139pub fn format_revise(whisper: &str, prev_clean: Option<&str>) -> String {
151 let pre = apply_spoken_commands(&apply_backtrack(whisper));
152 decapitalize_continuation(&pre, prev_clean)
153}
154
155pub fn deterministic_light(text: &str) -> String {
158 let trimmed = text.trim();
159 let without_lead = strip_leading_fillers(trimmed);
160 let capped = capitalize_sentences(&without_lead);
161 ensure_terminal(&capitalize_standalone_i(&capped))
162}
163
164fn capitalize_standalone_i(text: &str) -> String {
170 let chars: Vec<char> = text.chars().collect();
171 let mut out = String::with_capacity(text.len());
172 for (idx, &ch) in chars.iter().enumerate() {
173 let alone_before = idx == 0 || !chars[idx - 1].is_alphanumeric();
174 let alone_after = idx + 1 == chars.len() || !chars[idx + 1].is_alphanumeric();
175 out.push(if ch == 'i' && alone_before && alone_after { 'I' } else { ch });
176 }
177 out
178}
179
180fn strip_leading_fillers(text: &str) -> String {
181 let mut words: Vec<&str> = text.split_whitespace().collect();
182 while let Some(first) = words.first() {
183 let lw = first.trim_matches(|c: char| !c.is_alphanumeric()).to_lowercase();
185 if LEADING_DISFLUENCIES.contains(&lw.as_str()) { words.remove(0); } else { break; }
186 }
187 words.join(" ")
188}
189
190fn capitalize_sentences(text: &str) -> String {
191 let mut out = String::with_capacity(text.len());
192 let mut at_start = true;
193 for ch in text.chars() {
194 if at_start && ch.is_alphabetic() {
195 out.extend(ch.to_uppercase());
196 at_start = false;
197 } else {
198 out.push(ch);
199 if ch == '.' || ch == '!' || ch == '?' { at_start = true; }
200 }
201 }
202 out
203}
204
205fn ensure_terminal(text: &str) -> String {
206 let t = text.trim_end();
207 if t.is_empty() || matches!(t.chars().last(), Some('.') | Some('!') | Some('?')) {
208 t.to_string()
209 } else {
210 format!("{}.", t)
211 }
212}
213
214pub fn parse_level(s: &str) -> Level {
217 match s.trim().to_lowercase().as_str() {
218 "none" => Level::None,
219 "medium" => Level::Medium,
220 "high" => Level::High,
221 _ => Level::Light,
222 }
223}
224
225pub struct RewritePrompt {
230 pub system: String,
231 pub user: String,
232}
233
234pub fn rewrite_prompt(level: Level, text: &str) -> RewritePrompt {
239 let restraint = "You clean up raw voice transcripts. Return ONLY the cleaned text, nothing else — no preamble, no quotes. NEVER change meaning: never swap a word for a different one, never add words that change meaning, never drop a negation, never reorder clauses. When unsure, leave it as it is.";
240 let rule = match level {
241 Level::None => "Return the text exactly as given.",
242 Level::Light => "Fix only capitalization and punctuation, and drop leading non-lexical filler (um, uh, er, ah). Remove no other words.",
243 Level::Medium => "Also remove disfluencies and false starts and join fragments into sentences. Keep every meaning-bearing word.",
244 Level::High => "Also break into paragraphs at topic shifts and turn spoken lists into bullets. Keep every meaning-bearing word.",
245 };
246 RewritePrompt {
247 system: format!("{restraint} {rule}"),
248 user: format!("Clean this transcript:\n{text}"),
249 }
250}
251
252#[cfg(test)]
253mod tests {
254 use super::*;
255
256 #[test]
257 fn accepts_pure_punctuation_and_filler_cleanup() {
258 assert!(guard_accepts(
259 "um so the thing is i keep avoiding it",
260 "The thing is, I keep avoiding it.",
261 ));
262 }
263
264 #[test]
265 fn rejects_a_substituted_meaning_word() {
266 assert!(!guard_accepts("i love her", "I loathe her."));
268 }
269
270 #[test]
271 fn rejects_a_dropped_content_word() {
272 assert!(!guard_accepts("i never said that", "I said that."));
273 }
274
275 #[test]
276 fn rejects_an_added_content_word() {
277 assert!(!guard_accepts("i am tired", "I am very tired."));
278 }
279
280 #[test]
281 fn guard_permits_dropping_filler_homographs_known_limit() {
282 assert!(guard_accepts("do you know the way", "do the way"));
286 assert!(guard_accepts("i like it a lot", "it a lot"));
287 }
288
289 #[test]
290 fn deterministic_light_caps_and_terminates() {
291 assert_eq!(deterministic_light("um the thing is"), "The thing is.");
292 }
293
294 #[test]
295 fn does_not_strip_a_leading_content_word() {
296 assert_eq!(deterministic_light("i sometimes forget the small things"),
299 "I sometimes forget the small things.");
300 assert_eq!(deterministic_light("you should go now"), "You should go now.");
301 assert_eq!(deterministic_light("so i realized the answer"), "So I realized the answer.");
302 assert_eq!(deterministic_light("well that is the thing"), "Well that is the thing.");
303 }
304
305 #[test]
306 fn still_strips_leading_nonlexical_disfluencies() {
307 assert_eq!(deterministic_light("um uh the thing is"), "The thing is.");
308 assert_eq!(deterministic_light("ah i see it now"), "I see it now.");
309 assert_eq!(deterministic_light("um, the thing is"), "The thing is.");
311 }
312
313 #[test]
314 fn a_leading_pure_punctuation_token_survives() {
315 assert_eq!(deterministic_light("-- the thing is"), "-- The thing is.");
319 }
320
321 #[test]
322 fn standalone_i_is_capitalized_mid_sentence() {
323 assert_eq!(
324 deterministic_light("the thing is i keep avoiding it"),
325 "The thing is I keep avoiding it."
326 );
327 assert_eq!(
328 deterministic_light("i'm sure i'll try what i've found"),
329 "I'm sure I'll try what I've found."
330 );
331 assert_eq!(deterministic_light("it is in the bin"), "It is in the bin.");
333 }
334
335 #[test]
336 fn deterministic_light_is_guard_safe() {
337 let raw = "um so i keep avoiding the hard conversation";
338 assert!(guard_accepts(raw, &deterministic_light(raw)));
339 }
340
341 #[test]
342 fn spoken_command_becomes_newline() {
343 assert_eq!(apply_spoken_commands("a new line b"), "a\nb");
344 }
345
346 #[test]
347 fn backtrack_drops_preceding_clause() {
348 let out = apply_backtrack("the answer is yes scratch that the answer is no");
349 assert!(!out.contains("yes"));
350 assert!(out.contains("the answer is no"));
351 }
352
353 #[test]
354 fn backtrack_does_not_fire_inside_a_word() {
355 let out = apply_backtrack("well actually nobody knows the truth");
357 assert!(out.contains("nobody"));
358 assert!(out.contains("the truth"));
359 }
360
361 #[test]
362 fn spoken_command_at_phrase_start_and_end() {
363 assert_eq!(apply_spoken_commands("new line b"), "b");
364 assert_eq!(apply_spoken_commands("a new line"), "a");
365 }
366
367 #[test]
368 fn backtrack_handles_non_ascii_without_panicking() {
369 let out = apply_backtrack("aa bb ẞ scratch that ẞ tail");
371 assert!(out.contains("tail"));
372 assert!(!out.contains("scratch that"));
373 }
374
375 #[test]
376 fn parse_level_maps_known_and_defaults_to_light() {
377 assert_eq!(parse_level("none"), Level::None);
378 assert_eq!(parse_level("Medium"), Level::Medium);
379 assert_eq!(parse_level("HIGH"), Level::High);
380 assert_eq!(parse_level("light"), Level::Light);
381 assert_eq!(parse_level("nonsense"), Level::Light);
382 }
383
384 #[test]
385 fn rewrite_prompt_widens_by_level_and_carries_the_text() {
386 assert!(rewrite_prompt(Level::Light, "x").system.to_lowercase().contains("capitalization"));
387 assert!(rewrite_prompt(Level::Medium, "x").system.to_lowercase().contains("disfluencies"));
388 assert!(rewrite_prompt(Level::High, "x").system.to_lowercase().contains("paragraph"));
389 assert!(rewrite_prompt(Level::Light, "the raw phrase").user.contains("the raw phrase"));
390 }
391
392 #[test]
393 fn rewrite_prompt_always_states_the_restraint() {
394 for lvl in [Level::Light, Level::Medium, Level::High] {
395 assert!(rewrite_prompt(lvl, "x").system.to_lowercase().contains("never change meaning"));
396 }
397 }
398
399 #[test]
400 fn decapitalize_lowercases_an_allowlist_continuation_after_unterminated_prior() {
401 assert_eq!(
402 decapitalize_continuation("All these edge cases get sorted out.", Some("with their product")),
403 "all these edge cases get sorted out."
404 );
405 }
406
407 #[test]
408 fn decapitalize_keeps_capital_after_a_terminated_prior() {
409 assert_eq!(
410 decapitalize_continuation("All these edge cases.", Some("That worked.")),
411 "All these edge cases."
412 );
413 }
414
415 #[test]
416 fn decapitalize_never_lowercases_a_non_allowlist_word_protecting_proper_nouns() {
417 assert_eq!(
418 decapitalize_continuation("Whisper does the rest", Some("the tool i use is")),
419 "Whisper does the rest"
420 );
421 }
422
423 #[test]
424 fn format_revise_trusts_whisper_casing_and_applies_features() {
425 assert_eq!(format_revise("hello there", None), "hello there");
426 assert_eq!(format_revise("first line new line second", None), "first line\nsecond");
427 }
428}