Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

127 changes: 114 additions & 13 deletions apps/desktop-gpui/src/transcription.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
//! bundle's per-segment mic/system audio to 16kHz mono WAV via ffmpeg, then
//! run whisper-rs or parakeet-rs with word timestamps and chunk the words
//! into caption segments. `apply_caption_result` is
//! `applyCaptionResultToProject` (`captions.ts:469-527`) plus the
//! `applyCaptionResultToProject` (`captions.ts:524-591`) plus the
//! `deriveCaptionTrackSegments` projection (`captions.ts:323-366`) that the
//! Tauri app runs in TypeScript.

Expand Down Expand Up @@ -1652,6 +1652,10 @@ fn process_with_parakeet(
if samples.is_empty() {
return Err("No speech detected in the audio".to_string());
}
let pauses = cap_audio::SpeechPauses::detect(&samples, sample_rate);
if pauses.is_none() {
tracing::info!("Speech is not clearly above the noise; keeping word ends");
}

let mut tokens = Vec::new();
{
Expand All @@ -1678,16 +1682,18 @@ fn process_with_parakeet(

tracing::info!("Parakeet produced {} timed tokens", tokens.len());

caption_segments_from_tokens(tokens)
caption_segments_from_tokens(tokens, pauses.as_ref())
}

/// Parakeet's timed word tokens -> caption segments: drop empty tokens,
/// normalize the words and chunk them.
/// normalize the words, end them where their speech stops in the
/// transcription audio, and chunk them.
#[cfg(any(test, not(all(target_os = "macos", target_arch = "x86_64"))))]
fn caption_segments_from_tokens(
tokens: impl IntoIterator<Item = CaptionWord>,
pauses: Option<&cap_audio::SpeechPauses>,
) -> Result<Vec<CaptionSegment>, String> {
let words = normalize_caption_words(
let mut words = normalize_caption_words(
tokens
.into_iter()
.filter(|token| !token.text.trim().is_empty())
Expand All @@ -1698,6 +1704,9 @@ fn caption_segments_from_tokens(
})
.collect(),
);
if let Some(pauses) = pauses {
end_words_where_speech_stops(&mut words, pauses);
}

if words.is_empty() {
return Err("No speech detected in the audio".to_string());
Expand Down Expand Up @@ -1926,6 +1935,23 @@ fn normalize_caption_words(words: Vec<CaptionWord>) -> Vec<CaptionWord> {
normalized
}

/// `end_words_where_speech_stops` (`captions.rs`).
#[cfg(any(test, not(all(target_os = "macos", target_arch = "x86_64"))))]
fn end_words_where_speech_stops(words: &mut [CaptionWord], pauses: &cap_audio::SpeechPauses) {
let mut moved = 0;
for word in words.iter_mut() {
let end = pauses.audible_end(word.start, word.end);
if end < word.end {
word.end = end;
moved += 1;
}
}
tracing::info!(
"Ended {moved} of {} words where their speech stops",
words.len()
);
}

/// `caption_text_from_words` (`captions.rs:833-849`).
fn caption_text_from_words<'a>(words: impl IntoIterator<Item = &'a CaptionWord>) -> String {
let mut text = String::new();
Expand Down Expand Up @@ -2182,9 +2208,10 @@ pub fn write_caption_edit_to_source(
);
}

/// `applyCaptionResultToProject` (`captions.ts:469-527`): set the captions
/// `applyCaptionResultToProject` (`captions.ts:524-591`): set the captions
/// block (enabled, preserving existing style settings), mark it source-timed,
/// and re-derive the rendered track through the current edit list.
/// keep the transcript editor's cuts cut, and re-derive the rendered track
/// through the current edit list.
pub fn apply_caption_result(
project: &mut ProjectConfiguration,
segments: Vec<CaptionSegment>,
Expand Down Expand Up @@ -2225,19 +2252,19 @@ pub fn apply_caption_result(
image_segments: Vec::new(),
});
}
let captions = project.captions.get_or_insert_with(CaptionsData::default);
captions.segments = segments;
captions.settings = settings;
captions.source_timed = true;
cap_project::reconcile_transcript_cuts(captions);

let timeline = project
.timeline
.as_mut()
.expect("timeline was just created");

timeline.caption_segments =
derive_caption_track_segments(&segments, timeline, recording_durations);

project.captions = Some(CaptionsData {
segments,
settings,
source_timed: true,
});
derive_caption_track_segments(&captions.segments, timeline, recording_durations);
}

/// `getCaptionGenerationErrorMessage` (`captions.ts:634-662`).
Expand Down Expand Up @@ -2474,6 +2501,40 @@ mod tests {
}
}

