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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,15 @@ the JSON schema is versioned separately (`schema_version` in round files).
`tool`, `version` and `schema_version`.
- SARIF locations carry `uriBaseId: %SRCROOT%`.

### 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`.

### Documentation

- README: one table of supported inputs (annotated PDF, email notes, Word, Typst) with the
Expand Down
1 change: 1 addition & 0 deletions Cargo.lock

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

17 changes: 16 additions & 1 deletion crates/proofback-anchor/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
pub mod align;
mod classify;
pub mod ink;
mod locate;
pub mod sources;

use std::collections::{BTreeMap, HashMap};
Expand All @@ -29,6 +30,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.
Expand Down Expand Up @@ -279,7 +281,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<MarkedText>,
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.
Expand Down
161 changes: 161 additions & 0 deletions crates/proofback-anchor/src/locate.rs
Original file line number Diff line number Diff line change
@@ -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<Location> {
let boxes: HashMap<u32, &PageBox> = 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<u32, &PageBox>, 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<MarkedText>, 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<usize, usize> = 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))
}
1 change: 1 addition & 0 deletions crates/proofback-cli/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,7 @@ pub fn run(cli: &Cli) -> Result<u8> {
);
Ok(0)
}
Command::Locate(a) => crate::locate_cmd::run(&start, a, cli.quiet),
Command::Extract { .. } => unreachable!("handled in main"),
}
}
Expand Down
51 changes: 44 additions & 7 deletions crates/proofback-cli/src/extract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Extracted> {
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<Extracted> {
let list = pages
.iter()
.map(u32::to_string)
.collect::<Vec<_>>()
.join(",");
run_child(pdf, limits, Some(format!("pages={list}")))
}

fn run_child(pdf: &Path, limits: &LimitsConfig, mode: Option<String>) -> Result<Extracted> {
let exe = std::env::current_exe()
.map_err(|e| Error::Input(format!("cannot locate the proofback executable: {e}")))?;
let mut child = Command::new(exe)
Expand All @@ -26,6 +45,7 @@ pub fn extract_isolated(pdf: &Path, limits: &LimitsConfig) -> Result<Extracted>
.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())
Expand Down Expand Up @@ -78,9 +98,19 @@ pub fn extract_isolated(pdf: &Path, limits: &LimitsConfig) -> Result<Extracted>

/// 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<u32> = 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::<u64>().unwrap_or(0);
lower_limits(num(timeout));
Expand All @@ -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}");
Expand Down
Loading
Loading