Skip to content

Commit 2d7efcc

Browse files
huppifluppclaude
andcommitted
M10: Searchable Image drops stale results, reports signed documents once and says it is destructive
Review of storytold#5126: - ocr_recognize and ocr_recognize_files advertise destructiveHint: downsampling throws image detail away, and the multi-file tool replaces a same-named file in its folder (the input itself, given its own folder), with downsampled as a full rewrite. The descriptions say so, and that images is absent when no page was read. - Every Recognize Text run now records the document's edit generation, not only Edit's automatic one: a result that arrives after the document changed (a page moved or deleted) is dropped and the user is told, instead of adding words to and downsampling the page that now has the old index. - A signed document's refusal is ScanImages::refused, one reason for the document, not an entry in skipped, so the summary no longer reports it as "1 left as they are"; the toast and the multi-file summary say the signed document(s) kept their images. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 454bb9f commit 2d7efcc

6 files changed

Lines changed: 151 additions & 10 deletions

File tree

‎crates/automation/src/a11y/ocr.rs‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -557,10 +557,15 @@ impl Automation {
557557
}
558558

559559
/// What `output: "downsampled"` did to the images: how many the recognised pages draw, how many
560-
/// were resampled, their encoded bytes before and after, and each image above the resolution left
561-
/// as it is with why.
560+
/// were resampled, their encoded bytes before and after, each image above the resolution left
561+
/// as it is with why, and, for a document refused as a whole (a signed one), why under `refused`.
562562
pub(crate) fn images_json(i: &pdfcraft_engine::ocr::ScanImages) -> Value {
563-
json!({ "images": i.images, "downsampled": i.resampled, "bytes_before": i.bytes_before, "bytes_after": i.bytes_after, "skipped": i.skipped })
563+
let mut v =
564+
json!({ "images": i.images, "downsampled": i.resampled, "bytes_before": i.bytes_before, "bytes_after": i.bytes_after, "skipped": i.skipped });
565+
if let Some(why) = &i.refused {
566+
v["refused"] = json!(why);
567+
}
568+
v
564569
}
565570

566571
/// The file name an input is written under: its own file name, or `document.pdf` when it has none.