#[test]
fn parakeet_words_end_where_their_speech_stops() {
let mut samples = vec![0.0_f32; 16_000 * 5];
for (index, sample) in samples.iter_mut().enumerate() {
let time = index as f32 / 16_000.0;
if (1.0..1.5).contains(&time) || (2.5..3.0).contains(&time) {
*sample = 0.1 * (std::f32::consts::TAU * 220.0 * time).sin();
}
}
let pauses = cap_audio::SpeechPauses::detect(&samples, 16_000).expect("speech is audible");
let token = |text: &str, start: f32, end: f32| CaptionWord {
text: text.to_string(),
start,
end,
};

let segments = caption_segments_from_tokens(
[
token(" hello", 1.0, 2.5),
token(" world", 2.5, 3.04),
token(".", 3.04, 4.2),
],
Some(&pauses),
)
.expect("segments");

let words = &segments[0].words;
assert_eq!(caption_text_from_words(words), "hello world.");
assert_eq!((words[0].start, words[1].start), (1.0, 2.5));
assert!((words[0].end - 1.6).abs() < 0.02, "{}", words[0].end);
assert!((words[1].end - 3.1).abs() < 0.02, "{}", words[1].end);
assert_eq!(segments[0].end, words[1].end);
}

// -- Model paths ----------------------------------------------------------

#[test]
Expand Down Expand Up @@ -2694,6 +2755,7 @@ mod tests {
..CaptionSettings::default()
},
source_timed: false,
..Default::default()
});

