pdfsift 0.1.0

PDF to structured Markdown for LLM agents. Heuristics only: no AI model, no network.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
//! De-hyphenation decision for a line-final hyphen candidate (achados 003, 007, 009).
//!
//! Not wired into any output yet. It must run after reading order and header/footer
//! removal (achado 003, finding 5), over the sequence of lines of a block; until words
//! carry their chars, the candidates are built from the char stream ([`candidates`]).
//!
//! Decision order (most reliable first, achado 007 "Regra de extração proposta" and
//! achado 003 "Regra de desifenização proposta"):
//!
//! 1. Producer evidence on this hyphen:
//!    a. structure `Span` with ActualText U+00AD on the hyphen's MCID: join (LibreOffice tagged, 99/99);
//!    b. empty object with ActualText U+00AD right before the hyphen: join (Chrome, 1/1);
//!    c. the next line starts with an empty object with ActualText `-` (Typst repeats a
//!    compound hyphen): keep (Typst, 3/3);
//!    d. ActualText `-` on the hyphen itself: keep (Typst, 3/3).
//! 2. Evidence from the rest of the document about how this producer marks hyphens
//!    (inferred from one producer each; recorded as such in achado 009):
//!    a. the document puts ActualText `-` on real hyphens, and this one has none: join (Typst, 44/44);
//!    b. the document marks typesetter hyphens with U+00AD (1.a or 1.b seen), and this
//!    one has no mark: keep (LibreOffice tagged 7/7, Chrome 4/4);
//!    c. the hyphen is an object of its own after a multi-char run: join; or the document
//!    has such hyphens and this one sits inside the run: keep (LibreOffice, 106/106).
//! 3. Lexical (achado 003, rules 2 to 5): digit after, or capitals on both sides: keep;
//!    the joined word elsewhere in the document: join; only the hyphenated form: keep;
//!    Portuguese cues when the caller says the text is Portuguese; otherwise join.

// Not wired into the pipeline yet (only tests use it): see the module docs.
#![cfg_attr(not(test), allow(dead_code))]

use std::collections::BTreeSet;

use super::{Char, CharKind};

/// Join the two fragments (`hife-` + `nização` → `hifenização`) or keep the hyphen
/// (`segunda-` + `feira` → `segunda-feira`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Decision {
    Join,
    Keep,
}

/// Which rule decided (for debugging and the validation table).
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Reason {
    StructSoftHyphen,
    HiddenSoftHyphen,
    RepeatedHyphen,
    ActualTextHyphen,
    DocMarksRealHyphens,
    DocMarksSoftHyphens,
    OwnObject,
    InsideRun,
    DigitOrCapitals,
    SeenJoined,
    SeenHyphenated,
    PtSameVowel,
    PtH,
    PtClitic,
    Default,
}

/// Signals of one hyphen candidate, from [`crate::layout::CharSource`].
#[derive(Clone, Debug, Default, PartialEq)]
pub struct HyphenSignals {
    /// ActualText of the innermost mark of the hyphen's object.
    pub actual_text: Option<String>,
    /// ActualText of the structure element of the hyphen's MCID.
    pub struct_actual_text: Option<String>,
    /// ActualText of an empty object right before the hyphen's object.
    pub hidden_before: Option<String>,
    /// ActualText of an empty object right before the next line's first object.
    pub next_hidden_before: Option<String>,
    /// `Some(true)`: the hyphen is an object of its own and the letters before it come
    /// from a multi-char object. `Some(false)`: same object as the letters before it.
    /// None: unknown, or one object per glyph (Chrome), where granularity says nothing.
    pub own_object: Option<bool>,
}

/// A line-final hyphen: the word before it (`a`, without the hyphen) and the first word
/// of the next line (`b`, trailing punctuation removed).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Candidate {
    pub before: String,
    pub after: String,
    pub signals: HyphenSignals,
}

/// What the rest of the document says (built once per document).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct DocEvidence {
    /// Some char or empty object has ActualText `-` (Typst marks its real hyphens so).
    pub marks_real_hyphens: bool,
    /// Some candidate has rule 1.a or 1.b evidence.
    pub marks_soft_hyphens: bool,
    /// Some candidate is an object of its own after a multi-char run.
    pub separates_hyphen_objects: bool,
    /// Lowercased words of the document outside line breaks, trimmed of punctuation,
    /// U+00AD removed. Compounds keep their hyphen (`segunda-feira`).
    pub words: BTreeSet<String>,
    /// The text is Portuguese (enables rule 3's orthographic cues). The caller decides;
    /// nothing here detects the language.
    pub portuguese: bool,
}

