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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
//! Page furniture: running headers, footers and page numbers (docs/arquitetura.md,
//! part 2, stage 5; docs/achados/008-cabecalhos-rodapes.md).
//!
//! Runs on the **words of every page of the document**, before column detection.
//! Furniture is a page-level thing (the first and last text rows of the page), and
//! when it stays in the page it shapes the columns: a LaTeX running head that does
//! not cross the gutter lands at the top of column 1 and its page number at the top
//! of column 2 (finding 005, finding 7). Removing it first means the column split, the
//! lines and the blocks never see it, so nothing has to be recomputed.
//!
//! Only the **edge rows** of a page are candidates: the topmost and the bottommost
//! page-wide row (words clustered by baseline, [`columns::rows`]). Each edge row is
//! cut into *segments* at wide gaps (date | title in Chrome's header, running title |
//! page number in LaTeX). A segment is furniture when:
//!
//! - **Repeated** ([`Reason::Repeated`]): an edge segment with the same text after
//!   masking digits (`1/3` ≈ `2/3`), the same size, the same baseline and the same
//!   left, right or centre x (or the mirrored position, for two-sided layouts) exists
//!   on at least half of the pages (and on at least 2).
//! - **Page number** ([`Reason::PageNumber`]): the segment is a lone number (arabic,
//!   roman, `n/N`) whose value minus the page index equals the same offset as a lone
//!   number on an edge row of another page. This catches LaTeX's first page, whose
//!   number is in the footer while the other pages have it in the header.
//!   In a **single-page document** there is nothing to compare with: only a lone `1`
//!   that is alone in its edge row and far from the rest of the text is removed.
//! - **Shared row** ([`Reason::SharedRow`]): the rest of an edge row that already has
//!   a furniture segment. LaTeX's running title changes from page to page
//!   (`PALAVRAS COMPOSTAS`, `CONCLUSÃO`), so text repetition cannot find it; the page
//!   number next to it does.
//! - **Artifact** ([`Reason::Artifact`]): the extraction marked the word as
//!   pagination (see [`Hint`], the extension point for marked content).
//!
//! Every rule except the artifact hint also requires the edge row to be vertically
//! isolated from the rest of the page ([`ISOLATION`]). Being conservative here
//! keeps body text: a word is only removed with positive evidence, never because it
//! happens to be at the top of the page (titles on page 1 stay).
//!
//! Pure functions over our own types, unit-tested with synthetic words.

use super::columns::{self, Row};
use super::group::SIZE_TOL;
use super::{Block, Word};

/// Two words of an edge row separated by more than this (em of the larger size) are
/// different segments. Chrome's header: date → title ≈ 29 em, LaTeX's running title →
/// page number ≈ 21 em; word spaces are 0.17–0.6 em (finding 002) and justified gaps
/// at most 3.7 em (Chrome, finding 005), but body rows never match anyway. A low
/// value keeps `Page 3 of 10` or `29/11/2026, 08:54` (one space) in one segment.
pub const SEGMENT_GAP: f32 = 2.0;

/// Baselines of repeated furniture differ by less than this (em): every producer of
/// the corpus puts it at exactly the same baseline (Chrome 22.5 / 825.8, LaTeX 17.6,
/// Typst 786.1, LibreOffice 549.8 on every page; differences < 0.1 pt).
pub const POS_TOL: f32 = 0.5;

/// Left, right or centre x of repeated furniture differ by less than this (em). The
/// measured differences are below 0.1 pt; the tolerance only has to absorb a page
/// number gaining a digit (`9` → `10` moves a centred number by ≈ 0.25 em).
pub const X_TOL: f32 = 0.5;

/// Minimum baseline step from an edge row to the nearest other row, in em of the edge
/// row's size. Measured on the furniture rows of the corpus: Chrome 1.96 (8 pt header
/// above a 12 pt list item) to 47; LaTeX 2.89–5.92; LibreOffice 2.32–3.49; Typst
/// 3.01–58. Lines of a paragraph or table are at most 1.45 em apart (`MAX_LEADING`);
/// the guard keeps a repeated table header row (≈ 1.2–1.6 em above its first data row)
/// from looking like a running head.
pub const ISOLATION: f32 = 1.8;

