forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBb02f499Tahinli1 month ago1000 commits

transcript.rs599 lines, 23.3 KiBHistoryRawDownload
1//! The Transcript dock tab's state and doings: listen to the timeline once, then edit by
2//! words. Click a word to go there, select a run and delete it, remove the fillers.
3//!
4//! The listening is [`engine::speech`] (the Captions and Fillers cards' path) and every cut is
5//! [`speech::cut_spans`] -> `PlaybackSession::cut_regions`, the call the MCP word cuts end in,
6//! across every lane so linked picture and sound stay together, as one undo step. After a cut
7//! the words are re-mapped through it ([`speech::remap_words`]); an undo or redo finds the
8//! words that went with that state again, and any other edit to the timeline leaves the
9//! transcript stale until it is run again.
10
11use std::sync::Arc;
12
13use engine::speech::{self, Hear, Job, Spoken};
14
15use crate::creator;
16use crate::keymap::ActionId;
17use crate::player::tools::Running;
18use crate::viewport::secs_label;
19use crate::*;
20
21/// A silence this long (seconds) starts a new paragraph, as does a sentence end once a
22/// paragraph has run [`PARA_WORDS`] words.
23const PARA_GAP_SECS: f64 = 1.2;
24const PARA_WORDS: usize = 18;
25/// How many states of the transcript are kept for undo and redo to find again.
26const KEEP: usize = 64;
27
28/// What identifies a state of the timeline well enough to tell whose words these are.
29type Stamp = (usize, u32);
30
31pub(crate) struct Transcript {
32 /// The words as the timeline stands (timeline frames), `None` before the first listen.
33 pub(crate) words: Option<Vec<Spoken>>,
34 /// The timeline state `words` belong to, and the earlier and later ones undo can reach.
35 stamp: Stamp,
36 states: Vec<(Stamp, Vec<Spoken>)>,
37 /// True when the timeline was edited some other way since: the words no longer line up.
38 pub(crate) stale: bool,
39 /// The selected run: where it was started and where it reaches now (word indices).
40 pub(crate) anchor: Option<usize>,
41 pub(crate) head: usize,
42 pub(crate) dragging: bool,
43 pub(crate) search: String,
44 pub(crate) search_edit: bool,
45 /// The match the search is on now (a word index), once it was typed or stepped to.
46 pub(crate) search_at: Option<usize>,
47 pub(crate) running: Option<Running>,
48 /// The speech model being downloaded: its progress and cancel, and which download it is.
49 pub(crate) download: Option<(Arc<Job>, u64)>,
50 pub(crate) runs: u64,
51 pub(crate) status: String,
52 pub(crate) scroll: ScrollHandle,
53 /// The paragraph the playing word was last scrolled to, so the view moves once per paragraph.
54 pub(crate) followed: std::cell::Cell<Option<usize>>,
55}
56
57impl Transcript {
58 pub(crate) fn new() -> Self {
59 Transcript {
60 words: None,
61 stamp: (0, 0),
62 states: Vec::new(),
63 stale: false,
64 anchor: None,
65 head: 0,
66 dragging: false,
67 search: String::new(),
68 search_edit: false,
69 search_at: None,
70 running: None,
71 download: None,
72 runs: 0,
73 status: String::new(),
74 scroll: ScrollHandle::new(),
75 followed: std::cell::Cell::new(None),
76 }
77 }
78
79 /// The selected run, first to last word, when there is one.
80 pub(crate) fn selection(&self) -> Option<(usize, usize)> {
81 // A stale transcript has no selection: its words no longer line up with the timeline.
82 if self.stale {
83 return None;
84 }
85 let n = self.words.as_ref()?.len();
86 let a = self.anchor?;
87 let (lo, hi) = (a.min(self.head), a.max(self.head));
88 (n > 0).then(|| (lo.min(n - 1), hi.min(n - 1)))
89 }
90
91 /// Whether word `i` matches the search box (a word that contains what was typed).
92 pub(crate) fn matches(&self, i: usize) -> bool {
93 let q = speech::norm(&self.search);
94 !q.is_empty() && self.words.as_ref().and_then(|w| w.get(i)).is_some_and(|w| speech::norm(&w.text).contains(&q))
95 }
96
97 /// Every word index that matches the search, in order.
98 pub(crate) fn match_list(&self) -> Vec<usize> {
99 self.words.as_ref().map_or_else(Vec::new, |w| (0..w.len()).filter(|&i| self.matches(i)).collect())
100 }
101
102 /// Paragraphs as `(first, last)` word indices.
103 pub(crate) fn paragraphs(&self, fps: f64) -> Vec<(usize, usize)> {
104 let Some(words) = self.words.as_ref() else {
105 return Vec::new();
106 };
107 let gap = (PARA_GAP_SECS * fps).round() as u32;
108 let mut out: Vec<(usize, usize)> = Vec::new();
109 for (i, w) in words.iter().enumerate() {
110 let breaks = match out.last() {
111 None => true,
112 Some(&(first, _)) => {
113 let prev = &words[i - 1];
114 w.start_f.saturating_sub(prev.end_f) >= gap
115 || (i - first >= PARA_WORDS && prev.text.trim_end().ends_with(['.', '?', '!']))
116 }
117 };
118 match breaks {
119 true => out.push((i, i)),
120 false => out.last_mut().unwrap().1 = i,
121 }
122 }
123 out
124 }
125
126 /// The word the playhead is in, or the one that just ended.
127 pub(crate) fn playing_word(&self, frame: u32, fps: f64) -> Option<usize> {
128 let words = self.words.as_ref()?;
129 let i = words.partition_point(|w| w.start_f <= frame).checked_sub(1)?;
130 let hold = words[i].end_f.max(words[i].start_f + 1) + (fps / 4.0).round() as u32;
131 (frame < hold).then_some(i)
132 }
133
134 fn adopt(&mut self, stamp: Stamp, words: Vec<Spoken>) {
135 self.states.retain(|(s, _)| *s != stamp);
136 self.states.push((stamp, words.clone()));
137 if self.states.len() > KEEP {
138 self.states.remove(0);
139 }
140 self.words = Some(words);
141 self.stamp = stamp;
142 self.stale = false;
143 }
144}
145
146impl Player {
147 fn timeline_stamp(&self) -> Option<Stamp> {
148 let s = self.session.as_ref()?;
149 Some((s.undo_depth(), (s.timeline_duration() * self.fps).round() as u32))
150 }
151
152 /// Once a frame while the tab is up: undo and redo bring back the words of the state they
153 /// land on; a timeline that is in no state we know leaves the transcript stale.
154 pub(crate) fn sync_transcript(&mut self) {
155 if !self.transcript_open || self.transcript.words.is_none() {
156 return;
157 }
158 let Some(now) = self.timeline_stamp() else {
159 return;
160 };
161 if now == self.transcript.stamp {
162 return;
163 }
164 let t = &mut self.transcript;
165 match t.states.iter().find(|(s, _)| *s == now) {
166 Some((_, words)) => {
167 t.words = Some(words.clone());
168 t.stamp = now;
169 t.stale = false;
170 }
171 None => t.stale = true,
172 }
173 // Whatever was selected belonged to the words before; a stale transcript keeps none.
174 t.anchor = None;
175 t.dragging = false;
176 }
177
178 pub(crate) fn open_transcript(&mut self, cx: &mut Context<Self>) {
179 self.close_card();
180 self.transcript_open = true;
181 self.transcript.followed.set(None);
182 cx.notify();
183 }
184
185 /// The playhead's frame.
186 pub(crate) fn transcript_frame(&self) -> u32 {
187 self.session.as_ref().map_or(0, |s| (s.now() * self.fps).floor().max(0.0) as u32)
188 }
189
190 // ---- listening ----------------------------------------------------------------
191
192 /// Listens to the whole mix on a thread, with progress and Cancel on the tab.
193 pub(crate) fn start_transcribing(&mut self, cx: &mut Context<Self>) {
194 if self.transcript.running.is_some() {
195 return;
196 }
197 let fail = |this: &mut Self, why: String, cx: &mut Context<Self>| {
198 this.transcript.status = why.clone();
199 this.notify_user(why.into());
200 cx.notify();
201 };
202 if let Err(why) = speech::available() {
203 return fail(self, why, cx);
204 }
205 let Some(model) = speech::pick_model(|m| speech::check_model(m).is_ok()) else {
206 return fail(self, "No speech model is installed".into(), cx);
207 };
208 let Some(session) = self.session.as_ref() else {
209 return;
210 };
211 let heard = match speech::prepare(session, Hear::Mix) {
212 Ok(h) => h,
213 Err(why) => return fail(self, why, cx),
214 };
215 let job = Arc::new(Job::default());
216 let id = self.transcript.runs.wrapping_add(1);
217 self.transcript.runs = id;
218 self.transcript.running = Some(Running { what: "Transcribing", job: job.clone(), id });
219 self.transcript.status.clear();
220 let work = cx.background_executor().spawn({
221 let job = job.clone();
222 async move { speech::listen(heard, model, "auto", true, &job) }
223 });
224 cx.spawn(async move |this, cx| {
225 let heard = work.await;
226 this.update(cx, |this, cx| this.finish_transcribing(id, heard, cx)).ok();
227 })
228 .detach();
229 // The bar moves while the thread works: repaint until this run is over.
230 cx.spawn(async move |this, cx| {
231 loop {
232 cx.background_executor().timer(std::time::Duration::from_millis(200)).await;
233 let live = this
234 .update(cx, |this, cx| {
235 let live = this.transcript.running.as_ref().is_some_and(|r| r.id == id);
236 cx.notify();
237 live
238 })
239 .unwrap_or(false);
240 if !live {
241 break;
242 }
243 }
244 })
245 .detach();
246 cx.notify();
247 }
248
249 fn finish_transcribing(&mut self, id: u64, heard: Result<Vec<Spoken>, String>, cx: &mut Context<Self>) {
250 if self.transcript.running.as_ref().is_none_or(|r| r.id != id) {
251 return;
252 }
253 self.transcript.running = None;
254 match heard {
255 Ok(words) if words.is_empty() => self.transcript.status = "No speech found".into(),
256 Ok(words) => {
257 if let Some(stamp) = self.timeline_stamp() {
258 self.transcript.states.clear();
259 self.transcript.anchor = None;
260 self.transcript.adopt(stamp, words);
261 }
262 }
263 Err(e) if e == speech::CANCELLED => self.transcript.status = "Cancelled".into(),
264 Err(e) => {
265 self.transcript.status = e.clone();
266 self.notify_user(e.into());
267 }
268 }
269 cx.notify();
270 }
271
272 /// Fetches the speech model (the base one) with progress, off the UI thread. Nothing is
273 /// started while one is already coming.
274 pub(crate) fn start_model_download(&mut self, cx: &mut Context<Self>) {
275 if self.transcript.download.is_some() {
276 return;
277 }
278 let job = Arc::new(Job::default());
279 let id = self.transcript.runs.wrapping_add(1);
280 self.transcript.runs = id;
281 self.transcript.download = Some((job.clone(), id));
282 self.transcript.status.clear();
283 let work = cx.background_executor().spawn({
284 let job = job.clone();
285 async move { speech::download_model("base", &job) }
286 });
287 cx.spawn(async move |this, cx| {
288 let done = work.await;
289 this.update(cx, |this, cx| {
290 if this.transcript.download.as_ref().is_none_or(|(_, d)| *d != id) {
291 return;
292 }
293 this.transcript.download = None;
294 match done {
295 Ok(()) => this.notify_user("Speech model installed — Transcribe is ready".into()),
296 Err(e) if e == speech::CANCELLED => this.transcript.status = "Download cancelled".into(),
297 Err(e) => this.transcript.status = format!("Download failed: {e}"),
298 }
299 cx.notify();
300 })
301 .ok();
302 })
303 .detach();
304 // The bar moves while the thread works: repaint until this download is over.
305 cx.spawn(async move |this, cx| {
306 loop {
307 cx.background_executor().timer(std::time::Duration::from_millis(200)).await;
308 let live = this
309 .update(cx, |this, cx| {
310 cx.notify();
311 this.transcript.download.as_ref().is_some_and(|(_, d)| *d == id)
312 })
313 .unwrap_or(false);
314 if !live {
315 break;
316 }
317 }
318 })
319 .detach();
320 cx.notify();
321 }
322
323 pub(crate) fn cancel_model_download(&mut self, cx: &mut Context<Self>) {
324 if let Some((job, _)) = self.transcript.download.take() {
325 job.cancel.store(true, std::sync::atomic::Ordering::Relaxed);
326 self.transcript.status = "Download cancelled".into();
327 }
328 cx.notify();
329 }
330
331 /// Opens the folder the speech models live in with the desktop's own file manager.
332 pub(crate) fn open_models_folder(&mut self, cx: &mut Context<Self>) {
333 let dir = speech::models_dir();
334 let _ = std::fs::create_dir_all(&dir);
335 match std::process::Command::new("xdg-open").arg(&dir).stdin(std::process::Stdio::null()).spawn() {
336 Ok(_) => {}
337 Err(_) => self.notify_user(format!("Models go in {}", dir.display()).into()),
338 }
339 cx.notify();
340 }
341
342 pub(crate) fn cancel_transcribing(&mut self, cx: &mut Context<Self>) {
343 if let Some(running) = self.transcript.running.take() {
344 running.job.cancel.store(true, std::sync::atomic::Ordering::Relaxed);
345 self.transcript.status = "Cancelled".into();
346 }
347 cx.notify();
348 }
349
350 // ---- reading ------------------------------------------------------------------
351
352 /// A press on word `i`: it starts a selection (shift extends the last one) and, unextended,
353 /// takes the playhead to the word.
354 pub(crate) fn press_word(&mut self, i: usize, extend: bool, cx: &mut Context<Self>) {
355 let Some(frame) = self.transcript.words.as_ref().and_then(|w| w.get(i)).map(|w| w.start_f) else {
356 return;
357 };
358 let t = &mut self.transcript;
359 match (extend, t.anchor) {
360 (true, Some(_)) => t.head = i,
361 _ => {
362 t.anchor = Some(i);
363 t.head = i;
364 t.dragging = true;
365 let at = f64::from(frame) / self.fps;
366 self.seek(at, cx);
367 }
368 }
369 cx.notify();
370 }
371
372 pub(crate) fn drag_word(&mut self, i: usize, cx: &mut Context<Self>) {
373 if self.transcript.dragging && self.transcript.head != i {
374 self.transcript.head = i;
375 cx.notify();
376 }
377 }
378
379 pub(crate) fn release_word(&mut self, cx: &mut Context<Self>) {
380 if self.transcript.dragging {
381 self.transcript.dragging = false;
382 cx.notify();
383 }
384 }
385
386 /// Moves to the next (or previous) match: selects the word, takes the playhead there and
387 /// scrolls its paragraph into view. The first step lands on the first match after the playhead
388 /// (before it, going back); stepping past either end wraps round.
389 pub(crate) fn step_match(&mut self, forward: bool, cx: &mut Context<Self>) {
390 let frame = self.transcript_frame();
391 let list = self.transcript.match_list();
392 let Some(words) = self.transcript.words.as_ref() else {
393 return;
394 };
395 let pos = match self.transcript.search_at.and_then(|c| list.iter().position(|&i| i == c)) {
396 Some(p) if forward => (p + 1) % list.len(),
397 Some(p) => (p + list.len() - 1) % list.len(),
398 None if list.is_empty() => return,
399 None if forward => list.iter().position(|&i| words[i].start_f > frame).unwrap_or(0),
400 None => list.iter().rposition(|&i| words[i].start_f < frame).unwrap_or(list.len() - 1),
401 };
402 let i = list[pos];
403 let secs = f64::from(words[i].start_f) / self.fps;
404 self.transcript.search_at = Some(i);
405 self.transcript.anchor = Some(i);
406 self.transcript.head = i;
407 self.scroll_transcript_to(i);
408 self.seek(secs, cx);
409 }
410
411 /// The query changed: the current match is the first one, scrolled into view (the playhead
412 /// and the selection stay where they are while typing).
413 pub(crate) fn search_changed(&mut self) {
414 let first = self.transcript.match_list().first().copied();
415 self.transcript.search_at = first;
416 if let Some(i) = first {
417 self.scroll_transcript_to(i);
418 }
419 }
420
421 /// Scrolls the paragraph holding word `i` into view.
422 fn scroll_transcript_to(&self, i: usize) {
423 if let Some(p) = self.transcript.paragraphs(self.fps).iter().position(|&(a, b)| (a..=b).contains(&i)) {
424 self.transcript.scroll.scroll_to_item(p);
425 self.transcript.followed.set(Some(p));
426 }
427 }
428
429 /// Empties the search box, and with it the matches.
430 pub(crate) fn clear_search(&mut self) {
431 self.transcript.search.clear();
432 self.transcript.search_at = None;
433 }
434
435 // ---- editing ------------------------------------------------------------------
436
437 /// Cuts the selected words out of every lane, closing the hole: one undo step.
438 pub(crate) fn delete_selected_words(&mut self, cx: &mut Context<Self>) {
439 let Some((lo, hi)) = self.transcript.selection() else {
440 return;
441 };
442 if self.transcript.stale {
443 return;
444 }
445 let Some(words) = self.transcript.words.clone() else {
446 return;
447 };
448 let Some(session) = self.session.as_mut() else {
449 return;
450 };
451 let end = (session.timeline_duration() * self.fps).round() as u32;
452 let pad = (0.06 * self.fps).round() as u32;
453 let Some(span) = speech::word_span(&words, lo, hi, pad, end) else {
454 return;
455 };
456 let lanes = session.lanes();
457 let before = session.timeline_duration();
458 let n = hi - lo + 1;
459 let line = match speech::cut_spans(session, &[span], &lanes) {
460 Ok(regions) => {
461 let shorter = before - session.timeline_duration();
462 let kept = speech::remap_words(&words, &regions);
463 self.finish_word_edit(kept);
464 format!(
465 "{n} word{} cut — {} shorter · undo {}",
466 if n == 1 { "" } else { "s" },
467 secs_label(shorter),
468 self.keymap.display(ActionId::Undo)
469 )
470 }
471 Err(e) => format!("Nothing cut — {e}"),
472 };
473 self.notify_user(line.into());
474 cx.notify();
475 }
476
477 /// Cuts every filler word out of every lane: one undo step.
478 pub(crate) fn remove_transcript_fillers(&mut self, cx: &mut Context<Self>) {
479 let Some(words) = self.transcript.words.clone() else {
480 return;
481 };
482 if self.transcript.stale {
483 return;
484 }
485 let Some(session) = self.session.as_mut() else {
486 return;
487 };
488 let found = creator::fillers_in(session, &words);
489 if found.is_empty() {
490 self.notify_user("No filler words".into());
491 return cx.notify();
492 }
493 let before = session.timeline_duration();
494 let line = match creator::cut_fillers_regions(session, &found) {
495 Ok(regions) => {
496 let shorter = before - session.timeline_duration();
497 let n = found.len();
498 self.finish_word_edit(speech::remap_words(&words, &regions));
499 format!(
500 "{n} filler{} cut — {} shorter · undo {}",
501 if n == 1 { "" } else { "s" },
502 secs_label(shorter),
503 self.keymap.display(ActionId::Undo)
504 )
505 }
506 Err(e) => format!("Nothing cut — {e}"),
507 };
508 self.notify_user(line.into());
509 cx.notify();
510 }
511
512 /// What follows a cut: the words re-mapped become the transcript, the picture reseeks.
513 fn finish_word_edit(&mut self, kept: Vec<Spoken>) {
514 self.selected.clear();
515 self.reset_after_reseek();
516 self.mark_dirty();
517 self.transcript.anchor = None;
518 if let Some(stamp) = self.timeline_stamp() {
519 self.transcript.adopt(stamp, kept);
520 }
521 }
522
523 // ---- keys ---------------------------------------------------------------------
524
525 /// The tab's own keys, asked ahead of the keymap. The search field owns the keyboard once it
526 /// was clicked into; otherwise the tab answers only while it has focus, and only the strokes
527 /// that edit its words (Delete, Backspace, Esc, arrows over a selection, Ctrl+A): Space, S and
528 /// the rest still reach the timeline. `true` when the stroke was taken.
529 pub(crate) fn transcript_key(&mut self, key: &str, ctrl: bool, shift: bool, alt: bool, focused: bool, cx: &mut Context<Self>) -> bool {
530 if !self.transcript_open {
531 return false;
532 }
533 // Typing ends when the focus goes elsewhere (a click on the timeline).
534 if self.transcript.search_edit && !focused {
535 self.transcript.search_edit = false;
536 }
537 if self.transcript.search_edit {
538 match key {
539 // Esc clears what was typed; with nothing typed it leaves the field.
540 "escape" if self.transcript.search.is_empty() => self.transcript.search_edit = false,
541 "escape" => self.clear_search(),
542 "enter" => self.step_match(!shift, cx),
543 "backspace" => {
544 self.transcript.search.pop();
545 self.search_changed();
546 }
547 // Any other stroke is the search box's too: it is not passed on to the words or the keymap.
548 _ => {
549 if let Some(c) = crate::menus::typed(key).filter(|_| !ctrl && !alt) {
550 self.transcript.search.push(c);
551 self.search_changed();
552 }
553 }
554 }
555 cx.notify();
556 return true;
557 }
558 if !focused || alt {
559 return false;
560 }
561 let n = self.transcript.words.as_ref().map_or(0, Vec::len);
562 let sel = self.transcript.selection();
563 let taken = match (key, ctrl) {
564 ("delete" | "backspace", false) => {
565 self.delete_selected_words(cx);
566 true
567 }
568 ("a", true) if n > 0 => {
569 self.transcript.anchor = Some(0);
570 self.transcript.head = n - 1;
571 true
572 }
573 ("escape", false) if !self.transcript.search.is_empty() => {
574 self.clear_search();
575 true
576 }
577 ("escape", false) if sel.is_some() => {
578 self.transcript.anchor = None;
579 true
580 }
581 ("left" | "right", false) if sel.is_some() && n > 0 => {
582 let step = if key == "left" { -1i64 } else { 1 };
583 let to = (self.transcript.head as i64 + step).clamp(0, n as i64 - 1) as usize;
584 self.transcript.head = to;
585 if !shift {
586 self.transcript.anchor = Some(to);
587 let frame = self.transcript.words.as_ref().map_or(0, |w| w[to].start_f);
588 self.seek(f64::from(frame) / self.fps, cx);
589 }
590 true
591 }
592 _ => false,
593 };
594 if taken {
595 cx.notify();
596 }
597 taken
598 }
599}