const SOFT_HYPHEN: &str = "\u{AD}";

/// Decides one candidate. Pure; see the module docs for the order.
pub fn decide(c: &Candidate, doc: &DocEvidence) -> (Decision, Reason) {
    use Decision::{Join, Keep};
    let s = &c.signals;
    // 1. This hyphen's own marks.
    if s.struct_actual_text.as_deref() == Some(SOFT_HYPHEN) {
        return (Join, Reason::StructSoftHyphen);
    }
    if s.hidden_before.as_deref() == Some(SOFT_HYPHEN) {
        return (Join, Reason::HiddenSoftHyphen);
    }
    if s.next_hidden_before.as_deref() == Some("-") {
        return (Keep, Reason::RepeatedHyphen);
    }
    if s.actual_text.as_deref() == Some("-") {
        return (Keep, Reason::ActualTextHyphen);
    }
    // 2. How this document marks hyphens.
    if doc.marks_real_hyphens {
        return (Join, Reason::DocMarksRealHyphens);
    }
    if doc.marks_soft_hyphens {
        return (Keep, Reason::DocMarksSoftHyphens);
    }
    match s.own_object {
        Some(true) => return (Join, Reason::OwnObject),
        Some(false) if doc.separates_hyphen_objects => return (Keep, Reason::InsideRun),
        _ => {}
    }
    // 3. Lexical.
    let a = c.before.as_str();
    let b = c.after.as_str();
    let (Some(a_last), Some(b_first)) = (a.chars().last(), b.chars().next()) else {
        return (Join, Reason::Default);
    };
    if b_first.is_ascii_digit() || (a_last.is_uppercase() && b_first.is_uppercase()) {
        return (Keep, Reason::DigitOrCapitals);
    }
    let (al, bl) = (a.to_lowercase(), b.to_lowercase());
    if doc.words.contains(&format!("{al}{bl}")) {
        return (Join, Reason::SeenJoined);
    }
    if doc.words.contains(&format!("{al}-{bl}")) {
        return (Keep, Reason::SeenHyphenated);
    }
    if doc.portuguese {
        let a_last = base_letter(al.chars().last().unwrap_or(' '));
        let b_first = base_letter(bl.chars().next().unwrap_or(' '));
        // `micro-ondas`, `contra-ataque`, `anti-inflamatório`: Portuguese writes a hyphen
        // between a prefix and a word starting with the same vowel.
        if a_last == b_first && "aeiou".contains(a_last) {
            return (Keep, Reason::PtSameVowel);
        }
        // `h` only occurs inside a word in ch/lh/nh, which are never split.
        if b_first == 'h' {
            return (Keep, Reason::PtH);
        }
        // `fazê-lo`, `tratá-los`.
        let accented = al.chars().last().is_some_and(|ch| "áéíóúâêôã".contains(ch));
        if accented && ["lo", "la", "los", "las"].contains(&bl.as_str()) {
            return (Keep, Reason::PtClitic);
        }
    }
    (Join, Reason::Default)
}

/// Lowercase letter without its accent, for the vowel test.
fn base_letter(c: char) -> char {
    match c {
        'á' | 'à' | 'â' | 'ã' => 'a',
        'é' | 'ê' => 'e',
        'í' => 'i',
        'ó' | 'ô' | 'õ' => 'o',
        'ú' | 'ü' => 'u',
        _ => c,
    }
}

fn is_break(c: &Char) -> bool {
    c.ch.is_whitespace() || c.ch.is_control() || c.generated
}

/// Lowercase, U+00AD removed, leading and trailing non-alphanumerics trimmed.
fn clean_word(w: &str) -> String {
    w.chars()
        .filter(|&c| c != '\u{AD}')
        .collect::<String>()
        .trim_matches(|c: char| !c.is_alphanumeric())
        .to_lowercase()
}

