From 81e9413cd186b5480a996f0e6e3e045df7eafae5 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 00:46:25 +0000 Subject: [PATCH] Locator API: map a PDF position to a source range proofback_anchor::locate runs the import pipeline for stateless queries (page, rect, text) and returns file, line, columns, confidence and reason. Exposed as proofback locate (flags or JSON Lines on --stdin), in the WebAssembly build and the Node package with TypeScript types. Schema in site/schema/locate-v1.json (cargo xtask schema). PDF parsing stays in the isolated child; queries are bounded; no .proofback/ is read or written. Tests: the corpus asks every synthetic markup annotation as a query and gets the import's range and confidence; Node matches native on 90 sample queries; the perf test times 500 queries; a fuzz target covers the parser. Refs #19 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Xj9ekYmyESdZUsW8uWkzgv --- .github/workflows/fuzz.yml | 2 +- CHANGELOG.md | 9 + Cargo.lock | 1 + crates/proofback-anchor/src/lib.rs | 17 +- crates/proofback-anchor/src/locate.rs | 161 ++++++++++++++++ crates/proofback-cli/src/commands.rs | 1 + crates/proofback-cli/src/extract.rs | 51 ++++- crates/proofback-cli/src/locate_cmd.rs | 134 +++++++++++++ crates/proofback-cli/src/main.rs | 29 +++ crates/proofback-cli/tests/locate.rs | 242 ++++++++++++++++++++++++ crates/proofback-corpus/tests/locate.rs | 188 ++++++++++++++++++ crates/proofback-corpus/tests/perf.rs | 60 +++++- crates/proofback-model/src/lib.rs | 1 + crates/proofback-model/src/locate.rs | 196 +++++++++++++++++++ crates/proofback-pdf/src/lib.rs | 32 ++++ crates/proofback-pdf/src/text.rs | 2 +- crates/proofback-wasm/src/lib.rs | 51 +++++ docs/PLAN.md | 16 ++ fuzz/Cargo.lock | 205 ++++++++++++++++++++ fuzz/Cargo.toml | 8 + fuzz/fuzz_targets/locate_query.rs | 18 ++ npm/README.md | 24 +++ npm/lib/index.d.ts | 28 +++ npm/lib/index.js | 14 +- npm/test/import.test.js | 21 ++ site/llms.txt | 1 + site/schema/locate-v1.json | 146 ++++++++++++++ xtask/Cargo.toml | 1 + xtask/src/main.rs | 106 +++++++++-- 29 files changed, 1736 insertions(+), 29 deletions(-) create mode 100644 crates/proofback-anchor/src/locate.rs create mode 100644 crates/proofback-cli/src/locate_cmd.rs create mode 100644 crates/proofback-cli/tests/locate.rs create mode 100644 crates/proofback-corpus/tests/locate.rs create mode 100644 crates/proofback-model/src/locate.rs create mode 100644 fuzz/fuzz_targets/locate_query.rs create mode 100644 site/schema/locate-v1.json diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml index 21d26ce..c7327f0 100644 --- a/.github/workflows/fuzz.yml +++ b/.github/workflows/fuzz.yml @@ -19,7 +19,7 @@ jobs: strategy: fail-fast: false matrix: - target: [synctex, tex_normalize] + target: [synctex, tex_normalize, locate_query] steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: diff --git a/CHANGELOG.md b/CHANGELOG.md index 77de0db..640d0db 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,15 @@ the JSON schema is versioned separately (`schema_version` in round files). ## Unreleased +### Locator + +- `proofback locate` maps a position in the compiled PDF (page, rectangle, text) to + the file, line and columns of the source, with the same confidence rules as + `import`. One query from flags, or many as JSON Lines with `--stdin`. Stateless: no + `.proofback/` needed. Works without PDFium when each query has text. +- The same `locate` in the WebAssembly build and the Node package (with TypeScript + types). Schema: `site/schema/locate-v1.json`. + ## 0.2.0 (2026-11-25) ### Fixes diff --git a/Cargo.lock b/Cargo.lock index 29c893a..aaa7ac8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5403,6 +5403,7 @@ name = "xtask" version = "0.2.0" dependencies = [ "anyhow", + "proofback-anchor", "proofback-corpus", "proofback-model", "proofback-pdf", diff --git a/crates/proofback-anchor/src/lib.rs b/crates/proofback-anchor/src/lib.rs index 2fe8fe1..37a1024 100644 --- a/crates/proofback-anchor/src/lib.rs +++ b/crates/proofback-anchor/src/lib.rs @@ -13,6 +13,7 @@ pub mod align; mod classify; +mod locate; pub mod sources; use std::collections::{BTreeMap, HashMap}; @@ -28,6 +29,7 @@ use proofback_synctex::{SyncTex, resolve_input}; use proofback_tex::{BlockKind, fold_str}; pub use classify::{Classified, classify}; +pub use locate::locate; pub use sources::{SourceFile, Sources}; /// Characters of PDF context read on each side of the marked text. @@ -255,7 +257,20 @@ fn anchor_one( )]; } } - let cands = candidates(input, a.page, &points); + anchor_marked(input, a.page, marked, &points, is_point, kind) +} + +/// The shared core of [`anchor_one`] and [`locate`]: anchor marked text (or +/// nothing) found near `points` (SyncTeX coordinates) on `page`. +fn anchor_marked( + input: &Input<'_>, + page: u32, + marked: Option, + points: &[(f32, f32)], + is_point: bool, + kind: Kind, +) -> Anchored { + let cands = candidates(input, page, points); let marked_str = marked.as_ref().map(|m| m.text.clone()).unwrap_or_default(); // Figures, tables and display maths: nothing to align, point at the block. diff --git a/crates/proofback-anchor/src/locate.rs b/crates/proofback-anchor/src/locate.rs new file mode 100644 index 0000000..6f7608f --- /dev/null +++ b/crates/proofback-anchor/src/locate.rs @@ -0,0 +1,161 @@ +//! The locator: a stateless query from a PDF position to a source range, through the +//! same pipeline as [`crate::import`] (SyncTeX candidates, then text alignment), and +//! with the same honesty about confidence (D-14). + +use std::collections::HashMap; + +use proofback_model::locate::{Location, Query}; +use proofback_model::{Confidence, Kind}; +use proofback_pdf::{MarkedText, PageBox, PageText, marked_text}; +use proofback_tex::fold_str; + +use crate::{Anchored, CONTEXT, Input, anchor_marked}; + +/// Answer each query. `input.annotations` is not used; `input.texts` should hold the +/// text of the queried pages when PDFium is available (queries with `text` work +/// without it). Invalid queries get a `page` result that says why. +pub fn locate(input: &Input<'_>, queries: &[Query]) -> Vec { + let boxes: HashMap = input.boxes.iter().map(|b| (b.page, b)).collect(); + queries + .iter() + .map(|q| locate_one(input, &boxes, q)) + .collect() +} + +fn locate_one(input: &Input<'_>, boxes: &HashMap, q: &Query) -> Location { + if let Err(e) = q.validate() { + return Location::page_only(format!("invalid query: {e}")); + } + let Some(b) = boxes.get(&q.page) else { + return Location::page_only(format!("page {} is not in the PDF", q.page)); + }; + let page_text = input.texts.get(&q.page); + let rect_quads: Vec<[f32; 8]> = q.rect.map(quad).into_iter().collect(); + let (marked, quads) = match (q.text.as_deref(), page_text) { + (Some(t), Some(pt)) => match find_on_page(pt, t, q.rect) { + Some(found) => found, + None => (Some(plain(t)), rect_quads), + }, + (Some(t), None) => (Some(plain(t)), rect_quads), + (None, Some(pt)) => ( + marked_text(pt, &rect_quads, q.rect.unwrap_or_default(), CONTEXT), + rect_quads, + ), + (None, None) => (None, rect_quads), + }; + let points: Vec<(f32, f32)> = quads.iter().flat_map(|q| line_points(q, b)).collect(); + to_location(anchor_marked( + input, + q.page, + marked, + &points, + false, + Kind::Highlight, + )) +} + +fn to_location(a: Anchored) -> Location { + match a.target { + Some(t) if a.confidence != Confidence::Page => Location { + file: Some(t.file), + line: Some(t.line), + column: Some(t.column), + end_line: Some(t.end_line), + end_column: Some(t.end_column), + confidence: a.confidence, + reason: a.reason, + }, + _ => Location::page_only(a.reason), + } +} + +/// Query text with no PDF context around it. +fn plain(t: &str) -> MarkedText { + MarkedText { + text: t.to_owned(), + ..MarkedText::default() + } +} + +/// A quad over `[x0, y0, x1, y1]`, in the point order PDF applications use. +fn quad([x0, y0, x1, y1]: [f32; 4]) -> [f32; 8] { + [x0, y1, x1, y1, x0, y0, x1, y0] +} + +/// Sample points along the middle of a quad, as import samples a highlight. +fn line_points(q: &[f32; 8], b: &PageBox) -> Vec<(f32, f32)> { + let xs = [q[0], q[2], q[4], q[6]]; + let ys = [q[1], q[3], q[5], q[7]]; + let minx = xs.iter().copied().fold(f32::INFINITY, f32::min); + let maxx = xs.iter().copied().fold(f32::NEG_INFINITY, f32::max); + let ym = f32::midpoint( + ys.iter().copied().fold(f32::INFINITY, f32::min), + ys.iter().copied().fold(f32::NEG_INFINITY, f32::max), + ); + [minx + 1.0, f32::midpoint(minx, maxx), maxx - 1.0] + .into_iter() + .map(|x| b.to_top_left(x, ym)) + .collect() +} + +/// The query text on the page: the occurrence nearest to `rect`, or the only one +/// when there is no `rect`. Returns the marked text with its PDF context (as import +/// reads it) and one quad per text line it covers. +fn find_on_page( + pt: &PageText, + text: &str, + rect: Option<[f32; 4]>, +) -> Option<(Option, Vec<[f32; 8]>)> { + let page = fold_str(pt.chars.iter().map(|c| c.c)); + let page_s: String = page.chars.iter().collect(); + let needle: String = fold_str(text.chars()).chars.iter().collect(); + let needle = needle.trim(); + if needle.is_empty() { + return None; + } + // Folded character index of every byte offset at a char boundary. + let char_at: HashMap = page_s + .char_indices() + .enumerate() + .map(|(i, (b, _))| (b, i)) + .collect(); + let hits: Vec<(usize, usize)> = page_s + .match_indices(needle) + .map(|(b, m)| (char_at[&b], char_at[&b] + m.chars().count())) + .collect(); + let pick = match rect { + Some([x0, y0, x1, y1]) => { + let (cx, cy) = (f32::midpoint(x0, x1), f32::midpoint(y0, y1)); + hits.iter().copied().min_by(|a, b| { + let d = |h: &(usize, usize)| { + let (x, y) = pt.chars[page.origin[h.0]].center(); + (x - cx).hypot(y - cy) + }; + d(a).total_cmp(&d(b)) + })? + } + None if hits.len() == 1 => hits[0], + None => return None, + }; + let (first, last) = (page.origin[pick.0], page.origin[pick.1 - 1]); + let mut lines: Vec<[f32; 4]> = Vec::new(); + for c in pt.chars[first..=last] + .iter() + .filter(|c| !c.c.is_whitespace()) + { + match lines.last_mut() { + Some(l) if c.bbox[1] < l[3] && c.bbox[3] > l[1] => { + *l = [ + l[0].min(c.bbox[0]), + l[1].min(c.bbox[1]), + l[2].max(c.bbox[2]), + l[3].max(c.bbox[3]), + ]; + } + _ => lines.push(c.bbox), + } + } + let quads: Vec<[f32; 8]> = lines.into_iter().map(quad).collect(); + let m = marked_text(pt, &quads, [0.0; 4], CONTEXT); + Some((m, quads)) +} diff --git a/crates/proofback-cli/src/commands.rs b/crates/proofback-cli/src/commands.rs index bdb139e..11bb03d 100644 --- a/crates/proofback-cli/src/commands.rs +++ b/crates/proofback-cli/src/commands.rs @@ -136,6 +136,7 @@ pub fn run(cli: &Cli) -> Result { ); Ok(0) } + Command::Locate(a) => crate::locate_cmd::run(&start, a, cli.quiet), Command::Extract { .. } => unreachable!("handled in main"), } } diff --git a/crates/proofback-cli/src/extract.rs b/crates/proofback-cli/src/extract.rs index ef26a97..cfaf06e 100644 --- a/crates/proofback-cli/src/extract.rs +++ b/crates/proofback-cli/src/extract.rs @@ -17,6 +17,25 @@ const CHILD_MEMORY: u64 = 4 << 30; /// Parse a PDF in a child process. pub fn extract_isolated(pdf: &Path, limits: &LimitsConfig) -> Result { + run_child(pdf, limits, None) +} + +/// For the locator: page boxes and the text of `pages`, read in a child process. +/// Without PDFium the text is left out. +pub fn extract_pages_isolated( + pdf: &Path, + limits: &LimitsConfig, + pages: &[u32], +) -> Result { + let list = pages + .iter() + .map(u32::to_string) + .collect::>() + .join(","); + run_child(pdf, limits, Some(format!("pages={list}"))) +} + +fn run_child(pdf: &Path, limits: &LimitsConfig, mode: Option) -> Result { let exe = std::env::current_exe() .map_err(|e| Error::Input(format!("cannot locate the proofback executable: {e}")))?; let mut child = Command::new(exe) @@ -26,6 +45,7 @@ pub fn extract_isolated(pdf: &Path, limits: &LimitsConfig) -> Result .arg(limits.max_pages.to_string()) .arg(limits.max_annotations.to_string()) .arg(limits.parse_timeout_secs.to_string()) + .args(mode) .stdin(Stdio::null()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) @@ -78,9 +98,19 @@ pub fn extract_isolated(pdf: &Path, limits: &LimitsConfig) -> Result /// Entry point of the child process. Returns the process exit code. pub fn child_main(args: &[String]) -> i32 { - let [pdf, max_mb, max_pages, max_annots, timeout] = args else { - eprintln!("internal: bad __extract arguments"); - return 2; + let (pdf, max_mb, max_pages, max_annots, timeout, pages) = match args { + [a, b, c, d, e] => (a, b, c, d, e, None), + [a, b, c, d, e, m] if m.starts_with("pages=") => { + let list: Vec = m["pages=".len()..] + .split(',') + .filter_map(|p| p.parse().ok()) + .collect(); + (a, b, c, d, e, Some(list)) + } + _ => { + eprintln!("internal: bad __extract arguments"); + return 2; + } }; let num = |s: &String| s.parse::().unwrap_or(0); lower_limits(num(timeout)); @@ -106,14 +136,21 @@ pub fn child_main(args: &[String]) -> i32 { return 3; } }; - let pdfium = match proofback_pdf::load_pdfium(None) { - Ok(p) => p, - Err(e) => { + let pdfium = match (proofback_pdf::load_pdfium(None), &pages) { + (Ok(p), _) => Some(p), + // The locator works without PDFium when every query has text. + (Err(_), Some(_)) => None, + (Err(e), None) => { eprintln!("{e}"); return 3; } }; - match proofback_pdf::extract(&pdfium, &bytes, limits) { + let result = match (&pages, &pdfium) { + (Some(list), p) => proofback_pdf::extract_pages(p.as_ref(), &bytes, limits, list), + (None, Some(p)) => proofback_pdf::extract(p, &bytes, limits), + (None, None) => unreachable!("checked above"), + }; + match result { Ok(x) => { let json = serde_json::to_string(&x).expect("serialisable"); println!("{json}"); diff --git a/crates/proofback-cli/src/locate_cmd.rs b/crates/proofback-cli/src/locate_cmd.rs new file mode 100644 index 0000000..021d8e6 --- /dev/null +++ b/crates/proofback-cli/src/locate_cmd.rs @@ -0,0 +1,134 @@ +//! `proofback locate`: where in the source a PDF position comes from. Stateless: it +//! neither reads nor writes `.proofback/`. + +use std::collections::HashMap; +use std::io::Read; +use std::path::Path; + +use proofback_anchor::{Input, locate}; +use proofback_model::locate::{Location, MAX_QUERY_BYTES, Query, parse_queries}; +use proofback_store::{Config, Error, Project, Result}; +use proofback_synctex::SyncTex; + +use crate::LocateArgs; + +pub fn run(start: &Path, a: &LocateArgs, quiet: bool) -> Result { + let queries = if a.stdin { + if a.page.is_some() || a.rect.is_some() || a.text.is_some() { + return Err(Error::Usage( + "--stdin reads every query from standard input; leave out --page, --rect and --text".into(), + )); + } + let mut buf = String::new(); + std::io::stdin() + .take(MAX_QUERY_BYTES as u64 + 1) + .read_to_string(&mut buf) + .map_err(|e| Error::Input(format!("cannot read the queries: {e}")))?; + parse_queries(&buf).map_err(Error::Input)? + } else { + let page = a.page.ok_or_else(|| { + Error::Usage("give --page with --rect or --text, or use --stdin".into()) + })?; + let rect = a.rect.as_deref().map(parse_rect).transpose()?; + let q = Query { + page, + rect, + text: a.text.clone(), + }; + q.validate().map_err(Error::Usage)?; + vec![q] + }; + + // The project is only a source tree here: no configuration is read. + let root = start + .canonicalize() + .map_err(|e| Error::Input(format!("{}: {e}", start.display())))?; + let project = Project { + root: root.clone(), + config: Config::default(), + }; + let (sources, skipped) = project.load_sources()?; + if sources.is_empty() { + return Err(Error::Input(format!( + "no .tex files found in {}", + root.display() + ))); + } + if !quiet { + for s in skipped { + eprintln!("warning: skipped {s}"); + } + } + let limits = &project.config.limits; + let pages: Vec = queries.iter().map(|q| q.page).collect(); + let pdf_meta = std::fs::metadata(&a.pdf) + .map_err(|e| Error::Input(format!("cannot read {}: {e}", a.pdf.display())))?; + if !pdf_meta.is_file() { + return Err(Error::Input(format!("{} is not a file", a.pdf.display()))); + } + let extracted = crate::extract::extract_pages_isolated(&a.pdf, limits, &pages)?; + let synctex = match &a.synctex { + Some(path) => { + let bytes = crate::commands::read_limited(path, limits.max_synctex_mb)?; + Some( + SyncTex::parse(bytes.as_slice(), proofback_synctex::Limits::default()) + .map_err(|e| Error::Input(format!("{}: {e}", path.display())))?, + ) + } + None => None, + }; + let texts: HashMap = + extracted.texts.into_iter().map(|t| (t.page, t)).collect(); + let input = Input { + round: "locate", + annotations: &[], + boxes: &extracted.boxes, + texts: &texts, + synctex: synctex.as_ref(), + project_root: &root, + sources: &sources, + anonymize: false, + }; + let results = locate(&input, &queries); + if a.stdin { + for r in &results { + println!("{}", serde_json::to_string(r).expect("json")); + } + } else if a.json { + println!( + "{}", + serde_json::to_string_pretty(&results[0]).expect("json") + ); + } else { + println!("{}", human(&results[0])); + } + Ok(0) +} + +fn human(r: &Location) -> String { + match (&r.file, r.line, r.column, r.end_line, r.end_column) { + (Some(f), Some(l), Some(c), Some(el), Some(ec)) => { + let at = if el == l { + format!("{f}:{l}:{c}-{ec}") + } else { + format!("{f}:{l}:{c}-{el}:{ec}") + }; + format!("{at} {} ({})", r.confidence.as_str(), r.reason) + } + _ => format!("page only ({})", r.reason), + } +} + +fn parse_rect(s: &str) -> Result<[f32; 4]> { + let n: Vec = s + .split(',') + .map(|v| v.trim().parse::()) + .collect::>() + .map_err(|_| Error::Usage(format!("--rect takes x0,y0,x1,y1 in PDF points, not {s:?}")))?; + match n.as_slice() { + [a, b, c, d] => Ok([*a, *b, *c, *d]), + _ => Err(Error::Usage(format!( + "--rect takes four numbers, not {s:?}" + ))), + } +} diff --git a/crates/proofback-cli/src/main.rs b/crates/proofback-cli/src/main.rs index f09295f..1d68f65 100644 --- a/crates/proofback-cli/src/main.rs +++ b/crates/proofback-cli/src/main.rs @@ -5,6 +5,7 @@ mod commands; mod docx_cmd; mod extract; mod git; +mod locate_cmd; mod notes_cmd; mod output; mod triage; @@ -168,6 +169,9 @@ pub enum Command { Mcp, /// Print the JSON Schema of round files. Schema, + /// Where a position in the compiled PDF comes from in the source (stateless; no + /// .proofback/ needed). + Locate(LocateArgs), /// Internal: parse a PDF in an isolated process. #[command(name = "__extract", hide = true)] Extract { args: Vec }, @@ -231,6 +235,31 @@ pub struct ImportArgs { pub json: bool, } +#[derive(Debug, Args)] +pub struct LocateArgs { + /// The compiled PDF. + #[arg(long)] + pub pdf: PathBuf, + /// Its SyncTeX file. Without it, the locator searches by text alone. + #[arg(long)] + pub synctex: Option, + /// 1-based page. + #[arg(long)] + pub page: Option, + /// `x0,y0,x1,y1` in PDF points, origin at the bottom left. + #[arg(long, value_name = "X0,Y0,X1,Y1", allow_hyphen_values = true)] + pub rect: Option, + /// The text at that position. + #[arg(long)] + pub text: Option, + /// Read many queries as JSON Lines (`{"page": 3, "rect": [...], "text": "..."}`) + /// from standard input; print one JSON result per line. + #[arg(long)] + pub stdin: bool, + #[arg(long)] + pub json: bool, +} + #[derive(Debug, Args, Default)] pub struct ListArgs { #[arg(long)] diff --git a/crates/proofback-cli/tests/locate.rs b/crates/proofback-cli/tests/locate.rs new file mode 100644 index 0000000..f69848c --- /dev/null +++ b/crates/proofback-cli/tests/locate.rs @@ -0,0 +1,242 @@ +//! `proofback locate` through the real binary: single queries, JSON Lines on stdin, +//! exit codes, and no `.proofback/` read or written. +//! Needs PDFium; skipped when it is missing unless `PROOFBACK_REQUIRE_PDFIUM=1`. + +use std::io::Write; +use std::path::Path; +use std::process::{Command, Stdio}; + +fn run(dir: &Path, args: &[&str], stdin: Option<&str>) -> (i32, String, String) { + let mut child = Command::new(env!("CARGO_BIN_EXE_proofback")) + .args(args) + .current_dir(dir) + .env("NO_COLOR", "1") + .stdin(if stdin.is_some() { + Stdio::piped() + } else { + Stdio::null() + }) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + if let Some(s) = stdin { + child.stdin.take().unwrap().write_all(s.as_bytes()).unwrap(); + } + let out = child.wait_with_output().unwrap(); + ( + out.status.code().unwrap_or(-1), + String::from_utf8_lossy(&out.stdout).into_owned(), + String::from_utf8_lossy(&out.stderr).into_owned(), + ) +} + +fn copy_dir(from: &Path, to: &Path) { + std::fs::create_dir_all(to).unwrap(); + for e in std::fs::read_dir(from).unwrap() { + let e = e.unwrap(); + if e.path().is_dir() { + copy_dir(&e.path(), &to.join(e.file_name())); + } else { + std::fs::copy(e.path(), to.join(e.file_name())).unwrap(); + } + } +} + +#[test] +fn locate_maps_pdf_positions_to_source() { + let pdfium = match proofback_pdf::load_pdfium(None) { + Ok(p) => p, + Err(e) if std::env::var_os("PROOFBACK_REQUIRE_PDFIUM").is_none() => { + eprintln!("skipping: {e}"); + return; + } + Err(e) => panic!("{e}"), + }; + let dir = tempfile::tempdir().unwrap(); + let d = dir.path(); + copy_dir( + &Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/thesis-long"), + d, + ); + // A unique word run on page 3 and its rectangle, read from the PDF. + let pdf = std::fs::read(d.join("main.pdf")).unwrap(); + let page = proofback_pdf::TextExtractor::open(&pdfium, &pdf) + .unwrap() + .page(3) + .unwrap(); + let words: Vec<(String, [f32; 4])> = { + let mut v = Vec::new(); + let mut cur = String::new(); + let mut b = [f32::MAX, f32::MAX, f32::MIN, f32::MIN]; + for c in &page.chars { + if c.c.is_alphabetic() { + cur.push(c.c); + b = [ + b[0].min(c.bbox[0]), + b[1].min(c.bbox[1]), + b[2].max(c.bbox[2]), + b[3].max(c.bbox[3]), + ]; + } else if !cur.is_empty() { + v.push((std::mem::take(&mut cur), b)); + b = [f32::MAX, f32::MAX, f32::MIN, f32::MIN]; + } + } + v + }; + let (text, rect) = words + .windows(4) + .filter(|w| { + w.iter() + .all(|x| (x.1[1] - w[0].1[1]).abs() < 2.0 && x.0.len() > 3) + }) + .map(|w| { + let t = w.iter().map(|x| x.0.as_str()).collect::>().join(" "); + let r = [w[0].1[0], w[0].1[1], w[3].1[2], w[0].1[3]]; + (t, r) + }) + .find(|(t, _)| page.text().matches(t.as_str()).count() == 1) + .expect("a unique run of four words"); + let rect_arg = format!("{},{},{},{}", rect[0], rect[1], rect[2], rect[3]); + + let (code, out, err) = run( + d, + &[ + "locate", + "--pdf", + "main.pdf", + "--synctex", + "main.synctex.gz", + "--page", + "3", + "--rect", + &rect_arg, + "--text", + &text, + "--json", + ], + None, + ); + assert_eq!(code, 0, "{err}"); + let r: serde_json::Value = serde_json::from_str(&out).unwrap(); + assert_eq!(r["confidence"], "exact", "{r}"); + let file = r["file"].as_str().unwrap(); + let src = std::fs::read_to_string(d.join(file)).unwrap(); + let line = src + .lines() + .nth(r["line"].as_u64().unwrap() as usize - 1) + .unwrap(); + assert!( + line.contains(text.split(' ').next().unwrap()), + "{line} / {text}" + ); + + // Rectangle only (text from the PDF), and human output. + let (code, out, _) = run( + d, + &[ + "locate", + "--pdf", + "main.pdf", + "--synctex", + "main.synctex.gz", + "--page", + "3", + "--rect", + &rect_arg, + ], + None, + ); + assert_eq!(code, 0); + assert!(out.starts_with(file) && out.contains("exact"), "{out}"); + + // Many queries on stdin; text-only mode without --synctex. + let lines = format!( + "{{\"page\": 3, \"rect\": [{}, {}, {}, {}], \"text\": {}}}\n\n{{\"page\": 3, \"text\": \"zz qq not in the thesis\"}}\n{{\"page\": 999, \"text\": \"x\"}}\n", + rect[0], + rect[1], + rect[2], + rect[3], + serde_json::to_string(&text).unwrap() + ); + let (code, out, err) = run(d, &["locate", "--pdf", "main.pdf", "--stdin"], Some(&lines)); + assert_eq!(code, 0, "{err}"); + let rs: Vec = out + .lines() + .map(|l| serde_json::from_str(l).unwrap()) + .collect(); + assert_eq!(rs.len(), 3); + assert_eq!(rs[0]["file"], file); + assert_eq!(rs[1]["confidence"], "page"); + assert!( + rs[1].get("file").is_none() && rs[1].get("line").is_none(), + "{}", + rs[1] + ); + assert!(rs[2]["reason"].as_str().unwrap().contains("not in the PDF")); + + // Exit codes: usage 2, unreadable input 3. + assert_eq!( + run(d, &["locate", "--pdf", "main.pdf", "--page", "3"], None).0, + 2 + ); + assert_eq!( + run( + d, + &[ + "locate", "--pdf", "main.pdf", "--page", "3", "--rect", "1,2,3" + ], + None + ) + .0, + 2 + ); + assert_eq!( + run( + d, + &["locate", "--pdf", "main.pdf", "--stdin", "--page", "3"], + Some("") + ) + .0, + 2 + ); + assert_eq!( + run( + d, + &[ + "locate", + "--pdf", + "missing.pdf", + "--page", + "3", + "--text", + "abc" + ], + None + ) + .0, + 3 + ); + assert_eq!( + run( + d, + &[ + "locate", "--pdf", "main.tex", "--page", "3", "--text", "abc" + ], + None + ) + .0, + 3 + ); + let (code, _, err) = run( + d, + &["locate", "--pdf", "main.pdf", "--stdin"], + Some("{\"page\": 3}\n"), + ); + assert_eq!(code, 3, "{err}"); + assert!(err.contains("line 1"), "{err}"); + + // Stateless: nothing under .proofback/ was created. + assert!(!d.join(".proofback").exists()); +} diff --git a/crates/proofback-corpus/tests/locate.rs b/crates/proofback-corpus/tests/locate.rs new file mode 100644 index 0000000..ef3a81d --- /dev/null +++ b/crates/proofback-corpus/tests/locate.rs @@ -0,0 +1,188 @@ +//! The locator against the import: every synthetic markup annotation (highlight, +//! strike-out, underline, squiggly) asked as a locator query (its page, its +//! rectangle and the text the import read under it) gives the same range and +//! confidence as the import, with and without SyncTeX. +//! +//! Point annotations (carets, sticky notes) have no locator equivalent: a query asks +//! where a position's text comes from, not where to insert or which line a note sits +//! beside. +//! +//! Needs PDFium; skipped when it is missing unless `PROOFBACK_REQUIRE_PDFIUM=1`. + +use std::collections::HashMap; +use std::path::Path; + +use proofback_anchor::{Input, import, locate}; +use proofback_corpus::{Fixture, generate}; +use proofback_model::Origin; +use proofback_model::locate::Query; +use proofback_pdf::{Limits, PageText, extract}; + +fn pdfium() -> Option { + match proofback_pdf::load_pdfium(None) { + Ok(p) => Some(p), + Err(e) if std::env::var_os("PROOFBACK_REQUIRE_PDFIUM").is_none() => { + eprintln!("skipping: {e}"); + None + } + Err(e) => panic!("{e}"), + } +} + +#[test] +fn locator_matches_import() { + let Some(pdfium) = pdfium() else { return }; + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures"); + let mut compared = 0; + for name in ["thesis-long", "article-twocolumn", "thesis-basic"] { + let fx = Fixture::load(&root.join(name)).unwrap(); + let count = if name == "thesis-basic" { 16 } else { 120 }; + let (pdf, _) = generate(&fx, &pdfium, count, 42).unwrap(); + let ex = extract(&pdfium, &pdf, Limits::default()).unwrap(); + let texts: HashMap = ex.texts.into_iter().map(|t| (t.page, t)).collect(); + for synctex in [true, false] { + let input = Input { + round: "parity", + annotations: &ex.annotations, + boxes: &ex.boxes, + texts: &texts, + synctex: synctex.then_some(&fx.synctex), + project_root: &fx.root, + sources: &fx.sources, + anonymize: false, + }; + let items: Vec<_> = import(&input) + .into_iter() + .filter(|i| { + matches!(&i.origin, Origin::Pdf { subtype, .. } + if ["Highlight", "StrikeOut", "Underline", "Squiggly"].contains(&subtype.as_str())) + }) + .collect(); + let queries: Vec = items + .iter() + .map(|i| match &i.origin { + Origin::Pdf { + page, + rect, + marked_text, + .. + } => Query { + page: *page, + rect: Some(*rect), + text: Some(marked_text.clone()), + }, + _ => unreachable!(), + }) + .collect(); + let results = locate(&input, &queries); + let mut differ = Vec::new(); + for ((it, q), r) in items.iter().zip(&queries).zip(&results) { + let t = it + .target + .as_ref() + .filter(|_| it.anchor.confidence != proofback_model::Confidence::Page); + let want = ( + it.anchor.confidence, + t.map(|t| (t.file.clone(), t.line, t.column, t.end_line, t.end_column)), + ); + let got = ( + r.confidence, + r.file.clone().map(|f| { + ( + f, + r.line.unwrap(), + r.column.unwrap(), + r.end_line.unwrap(), + r.end_column.unwrap(), + ) + }), + ); + if want != got { + differ.push(format!( + "{q:?}: import {want:?} ({}), locate {got:?} ({})", + it.anchor.reason, r.reason + )); + } + } + compared += items.len(); + assert!( + differ.is_empty(), + "{name} synctex={synctex}: {} of {} differ:\n{}", + differ.len(), + items.len(), + differ.join("\n") + ); + } + } + eprintln!("locator equals import on {compared} queries"); + assert!(compared > 300, "{compared}"); +} + +#[test] +fn locator_without_pdf_text_uses_the_query_text() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/thesis-long"); + let fx = Fixture::load(&root).unwrap(); + let (boxes, _) = proofback_pdf::read_annotations(&fx.pdf, Limits::default()).unwrap(); + let texts = HashMap::new(); + let input = Input { + round: "locate", + annotations: &[], + boxes: &boxes, + texts: &texts, + synctex: None, + project_root: &fx.root, + sources: &fx.sources, + anonymize: false, + }; + // A sentence from the sources, unique and long: exact without PDFium or SyncTeX. + let (file, src) = fx.sources.files().find(|(f, _)| f.contains("ch3")).unwrap(); + let line = src + .text + .lines() + .find(|l| l.len() > 60 && !l.contains('\\') && !l.contains('$') && !l.contains('~')) + .unwrap(); + let phrase: String = line + .split_whitespace() + .take(6) + .collect::>() + .join(" "); + let r = locate( + &input, + &[ + Query { + page: 1, + rect: None, + text: Some(phrase.clone()), + }, + Query { + page: 1, + rect: None, + text: Some("zzz qqq not in the sources".into()), + }, + Query { + page: 9999, + rect: None, + text: Some(phrase.clone()), + }, + Query { + page: 1, + rect: None, + text: None, + }, + ], + ); + if fx + .sources + .files() + .map(|(_, s)| s.find_folded(&phrase.to_lowercase()).len()) + .sum::() + == 1 + { + assert_eq!(r[0].file.as_deref(), Some(file), "{:?}", r[0]); + } + assert!(r[0].line.is_some(), "{:?}", r[0]); + assert_eq!(r[1].confidence, proofback_model::Confidence::Page); + assert!(r[1].file.is_none() && r[1].line.is_none()); + assert!(r[2].reason.contains("not in the PDF"), "{:?}", r[2]); + assert!(r[3].reason.contains("invalid query"), "{:?}", r[3]); +} diff --git a/crates/proofback-corpus/tests/perf.rs b/crates/proofback-corpus/tests/perf.rs index ebcb4bb..ace442d 100644 --- a/crates/proofback-corpus/tests/perf.rs +++ b/crates/proofback-corpus/tests/perf.rs @@ -75,9 +75,60 @@ fn import_meets_budgets() { let sync = t2.elapsed(); assert_eq!(rep.lost, 0); + // Locator, cold: 500 queries (page, rectangle and text of each annotation) with + // the PDF, SyncTeX and sources parsed from scratch. Budget: the cold import's. + let queries: Vec = items + .iter() + .filter_map(|i| match &i.origin { + proofback_model::Origin::Pdf { + page, + rect, + marked_text, + .. + } => Some(proofback_model::locate::Query { + page: *page, + rect: Some(*rect), + text: (!marked_text.trim().is_empty()).then(|| marked_text.clone()), + }), + _ => None, + }) + .collect(); + let t3 = Instant::now(); + let pages: Vec = { + let mut p: Vec = queries.iter().map(|q| q.page).collect(); + p.sort_unstable(); + p.dedup(); + p + }; + let (boxes, _) = + proofback_pdf::read_annotations(&pdf, proofback_pdf::Limits::default()).unwrap(); + let ex = proofback_pdf::TextExtractor::open(&pdfium, &pdf).unwrap(); + let ltexts: std::collections::HashMap = + pages.iter().map(|&p| (p, ex.page(p).unwrap())).collect(); + let lsynctex = SyncTex::parse( + synctex_bytes.as_slice(), + proofback_synctex::Limits::default(), + ) + .unwrap(); + let lsources = Sources::new(files.clone()); + let linput = Input { + round: "locate", + annotations: &[], + boxes: &boxes, + texts: <exts, + synctex: Some(&lsynctex), + project_root: &dir, + sources: &lsources, + anonymize: false, + }; + let located = proofback_anchor::locate(&linput, &queries); + let locate_cold = t3.elapsed(); + assert_eq!(located.len(), queries.len()); + assert!(queries.len() >= 480, "{} queries", queries.len()); + let peak_mb = peak_rss_mb(); eprintln!( - "pages {} annotations {}: extract {:?}, synctex {:?}, cold import {:?}, warm import {:?}, sync {:?}, peak RSS {:?} MB", + "pages {} annotations {}: extract {:?}, synctex {:?}, cold import {:?}, warm import {:?}, sync {:?}, locate {} queries cold {:?}, peak RSS {:?} MB", fx.synctex.pages().len(), items.len(), t_extract, @@ -85,6 +136,8 @@ fn import_meets_budgets() { cold, warm, sync, + queries.len(), + locate_cold, peak_mb ); if cfg!(debug_assertions) { @@ -97,6 +150,11 @@ fn import_meets_budgets() { "warm import {warm:?} exceeds 300 ms" ); assert!(sync.as_secs_f64() < 0.3, "sync {sync:?} exceeds 300 ms"); + assert!( + locate_cold.as_secs_f64() < 1.0, + "{} locator queries took {locate_cold:?}, over the 1 s cold import budget", + queries.len() + ); if let Some(mb) = peak_mb { assert!(mb < 300, "peak memory {mb} MB exceeds 300 MB"); } diff --git a/crates/proofback-model/src/lib.rs b/crates/proofback-model/src/lib.rs index 4148152..9e4d72b 100644 --- a/crates/proofback-model/src/lib.rs +++ b/crates/proofback-model/src/lib.rs @@ -5,6 +5,7 @@ //! and merges stay readable (see [`RoundFile::to_json`]). mod id; +pub mod locate; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; diff --git a/crates/proofback-model/src/locate.rs b/crates/proofback-model/src/locate.rs new file mode 100644 index 0000000..ecfca4f --- /dev/null +++ b/crates/proofback-model/src/locate.rs @@ -0,0 +1,196 @@ +//! The locator: map a position in a compiled PDF to a range of the source, without +//! a review round. Queries and results are plain data with a published JSON Schema +//! ([`LOCATE_SCHEMA_URL`]). + +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +use crate::Confidence; + +/// Public location of the JSON Schema for [`Query`] and [`Location`]. +pub const LOCATE_SCHEMA_URL: &str = "https://amet13.github.io/proofback/schema/locate-v1.json"; + +/// Most queries accepted in one call. +pub const MAX_QUERIES: usize = 100_000; +/// Most characters of `text` in one query. +pub const MAX_QUERY_TEXT: usize = 4_096; +/// Largest JSON Lines input accepted, in bytes. +pub const MAX_QUERY_BYTES: usize = 64 << 20; + +/// Where in the PDF to look. At least one of `rect` and `text` is required. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Query { + /// 1-based page number. + pub page: u32, + /// `[x0, y0, x1, y1]` in PDF points, origin at the bottom left of the page. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub rect: Option<[f32; 4]>, + /// The text at that position, as the PDF shows it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub text: Option, +} + +impl Query { + /// Check the bounds of a query (untrusted input). + pub fn validate(&self) -> Result<(), String> { + if self.page == 0 { + return Err("`page` is 1-based".into()); + } + if self.rect.is_none() && self.text.as_deref().is_none_or(|t| t.trim().is_empty()) { + return Err("a query needs `rect` or a non-empty `text`".into()); + } + if let Some([x0, y0, x1, y1]) = self.rect { + if ![x0, y0, x1, y1] + .iter() + .all(|v| v.is_finite() && v.abs() < 1e6) + { + return Err("`rect` must hold four finite numbers".into()); + } + if x0 > x1 || y0 > y1 { + return Err("`rect` is `[x0, y0, x1, y1]` with x0 <= x1 and y0 <= y1".into()); + } + } + if let Some(t) = &self.text + && t.chars().count() > MAX_QUERY_TEXT + { + return Err(format!("`text` is longer than {MAX_QUERY_TEXT} characters")); + } + Ok(()) + } +} + +/// Where a query points in the source. With confidence `page` there is no source +/// location: `file`, `line` and the columns are absent. Lines and columns have the +/// units of [`crate::Target`]: 1-based, columns in Unicode code points, +/// `end_column` exclusive. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Location { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub file: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub line: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub column: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub end_line: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub end_column: Option, + pub confidence: Confidence, + /// Human-readable explanation of the confidence level. + pub reason: String, +} + +impl Location { + /// A result that only knows the page. + pub fn page_only(reason: impl Into) -> Self { + Self { + file: None, + line: None, + column: None, + end_line: None, + end_column: None, + confidence: Confidence::Page, + reason: reason.into(), + } + } +} + +/// Parse queries from JSON Lines (one object per line; blank lines are skipped) +/// and validate each. Errors name the 1-based line. +pub fn parse_queries(input: &str) -> Result, String> { + if input.len() > MAX_QUERY_BYTES { + return Err(format!( + "the queries are larger than {MAX_QUERY_BYTES} bytes" + )); + } + let mut out = Vec::new(); + for (n, line) in input.lines().enumerate() { + if line.trim().is_empty() { + continue; + } + if out.len() == MAX_QUERIES { + return Err(format!("more than {MAX_QUERIES} queries")); + } + let q: Query = + serde_json::from_str(line).map_err(|e| format!("query on line {}: {e}", n + 1))?; + q.validate() + .map_err(|e| format!("query on line {}: {e}", n + 1))?; + out.push(q); + } + Ok(out) +} + +/// Both shapes in one document, for the published schema. +#[derive(JsonSchema)] +#[allow(dead_code)] // only used for its schema +struct LocateSchema { + /// One query per line of JSON Lines input (or the elements of an array). + queries: Vec, + /// One result per query, in the same order. + results: Vec, +} + +/// JSON Schema for locator queries and results. +pub fn locate_schema() -> serde_json::Value { + let mut schema = + serde_json::to_value(schemars::schema_for!(LocateSchema)).expect("schema serialises"); + if let Some(obj) = schema.as_object_mut() { + obj.insert("$id".into(), LOCATE_SCHEMA_URL.into()); + obj.insert( + "title".into(), + "proofback locator queries and results".into(), + ); + } + schema +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn queries_are_validated() { + let ok = parse_queries( + "{\"page\": 3, \"rect\": [1, 2, 3, 4]}\n\n{\"page\": 1, \"text\": \"robust\"}\n", + ) + .unwrap(); + assert_eq!(ok.len(), 2); + for bad in [ + "{\"page\": 0, \"text\": \"x\"}", + "{\"page\": 1}", + "{\"page\": 1, \"text\": \" \"}", + "{\"page\": 1, \"rect\": [3, 2, 1, 4]}", + "{\"page\": 1, \"rect\": [1, 2, 3]}", + "{\"page\": 1, \"text\": \"x\", \"extra\": 1}", + "{\"page\": -1, \"text\": \"x\"}", + "not json", + ] { + let e = parse_queries(&format!("{{\"page\": 1, \"text\": \"a\"}}\n{bad}")).unwrap_err(); + assert!(e.contains("line 2"), "{bad}: {e}"); + } + let long = format!( + "{{\"page\": 1, \"text\": \"{}\"}}", + "a".repeat(MAX_QUERY_TEXT + 1) + ); + assert!(parse_queries(&long).is_err()); + } + + #[test] + fn page_results_have_no_source_fields() { + let v = serde_json::to_value(Location::page_only("why")).unwrap(); + assert_eq!( + v, + serde_json::json!({"confidence": "page", "reason": "why"}) + ); + } + + #[test] + fn schema_names_both_shapes() { + let s = locate_schema().to_string(); + assert!( + s.contains(LOCATE_SCHEMA_URL) && s.contains("\"Query\"") && s.contains("\"Location\"") + ); + } +} diff --git a/crates/proofback-pdf/src/lib.rs b/crates/proofback-pdf/src/lib.rs index 203cc80..da43598 100644 --- a/crates/proofback-pdf/src/lib.rs +++ b/crates/proofback-pdf/src/lib.rs @@ -46,6 +46,38 @@ pub struct Extracted { pub texts: Vec, } +/// For the locator: page boxes, and the text of `pages` when PDFium is given. +/// Pages that are not in the PDF are left out. Annotations are not read. +pub fn extract_pages( + pdfium: Option<&pdfium_render::prelude::Pdfium>, + bytes: &[u8], + limits: Limits, + pages: &[u32], +) -> Result { + let (boxes, _) = read_annotations(bytes, limits)?; + let mut texts = Vec::new(); + if let Some(p) = pdfium { + let mut wanted: Vec = pages + .iter() + .copied() + .filter(|n| boxes.iter().any(|b| b.page == *n)) + .collect(); + wanted.sort_unstable(); + wanted.dedup(); + if !wanted.is_empty() { + let ex = TextExtractor::open(p, bytes)?; + for n in wanted { + texts.push(ex.page(n)?); + } + } + } + Ok(Extracted { + boxes, + annotations: Vec::new(), + texts, + }) +} + /// Read annotations and the text of annotated pages. pub fn extract( pdfium: &pdfium_render::prelude::Pdfium, diff --git a/crates/proofback-pdf/src/text.rs b/crates/proofback-pdf/src/text.rs index e126107..86f4a8f 100644 --- a/crates/proofback-pdf/src/text.rs +++ b/crates/proofback-pdf/src/text.rs @@ -16,7 +16,7 @@ pub struct TextChar { } impl TextChar { - fn center(&self) -> (f32, f32) { + pub fn center(&self) -> (f32, f32) { ( f32::midpoint(self.bbox[0], self.bbox[2]), f32::midpoint(self.bbox[1], self.bbox[3]), diff --git a/crates/proofback-wasm/src/lib.rs b/crates/proofback-wasm/src/lib.rs index 735029d..882806a 100644 --- a/crates/proofback-wasm/src/lib.rs +++ b/crates/proofback-wasm/src/lib.rs @@ -308,6 +308,57 @@ pub fn resolve_item( Ok(rf.to_json()) } +/// Where PDF positions come from in the source (the locator). `queries_json` is a +/// JSON array of `{ "page", "rect"?, "text"? }`; returns a JSON array of results in +/// the same order (schema: `site/schema/locate-v1.json`). Writes nothing. +#[wasm_bindgen] +#[allow(clippy::needless_pass_by_value)] // wasm-bindgen needs owned arguments +pub fn locate( + pdf: &[u8], + synctex: Option>, + sources_json: &str, + queries_json: &str, +) -> Result { + use proofback_model::locate::{MAX_QUERIES, MAX_QUERY_BYTES, Query}; + if queries_json.len() > MAX_QUERY_BYTES { + return Err(err("the queries are too large")); + } + let queries: Vec = serde_json::from_str(queries_json).map_err(err)?; + if queries.len() > MAX_QUERIES { + return Err(err(format!("more than {MAX_QUERIES} queries"))); + } + for (i, q) in queries.iter().enumerate() { + q.validate().map_err(|e| err(format!("query {i}: {e}")))?; + } + let sources = sources_from_json(sources_json)?; + let pages: Vec = queries.iter().map(|q| q.page).collect(); + let limits = proofback_pdf::Limits::default(); + // Queries with text work without PDFium; use it for page text when it is there. + let extracted = + with_pdfium(|p| proofback_pdf::extract_pages(Some(p), pdf, limits, &pages).map_err(err)) + .or_else(|_| proofback_pdf::extract_pages(None, pdf, limits, &pages).map_err(err))?; + let st = match &synctex { + Some(b) if !b.is_empty() => { + Some(SyncTex::parse(b.as_slice(), proofback_synctex::Limits::default()).map_err(err)?) + } + _ => None, + }; + let texts: HashMap = + extracted.texts.into_iter().map(|t| (t.page, t)).collect(); + let root = std::path::Path::new("/proofback-browser-project"); + let input = Input { + round: "locate", + annotations: &[], + boxes: &extracted.boxes, + texts: &texts, + synctex: st.as_ref(), + project_root: root, + sources: &sources, + anonymize: false, + }; + serde_json::to_string(&proofback_anchor::locate(&input, &queries)).map_err(err) +} + /// Page size in PDF points: `[width, height]`. #[wasm_bindgen] pub fn page_size(pdf: &[u8], page: u32) -> Result, JsError> { diff --git a/docs/PLAN.md b/docs/PLAN.md index c421728..7c28886 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -383,6 +383,7 @@ it in `$schema` and carries `schema_version`. | `stats` | Counts by round, status, file and reviewer | | `mcp` | Run the MCP server on stdio (v0.3) | | `doctor` | Check SyncTeX presence, encodings and project root | +| `locate` | Map a PDF position to a source range, without a round (below) | Global flags: `--json`, `--project `, `--quiet`, `--color auto|always|never`. @@ -392,6 +393,21 @@ encoding, path outside project). `--json` output is stable within a schema version and documented per command. +**Locator** (#19). `proofback locate --pdf [--synctex ] --page +[--rect x0,y0,x1,y1] [--text ] [--json]`, or `--stdin` with one JSON query per line +(`{"page": 3, "rect": [x0, y0, x1, y1], "text": "..."}`), printing one JSON result per +line. Rectangles are in PDF points, origin bottom-left. A result has `file`, `line`, +`column`, `end_line`, `end_column` (the units of `Target`), `confidence` and +`reason`; with confidence `page` it has no source fields. It runs the import pipeline +(`proofback_anchor::locate`), so confidence follows D-14. Stateless: it reads only +the sources under `--project` (or the current directory) and never reads or writes +`.proofback/`. PDF parsing runs in the isolated child process with the usual limits; +queries are bounded (100,000 per call, 4,096 characters of text, 64 MB of input). +Queries with `text` work without PDFium; without SyncTeX it searches by text alone. +Exit codes: `2` for a malformed command line, `3` for an unreadable PDF or SyncTeX +file or an invalid query line. Same API in WebAssembly (`locate`) and Node +(`require('proofback').locate`). Schema: `site/schema/locate-v1.json`. + --- ## 8. AI and agents (D-09) diff --git a/fuzz/Cargo.lock b/fuzz/Cargo.lock index 58b7237..9078ca5 100644 --- a/fuzz/Cargo.lock +++ b/fuzz/Cargo.lock @@ -14,6 +14,15 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + [[package]] name = "cc" version = "1.11.3" @@ -32,6 +41,21 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + [[package]] name = "crc32fast" version = "1.5.6" @@ -41,6 +65,32 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", +] + +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + [[package]] name = "find-msvc-tools" version = "0.1.15" @@ -69,6 +119,21 @@ dependencies = [ "r-efi", ] +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + [[package]] name = "jobserver" version = "0.1.35" @@ -95,6 +160,12 @@ dependencies = [ "cc", ] +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + [[package]] name = "miniz_oxide" version = "0.9.1" @@ -119,10 +190,22 @@ name = "proofback-fuzz" version = "0.0.0" dependencies = [ "libfuzzer-sys", + "proofback-model", "proofback-synctex", "proofback-tex", ] +[[package]] +name = "proofback-model" +version = "0.2.0" +dependencies = [ + "schemars", + "serde", + "serde_json", + "sha2", + "thiserror", +] + [[package]] name = "proofback-synctex" version = "0.2.0" @@ -153,6 +236,116 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "ref-cast" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "schemars" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" +dependencies = [ + "dyn-clone", + "ref-cast", + "schemars_derive", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1c3a92094fa7d61aa124645844facb6b554dfc797136d0f5fd1f890e2bffc69" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_derive_internals" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "820083d430c52864bf834423fc988cbcf61685d6f9d22a765a64e3f6cfe3521c" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "shlex" version = "2.0.1" @@ -202,6 +395,12 @@ version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + [[package]] name = "unicode-ident" version = "1.0.27" @@ -222,3 +421,9 @@ name = "zlib-rs" version = "0.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index 9473b57..7ac6430 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -9,6 +9,7 @@ cargo-fuzz = true [dependencies] libfuzzer-sys = "0.4" +proofback-model = { path = "../crates/proofback-model" } proofback-synctex = { path = "../crates/proofback-synctex" } proofback-tex = { path = "../crates/proofback-tex" } @@ -25,3 +26,10 @@ path = "fuzz_targets/tex_normalize.rs" test = false doc = false bench = false + +[[bin]] +name = "locate_query" +path = "fuzz_targets/locate_query.rs" +test = false +doc = false +bench = false diff --git a/fuzz/fuzz_targets/locate_query.rs b/fuzz/fuzz_targets/locate_query.rs new file mode 100644 index 0000000..1ba5fce --- /dev/null +++ b/fuzz/fuzz_targets/locate_query.rs @@ -0,0 +1,18 @@ +#![no_main] +//! The locator's query parser (`proofback_model::locate::parse_queries`): JSON Lines +//! from an untrusted caller. Accepted queries must pass validation. +use libfuzzer_sys::fuzz_target; +use proofback_model::locate::{MAX_QUERIES, MAX_QUERY_TEXT, parse_queries}; + +fuzz_target!(|data: &[u8]| { + let Ok(s) = std::str::from_utf8(data) else { return }; + if let Ok(qs) = parse_queries(s) { + assert!(qs.len() <= MAX_QUERIES); + for q in &qs { + assert!(q.validate().is_ok()); + assert!(q.page >= 1); + assert!(q.rect.is_some() || q.text.as_ref().is_some_and(|t| !t.trim().is_empty())); + assert!(q.text.as_ref().is_none_or(|t| t.chars().count() <= MAX_QUERY_TEXT)); + } + } +}); diff --git a/npm/README.md b/npm/README.md index 3c70374..09098b5 100644 --- a/npm/README.md +++ b/npm/README.md @@ -20,4 +20,28 @@ await pb.load(); const round = pb.importReview(pdfBytes, { synctex, sources: { 'main.tex': text }, round: 'r1' }); ``` +## Locator + +`locate` answers "where in the source does this place in the PDF come from?", +without a review round and without writing anything: + +```js +const results = pb.locate(pdfBytes, { + synctex, // optional; without it, text-only search + sources: { 'main.tex': text }, + queries: [ + { page: 3, rect: [72, 640, 300, 652] }, // PDF points, origin bottom-left + { page: 5, text: 'the estimator is robust' }, + ], +}); +// [{ file: 'main.tex', line: 41, column: 18, end_line: 41, end_column: 24, +// confidence: 'exact', reason: '...' }, { confidence: 'page', reason: '...' }] +``` + +A query needs `rect`, `text` or both. A result with confidence `page` has no `file` or +`line`. Lines and columns are 1-based, columns count Unicode code points, and +`end_column` is exclusive. When proofback is not sure, it says `line` or `page` +rather than guessing. Schema: +. An invalid query throws. + See . diff --git a/npm/lib/index.d.ts b/npm/lib/index.d.ts index 0276ab0..168a95c 100644 --- a/npm/lib/index.d.ts +++ b/npm/lib/index.d.ts @@ -18,3 +18,31 @@ export function resolveItem( id: string, opts?: { status?: string; reply?: string; author?: string }, ): RoundFile; + +/** A locator query: at least one of `rect` and `text`. */ +export interface LocateQuery { + /** 1-based page. */ + page: number; + /** `[x0, y0, x1, y1]` in PDF points, origin at the bottom left. */ + rect?: [number, number, number, number]; + /** The text at that position. */ + text?: string; +} +/** + * Where a query points. With confidence `page` there is no source location. Lines + * and columns are 1-based; columns count Unicode code points; `end_column` is + * exclusive. Schema: https://amet13.github.io/proofback/schema/locate-v1.json + */ +export interface LocateResult { + file?: string; + line?: number; + column?: number; + end_line?: number; + end_column?: number; + confidence: 'exact' | 'line' | 'region' | 'page'; + reason: string; +} +export function locate( + pdf: Uint8Array, + opts: { synctex?: Uint8Array; sources: Record; queries: LocateQuery[] }, +): LocateResult[]; diff --git a/npm/lib/index.js b/npm/lib/index.js index 3128863..10094d1 100644 --- a/npm/lib/index.js +++ b/npm/lib/index.js @@ -76,4 +76,16 @@ function resolveItem(round, sources, id, { status = '', reply = '', author = 'me return JSON.parse(need().resolve_item(JSON.stringify(round), JSON.stringify(sources), id, status, reply, author, now())); } -module.exports = { load, importReview, patch, exportRound, answer, resolveItem }; +/** + * Where positions in a compiled PDF come from in the source. Stateless; writes + * nothing. A query needs `rect` or `text`; with `text` it works without the PDF text. + * @param {Uint8Array} pdf + * @param {{ synctex?: Uint8Array, sources: Record, queries: Array<{ page: number, rect?: number[], text?: string }> }} opts + * @returns {Array} one result per query, in order + */ +function locate(pdf, opts) { + const json = need().locate(pdf, opts.synctex, JSON.stringify(opts.sources), JSON.stringify(opts.queries)); + return JSON.parse(json); +} + +module.exports = { load, importReview, patch, exportRound, answer, resolveItem, locate }; diff --git a/npm/test/import.test.js b/npm/test/import.test.js index 98b8c51..55afc25 100644 --- a/npm/test/import.test.js +++ b/npm/test/import.test.js @@ -34,3 +34,24 @@ test('Node import matches the native import exactly', async () => { const diff = pb.patch(rf, sources); assert.match(diff, /sharper wording/); }); + +test('Node locator matches the native locator exactly', async () => { + await pb.load(); + const fx = path.join(repo, 'fixtures', 'thesis-long'); + const sources = {}; + for (const f of ['main.tex', ...fs.readdirSync(path.join(fx, 'chapters')).map((c) => `chapters/${c}`)]) { + sources[f] = fs.readFileSync(path.join(fx, f), 'utf8'); + } + const sample = path.join(repo, 'target', 'sample'); + const queries = JSON.parse(fs.readFileSync(path.join(sample, 'locate-queries.json'), 'utf8')); + const expected = JSON.parse(fs.readFileSync(path.join(sample, 'locate-expected.json'), 'utf8')); + assert.ok(queries.length >= 60, `${queries.length} queries`); + const got = pb.locate(fs.readFileSync(path.join(fx, 'main.pdf')), { + synctex: fs.readFileSync(path.join(fx, 'main.synctex.gz')), + sources, + queries, + }); + assert.deepStrictEqual(got, expected); + // An invalid query is an error, not a guess. + assert.throws(() => pb.locate(fs.readFileSync(path.join(fx, 'main.pdf')), { sources, queries: [{ page: 1 }] })); +}); diff --git a/site/llms.txt b/site/llms.txt index 27787c2..e481760 100644 --- a/site/llms.txt +++ b/site/llms.txt @@ -13,6 +13,7 @@ ## Interfaces - CLI: `proofback init|import|list|show|triage|resolve|confirm|suggest|patch|apply|sync|answer|letter|inline|docx export|sarif|stats|mcp|doctor|schema`, `--json` on every command, exit codes 0 to 4 +- Locator: `proofback locate --pdf main.pdf --synctex main.synctex.gz --page 3 --rect x0,y0,x1,y1 --json` (or `--stdin` with JSON Lines) maps a PDF position to file, line and columns; also `locate` in the Node package. Schema: https://amet13.github.io/proofback/schema/locate-v1.json - MCP tools (stdio): list_items, get_item, propose_patch, apply_patch, resolve_item, sync, export - Item IDs: `pb_` plus base32, unique prefixes accepted diff --git a/site/schema/locate-v1.json b/site/schema/locate-v1.json new file mode 100644 index 0000000..f5e7cca --- /dev/null +++ b/site/schema/locate-v1.json @@ -0,0 +1,146 @@ +{ + "$defs": { + "Confidence": { + "description": "How precisely an item is located. Ordered from best to worst.", + "oneOf": [ + { + "const": "exact", + "description": "Exact character range.", + "type": "string" + }, + { + "const": "line", + "description": "Correct line, character range uncertain.", + "type": "string" + }, + { + "const": "region", + "description": "A figure, table or display-maths block.", + "type": "string" + }, + { + "const": "page", + "description": "Only the page is known; needs a human.", + "type": "string" + } + ] + }, + "Location": { + "additionalProperties": false, + "description": "Where a query points in the source. With confidence `page` there is no source\nlocation: `file`, `line` and the columns are absent. Lines and columns have the\nunits of [`crate::Target`]: 1-based, columns in Unicode code points,\n`end_column` exclusive.", + "properties": { + "column": { + "format": "uint32", + "minimum": 0, + "type": [ + "integer", + "null" + ] + }, + "confidence": { + "$ref": "#/$defs/Confidence" + }, + "end_column": { + "format": "uint32", + "minimum": 0, + "type": [ + "integer", + "null" + ] + }, + "end_line": { + "format": "uint32", + "minimum": 0, + "type": [ + "integer", + "null" + ] + }, + "file": { + "type": [ + "string", + "null" + ] + }, + "line": { + "format": "uint32", + "minimum": 0, + "type": [ + "integer", + "null" + ] + }, + "reason": { + "description": "Human-readable explanation of the confidence level.", + "type": "string" + } + }, + "required": [ + "confidence", + "reason" + ], + "type": "object" + }, + "Query": { + "additionalProperties": false, + "description": "Where in the PDF to look. At least one of `rect` and `text` is required.", + "properties": { + "page": { + "description": "1-based page number.", + "format": "uint32", + "minimum": 0, + "type": "integer" + }, + "rect": { + "description": "`[x0, y0, x1, y1]` in PDF points, origin at the bottom left of the page.", + "items": { + "format": "float", + "type": "number" + }, + "maxItems": 4, + "minItems": 4, + "type": [ + "array", + "null" + ] + }, + "text": { + "description": "The text at that position, as the PDF shows it.", + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "page" + ], + "type": "object" + } + }, + "$id": "https://amet13.github.io/proofback/schema/locate-v1.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "description": "Both shapes in one document, for the published schema.", + "properties": { + "queries": { + "description": "One query per line of JSON Lines input (or the elements of an array).", + "items": { + "$ref": "#/$defs/Query" + }, + "type": "array" + }, + "results": { + "description": "One result per query, in the same order.", + "items": { + "$ref": "#/$defs/Location" + }, + "type": "array" + } + }, + "required": [ + "queries", + "results" + ], + "title": "proofback locator queries and results", + "type": "object" +} diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index a94d30c..830348f 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -10,6 +10,7 @@ publish.workspace = true [dependencies] anyhow = "1.0.105" +proofback-anchor = { version = "0.2.0", path = "../crates/proofback-anchor" } proofback-corpus = { version = "0.2.0", path = "../crates/proofback-corpus" } proofback-model = { version = "0.2.0", path = "../crates/proofback-model" } proofback-pdf = { version = "0.2.0", path = "../crates/proofback-pdf" } diff --git a/xtask/src/main.rs b/xtask/src/main.rs index d82ceef..9cc4832 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -1,6 +1,6 @@ //! Development tasks: `cargo xtask `. //! -//! - `schema [--check]` write (or verify) `site/schema/v1.json` +//! - `schema [--check]` write (or verify) `site/schema/v1.json` and `locate-v1.json` //! - `fixtures` rebuild PDFs and `SyncTeX` files under `fixtures/` with pdflatex use std::path::{Path, PathBuf}; @@ -47,23 +47,34 @@ fn main() -> Result<()> { } fn schema(root: &Path, check: bool) -> Result<()> { - let path = root.join("site/schema/v1.json"); - let mut text = serde_json::to_string_pretty(&proofback_model::round_file_schema())?; - text.push('\n'); - if check { - let current = std::fs::read_to_string(&path).unwrap_or_default(); - if current != text { - bail!( - "{} is out of date; run `cargo xtask schema`", - path.display() - ); + let schemas = [ + ("site/schema/v1.json", proofback_model::round_file_schema()), + ( + "site/schema/locate-v1.json", + proofback_model::locate::locate_schema(), + ), + ]; + for (rel, value) in schemas { + let path = root.join(rel); + let mut text = serde_json::to_string_pretty(&value)?; + text.push('\n'); + if check { + let current = std::fs::read_to_string(&path).unwrap_or_default(); + if current != text { + bail!( + "{} is out of date; run `cargo xtask schema`", + path.display() + ); + } + continue; } - println!("schema up to date"); - return Ok(()); + std::fs::create_dir_all(path.parent().context("schema dir")?)?; + std::fs::write(&path, text)?; + println!("wrote {}", path.display()); + } + if check { + println!("schemas up to date"); } - std::fs::create_dir_all(path.parent().context("schema dir")?)?; - std::fs::write(&path, text)?; - println!("wrote {}", path.display()); Ok(()) } @@ -346,7 +357,68 @@ fn sample(root: &Path) -> Result<()> { out.join("expected.json"), serde_json::to_string_pretty(&expected)?, )?; - println!("wrote {} items to {}", expected.len(), out.display()); + // Locator parity: the markup annotations as queries (page, rectangle, text), plus + // text-only and rectangle-only queries; the native results are the expectation. + let mut queries: Vec = Vec::new(); + for i in &items { + if let proofback_model::Origin::Pdf { + page, + rect, + marked_text, + subtype, + .. + } = &i.origin + && ["Highlight", "StrikeOut", "Underline", "Squiggly"].contains(&subtype.as_str()) + { + queries.push(proofback_model::locate::Query { + page: *page, + rect: Some(*rect), + text: Some(marked_text.clone()), + }); + queries.push(proofback_model::locate::Query { + page: *page, + rect: None, + text: Some(marked_text.clone()), + }); + queries.push(proofback_model::locate::Query { + page: *page, + rect: Some(*rect), + text: None, + }); + } + } + let ex = proofback_pdf::extract_pages( + Some(&pdfium), + &fx.pdf, + proofback_pdf::Limits::default(), + &queries.iter().map(|q| q.page).collect::>(), + )?; + let texts = ex.texts.into_iter().map(|t| (t.page, t)).collect(); + let input = proofback_anchor::Input { + round: "locate", + annotations: &[], + boxes: &ex.boxes, + texts: &texts, + synctex: Some(&fx.synctex), + project_root: Path::new("/proofback-browser-project"), + sources: &fx.sources, + anonymize: false, + }; + let located = proofback_anchor::locate(&input, &queries); + std::fs::write( + out.join("locate-queries.json"), + serde_json::to_string_pretty(&queries)?, + )?; + std::fs::write( + out.join("locate-expected.json"), + serde_json::to_string_pretty(&located)?, + )?; + println!( + "wrote {} items and {} locator queries to {}", + expected.len(), + queries.len(), + out.display() + ); Ok(()) }