/// Stricter isolation for the single-page rule, in em of the LARGER of the two rows'
/// sizes: lone page numbers measure 2.32 (LibreOffice, number above a 10 pt
/// footnote) to 10.2; the widest steps between body blocks at a page edge are 2.01
/// (LibreOffice caption → paragraph) and 2.02 (LaTeX title → author).
pub const SINGLE_PAGE_ISOLATION: f32 = 2.2;

/// Why a word was taken out of the reading order.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Reason {
    /// Marked as pagination by the producer (see [`Hint`]).
    Artifact,
    /// Same masked text at the same place on at least half of the pages.
    Repeated,
    /// A lone number consistent with the page sequence.
    PageNumber,
    /// Shares an isolated edge row with other furniture.
    SharedRow,
}

impl Reason {
    /// Label for debug output.
    pub fn label(self) -> &'static str {
        match self {
            Reason::Artifact => "artifact",
            Reason::Repeated => "repeated",
            Reason::PageNumber => "page-number",
            Reason::SharedRow => "shared-row",
        }
    }
}

/// A block of page furniture, kept out of the reading order (shown by
/// `pdfsift blocks` for inspection).
#[derive(Clone, Debug, PartialEq)]
pub struct Furniture {
    pub block: Block,
    pub reason: Reason,
}

/// Producer evidence about a word from marked content, filled by extraction.
///
/// **Extension point (finding 007):** Chrome marks its header and footer as
/// `/Artifact <</Type /Pagination /Subtype /Header|/Footer>>`, Typst its footer as
/// `/Artifact <</Type /Pagination …>>`, and tagged LibreOffice uses a bare
/// `/Artifact BMC`. PDFium does not expose name-valued properties yet, and per-char
/// marks are not carried into [`super::Char`]. When they are, extraction should
/// set [`Hint::Pagination`] on words whose content is a `/Pagination` artifact; such
/// words are furniture without any geometric test. A bare `/Artifact` (no
/// properties) can also be decoration, so it should stay [`Hint::None`] until it is
/// measured.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Hint {
    #[default]
    None,
    /// The word is inside a `/Pagination` artifact (running header, footer, number).
    Pagination,
}

/// The input for one page.
#[derive(Clone, Copy, Debug)]
pub struct PageWords<'a> {
    /// 1-based page number (its position in the document).
    pub number: usize,
    pub width: f32,
    pub words: &'a [Word],
    /// One hint per word, or empty when the extraction has none.
    pub hints: &'a [Hint],
}