/// Line-final hyphen candidates of a char sequence in reading order. A candidate whose
/// next word is not in `chars` (a break across pages, or the end of the text) is skipped.
pub fn candidates(chars: &[Char]) -> Vec<Candidate> {
    let mut out = Vec::new();
    for (h, hy) in chars.iter().enumerate() {
        if hy.kind != CharKind::LineEndHyphen {
            continue;
        }
        let start = chars[..h].iter().rposition(is_break).map_or(0, |p| p + 1);
        let before: String = chars[start..h].iter().map(|c| c.ch).collect();
        let Some(b0) = chars[h + 1..]
            .iter()
            .position(|c| !is_break(c))
            .map(|p| p + h + 1)
        else {
            continue;
        };
        let end = chars[b0..]
            .iter()
            .position(is_break)
            .map_or(chars.len(), |p| p + b0);
        let after_raw: String = chars[b0..end].iter().map(|c| c.ch).collect();
        let after = after_raw
            .trim_end_matches(|c: char| !c.is_alphanumeric())
            .to_string();
        let own_object = (|| {
            let prev = chars[start..h].last()?;
            let (po, ho) = (prev.source.object?, hy.source.object?);
            if po == ho {
                return Some(false);
            }
            let run = chars.iter().filter(|c| c.source.object == Some(po)).count();
            (run >= 2).then_some(true)
        })();
        out.push(Candidate {
            before,
            after,
            signals: HyphenSignals {
                actual_text: hy.source.actual_text.clone(),
                struct_actual_text: hy.source.struct_actual_text.clone(),
                hidden_before: hy.source.hidden_text_before.clone(),
                next_hidden_before: chars[b0].source.hidden_text_before.clone(),
                own_object,
            },
        });
    }
    out
}

