Repository navigation
Custom ribbon groups and spoken-word search #654
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -57,6 +57,8 @@ pub enum Output { | |
| Tagged(Vec<Tagged>), | ||
| Report(Report), | ||
| Count(usize), | ||
| /// Spoken words found in approved transcripts, and the recordings with none (issue #550). | ||
| Spoken(notecraft_store::spoken::Found), | ||
| } | ||
|
|
||
| pub struct CommandSpec { | ||
|
|
@@ -778,6 +780,26 @@ fn search_query(s: &mut Session, p: &Params) -> Result<Output, EngineError> { | |
| Ok(Output::Hits(hits)) | ||
| } | ||
|
|
||
| /// Spoken words in approved transcripts (issue #550): the timed lines that hold the query, with | ||
| /// the recording and the time each was said, and the recordings in the scope with no timed | ||
| /// transcript to search. Refused while the audio search setting is off. | ||
| fn search_spoken(s: &mut Session, p: &Params) -> Result<Output, EngineError> { | ||
| use notecraft_store::spoken; | ||
| if s.settings.get(spoken::SETTING).as_deref().map(str::trim) != Some("true") { | ||
| return Err(EngineError::BadParam(format!("searching spoken words is off; set {} to true to turn it on", spoken::SETTING))); | ||
| } | ||
| let limit = match p.get("limit") { | ||
| Some(l) => l.trim().parse::<usize>().map_err(|_| EngineError::BadParam("limit must be a number".into()))?.min(500), | ||
| None => 40, | ||
| }; | ||
| let query = req(p, "q")?; | ||
| let found = match p.get("scope").map(|scope| scope.trim()).filter(|scope| !scope.is_empty()) { | ||
| Some(scope) => spoken::search([s.resolve(scope)?], query, limit), | ||
| None => spoken::search(tree::child_dirs(s.root()).into_iter().chain(s.opened_elsewhere().iter().cloned()), query, limit), | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Search open notebook roots for an unscoped request. If a notebook inside Use the session's open notebook paths for this branch. Preserve explicit scoped searches and notebooks opened elsewhere.
|
||
| }; | ||
| Ok(Output::Spoken(found)) | ||
| } | ||
|
|
||
| /// The tagged notes in a scope: what Find Tags lists in its Tags Summary (issue #166). | ||
| fn tags_find(s: &mut Session, p: &Params) -> Result<Output, EngineError> { | ||
| let limit = match p.get("limit") { | ||
|
|
@@ -1378,6 +1400,13 @@ text (optional): the alt text; empty removes it", | |
| changes_tree: false, | ||
| run: search_query, | ||
| }, | ||
| CommandSpec { | ||
| id: "search.spoken", | ||
| label: "Search spoken words in recordings", | ||
| params: "q (required): words said in a recording\nlimit (optional): at most this many lines (default 40, at most 500)\nscope (optional): page or folder to search, relative to the notebooks folder; every open notebook when left out\nThe words searched are the timed lines of transcripts approved with Insert > Transcribe. Off until the setting audio_search is true", | ||
| changes_tree: false, | ||
| run: search_spoken, | ||
| }, | ||
| CommandSpec { | ||
| id: "tags.find", | ||
| label: "Find tagged notes", | ||
|
|
@@ -2528,4 +2557,31 @@ mod tests { | |
| } | ||
| assert_eq!(std::fs::read_to_string(&outside).expect("outside"), "keep"); | ||
| } | ||
|
|
||
| /// Issue #550: spoken words are searched only once the setting is on, and a recording with no | ||
| /// timed transcript is reported. | ||
| #[test] | ||
| fn spoken_words_are_searched_once_audio_search_is_on() { | ||
| let t = TempDir::new("engine-spoken"); | ||
| let settings = Settings::at(t.path().join("settings").join("s.toml")); | ||
| let mut s = Session::new(&t.path().join("notebooks"), settings.clone()).expect("session"); | ||
| let book = path_of(s.run("notebook.create", &p(&[("name", "Book")])).expect("notebook")); | ||
| let section = | ||
| path_of(s.run("node.create", &p(&[("parent", &book.to_string_lossy()), ("kind", "section"), ("title", "Talks")])).expect("section")); | ||
| let page = | ||
| path_of(s.run("node.create", &p(&[("parent", §ion.to_string_lossy()), ("kind", "page"), ("title", "Kickoff")])).expect("page")); | ||
| std::fs::create_dir_all(page.join("assets")).expect("assets"); | ||
| std::fs::write(page.join("assets").join("Talk.wav"), b"RIFF").expect("audio"); | ||
| std::fs::write(page.join("assets").join("Other.mp3"), b"ID3").expect("audio"); | ||
| let body = "<p><a href=\"assets/Talk.wav\">Talk.wav</a></p><p>[00:02:03.400 - 00:02:07.000] Ship the importer next</p>"; | ||
| s.run("page.save", &p(&[("path", &page.to_string_lossy()), ("body", body)])).expect("save"); | ||
| assert!(s.run("search.spoken", &p(&[("q", "importer")])).is_err(), "off until it is turned on"); | ||
| settings.set(notecraft_store::spoken::SETTING, "true").expect("setting"); | ||
| let Output::Spoken(found) = s.run("search.spoken", &p(&[("q", "importer")])).expect("search") else { panic!("spoken") }; | ||
| assert_eq!(found.clips.len(), 1); | ||
| assert_eq!((found.clips[0].recording.as_str(), found.clips[0].start_ms), ("assets/Talk.wav", 123_400)); | ||
| assert_eq!(found.unindexed.iter().map(|u| u.recording.as_str()).collect::<Vec<_>>(), ["assets/Other.mp3"]); | ||
| let json = crate::output_json(&Output::Spoken(found)); | ||
| assert_eq!(json["clips"][0]["start"], "00:02:03"); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,251 @@ | ||
| //! Spoken words in recordings, for search (issue #550). | ||
| //! | ||
| //! NoteCraft hears nothing by itself: the words it can search are the ones a person approved | ||
| //! from a recording. Insert > Transcribe puts a link to the recording on the page and, under it, | ||
| //! each line of the approved transcript with its time in the recording: | ||
| //! `[00:01:05.200 - 00:01:09.800] the words`. Those lines are the index. A line belongs to the | ||
| //! last recording linked above it on the page. | ||
| //! | ||
| //! A recording or video beside a page with no timed line under any link to it cannot be | ||
| //! searched, and is reported as such, so the person knows which clips still need a transcript. | ||
|
|
||
| use crate::page::load_page; | ||
| use crate::tree::{child_dirs, page_file, read_node}; | ||
| use notecraft_formats::{Block, boxes, render}; | ||
| use std::path::{Path, PathBuf}; | ||
|
|
||
| /// The setting that turns searching spoken words on. Off unless it is `true`, as OneNote's | ||
| /// Audio Search is off until it is turned on. | ||
| pub const SETTING: &str = "audio_search"; | ||
|
|
||
| /// The kinds of file taken for a recording or a video. | ||
| pub const MEDIA_EXTENSIONS: &[&str] = &["wav", "mp3", "m4a", "aac", "ogg", "oga", "opus", "flac", "wma", "webm", "mp4", "m4v", "mov", "mkv", "avi"]; | ||
|
|
||
| /// Whether a link or file name names a recording or a video. | ||
| pub fn is_media(name: &str) -> bool { | ||
| let name = name.split(['#', '?']).next().unwrap_or(name); | ||
| Path::new(name).extension().and_then(|e| e.to_str()).is_some_and(|e| MEDIA_EXTENSIONS.iter().any(|m| m.eq_ignore_ascii_case(e))) | ||
| } | ||
|
|
||
| /// One timed line of an approved transcript. | ||
| #[derive(Clone, Debug, PartialEq, Eq)] | ||
| pub struct Clip { | ||
| /// The page the line is on. | ||
| pub page: PathBuf, | ||
| pub title: String, | ||
| /// The recording, as the page links to it (`assets/Meeting.wav`). | ||
| pub recording: String, | ||
| pub start_ms: u64, | ||
| pub end_ms: u64, | ||
| /// The words, without their time. | ||
| pub text: String, | ||
| /// The line's block on the page, to put the caret on. | ||
| pub block: usize, | ||
| } | ||
|
|
||
| /// A recording beside a page, or linked from it, with no timed transcript to search. | ||
| #[derive(Clone, Debug, PartialEq, Eq)] | ||
| pub struct Unindexed { | ||
| pub page: PathBuf, | ||
| pub title: String, | ||
| pub recording: String, | ||
| } | ||
|
|
||
| /// What a search of spoken words found, and the recordings it could not look in. | ||
| #[derive(Clone, Debug, Default, PartialEq, Eq)] | ||
| pub struct Found { | ||
| pub clips: Vec<Clip>, | ||
| pub unindexed: Vec<Unindexed>, | ||
| } | ||
|
|
||
| /// `hh:mm:ss.mmm` in milliseconds. | ||
| fn millis(stamp: &str) -> Option<u64> { | ||
| let (clock, ms) = stamp.trim().split_once('.')?; | ||
| let mut parts = clock.split(':'); | ||
| let (h, m, s) = (parts.next()?.parse::<u64>().ok()?, parts.next()?.parse::<u64>().ok()?, parts.next()?.parse::<u64>().ok()?); | ||
| if parts.next().is_some() || m > 59 || s > 59 || ms.len() != 3 { | ||
| return None; | ||
| } | ||
| Some(((h * 60 + m) * 60 + s) * 1000 + ms.parse::<u64>().ok()?) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Reject timestamps that overflow A transcript can contain Use checked multiplication and addition. Return
|
||
| } | ||
|
|
||
| /// A transcript line's time and words: `[start - end] words`. | ||
| pub fn timed_line(text: &str) -> Option<(u64, u64, &str)> { | ||
| let rest = text.trim_start().strip_prefix('[')?; | ||
| let (range, words) = rest.split_once(']')?; | ||
| let (start, end) = range.split_once(" - ")?; | ||
| let (start, end) = (millis(start)?, millis(end)?); | ||
| let words = words.trim(); | ||
| (end >= start && !words.is_empty()).then_some((start, end, words)) | ||
| } | ||
|
|
||
| /// `hh:mm:ss`, for showing where in a recording a line is. | ||
| pub fn clock(ms: u64) -> String { | ||
| let s = ms / 1000; | ||
| format!("{:02}:{:02}:{:02}", s / 3600, s / 60 % 60, s % 60) | ||
| } | ||
|
|
||
| /// The recording a block links to, if it links to one. | ||
| fn linked_recording(block: &Block) -> Option<String> { | ||
| let Block::Paragraph(spans, _) = block else { return None }; | ||
| spans.iter().filter_map(|span| span.link.as_deref()).find(|link| is_media(link) && !link.contains("://")).map(str::to_string) | ||
| } | ||
|
|
||
| /// The timed transcript lines of one page, and its recordings that have none. | ||
| pub fn page_clips(dir: &Path) -> (Vec<Clip>, Vec<Unindexed>) { | ||
| let Ok(page) = load_page(dir) else { return (Vec::new(), Vec::new()) }; | ||
| let title = read_node(dir).map(|n| n.title).unwrap_or_default(); | ||
| let blocks = boxes::read(page.format, &page.body).0; | ||
| let mut clips = Vec::new(); | ||
| let mut linked: Vec<String> = Vec::new(); | ||
| let mut current: Option<String> = None; | ||
| for (index, block) in blocks.iter().enumerate() { | ||
| if let Some(recording) = linked_recording(block) { | ||
| if !linked.contains(&recording) { | ||
| linked.push(recording.clone()); | ||
| } | ||
| current = Some(recording); | ||
| continue; | ||
| } | ||
| let Some(recording) = ¤t else { continue }; | ||
| let text = render::blocks_to_text(std::slice::from_ref(block)); | ||
| if let Some((start_ms, end_ms, words)) = timed_line(&text) { | ||
| clips.push(Clip { | ||
| page: dir.to_path_buf(), | ||
| title: title.clone(), | ||
| recording: recording.clone(), | ||
| start_ms, | ||
| end_ms, | ||
| text: words.to_string(), | ||
| block: index, | ||
| }); | ||
| } | ||
| } | ||
| // Every recording the page links to or keeps beside it, once, by its link. | ||
| let mut recordings = linked; | ||
| let mut files: Vec<String> = | ||
| crate::assets::list(dir).into_iter().map(|(name, _)| format!("assets/{name}")).filter(|name| is_media(name)).collect(); | ||
| files.sort(); | ||
| for file in files { | ||
| if !recordings.contains(&file) { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Compare recording identities without link fragments. If a transcript links to Normalize local recording identities for deduplication and indexed checks. Keep the original link for display.
|
||
| recordings.push(file); | ||
| } | ||
| } | ||
| let unindexed = recordings | ||
| .into_iter() | ||
| .filter(|recording| !clips.iter().any(|clip| &clip.recording == recording)) | ||
| .map(|recording| Unindexed { page: dir.to_path_buf(), title: title.clone(), recording }) | ||
| .collect(); | ||
| (clips, unindexed) | ||
| } | ||
|
|
||
| fn collect_pages(dir: &Path, out: &mut Vec<PathBuf>) { | ||
| if page_file(dir).is_some() { | ||
| out.push(dir.to_path_buf()); | ||
| } | ||
| for child in child_dirs(dir) { | ||
| collect_pages(&child, out); | ||
| } | ||
| } | ||
|
|
||
| /// The timed transcript lines under `roots` (pages, or folders of them) that hold every word of | ||
| /// `query`, in page order, at most `limit`, and every recording there with no timed transcript. | ||
| /// A word of the query matches a word of the line that starts with it, ignoring case. | ||
| pub fn search(roots: impl IntoIterator<Item = PathBuf>, query: &str, limit: usize) -> Found { | ||
| let wanted = notecraft_search::tokenize(query); | ||
| let mut found = Found::default(); | ||
| let mut pages = Vec::new(); | ||
| for root in roots { | ||
| collect_pages(&root, &mut pages); | ||
| } | ||
| for page in pages { | ||
| let (clips, unindexed) = page_clips(&page); | ||
| found.unindexed.extend(unindexed); | ||
| if wanted.is_empty() { | ||
| continue; | ||
| } | ||
| for clip in clips { | ||
| if found.clips.len() >= limit { | ||
| break; | ||
| } | ||
| let words = notecraft_search::tokenize(&clip.text); | ||
| if wanted.iter().all(|want| words.iter().any(|word| word.starts_with(want.as_str()))) { | ||
| found.clips.push(clip); | ||
| } | ||
| } | ||
| } | ||
| found | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| use crate::testing::TempDir; | ||
| use crate::{NodeKind, PageFormat, Settings, ops, page}; | ||
|
|
||
| fn transcript_page(t: &TempDir, format: PageFormat) -> (PathBuf, PathBuf) { | ||
| let settings = Settings::at(t.path().join("settings.toml")); | ||
| let book = ops::create_notebook(t.path(), "Book", Some(format), &settings).expect("notebook"); | ||
| let section = ops::create_node(&book, "Meetings", NodeKind::Section, Some(format), &settings).expect("section"); | ||
| let page = ops::create_node(§ion, "Standup", NodeKind::Page, Some(format), &settings).expect("page"); | ||
| std::fs::create_dir_all(page.join("assets")).expect("assets"); | ||
| std::fs::write(page.join("assets/Meeting.wav"), b"RIFF").expect("audio"); | ||
| std::fs::write(page.join("assets/Silent.mp4"), b"video").expect("video"); | ||
| let lines = [ | ||
| "Before the recording: budget talk elsewhere.", | ||
| "[00:00:01.520 - 00:00:05.321] The budget for the quarter", | ||
| "[00:01:05.000 - 00:01:09.800] Ship the folder format first", | ||
| "Unstamped words", | ||
| ]; | ||
| let body = match format { | ||
| PageFormat::Html => { | ||
| let mut b = format!("<p>{}</p><p><a href=\"assets/Meeting.wav\">Meeting.wav</a></p>", lines[0]); | ||
| for line in &lines[1..] { | ||
| b.push_str(&format!("<p>{line}</p>")); | ||
| } | ||
| b | ||
| } | ||
| PageFormat::Cmgfm => { | ||
| let mut b = format!("{}\n\n[Meeting.wav](assets/Meeting.wav)\n\n", lines[0]); | ||
| for line in &lines[1..] { | ||
| b.push_str(&format!("{}\n\n", line.replace('[', "\\[").replace(']', "\\]"))); | ||
| } | ||
| b | ||
| } | ||
| }; | ||
| page::save_body(&page, &body).expect("save"); | ||
| (book, page) | ||
| } | ||
|
|
||
| #[test] | ||
| fn timed_lines_under_a_recording_are_found_with_their_time() { | ||
| for format in PageFormat::ALL { | ||
| let t = TempDir::new("spoken-search"); | ||
| let (book, page) = transcript_page(&t, format); | ||
| let found = search([book.clone()], "BUDGET quart", 10); | ||
| assert_eq!(found.clips.len(), 1, "{format:?}: only the timed line, not the words above the link: {found:?}"); | ||
| let clip = &found.clips[0]; | ||
| assert_eq!((clip.recording.as_str(), clip.start_ms, clip.end_ms), ("assets/Meeting.wav", 1520, 5321), "{format:?}"); | ||
| assert_eq!(clip.text, "The budget for the quarter"); | ||
| assert_eq!(clip.title, "Standup"); | ||
| let (clips, _) = page_clips(&page); | ||
| assert_eq!(clips.iter().map(|c| c.block).collect::<Vec<_>>(), [clip.block, clip.block + 1], "{format:?}"); | ||
| assert_eq!(search([book.clone()], "folder", 10).clips[0].start_ms, 65_000); | ||
| assert!(search([book.clone()], "unstamped", 10).clips.is_empty(), "a line with no time is not a clip"); | ||
| // The video has no transcript: it is reported, not searched. | ||
| assert_eq!(found.unindexed.iter().map(|u| u.recording.as_str()).collect::<Vec<_>>(), ["assets/Silent.mp4"], "{format:?}"); | ||
| } | ||
| } | ||
|
|
||
| #[test] | ||
| fn transcript_times_are_read_strictly() { | ||
| assert_eq!(timed_line("[00:00:01.520 - 00:00:05.321] Words"), Some((1520, 5321, "Words"))); | ||
| assert_eq!(timed_line("[01:02:03.004 - 01:02:04.000] x "), Some((3_723_004, 3_724_000, "x"))); | ||
| assert_eq!(timed_line("[00:00:05.000 - 00:00:01.000] backwards"), None); | ||
| assert_eq!(timed_line("[00:61:00.000 - 00:62:00.000] bad minutes"), None); | ||
| assert_eq!(timed_line("[00:00:01.520 - 00:00:05.321]"), None); | ||
| assert_eq!(timed_line("No time here"), None); | ||
| assert_eq!(clock(65_400), "00:01:05"); | ||
| assert!(is_media("assets/clip.MP4") && is_media("a.wav#t=5") && !is_media("photo.png")); | ||
| } | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Include the originating page path in CLI results.
If two pages have the same title and recording name, these lines cannot identify which page contains each result.
Foundcontains the distinct page paths, butdescribediscards them. The same problem affects unindexed notices.Include
display_path(&c.page)anddisplay_path(&u.page)so callers can locate the correct note.Also applies to: 212-212