/// An edge-row segment, a candidate for furniture.
#[derive(Clone, Debug)]
struct Segment {
    page: usize,
    /// Index of the edge row on its page (0 = top edge, 1 = bottom edge).
    edge: usize,
    words: Vec<usize>,
    left: f32,
    right: f32,
    baseline: f32,
    size: f32,
    masked: String,
    number: Option<(Numeral, i64)>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Numeral {
    Arabic,
    Roman,
}

/// An edge row of a page with its segments.
struct Edge {
    isolated: bool,
    /// Isolation in em of the larger size of the two rows (single-page rule).
    step_max_em: f32,
    segments: Vec<usize>,
}

/// Returns, for every page, one entry per word: `Some(reason)` when the word is page
/// furniture. Deterministic; never panics on odd geometry (non-finite words are
/// never furniture).
pub fn detect(pages: &[PageWords]) -> Vec<Vec<Option<Reason>>> {
    let mut out: Vec<Vec<Option<Reason>>> =
        pages.iter().map(|p| vec![None; p.words.len()]).collect();

    let mut segs: Vec<Segment> = Vec::new();
    let mut edges: Vec<Vec<Edge>> = Vec::new();
    for (pi, p) in pages.iter().enumerate() {
        let rows = columns::rows(p.words);
        let mut page_edges = Vec::new();
        let ends: &[(usize, Option<usize>)] = match rows.len() {
            0 => &[],
            1 => &[(0, None)],
            n => &[(0, Some(1)), (n - 1, Some(n - 2))],
        };
        for (e, &(ri, ni)) in ends.iter().enumerate() {
            let row = &rows[ri];
            let size = row_size(p.words, row);
            let (isolated, step_max_em) = match ni.map(|n| &rows[n]) {
                None => (true, f32::INFINITY),
                Some(nb) => {
                    let step = (row.baseline - nb.baseline).abs();
                    let max = size.max(row_size(p.words, nb));
                    (step >= ISOLATION * size, step / max)
                }
            };
            let mut ids = Vec::new();
            for words in segments(p.words, row) {
                ids.push(segs.len());
                segs.push(make_segment(pi, e, p.words, words));
            }
            page_edges.push(Edge {
                isolated,
                step_max_em,
                segments: ids,
            });
        }
        edges.push(page_edges);
    }

    let n = pages.len();
    let min_support = n.div_ceil(2).max(2);
    let mut reason: Vec<Option<Reason>> = vec![None; segs.len()];
    for (si, s) in segs.iter().enumerate() {
        let edge = &edges[s.page][s.edge];
        if !edge.isolated {
            continue;
        }
        // Repeated: distinct pages with a matching segment (this one included).
        let mut support: Vec<usize> = segs
            .iter()
            .filter(|t| same_furniture(s, t, pages))
            .map(|t| t.page)
            .collect();
        support.sort_unstable();
        support.dedup();
        if support.len() >= min_support {
            reason[si] = Some(Reason::Repeated);
            continue;
        }
        let Some((kind, value)) = s.number else {
            continue;
        };
        let offset = value - page_number(pages, s.page);
        let confirmed = segs.iter().any(|t| {
            t.page != s.page
                && edges[t.page][t.edge].isolated
                && t.number
                    .is_some_and(|(k, v)| k == kind && v - page_number(pages, t.page) == offset)
        });
        // A single-page document has nothing to compare with: only a lone arabic `1`
        // alone in its row, far from the text.
        let single = n == 1
            && kind == Numeral::Arabic
            && value == 1
            && edge.segments.len() == 1
            && edge.step_max_em >= SINGLE_PAGE_ISOLATION;
        if confirmed || single {
            reason[si] = Some(Reason::PageNumber);
        }
    }

    // The rest of an isolated edge row that holds furniture is furniture too.
    for page_edges in &edges {
        for e in page_edges {
            if e.isolated && e.segments.iter().any(|&s| reason[s].is_some()) {
                for &s in &e.segments {
                    reason[s].get_or_insert(Reason::SharedRow);
                }
            }
        }
    }

    for (s, r) in segs.iter().zip(&reason) {
        if let Some(r) = r {
            for &w in &s.words {
                out[s.page][w] = Some(*r);
            }
        }
    }
    for (pi, p) in pages.iter().enumerate() {
        for (wi, h) in p.hints.iter().enumerate().take(p.words.len()) {
            if *h == Hint::Pagination {
                out[pi][wi] = Some(Reason::Artifact);
            }
        }
    }
    out
}

fn page_number(pages: &[PageWords], i: usize) -> i64 {
    pages
        .get(i)
        .map_or(0, |p| i64::try_from(p.number).unwrap_or(i64::MAX))
}

fn row_size(words: &[Word], row: &Row) -> f32 {
    row.words
        .iter()
        .map(|&i| words[i].size)
        .fold(0.0f32, f32::max)
}

/// Word indices of a row cut at gaps wider than [`SEGMENT_GAP`].
fn segments(words: &[Word], row: &Row) -> Vec<Vec<usize>> {
    let mut out: Vec<Vec<usize>> = Vec::new();
    let mut right = f32::NEG_INFINITY;
    let mut size = 0.0f32;
    for &i in &row.words {
        let w = &words[i];
        let gap = w.bbox.left - right;
        match out.last_mut() {
            Some(seg) if gap <= SEGMENT_GAP * size.max(w.size) => seg.push(i),
            _ => out.push(vec![i]),
        }
        right = right.max(w.bbox.right);
        size = w.size;
    }
    out
}

fn make_segment(page: usize, edge: usize, words: &[Word], ids: Vec<usize>) -> Segment {
    let mut text = String::new();
    let (mut left, mut right, mut size) = (f32::INFINITY, f32::NEG_INFINITY, 0.0f32);
    for (k, &i) in ids.iter().enumerate() {
        let w = &words[i];
        if k > 0 && !w.glued {
            text.push(' ');
        }
        text.push_str(&w.text);
        left = left.min(w.bbox.left);
        right = right.max(w.bbox.right);
        size = size.max(w.size);
    }
    let baseline = ids.first().map_or(0.0, |&i| words[i].baseline);
    Segment {
        page,
        edge,
        left,
        right,
        baseline,
        size,
        masked: mask(&text),
        number: numeral(&text),
        words: ids,
    }
}

/// Text with every run of digits replaced by `#` (page numbers, dates and times vary
/// from page to page), and a lone roman numeral replaced by `#` too.
fn mask(text: &str) -> String {
    if roman(text.trim()).is_some() {
        return "#".into();
    }
    let mut out = String::new();
    for c in text.chars() {
        if c.is_ascii_digit() {
            if !out.ends_with('#') {
                out.push('#');
            }
        } else {
            out.push(c);
        }
    }
    out
}

/// The value of a lone page number: `7`, `- 7 -`, `7/12`, `vii`. Decorations are
/// dashes and bars around the number.
fn numeral(text: &str) -> Option<(Numeral, i64)> {
    let t = text
        .trim()
        .trim_matches(|c: char| c.is_whitespace() || matches!(c, '-' | '–' | '—' | '|'));
    if let Some((a, b)) = t.split_once('/') {
        let (a, b) = (a.trim(), b.trim());
        return (is_digits(a) && is_digits(b))
            .then(|| a.parse().ok())
            .flatten()
            .map(|v| (Numeral::Arabic, v));
    }
    if is_digits(t) {
        return t.parse().ok().map(|v| (Numeral::Arabic, v));
    }
    roman(t).map(|v| (Numeral::Roman, v))
}

fn is_digits(t: &str) -> bool {
    !t.is_empty() && t.len() <= 5 && t.bytes().all(|b| b.is_ascii_digit())
}

/// Value of a canonical roman numeral in one case (`xiv`, `XIV`), up to 3999.
fn roman(t: &str) -> Option<i64> {
    if t.is_empty() || t.len() > 15 {
        return None;
    }
    let lower = t.chars().all(|c| "ivxlcdm".contains(c));
    let upper = t.chars().all(|c| "IVXLCDM".contains(c));
    if !(lower || upper) {
        return None;
    }
    let digit = |c: char| match c.to_ascii_lowercase() {
        'i' => 1,
        'v' => 5,
        'x' => 10,
        'l' => 50,
        'c' => 100,
        'd' => 500,
        _ => 1000,
    };
    let vals: Vec<i64> = t.chars().map(digit).collect();
    let mut v = 0;
    for (i, &d) in vals.iter().enumerate() {
        if vals.get(i + 1).is_some_and(|&n| n > d) {
            v -= d;
        } else {
            v += d;
        }
    }
    // Only canonical spellings (`iiii`, `vx`, `im` are not page numbers).
    (v > 0 && v < 4000 && to_roman(v) == t.to_ascii_lowercase()).then_some(v)
}

fn to_roman(mut v: i64) -> String {
    const TABLE: [(i64, &str); 13] = [
        (1000, "m"),
        (900, "cm"),
        (500, "d"),
        (400, "cd"),
        (100, "c"),
        (90, "xc"),
        (50, "l"),
        (40, "xl"),
        (10, "x"),
        (9, "ix"),
        (5, "v"),
        (4, "iv"),
        (1, "i"),
    ];
    let mut s = String::new();
    for (n, r) in TABLE {
        while v >= n {
            s.push_str(r);
            v -= n;
        }
    }
    s
}

/// Whether `t` repeats `s` as furniture: same masked text and size, same baseline,
/// and the same left, right or centre x, directly or mirrored (two-sided layouts put
/// the number on the outer margin; mirrored positions are not in the corpus).
fn same_furniture(s: &Segment, t: &Segment, pages: &[PageWords]) -> bool {
    let size = s.size.max(t.size);
    if s.masked != t.masked
        || (s.size - t.size).abs() > SIZE_TOL * size
        || (s.baseline - t.baseline).abs() > POS_TOL * size
    {
        return false;
    }
    let tol = X_TOL * size;
    let near = |a: f32, b: f32| (a - b).abs() <= tol;
    let centre = |l: f32, r: f32| (l + r) / 2.0;
    if near(s.left, t.left)
        || near(s.right, t.right)
        || near(centre(s.left, s.right), centre(t.left, t.right))
    {
        return true;
    }
    let wt = pages.get(t.page).map_or(0.0, |p| p.width);
    near(s.left, wt - t.right) || near(s.right, wt - t.left)
}

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