impl DocEvidence {
    /// Evidence from every page's chars (each in reading order) and their candidates.
    pub fn from_pages(pages: &[Vec<Char>], portuguese: bool) -> Self {
        let mut ev = DocEvidence {
            portuguese,
            ..Default::default()
        };
        for chars in pages {
            ev.marks_real_hyphens |= chars.iter().any(|c| {
                c.source.actual_text.as_deref() == Some("-")
                    || c.source.hidden_text_before.as_deref() == Some("-")
            });
            for cand in candidates(chars) {
                let s = &cand.signals;
                ev.marks_soft_hyphens |= s.struct_actual_text.as_deref() == Some(SOFT_HYPHEN)
                    || s.hidden_before.as_deref() == Some(SOFT_HYPHEN);
                ev.separates_hyphen_objects |= s.own_object == Some(true);
            }
            // Words, skipping the two fragments around each line-final hyphen.
            let mut word = String::new();
            let mut skip_next = false;
            let mut flush = |word: &mut String, hyphen: bool, skip_next: &mut bool| {
                if !word.is_empty() {
                    if !hyphen && !*skip_next {
                        let w = clean_word(word);
                        if !w.is_empty() {
                            ev.words.insert(w);
                        }
                    }
                    *skip_next = hyphen;
                }
                word.clear();
            };
            let mut hyphen = false;
            for c in chars {
                if is_break(c) {
                    flush(&mut word, hyphen, &mut skip_next);
                    hyphen = false;
                } else if c.kind == CharKind::LineEndHyphen {
                    hyphen = true;
                } else {
                    word.push(c.ch);
                }
            }
            flush(&mut word, hyphen, &mut skip_next);
        }
        ev
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::layout::{CharSource, Rect, Style};

    fn cand(before: &str, after: &str) -> Candidate {
        Candidate {
            before: before.into(),
            after: after.into(),
            signals: HyphenSignals::default(),
        }
    }

    fn doc() -> DocEvidence {
        DocEvidence::default()
    }

    #[test]
    fn structural_evidence_comes_first() {
        let mut c = cand("segunda", "feira");
        c.signals.struct_actual_text = Some("\u{AD}".into());
        assert_eq!(decide(&c, &doc()).0, Decision::Join);
        let mut c = cand("hipertextografia", "mente");
        c.signals.hidden_before = Some("\u{AD}".into());
        assert_eq!(
            decide(&c, &doc()),
            (Decision::Join, Reason::HiddenSoftHyphen)
        );
        let mut c = cand("des-en-vol", "vi-men-to");
        c.signals.next_hidden_before = Some("-".into());
        assert_eq!(decide(&c, &doc()), (Decision::Keep, Reason::RepeatedHyphen));
        let mut c = cand("pas", "sa-gem");
        c.signals.actual_text = Some("-".into());
        // Even with the document rule 2.a active.
        let d = DocEvidence {
            marks_real_hyphens: true,
            ..doc()
        };
        assert_eq!(decide(&c, &d), (Decision::Keep, Reason::ActualTextHyphen));
    }

    #[test]
    fn document_conventions() {
        let typst = DocEvidence {
            marks_real_hyphens: true,
            ..doc()
        };
        assert_eq!(decide(&cand("hife", "nização"), &typst).0, Decision::Join);
        let tagged = DocEvidence {
            marks_soft_hyphens: true,
            ..doc()
        };
        assert_eq!(
            decide(&cand("beija", "flor"), &tagged),
            (Decision::Keep, Reason::DocMarksSoftHyphens)
        );
        let lo = DocEvidence {
            separates_hyphen_objects: true,
            ..doc()
        };
        let mut c = cand("beija", "flor");
        c.signals.own_object = Some(false);
        assert_eq!(decide(&c, &lo), (Decision::Keep, Reason::InsideRun));
        c.signals.own_object = Some(true);
        assert_eq!(decide(&c, &lo), (Decision::Join, Reason::OwnObject));
        // Same object as the letters, but the document never separates: no decision.
        c.signals.own_object = Some(false);
        assert_eq!(decide(&c, &doc()).1, Reason::Default);
    }

    #[test]
    fn lexical_rules() {
        let d = DocEvidence {
            words: ["hifenização", "segunda-feira"]
                .into_iter()
                .map(String::from)
                .collect(),
            portuguese: true,
            ..doc()
        };
        let r = |a: &str, b: &str| decide(&cand(a, b), &d);
        assert_eq!(r("NBR", "6023"), (Decision::Keep, Reason::DigitOrCapitals));
        // `La-` / `TeX`: only capitals on both sides keep the hyphen.
        assert_eq!(r("La", "TeX").0, Decision::Join);
        assert_eq!(r("Hife", "nização"), (Decision::Join, Reason::SeenJoined));
        assert_eq!(
            r("segunda", "feira"),
            (Decision::Keep, Reason::SeenHyphenated)
        );
        assert_eq!(r("micro", "ondas"), (Decision::Keep, Reason::PtSameVowel));
        assert_eq!(r("arco", "íris").1, Reason::Default);
        assert_eq!(r("disse", "lhe").1, Reason::Default);
        assert_eq!(r("super", "homem"), (Decision::Keep, Reason::PtH));
        assert_eq!(r("fazê", "lo"), (Decision::Keep, Reason::PtClitic));
        assert_eq!(r("compo", "sição"), (Decision::Join, Reason::Default));
        let not_pt = DocEvidence {
            portuguese: false,
            ..d
        };
        assert_eq!(decide(&cand("micro", "ondas"), &not_pt).0, Decision::Join);
        assert_eq!(decide(&cand("", ""), &not_pt).0, Decision::Join);
    }

    fn ch(c: char, x: f32, base: f32, obj: Option<u32>) -> Char {
        Char {
            ch: c,
            bbox: Rect::new(x, base - 9.0, x + 5.0, base + 2.0),
            baseline: base,
            size: 10.0,
            font: "Serif".into(),
            style: Style::default(),
            generated: c.is_whitespace(),
            kind: if c == '-' {
                CharKind::LineEndHyphen
            } else {
                CharKind::Text
            },
            source: CharSource {
                object: obj,
                ..Default::default()
            },
        }
    }

    /// `"um beija" "-"` / `"\r\n"` / `"flor, e"`: objects 0, 1 and 2.
    fn line_pair(hyphen_obj: u32) -> Vec<Char> {
        let mut v = Vec::new();
        for (i, c) in "um beija".chars().enumerate() {
            v.push(ch(c, i as f32 * 5.0, 100.0, (c != ' ').then_some(0)));
        }
        v.push(ch('-', 40.0, 100.0, Some(hyphen_obj)));
        v.push(ch('\r', 45.0, 100.0, None));
        v.push(ch('\n', 45.0, 100.0, None));
        for (i, c) in "flor, e".chars().enumerate() {
            v.push(ch(c, i as f32 * 5.0, 112.0, (c != ' ').then_some(2)));
        }
        v
    }

    #[test]
    fn candidates_from_chars() {
        let c = candidates(&line_pair(1));
        assert_eq!(c.len(), 1);
        assert_eq!(
            (c[0].before.as_str(), c[0].after.as_str()),
            ("beija", "flor")
        );
        assert_eq!(c[0].signals.own_object, Some(true));
        assert_eq!(candidates(&line_pair(0))[0].signals.own_object, Some(false));
        // Nothing after the hyphen: skipped.
        let mut v = line_pair(1);
        v.truncate(9);
        assert!(candidates(&v).is_empty());
    }

    #[test]
    fn evidence_skips_break_fragments() {
        let ev = DocEvidence::from_pages(&[line_pair(1)], false);
        assert!(ev.separates_hyphen_objects && !ev.marks_real_hyphens);
        let words: Vec<&str> = ev.words.iter().map(String::as_str).collect();
        assert_eq!(words, ["e", "um"]);
    }
}

/// Validation on the generated two-column corpus against `source.md` (achado 009). Needs
/// PDFium, which this crate only loads at run time: skipped with a message without it.
/// There is no library target, so this lives here instead of `tests/`.
#[cfg(test)]
mod corpus {
    use std::path::Path;