apply_caption_result(
Expand All @@ -2716,6 +2778,45 @@ mod tests {
assert_eq!(track[0].text, "hello");
}

#[test]
fn apply_caption_result_keeps_transcript_cuts() {
let mut project: ProjectConfiguration = serde_json::from_value(serde_json::json!({
"timeline": {
"segments": [
{ "recordingSegment": 0, "timescale": 1.0, "start": 0.0, "end": 1.6 },
{ "recordingSegment": 0, "timescale": 1.0, "start": 1.9, "end": 10.0 }
],
"zoomSegments": []
},
"captions": {
"segments": [],
"settings": {},
"transcriptCuts": [
{ "id": "cut", "kind": "word", "text": "um", "start": 1.6, "end": 1.9 }
],
"transcriptRemoved": [{ "start": 1.6, "end": 1.9 }]
}
}))
.unwrap();

apply_caption_result(
&mut project,
vec![caption(
"segment-0-0",
1.0,
2.5,
&[("hello", 1.0, 1.4), ("um", 1.6, 1.9), ("world", 2.0, 2.5)],
)],
&[10.0],
10.0,
);

let captions = project.captions.as_ref().unwrap();
assert_eq!(captions.segments[0].text, "hello world");
assert_eq!(captions.transcript_cuts.len(), 1);
assert_eq!(captions.transcript_removed.len(), 1);
}

#[test]
fn apply_caption_result_synthesises_a_timeline_when_missing() {
let mut project = ProjectConfiguration::default();
Expand Down
7 changes: 4 additions & 3 deletions apps/desktop-gpui/src/transcription/verify_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
//! timed tokens (one word per marker, some followed by a punctuation token
//! and empty tokens). Every word must sit at its source time on the
//! concatenated recordings, and the caption segments built by the Parakeet
//! path ([`caption_segments_from_tokens`]) must match the reference
//! path ([`caption_segments_from_tokens`], without the audio pause pass
//! that `cap_audio::SpeechPauses` covers) must match the reference
//! segmentation below. Multi-segment Studio projects with per-track start
//! offsets, legacy single-segment Studio projects, and Instant projects
//! (refused: Instant recordings are transcribed by the web app).
Expand Down Expand Up @@ -337,7 +338,7 @@ fn check_project(case: &mut Case, project: &Path, takes: &Takes) {
let mut tokens = Vec::new();
let result = transcribe_project_with(project, |audio_path| {
tokens = fake_tokens(audio_path)?;
caption_segments_from_tokens(tokens.clone())
caption_segments_from_tokens(tokens.clone(), None)
});
let segments = match result {
Ok(segments) => segments,
Expand Down Expand Up @@ -606,7 +607,7 @@ fn segmentation_case(id: &str, unicode: bool) {
unicode,
);
let reference = reference_segments(&tokens);
match caption_segments_from_tokens(tokens.clone()) {
match caption_segments_from_tokens(tokens.clone(), None) {
Err(e) if reference.is_empty() && e.contains("No speech") => empty += 1,
Err(e) => {
failed += 1;
Expand Down
1 change: 1 addition & 0 deletions apps/desktop/src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ cap-camera-ffmpeg = { path = "../../../crates/camera-ffmpeg" }

[target.'cfg(not(all(target_os = "macos", target_arch = "x86_64")))'.dependencies]
parakeet-rs = "0.3.4"
hound = "3.5"

[target.'cfg(target_os = "linux")'.dependencies]
libappindicator = "0.9.0"
Expand Down
73 changes: 70 additions & 3 deletions apps/desktop/src-tauri/src/captions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -865,6 +865,22 @@ fn normalize_caption_words(words: Vec<CaptionWord>) -> Vec<CaptionWord> {
normalized
}

#[cfg(not(all(target_os = "macos", target_arch = "x86_64")))]
fn end_words_where_speech_stops(words: &mut [CaptionWord], pauses: &cap_audio::SpeechPauses) {
let mut moved = 0;
for word in words.iter_mut() {
let end = pauses.audible_end(word.start, word.end);
if end < word.end {
word.end = end;
moved += 1;
}
}
tracing::info!(
"Ended {moved} of {} words where their speech stops",
words.len()
);
}

fn caption_text_from_words<'a>(words: impl IntoIterator<Item = &'a CaptionWord>) -> String {
let mut text = String::new();

Expand Down Expand Up @@ -1284,19 +1300,35 @@ fn process_with_parakeet(
}
};

let mut reader = hound::WavReader::open(audio_path)
.map_err(|e| format!("Failed to open audio file: {e} at path: {audio_path:?}"))?;
let spec = reader.spec();
if spec.channels != 1 || spec.sample_rate != WHISPER_SAMPLE_RATE {
return Err(format!(
"Expected 16 kHz mono audio, got {} Hz with {} channels",
spec.sample_rate, spec.channels
));
}
let samples = reader
.samples::<i16>()
.map(|sample| sample.map(|sample| f32::from(sample) / 32768.0))
.collect::<Result<Vec<_>, _>>()
.map_err(|e| format!("Failed to read audio file: {e}"))?;
let pauses = cap_audio::SpeechPauses::detect(&samples, spec.sample_rate);

let result = {
let mut parakeet = model_arc
.lock()
.map_err(|e| format!("Failed to lock Parakeet model: {e}"))?;
parakeet
.transcribe_file(audio_path, Some(TimestampMode::Words))
.transcribe_samples(samples, spec.sample_rate, 1, Some(TimestampMode::Words))
.map_err(|e| format!("Parakeet transcription failed: {e}"))?
};

tracing::info!("Transcription text: {}", result.text);
tracing::info!("Got {} timed tokens", result.tokens.len());

let words = normalize_caption_words(
let mut words = normalize_caption_words(
result
.tokens
.iter()
Expand All @@ -1308,6 +1340,10 @@ fn process_with_parakeet(
})
.collect(),
);
match &pauses {
Some(pauses) => end_words_where_speech_stops(&mut words, pauses),
None => tracing::info!("Speech is not clearly above the noise; keeping word ends"),
}

if words.is_empty() {
tracing::warn!("Parakeet produced no words");
Expand Down Expand Up @@ -2885,9 +2921,40 @@ mod tests {

#[cfg(not(all(target_os = "macos", target_arch = "x86_64")))]
mod parakeet {
use super::super::parakeet_model_dir_matches;
use super::super::{CaptionWord, end_words_where_speech_stops, parakeet_model_dir_matches};
use tempfile::tempdir;

#[test]
fn stretched_words_end_where_their_speech_stops() {
let mut samples = vec![0.0_f32; 16_000 * 4];
for (index, sample) in samples.iter_mut().enumerate() {
let time = index as f32 / 16_000.0;
if (1.0..1.5).contains(&time) || (2.5..3.0).contains(&time) {
*sample = 0.1 * (std::f32::consts::TAU * 220.0 * time).sin();
}
}
let pauses =
cap_audio::SpeechPauses::detect(&samples, 16_000).expect("speech is audible");
let mut words = vec![
CaptionWord {
text: "hello".to_string(),
start: 1.0,
end: 2.5,
},
CaptionWord {
text: "world.".to_string(),
start: 2.5,
end: 3.0,
},
];

end_words_where_speech_stops(&mut words, &pauses);

assert_eq!(words[0].start, 1.0);
assert!((words[0].end - 1.6).abs() < 0.02, "{}", words[0].end);
assert_eq!((words[1].start, words[1].end), (2.5, 3.0));
}

#[test]
fn parakeet_model_dir_match_uses_full_directory_path() {
let dir = tempdir().unwrap();
Expand Down
7 changes: 7 additions & 0 deletions apps/desktop/src/routes/editor/Timeline/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ import {
sortTrackSegments,
trackInsertionIndex,
} from "../timelineTracks";
import { hideCaptionSpeech } from "../transcript-cuts";
import { formatTime } from "../utils";
import { type AudioSegmentDragState, AudioTrack } from "./AudioTrack";
import { type CaptionSegmentDragState, CaptionsTrack } from "./CaptionsTrack";
Expand Down Expand Up @@ -742,6 +743,12 @@ export function Timeline(props: {
setProject(
produce((project) => {
if (project.captions) {
hideCaptionSpeech(
project.captions,
project.captions.segments.flatMap((segment) =>
segment.words?.length ? segment.words : [segment],
),
);
project.captions.segments = [];
project.captions.settings = {
...defaultCaptionSettings,
Expand Down
Loading