    /// One word; every glyph advances 0.5 em.
    fn w(text: &str, left: f32, base: f32, size: f32) -> Word {
        let right = left + 0.5 * size * text.chars().count() as f32;
        Word {
            text: text.into(),
            bbox: Rect::new(left, base - 0.9 * size, right, base + 0.25 * size),
            baseline: base,
            size,
            font: "Serif".into(),
            style: Style::default(),
            glued: false,
            len: text.chars().count(),
            chars: 0..0,
            figure: None,
        }
    }

    /// A line of words separated by 0.25 em spaces.
    fn line(text: &str, left: f32, base: f32, size: f32) -> Vec<Word> {
        let mut x = left;
        text.split(' ')
            .map(|t| {
                let word = w(t, x, base, size);
                x = word.bbox.right + 0.25 * size;
                word
            })
            .collect()
    }

    /// A body paragraph of `n` lines of 10 pt at 1.2 em leading.
    fn body(first_base: f32, n: usize, seed: &str) -> Vec<Word> {
        (0..n)
            .flat_map(|i| {
                line(
                    &format!("{seed} linha {i} de texto corrido"),
                    72.0,
                    first_base + 12.0 * i as f32,
                    10.0,
                )
            })
            .collect()
    }

    fn run(pages: &[Vec<Word>]) -> Vec<Vec<Option<Reason>>> {
        let inputs: Vec<PageWords> = pages
            .iter()
            .enumerate()
            .map(|(i, ws)| PageWords {
                number: i + 1,
                width: 595.0,
                words: ws,
                hints: &[],
            })
            .collect();
        detect(&inputs)
    }