    use super::*;
    use crate::layout::extract;
    use crate::{engine, tags};
    use pdfium_render::prelude::PdfiumLibraryBindingsAccessor;

    /// Expected decision from the source text: `a-b` in it means keep, `ab` means join.
    fn expected(src: &str, c: &Candidate) -> Option<Decision> {
        let (a, b) = (c.before.to_lowercase(), c.after.to_lowercase());
        if b.is_empty() {
            return None;
        }
        if src.contains(&format!("{a}-{b}")) {
            Some(Decision::Keep)
        } else if src.contains(&format!("{a}{b}")) {
            Some(Decision::Join)
        } else {
            None
        }
    }

    #[derive(Default)]
    struct Row {
        decided: usize,
        /// No `a-b` nor `ab` in the source: the two breaks across pages, where the next
        /// "word" is the page number (no header/footer removal yet).
        unknown: Vec<String>,
        /// Errors with every rule, Portuguese cues on.
        errors: Vec<String>,
        /// Errors without the Portuguese cues.
        errors_no_pt: usize,
        /// Errors with the lexical rules only (no marks, no document conventions):
        /// the achado 003 baseline.
        errors_lexical: usize,
        reasons: std::collections::BTreeMap<Reason, usize>,
    }

    fn evaluate(pdfium: &pdfium_render::prelude::Pdfium, producer: &str, src: &str) -> Option<Row> {
        let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/corpus/generated/two-columns");
        let file = dir.join(format!("out/{producer}.pdf"));
        let doc = pdfium.load_pdf_from_file(&file, None).ok()?;
        let raw = tags::RawDoc::open(doc.bindings(), &file.to_string_lossy());
        let pages: Vec<Vec<Char>> = (0..doc.pages().len())
            .filter_map(|i| {
                let page = doc.pages().get(i).ok()?;
                let rp = raw.as_ref().and_then(|d| d.page(i));
                Some(extract::page_chars(&page, rp.as_ref()))
            })
            .collect();
        let ev = DocEvidence::from_pages(&pages, true);
        let ev_no_pt = DocEvidence {
            portuguese: false,
            ..ev.clone()
        };
        let ev_lexical = DocEvidence {
            marks_real_hyphens: false,
            marks_soft_hyphens: false,
            separates_hyphen_objects: false,
            ..ev.clone()
        };
        let mut row = Row::default();
        for c in pages.iter().flat_map(|p| candidates(p)) {
            let Some(want) = expected(src, &c) else {
                row.unknown.push(format!("{}-/{}", c.before, c.after));
                continue;
            };
            row.decided += 1;
            let (got, why) = decide(&c, &ev);
            *row.reasons.entry(why).or_default() += 1;
            if got != want {
                row.errors
                    .push(format!("{got:?} {}-/{} ({why:?})", c.before, c.after));
            }
            row.errors_no_pt += usize::from(decide(&c, &ev_no_pt).0 != want);
            let bare = Candidate {
                signals: HyphenSignals::default(),
                ..c.clone()
            };
            row.errors_lexical += usize::from(decide(&bare, &ev_lexical).0 != want);
        }
        Some(row)
    }

    #[test]
    fn two_columns_against_source() {
        let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/corpus/generated/two-columns");
        let src = std::fs::read_to_string(dir.join("source.md"))
            .expect("source.md")
            .replace('\u{AD}', "")
            .to_lowercase();
        // (producer, max errors with Portuguese cues, without): measured in achado 009.
        const LIMITS: &[(&str, usize, usize)] = &[
            ("pandoc-lualatex", 5, 6),
            ("pandoc-typst", 0, 0),
            ("libreoffice", 0, 0),
            ("libreoffice-tagged", 0, 0),
            ("chrome", 0, 0),
        ];
        // PDFium can be bound only once per process.
        let Ok(pdfium) = engine::load() else {
            eprintln!("SKIPPED: PDFium not found (set PDFSIFT_PDFIUM to run this test)");
            return;
        };
        for (producer, max_pt, max) in LIMITS {
            let row = evaluate(&pdfium, producer, &src).expect("corpus PDF opens");
            eprintln!(
                "{producer}: {} decided, {} errors (pt), {} (no pt), {} (lexical only); unknown {:?}; reasons {:?}",
                row.decided,
                row.errors.len(),
                row.errors_no_pt,
                row.errors_lexical,
                row.unknown,
                row.reasons
            );
            for e in &row.errors {
                eprintln!("    {e}");
            }
            assert!(
                row.errors.len() <= *max_pt && row.errors_no_pt <= *max,
                "{producer}: {:?}",
                row.errors
            );
        }
    }
}