From 2626ce25d9f81caf0dcb302b46380a0da2290aa4 Mon Sep 17 00:00:00 2001 From: Praveen Perera Date: Mon, 23 Nov 2026 17:29:54 -0600 Subject: [PATCH 1/3] Keep long-form merge frames in order The long-form merge hands over from the transcript so far to the next window at the end of the longest run of matching tokens. Tokens up to 25 frames apart still match, so when one window drops a short restart that the other kept, such as "solve a similar" against "solve a this a similar", the run's tail pairs a word with the other window's earlier copy of it. The next window's tokens then start before the last kept one, and a word could end before it started. Hand over at the latest point in the run where frames stay in order. The run's tokens are the same in both windows, so the text never changes; only the timestamps of those tokens move to the later window. As a last guard, drop any later-window token that would still run back. The longest-common-subsequence path is removed: it ran only when no single token matched, and then it found no match either. --- src/long_form/merge.rs | 381 ++++++++++++++++++++++++++--------------- 1 file changed, 245 insertions(+), 136 deletions(-) diff --git a/src/long_form/merge.rs b/src/long_form/merge.rs index efafc9d..1e2d1eb 100644 --- a/src/long_form/merge.rs +++ b/src/long_form/merge.rs @@ -1,10 +1,10 @@ -use std::ops::Range; - -use crate::decode::RawTranscription; +use crate::decode::{RawToken, RawTranscription}; /// Most encoder frames apart two tokens can be and still count as the same token const MAX_MATCH_FRAMES: usize = 25; +/// Merges consecutive overlapping windows into one transcription whose token +/// frames never decrease pub(crate) fn merge_overlapping_windows(windows: Vec) -> RawTranscription { let mut iter = windows.into_iter(); let Some(mut merged) = iter.next() else { @@ -26,19 +26,13 @@ fn merge_pair(left: RawTranscription, right: RawTranscription) -> RawTranscripti } // `left` is everything merged so far; only its tail can reach `right`, so the - // searches start there rather than rescanning the whole transcript per window + // search starts there rather than rescanning the whole transcript per window let left_start = first_reachable(&left, &right); - let matches = contiguous_matches(&left, left_start, &right); - if !matches.is_empty() { - return merge_using_matches(left, right, &matches); - } - - let matches = lcs_matches(&left, left_start, &right); - if !matches.is_empty() { - return merge_using_matches(left, right, &matches); - } - - merge_by_midpoint(left, right) + let seam = match longest_agreement(&left, left_start, &right) { + Some(run) => run.seam(&left, &right), + None => Seam::at_midpoint(&left, &right), + }; + seam.join(left, right) } /// Index of the first `left` token within match distance of any `right` frame; no @@ -53,75 +47,69 @@ fn first_reachable(left: &RawTranscription, right: &RawTranscription) -> usize { .unwrap_or(left.tokens.len()) } -fn contiguous_matches( - left: &RawTranscription, - left_start: usize, - right: &RawTranscription, -) -> Vec<(usize, usize)> { - let mut best = Vec::new(); - for left_idx in left_start..left.tokens.len() { - for right_idx in 0..right.tokens.len() { - if !tokens_match(left, left_idx, right, right_idx) { - continue; - } - let mut current = Vec::new(); - let mut lhs = left_idx; - let mut rhs = right_idx; - while lhs < left.tokens.len() && rhs < right.tokens.len() { - if !tokens_match(left, lhs, right, rhs) { - break; - } - current.push((lhs, rhs)); - lhs += 1; - rhs += 1; - } - if current.len() > best.len() { - best = current; - } - } +/// A run of consecutive tokens both windows transcribed the same, token for token +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct AgreedRun { + left: usize, + right: usize, + len: usize, +} + +impl AgreedRun { + /// Where to hand over from `left` to `right` inside this run + /// + /// Both windows hold the same token ids along the run, so any handover point + /// gives the same text and only decides whose timestamps the run's tokens keep. + /// The handover point is the run's latest one whose join keeps frames in order. + /// The run's end is not always such a point: tokens up to `MAX_MATCH_FRAMES` + /// apart still match, so when one window drops a short restart the other kept, + /// such as "solve a similar" against "solve a this a similar", the run's tail + /// pairs left's word with right's earlier copy of it, and right's next token + /// then starts before left's last + fn seam(self, left: &RawTranscription, right: &RawTranscription) -> Seam { + (0..=self.len) + .rev() + .map(|offset| Seam { + left_end: self.left + offset, + right_start: self.right + offset, + }) + .find(|seam| seam.is_ordered(left, right)) + // no handover point keeps frames in order, as when right's timing runs + // well ahead of left's along the whole run; the run's end keeps the + // most of `left`, and `join` drops the right tokens that run back + .unwrap_or(Seam { + left_end: self.left + self.len, + right_start: self.right + self.len, + }) } - best } -/// Longest common subsequence of `left[left_start..]` and `right`; rows before -/// `left_start` would all be zero, so the table and its traceback start there -fn lcs_matches( +/// The longest run of matching consecutive tokens, the earliest one on a tie +fn longest_agreement( left: &RawTranscription, left_start: usize, right: &RawTranscription, -) -> Vec<(usize, usize)> { - let left_len = left.tokens.len() - left_start; - let matches_at = |row: usize, col: usize| tokens_match(left, left_start + row, right, col); - let mut dp = vec![vec![0usize; right.tokens.len() + 1]; left_len + 1]; - for left_idx in 1..=left_len { - for right_idx in 1..=right.tokens.len() { - if matches_at(left_idx - 1, right_idx - 1) { - dp[left_idx][right_idx] = dp[left_idx - 1][right_idx - 1] + 1; - } else { - dp[left_idx][right_idx] = - dp[left_idx - 1][right_idx].max(dp[left_idx][right_idx - 1]); +) -> Option { + let mut best: Option = None; + for left_idx in left_start..left.tokens.len() { + for right_idx in 0..right.tokens.len() { + let len = (0..) + .take_while(|offset| { + left_idx + offset < left.tokens.len() + && right_idx + offset < right.tokens.len() + && tokens_match(left, left_idx + offset, right, right_idx + offset) + }) + .count(); + if len > best.map_or(0, |run| run.len) { + best = Some(AgreedRun { + left: left_idx, + right: right_idx, + len, + }); } } } - - let mut matches = Vec::new(); - let mut left_idx = left_len; - let mut right_idx = right.tokens.len(); - while left_idx > 0 && right_idx > 0 { - if matches_at(left_idx - 1, right_idx - 1) { - matches.push((left_start + left_idx - 1, right_idx - 1)); - left_idx -= 1; - right_idx -= 1; - continue; - } - if dp[left_idx - 1][right_idx] > dp[left_idx][right_idx - 1] { - left_idx -= 1; - } else { - right_idx -= 1; - } - } - matches.reverse(); - matches + best } fn tokens_match( @@ -134,77 +122,82 @@ fn tokens_match( left.id == right.id && left.frame.abs_diff(right.frame) <= MAX_MATCH_FRAMES } -fn merge_using_matches( - left: RawTranscription, - right: RawTranscription, - matches: &[(usize, usize)], -) -> RawTranscription { - let left_indices: Vec = matches.iter().map(|(left_idx, _)| *left_idx).collect(); - let right_indices: Vec = matches.iter().map(|(_, right_idx)| *right_idx).collect(); - - let mut merged = RawTranscription::empty(); +/// Where a merge hands over: `left` up to `left_end`, then `right` from +/// `right_start` +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct Seam { + left_end: usize, + right_start: usize, +} - if let Some(first_left) = left_indices.first().copied() { - copy_tokens(&mut merged, &left, 0..first_left); - } +impl Seam { + /// With no token in common, each window keeps the tokens on its side of the + /// midpoint between left's last frame and right's first + fn at_midpoint(left: &RawTranscription, right: &RawTranscription) -> Self { + let left_cutoff = left.tokens.last().map_or(0, |token| token.frame); + let right_first = right + .tokens + .first() + .map_or(left_cutoff, |token| token.frame); + let midpoint = (left_cutoff + right_first) / 2; - for (match_idx, (left_idx, right_idx)) in matches.iter().copied().enumerate() { - copy_tokens(&mut merged, &left, left_idx..left_idx + 1); - if match_idx == matches.len() - 1 { - continue; - } - let next_left = left_indices[match_idx + 1]; - let next_right = right_indices[match_idx + 1]; - let left_gap = next_left.saturating_sub(left_idx + 1); - let right_gap = next_right.saturating_sub(right_idx + 1); - if right_gap > left_gap { - copy_tokens(&mut merged, &right, right_idx + 1..next_right); - } else { - copy_tokens(&mut merged, &left, left_idx + 1..next_left); + Self { + left_end: left.tokens.partition_point(|token| token.frame < midpoint), + right_start: right.tokens.partition_point(|token| token.frame < midpoint), } } - if let Some(last_right) = right_indices.last().copied() { - copy_tokens(&mut merged, &right, last_right + 1..right.tokens.len()); + /// Whether right's first kept token starts no earlier than left's last + fn is_ordered(self, left: &RawTranscription, right: &RawTranscription) -> bool { + let Some(last_left) = self.left_end.checked_sub(1) else { + return true; + }; + right + .tokens + .get(self.right_start) + .is_none_or(|first_right| first_right.frame >= left.tokens[last_left].frame) } - merged -} - -fn merge_by_midpoint(left: RawTranscription, right: RawTranscription) -> RawTranscription { - let left_cutoff = left.tokens.last().map_or(0, |token| token.frame); - let right_start = right - .tokens - .first() - .map_or(left_cutoff, |token| token.frame); - let midpoint = (left_cutoff + right_start) / 2; - - let mut merged = RawTranscription::empty(); - for token in &left.tokens { - if token.frame < midpoint { - merged.tokens.push(*token); - } + /// Joins the two sides, dropping any `right` token that would start before + /// the token kept ahead of it + /// + /// Each window's frames already rise, so with an ordered seam this drops + /// nothing; it holds the merged order whatever the windows hold, since a + /// token that runs back is a second copy of audio already transcribed + fn join(self, left: RawTranscription, right: RawTranscription) -> RawTranscription { + let mut tokens = left.tokens; + tokens.truncate(self.left_end); + let mut last_frame = tokens.last().map_or(0, |token| token.frame); + let rest = right.tokens.into_iter().skip(self.right_start); + tokens.extend(rest.filter(|token: &RawToken| { + let in_order = token.frame >= last_frame; + last_frame = last_frame.max(token.frame); + in_order + })); + RawTranscription { tokens } } - for token in &right.tokens { - if token.frame >= midpoint { - merged.tokens.push(*token); - } - } - merged -} - -/// Appends `source`'s tokens at `range`, which may be empty or reversed -fn copy_tokens(merged: &mut RawTranscription, source: &RawTranscription, range: Range) { - merged - .tokens - .extend(range.map(|index| source.tokens[index])); } #[cfg(test)] mod tests { use super::merge_overlapping_windows; + use crate::decode::RawTranscription; use crate::decode::test_support::raw_from_columns; + fn window(tokens: &[(u32, usize)]) -> RawTranscription { + let ids: Vec = tokens.iter().map(|(id, _)| *id).collect(); + let frames: Vec = tokens.iter().map(|(_, frame)| *frame).collect(); + raw_from_columns(&ids, &frames, &vec![1; ids.len()], &vec![0.9; ids.len()]) + } + + fn assert_frames_rise(merged: &RawTranscription) { + let frames = merged.frames(); + assert!( + frames.windows(2).all(|pair| pair[0] <= pair[1]), + "frames run backward: {frames:?}" + ); + } + #[test] fn contiguous_tokens_are_deduplicated() { let left = raw_from_columns(&[1, 2, 3], &[0, 10, 20], &[1, 1, 1], &[0.9; 3]); @@ -218,11 +211,127 @@ mod tests { let left = raw_from_columns(&[1, 2], &[0, 10], &[1, 1], &[0.9; 2]); let right = raw_from_columns(&[9, 10], &[8, 18], &[1, 1], &[0.9; 2]); let merged = merge_overlapping_windows(vec![left, right]); - assert!( - merged - .frames() - .windows(2) - .all(|window| window[0] <= window[1]) + assert_frames_rise(&merged); + } + + /// Two windows of "To solve a this a similar": the earlier window heard only + /// "To solve a similar", so the matched run ends on its "a" at frame 615, + /// paired with the later window's first "a" at 607 + /// + /// Frames are from a Parakeet v3 run on a podcast episode, where the run's end + /// put "this" at 611 after "a" at 615 + #[test] + fn dropped_restart_keeps_frames_in_order() { + const TO: u32 = 1; + const SOL: u32 = 2; + const VE: u32 = 3; + const A: u32 = 4; + const THIS: u32 = 5; + const SIM: u32 = 6; + const NEED: u32 = 7; + let left = window(&[(TO, 598), (SOL, 602), (VE, 605), (A, 615), (SIM, 616)]); + let right = window(&[ + (TO, 598), + (SOL, 602), + (VE, 605), + (A, 607), + (THIS, 611), + (A, 615), + (SIM, 616), + (NEED, 620), + ]); + + let merged = merge_overlapping_windows(vec![left, right]); + + assert_eq!(merged.ids(), vec![TO, SOL, VE, A, THIS, A, SIM, NEED]); + assert_eq!( + merged.frames(), + vec![598, 602, 605, 607, 611, 615, 616, 620] + ); + } + + /// "But I say" in the earlier window against "But I think but I say" in the + /// later one, which matches "But I" 13 frames early + #[test] + fn restart_heard_late_in_the_run_takes_the_later_windows_frames() { + const BIG: u32 = 1; + const STOP: u32 = 2; + const BUT_UPPER: u32 = 3; + const I: u32 = 4; + const THINK: u32 = 5; + const BUT: u32 = 6; + const SAY: u32 = 7; + let left = window(&[ + (BIG, 48931), + (STOP, 48934), + (BUT_UPPER, 48949), + (I, 48950), + (SAY, 48951), + ]); + let right = window(&[ + (BIG, 48931), + (STOP, 48932), + (BUT_UPPER, 48936), + (I, 48937), + (THINK, 48938), + (BUT, 48949), + (I, 48951), + (SAY, 48952), + ]); + + let merged = merge_overlapping_windows(vec![left, right]); + + assert_eq!( + merged.ids(), + vec![BIG, STOP, BUT_UPPER, I, THINK, BUT, I, SAY] + ); + assert_eq!( + merged.frames(), + vec![48931, 48934, 48936, 48937, 48938, 48949, 48951, 48952] ); } + + /// A run whose every handover point runs back still merges in order, by + /// dropping the later window's tokens that start before the kept ones + #[test] + fn unordered_run_drops_tokens_that_run_back() { + let left = window(&[(9, 98), (1, 100), (2, 120)]); + let right = window(&[(1, 90), (2, 95), (3, 110), (4, 130)]); + + let merged = merge_overlapping_windows(vec![left, right]); + + assert_eq!(merged.ids(), vec![9, 1, 2, 4]); + assert_eq!(merged.frames(), vec![98, 100, 120, 130]); + } + + /// Merges many windows of a small vocabulary, where repeats and near-miss + /// timings are common, and checks that frames never run backward + #[test] + fn merged_frames_never_run_backward() { + let mut state: u64 = 0x9e37_79b9_7f4a_7c15; + let mut next = |bound: u64| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state % bound + }; + + for _ in 0..2_000 { + let mut windows = Vec::new(); + let mut start = 0usize; + for _ in 0..4 { + let mut frame = start; + let tokens: Vec<(u32, usize)> = (0..30) + .map(|_| { + frame += next(4) as usize; + (next(4) as u32, frame) + }) + .collect(); + windows.push(window(&tokens)); + start += 20 + next(30) as usize; + } + + assert_frames_rise(&merge_overlapping_windows(windows)); + } + } } From d04ac7afe9cbd0bd3d45ff288743e7537f0900a0 Mon Sep 17 00:00:00 2001 From: Praveen Perera Date: Mon, 23 Nov 2026 17:29:54 -0600 Subject: [PATCH 2/3] Release 0.5.1 --- CHANGELOG.md | 12 ++++++++++++ Cargo.lock | 2 +- Cargo.toml | 2 +- crates/scriptrs-python/Cargo.lock | 4 ++-- crates/scriptrs-python/Cargo.toml | 2 +- 5 files changed, 17 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9b16923..a6ed30e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,17 @@ follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions f [Semantic Versioning](https://semver.org/). The Rust crate and the Python package share one version. +## [0.5.1] - 2026-11-23 + +### Fixed + +- Long-form token timestamps no longer run backward where two overlapping windows + meet. When one window heard a short restart that the other missed, such as "solve a + this a similar" against "solve a similar", the merge gave a few tokens the earlier + window's timestamps, which belong to a later word. A token could then start before + the one ahead of it, and a word built from its tokens could end before it started. + The text is unchanged, and those tokens now take the later window's timestamps. + ## [0.5.0] - 2026-11-07 The first release on PyPI. It has breaking changes to the Rust API; the README's @@ -77,5 +88,6 @@ The first release on PyPI. It has breaking changes to the Rust API; the README's - VAD regions are padded by 0.2 s so soft first words are kept. - The relative-position attention runs as one fused kernel on CUDA. +[0.5.1]: https://github.com/avencera/scriptrs/compare/v0.5.0...v0.5.1 [0.5.0]: https://github.com/avencera/scriptrs/compare/v0.4.0...v0.5.0 [0.4.0]: https://github.com/avencera/scriptrs/releases/tag/v0.4.0 diff --git a/Cargo.lock b/Cargo.lock index 9251e3d..81beb61 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -651,7 +651,7 @@ dependencies = [ [[package]] name = "scriptrs" -version = "0.5.0" +version = "0.5.1" dependencies = [ "approx", "block2", diff --git a/Cargo.toml b/Cargo.toml index ecd2526..d5fc893 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "scriptrs" -version = "0.5.0" +version = "0.5.1" edition = "2024" rust-version = "1.96" exclude = ["fixtures/", "dev-tools/", "crates/"] diff --git a/crates/scriptrs-python/Cargo.lock b/crates/scriptrs-python/Cargo.lock index bb0ec0d..404d7f4 100644 --- a/crates/scriptrs-python/Cargo.lock +++ b/crates/scriptrs-python/Cargo.lock @@ -755,7 +755,7 @@ dependencies = [ [[package]] name = "scriptrs" -version = "0.5.0" +version = "0.5.1" dependencies = [ "block2", "cudakit", @@ -774,7 +774,7 @@ dependencies = [ [[package]] name = "scriptrs-python" -version = "0.5.0" +version = "0.5.1" dependencies = [ "pyo3", "rubato", diff --git a/crates/scriptrs-python/Cargo.toml b/crates/scriptrs-python/Cargo.toml index db5a646..aebc4d4 100644 --- a/crates/scriptrs-python/Cargo.toml +++ b/crates/scriptrs-python/Cargo.toml @@ -2,7 +2,7 @@ name = "scriptrs-python" # keep equal to the scriptrs version; the release workflow checks the wheel names # against the tag -version = "0.5.0" +version = "0.5.1" edition = "2024" license = "Apache-2.0" repository = "https://github.com/avencera/scriptrs" From 2659d061789a21629ce536777b03e84386852697 Mon Sep 17 00:00:00 2001 From: Praveen Perera Date: Mon, 23 Nov 2026 17:39:45 -0600 Subject: [PATCH 3/3] Retime rather than drop tokens that run back When no point in the matched run keeps frames in order, the merge hands over at the run's end. The later window's tokens kept after it follow everything kept from the earlier window, so they are new text, not a second copy. Move such a token to the frame of the token before it instead of dropping it, so the merge keeps its text and its order. --- CHANGELOG.md | 4 +++- src/long_form/merge.rs | 32 ++++++++++++++++++-------------- 2 files changed, 21 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a6ed30e..82115a4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,7 +14,9 @@ one version. this a similar" against "solve a similar", the merge gave a few tokens the earlier window's timestamps, which belong to a later word. A token could then start before the one ahead of it, and a word built from its tokens could end before it started. - The text is unchanged, and those tokens now take the later window's timestamps. + Those tokens now take the later window's timestamps, and the text stays the same. + In the rare case where the two windows' timings can't be joined in order, a later + window's token that would start too early starts with the token before it instead. ## [0.5.0] - 2026-11-07 diff --git a/src/long_form/merge.rs b/src/long_form/merge.rs index 1e2d1eb..c2da8ae 100644 --- a/src/long_form/merge.rs +++ b/src/long_form/merge.rs @@ -76,7 +76,7 @@ impl AgreedRun { .find(|seam| seam.is_ordered(left, right)) // no handover point keeps frames in order, as when right's timing runs // well ahead of left's along the whole run; the run's end keeps the - // most of `left`, and `join` drops the right tokens that run back + // most of `left`, and `join` retimes the right tokens that run back .unwrap_or(Seam { left_end: self.left + self.len, right_start: self.right + self.len, @@ -158,21 +158,24 @@ impl Seam { .is_none_or(|first_right| first_right.frame >= left.tokens[last_left].frame) } - /// Joins the two sides, dropping any `right` token that would start before - /// the token kept ahead of it + /// Joins the two sides, moving any `right` token that would start before the + /// token kept ahead of it to that token's frame /// - /// Each window's frames already rise, so with an ordered seam this drops - /// nothing; it holds the merged order whatever the windows hold, since a - /// token that runs back is a second copy of audio already transcribed + /// Each window's frames already rise, so with an ordered seam this moves + /// nothing. It holds the merged order whatever the seam: the `right` tokens + /// kept are the text after everything kept from `left`, never a second copy of + /// it, so a token that runs back is retimed rather than dropped fn join(self, left: RawTranscription, right: RawTranscription) -> RawTranscription { let mut tokens = left.tokens; tokens.truncate(self.left_end); let mut last_frame = tokens.last().map_or(0, |token| token.frame); let rest = right.tokens.into_iter().skip(self.right_start); - tokens.extend(rest.filter(|token: &RawToken| { - let in_order = token.frame >= last_frame; + tokens.extend(rest.map(|token| { last_frame = last_frame.max(token.frame); - in_order + RawToken { + frame: last_frame, + ..token + } })); RawTranscription { tokens } } @@ -291,17 +294,18 @@ mod tests { ); } - /// A run whose every handover point runs back still merges in order, by - /// dropping the later window's tokens that start before the kept ones + /// A run whose every handover point runs back still merges in order and keeps + /// every token, by moving the later window's tokens that start before the + /// kept ones up to them #[test] - fn unordered_run_drops_tokens_that_run_back() { + fn unordered_run_retimes_tokens_that_run_back() { let left = window(&[(9, 98), (1, 100), (2, 120)]); let right = window(&[(1, 90), (2, 95), (3, 110), (4, 130)]); let merged = merge_overlapping_windows(vec![left, right]); - assert_eq!(merged.ids(), vec![9, 1, 2, 4]); - assert_eq!(merged.frames(), vec![98, 100, 120, 130]); + assert_eq!(merged.ids(), vec![9, 1, 2, 3, 4]); + assert_eq!(merged.frames(), vec![98, 100, 120, 120, 130]); } /// Merges many windows of a small vocabulary, where repeats and near-miss