    /// (text, reason) of the furniture words of a page.
    fn furniture(ws: &[Word], r: &[Option<Reason>]) -> Vec<(String, Reason)> {
        ws.iter()
            .zip(r)
            .filter_map(|(w, r)| r.map(|r| (w.text.clone(), r)))
            .collect()
    }

    fn none(r: &[Vec<Option<Reason>>]) -> bool {
        r.iter().flatten().all(Option::is_none)
    }

    #[test]
    fn chrome_header_and_footer_repeat_with_varying_digits() {
        let pages: Vec<Vec<Word>> = (1..=3)
            .map(|p| {
                let mut ws = line(&format!("29/11/2026, 0{p}:54"), 24.0, 22.5, 8.0);
                ws.extend(line("Tabelas Difíceis", 316.0, 22.5, 8.0));
                if p == 1 {
                    // The same title as body text, at 24 pt: not furniture.
                    ws.extend(line("Tabelas Difíceis", 218.0, 120.8, 24.0));
                }
                ws.extend(body(160.0, 5, &format!("p{p}")));
                ws.extend(line("file:///tmp/chrome.html", 24.0, 825.8, 8.0));
                ws.extend(line(&format!("{p}/3"), 560.0, 825.8, 8.0));
                ws
            })
            .collect();
        let r = run(&pages);
        for (ws, r) in pages.iter().zip(&r) {
            let f = furniture(ws, r);
            assert_eq!(f.len(), 6, "{f:?}");
            assert!(f.iter().all(|(_, r)| *r == Reason::Repeated), "{f:?}");
        }
        assert!(
            pages[0]
                .iter()
                .zip(&r[0])
                .any(|(w, r)| w.size == 24.0 && r.is_none())
        );
    }