‎crates/automation/src/tools.rs‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1523,7 +1523,8 @@ pub fn tools() -> Vec<ToolDef> {
15231523
)),
15241524
t("js_enabled", "JavaScript on or off", "Preferences ▸ JavaScript ▸ Enable Acrobat JavaScript: set it with `enabled`, or read it. With JavaScript off, field scripts other than Acrobat's AF calls don't run.")
15251525
.with(schema(json!({ "enabled": { "type": "boolean" } }), &[])),
1526-
t("ocr_recognize", "Recognize text (OCR)", "Scan & OCR ▸ Recognize text: render pages, read the words in them and add them as invisible text over the page image, so scanned pages become searchable and selectable. output \"exact\" (default, Searchable Image (Exact)) leaves the page images exactly as they are; \"downsampled\" (Searchable Image) also resamples the images on the pages that were read down to dpi where they are finer (more than 5% above), in place and in the same undo step: same object and placement (the new text still lines up), colour space, decode array and masks kept, JPEG stays JPEG, black-and-white stays 1-bit and lossless; images that can't be handled (CMYK, indexed, 16-bit, JPEG 2000, JBIG2, CCITT, colour-key masks) are left alone and listed under images.skipped with why. Pages that already have text are skipped unless skip_text_pages or force_ocr say otherwise; words overlapping existing text are omitted and counted as already_on_page. With output_mode \"editable\" nothing is applied: a NEW document of visible text at the recognised boxes is written to out (which must not be the source; empty pages stay blank). engine and strategy choose the readers (an engine that cannot run is an error named up front); the four preprocessing flags clean the raster first. region reads just that part of one page ([x0, y0, x1, y1] in points from the top-left of the displayed page). Returns each page's recognised text, word count or why it was skipped. Needs the engines (ocr_status). Searchable output is undoable as one step.")
1526+
t("ocr_recognize", "Recognize text (OCR)", "Scan & OCR ▸ Recognize text: render pages, read the words in them and add them as invisible text over the page image, so scanned pages become searchable and selectable. output \"exact\" (default, Searchable Image (Exact)) leaves the page images exactly as they are; \"downsampled\" (Searchable Image) also resamples the images on the pages that were read down to dpi where they are finer (more than 5% above), in place and in the same undo step: same object and placement (the new text still lines up), colour space, decode array and masks kept, JPEG stays JPEG, black-and-white stays 1-bit and lossless; images that can't be handled (CMYK, indexed, 16-bit, JPEG 2000, JBIG2, CCITT, colour-key masks) are left alone and listed under images.skipped with why; a signed document keeps all its images and says why under images.refused. The detail removed is gone once the document is saved, and that save is a full rewrite (the earlier revisions leave the file). images is absent when no page was read (every page skipped, e.g. because each already has text). Pages that already have text are skipped unless skip_text_pages or force_ocr say otherwise; words overlapping existing text are omitted and counted as already_on_page. With output_mode \"editable\" nothing is applied: a NEW document of visible text at the recognised boxes is written to out (which must not be the source; empty pages stay blank). engine and strategy choose the readers (an engine that cannot run is an error named up front); the four preprocessing flags clean the raster first. region reads just that part of one page ([x0, y0, x1, y1] in points from the top-left of the displayed page). Returns each page's recognised text, word count or why it was skipped. Needs the engines (ocr_status). Searchable output is undoable as one step.")
1527+
.destructive()
15271528
.cmd("ocr.recognize")
15281529
.with(schema(
15291530
json!({
@@ -1543,7 +1544,7 @@ pub fn tools() -> Vec<ToolDef> {
15431544
"deskew": { "type": "boolean", "description": "Straighten skewed text lines before reading (default false)." },
15441545
"denoise": { "type": "boolean", "description": "A 3×3 median filter against scan speckle (default false)." },
15451546
"binarize": { "type": "boolean", "description": "Sauvola binarization: ink to black, paper to white (default false)." },
1546-
"output": { "type": "string", "enum": ["exact", "downsampled"], "description": "exact (default): the page images are not changed. downsampled: images on the pages read are reduced to dpi where they are finer; the result carries an images report." },
1547+
"output": { "type": "string", "enum": ["exact", "downsampled"], "description": "exact (default): the page images are not changed. downsampled: images on the pages read are reduced to dpi where they are finer; the result carries an images report unless no page was read." },
15471548
}),
15481549
&["doc"],
15491550
)),
@@ -1576,7 +1577,8 @@ pub fn tools() -> Vec<ToolDef> {
15761577
.destructive()
15771578
.cmd("ocr.correct")
15781579
.with(schema(json!({ "path": { "type": "string" }, "add": { "type": "array", "maxItems": 65536, "items": { "type": "string" } }, "remove": { "type": "array", "maxItems": 65536, "items": { "type": "string" } } }), &["path"])),
1579-
t("ocr_recognize_files", "Recognize text in multiple files", "Scan & OCR ▸ Recognize text ▸ In multiple files: read every page of each PDF in paths and write the searchable result into folder under the same name. skip_text_files leaves whole files that already contain text alone (they are their own skipped bucket, nothing is written); skip_text_pages leaves single text pages alone; force_ocr reads regardless of both. Every output name is checked before the first page is read: two paths sharing a file name (from different folders) are refused, and a file of that name already in folder aborts the batch, with the names in the error. Each written file carries a low_confidence note when words at or under 60 confidence sit on it (1-based sorted pages). Returns, per file, the output path, word count, skipped pages or the error, plus recognized/words/skipped_files totals. Needs the engines (ocr_status).")
1580+
t("ocr_recognize_files", "Recognize text in multiple files", "Scan & OCR ▸ Recognize text ▸ In multiple files: read every page of each PDF in paths and write the searchable result into folder under the same name. skip_text_files leaves whole files that already contain text alone (they are their own skipped bucket, nothing is written); skip_text_pages leaves single text pages alone; force_ocr reads regardless of both. Every output name is checked before the first page is read: two paths sharing a file name (from different folders) are refused, and a file of that name already in folder aborts the batch, with the names in the error. With output downsampled a written file is a full rewrite, without the input's earlier revisions or the detail its images lost. Each written file carries a low_confidence note when words at or under 60 confidence sit on it (1-based sorted pages). Returns, per file, the output path, word count, skipped pages or the error, plus recognized/words/skipped_files totals. Needs the engines (ocr_status).")
1581+
.destructive()
15801582
.cmd("ocr.recognize_batch")
15811583
.with(schema(
15821584
json!({
@@ -1593,7 +1595,7 @@ pub fn tools() -> Vec<ToolDef> {
15931595
"deskew": { "type": "boolean" },
15941596
"denoise": { "type": "boolean" },
15951597
"binarize": { "type": "boolean" },
1596-
"output": { "type": "string", "enum": ["exact", "downsampled"], "description": "As in ocr_recognize (default exact); with downsampled each file reports images." },
1598+
"output": { "type": "string", "enum": ["exact", "downsampled"], "description": "As in ocr_recognize (default exact); with downsampled each file reports images, unless none of its pages was read." },
15971599
}),
15981600
&["paths", "folder"],
15991601
)),

‎crates/automation/tests/it/automation.rs‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -888,6 +888,17 @@ fn file_writing_tools_are_not_read_only() {
888888
}
889889
}
890890

891+
/// Recognize text with `output: "downsampled"` throws image detail away, and the multi-file tool
892+
/// replaces a file of the same name in its folder (the input itself, given the input's folder),
893+
/// so neither may tell MCP clients it only adds.
894+
#[test]
895+
fn ocr_tools_that_can_lose_image_detail_are_destructive() {
896+
for name in ["ocr_recognize", "ocr_recognize_files"] {
897+
let t = tools().into_iter().find(|t| t.name == name).unwrap();
898+
assert!(!t.read_only && t.destructive, "{name} can downsample images but advertises non-destructive");
899+
}
900+
}
901+
891902
#[test]
892903
fn open_inspect_render_and_find() {
893904
let dir = workdir("inspect");

‎crates/engine/src/ocr.rs‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1067,7 +1067,7 @@ impl Session {
10671067
edits.push(Edit::DownsampleImages { pages: read, ppi: f64::from(settings.dpi.clamp(72.0, 600.0)) });
10681068
}
10691069
let refused = signed.then(|| ScanImages {
1070-
skipped: vec!["the document is signed: its images are left as they are, since a smaller file needs a full rewrite, which would break the signatures".into()],
1070+
refused: Some("the document is signed: its images are left as they are, since a smaller file needs a full rewrite, which would break the signatures".into()),
10711071
..Default::default()
10721072
});
10731073
if edits.is_empty() {
@@ -2532,6 +2532,28 @@ mod tests {
25322532
assert_eq!(s.get(id).unwrap().can_undo(), None);
25332533
}
25342534

2535+
/// A signed document keeps its images, and the report gives the reason once for the
2536+
/// document, not as an image of its own left as it is: `skipped` lists images only.
2537+
#[test]
2538+
fn a_signed_document_is_refused_as_a_whole_not_as_one_skipped_image() {
2539+
// After the test certificate's start date (2026-10-02).
2540+
let mut s = Session::new().with_clock(|| 1_800_000_000);
2541+
let (id, found) = scan_600(&mut s);
2542+
let p12 = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../sign/tests/data/ec-p256.p12")).unwrap();
2543+
let digital_id = pdfcraft_sign::pkcs12::open(&p12, "test").unwrap();
2544+
let opts = crate::SignOptions { page: 0, rect: Some([20.0, 20.0, 180.0, 60.0]), ..Default::default() };
2545+
let signed = s.sign(id, &digital_id, opts).unwrap();
2546+
let id = s.open("signed.pdf", None, signed, None).unwrap();
2547+
assert!(s.get(id).unwrap().is_signed());
2548+
let width = s.get(id).unwrap().page_images(0)[0].width;
2549+
let settings = OcrSettings { output: OcrOutput::Downsampled, dpi: 300.0, ..Default::default() };
2550+
let images = s.apply_ocr_with(id, &found, &settings).unwrap().images.expect("a report");
2551+
assert!(images.skipped.is_empty(), "no image was looked at: {:?}", images.skipped);
2552+
assert!(images.refused.as_deref().is_some_and(|why| why.contains("signed")), "{images:?}");
2553+
assert_eq!((images.images, images.resampled), (0, 0));
2554+
assert_eq!(s.get(id).unwrap().page_images(0)[0].width, width, "the images are left as they are");
2555+
}
2556+
25352557
#[test]
25362558
fn output_names_round_trip() {
25372559
for o in OcrOutput::ALL {

‎crates/optimize/src/scans.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,9 @@ pub struct ScanImages {
3838
pub bytes_after: usize,
3939
/// Images above the target that were left as they are, each with why.
4040
pub skipped: Vec<String>,
41+
/// Why no image of the document was looked at, when the whole document was refused (a
42+
/// signed one): one reason for the document, not one per image, so it is not in `skipped`.
43+
pub refused: Option<String>,
4144
}
4245

4346
/// Resample the images that `pages` draw, where their effective resolution is above `target_ppi`,

0 commit comments

Comments
 (0)