    #[test]
    fn latex_running_head_changes_but_its_page_number_carries_it() {
        // Page 1: number in the footer. Pages 2-3: running title + number in the
        // header; their first body lines are at the same place (and must stay).
        let mut p1 = line("Título do documento", 150.0, 84.4, 17.2);
        p1.extend(body(130.0, 30, "um"));
        p1.extend(line("1", 207.3, 582.6, 10.0));
        let mut p2 = line("PALAVRAS COMPOSTAS", 42.5, 17.6, 10.0);
        p2.extend(line("2", 372.0, 17.6, 10.0));
        p2.extend(body(52.5, 40, "dois"));
        let mut p3 = line("CONCLUSÃO", 42.5, 17.6, 10.0);
        p3.extend(line("3", 372.0, 17.6, 10.0));
        p3.extend(body(52.5, 40, "três"));
        let pages = vec![p1, p2, p3];
        let r = run(&pages);
        assert_eq!(
            furniture(&pages[0], &r[0]),
            [("1".to_string(), Reason::PageNumber)]
        );
        assert_eq!(
            furniture(&pages[1], &r[1]),
            [
                ("PALAVRAS".to_string(), Reason::SharedRow),
                ("COMPOSTAS".to_string(), Reason::SharedRow),
                ("2".to_string(), Reason::Repeated)
            ]
        );
        assert_eq!(furniture(&pages[2], &r[2]).len(), 2);
        let total = r.iter().flatten().filter(|x| x.is_some()).count();
        assert_eq!(total, 1 + 3 + 2);
    }

    #[test]
    fn page_numbers_on_different_edges_confirm_each_other() {
        // Two pages: the numbers are at different places (no repetition), but 1 on
        // page 1 and 2 on page 2 share the offset 0.
        let mut p1 = body(100.0, 20, "a");
        p1.extend(line("1", 290.0, 800.0, 10.0));
        let mut p2 = line("2", 520.0, 46.0, 10.0);
        p2.extend(body(80.0, 20, "b"));
        let r = run(&[p1.clone(), p2.clone()]);
        assert_eq!(
            furniture(&p1, &r[0]),
            [("1".to_string(), Reason::PageNumber)]
        );
        assert_eq!(
            furniture(&p2, &r[1]),
            [("2".to_string(), Reason::PageNumber)]
        );
        // A number with another offset does not confirm it.
        let mut p2b = line("8", 520.0, 46.0, 10.0);
        p2b.extend(body(80.0, 20, "b"));
        assert!(none(&run(&[p1, p2b])));
    }

    #[test]
    fn single_page_keeps_all_but_a_clear_lone_number_one() {
        let mut p = line("Um título no topo", 72.0, 60.0, 17.0);
        p.extend(body(100.0, 20, "x"));
        p.extend(line("1", 290.0, 400.0, 10.0));
        let r = run(std::slice::from_ref(&p));
        assert_eq!(
            furniture(&p, &r[0]),
            [("1".to_string(), Reason::PageNumber)]
        );

        // 2.0 em below the text: could be body text.
        let mut q = body(100.0, 20, "x");
        q.extend(line("1", 290.0, 100.0 + 19.0 * 12.0 + 20.0, 10.0));
        assert!(none(&run(&[q])));
        // Another number, or a number sharing its row: kept.
        let mut q = body(100.0, 20, "x");
        q.extend(line("7", 290.0, 400.0, 10.0));
        assert!(none(&run(&[q])));
        let mut q = body(100.0, 20, "x");
        q.extend(line("Rascunho", 72.0, 400.0, 10.0));
        q.extend(line("1", 290.0, 400.0, 10.0));
        assert!(none(&run(&[q])));
    }

    #[test]
    fn repeated_row_close_to_the_text_is_kept() {
        // A table header repeated at the top of every page, 1.2 em above the first
        // data row: same text and place, but not isolated.
        let pages: Vec<Vec<Word>> = (0..3)
            .map(|p| {
                let mut ws = line("Nome", 72.0, 60.0, 10.0);
                ws.extend(line("Valor", 300.0, 60.0, 10.0));
                ws.extend(body(72.0, 20, &format!("p{p}")));
                ws
            })
            .collect();
        assert!(none(&run(&pages)));
    }

    #[test]
    fn same_text_on_a_minority_of_pages_is_kept() {
        // "Capítulo N" at the top of 2 pages out of 6, far from the text.
        let pages: Vec<Vec<Word>> = (1..=6)
            .map(|p| {
                let mut ws = Vec::new();
                if p % 3 == 1 {
                    ws.extend(line(&format!("Capítulo {p}"), 72.0, 60.0, 20.0));
                }
                ws.extend(body(120.0, 20, &format!("p{p}")));
                ws
            })
            .collect();
        assert!(none(&run(&pages)));
    }

    #[test]
    fn mirrored_page_numbers_of_two_sided_layouts_repeat() {
        let pages: Vec<Vec<Word>> = (1..=4)
            .map(|p| {
                let mut ws = body(100.0, 20, &format!("p{p}"));
                let x = if p % 2 == 0 { 72.0 } else { 595.0 - 72.0 - 5.0 };
                ws.extend(line(&format!("{p}"), x, 800.0, 10.0));
                ws
            })
            .collect();
        let r = run(&pages);
        for (ws, r) in pages.iter().zip(&r) {
            assert_eq!(furniture(ws, r).len(), 1, "{:?}", furniture(ws, r));
        }
    }

    #[test]
    fn pagination_hint_is_furniture_without_geometry() {
        let ws = body(100.0, 3, "x");
        let hints = [Hint::Pagination];
        let r = detect(&[PageWords {
            number: 1,
            width: 595.0,
            words: &ws,
            hints: &hints,
        }]);
        assert_eq!(r[0][0], Some(Reason::Artifact));
        assert!(r[0][1..].iter().all(Option::is_none));
    }

    #[test]
    fn numerals_and_masks() {
        assert_eq!(numeral("12"), Some((Numeral::Arabic, 12)));
        assert_eq!(numeral("– 3 –"), Some((Numeral::Arabic, 3)));
        assert_eq!(numeral("2/3"), Some((Numeral::Arabic, 2)));
        assert_eq!(numeral("xiv"), Some((Numeral::Roman, 14)));
        assert_eq!(numeral("XIV"), Some((Numeral::Roman, 14)));
        for t in ["", "3.", "a/3", "iiii", "Xiv", "texto", "1234567", "9.500"] {
            assert_eq!(numeral(t), None, "{t:?}");
        }
        assert_eq!(mask("29/11/2026, 08:54"), "#/#/#, #:#");
        assert_eq!(mask("vii"), "#");
        assert_eq!(mask("Página 3 de 10"), "Página # de #");
    }

    #[test]
    fn odd_input_does_not_panic_and_is_deterministic() {
        let mut ws = body(100.0, 3, "x");
        ws.push(w("1", f32::NAN, 800.0, 10.0));
        ws.push(w("2", 10.0, f32::INFINITY, 10.0));
        ws.push(w("3", 10.0, 700.0, 0.0));
        let pages = vec![ws.clone(), ws, Vec::new()];
        let a = run(&pages);
        assert_eq!(a, run(&pages));
        assert!(detect(&[]).is_empty());
        assert_eq!(run(&[Vec::new()]), vec![Vec::<Option<Reason>>::new()]);
    }
}