Compare commits

..
Author SHA1 Message Date
Abimael Martell afca0c5ac8 fix(markdown): locate drop-cap paragraphs by indent run, not cap size
The previous rule only handled two-line caps: it took the line
immediately above the cap and required the cap's em to be under 2.5
line-steps. That fired on exactly one document in 386 — Shannon — and
rejected every other real initial, because production initials are
36-47pt over 11-14pt leading and cover three or four lines.

A drop cap pushes every line it covers to the right of the glyph, so
the paragraph's first line is the topmost line sharing that indent,
whatever the line count. Walk that run instead of deriving a count from
the font size, and evaluate the paragraph-start and continuation guards
against the run's top rather than the cap's immediate neighbour.

A cap in a different column has no such run, so it is left alone.

Across pdf-evals (192) and opendataloader-bench (200) this now fixes
three documents instead of one, each losing a truncated first word and
a junk heading built from the orphaned cap ("# Omany patients"). The
opendataloader score moves 0.87836 -> 0.87912 overall and 0.7878 ->
0.7906 MHS with no metric regressing; 275_41c50d3a's pdf-evals
composite moves 0.5772 -> 0.5862.
2026-08-08 12:41:02 -07:00
Abimael Martell 764ec6e081 test: cover the byte-vs-character bound with a real two-character segment
Valid, and the third time this review has caught a test that did not
exercise its own fix. My cases used single-character segments ('т', 'е',
'ú'), which are 2 bytes each and so already satisfied the old
seg.len() <= 2 bound — a revert to len() would have passed them.

Added 'и т.пр.', whose final segment 'пр' is 2 characters but 4 bytes,
which is precisely the case the two bounds disagree on.

This time I verified the discrimination directly rather than assuming
it: with seg.len() the new assertion fails, with seg.chars().count() it
passes. 998 tests, clippy clean.
2026-08-07 20:14:48 -07:00
Abimael Martell 631f3ff192 review: measure abbreviation segments in characters, not bytes
Valid. The segment-length bound used seg.len(), which counts bytes, so a
two-letter non-ASCII abbreviation ('т.е.', 'ú.d.') measured four or more
bytes, failed the check, and was read as a completed sentence — which
would let a drop cap merge into a continuation.

Counts characters now, with both examples pinned in the test.

998 tests pass, clippy clean; Shannon and the corpus are unchanged.
2026-08-07 19:47:00 -07:00
Abimael Martell ba1807dce5 review: make enumerator and abbreviation tests precise in ends_sentence
Two findings, pulling in opposite directions, which is what made the
original rule wrong in both.

conf 10 — lowercase roman markers ('ii.') were not recognised, because
the numeral check compared uppercase characters only. Now
case-insensitive.

conf 7 — the same check was too broad in the other direction: any last
token of digits or roman letters counted as a marker, so 'published in
2020.', 'He scored 5.' and 'after World War II.' were not sentence ends
and a legitimate drop cap would be left in place mid-sentence.

Resolved by using position rather than shape: an enumerator stands alone
on its line ('1.', 'ii.', 'IV.'), whereas a number or numeral closing a
sentence has words before it. The marker test now applies only when the
line is a single token.

The abbreviation test had the same flaw. 'e.g.' and 'example.com.' both
carry an internal period with letters, so the old rule classified the
domain as an abbreviation. Abbreviation segments are short and
alphabetic ('e.g.', 'U.S.'), so every dot-separated segment must now be
at most two alphabetic characters; domains and decimals ('3.14.') fall
through as sentence ends.

Unchanged: Shannon reads 'THE recent development ...', 0 of 186
pdf-evals documents affected. 998 tests pass, clippy clean.
2026-08-07 19:41:45 -07:00
Abimael Martell 597e125731 review: drop stray diagnostic, scope to page, require a real sentence end
Three findings from the third review, all valid.

P2 (conf 10) — a GEO log::warn! diagnostic I used while measuring the
cap geometry was left in the committed code, so every embedded-cap
candidate emitted a warning during ordinary conversion, including
candidates deliberately left untouched. Removed. It should never have
been committed; verified with RUST_LOG=warn that conversion is now
silent apart from a pre-existing lopdf encoding warning.

P2 (conf 9) — a cap on the first paragraph of a new page could be
suppressed because before_target could come from the previous page,
whose y is unrelated, making the leading comparison meaningless.
before_target is now scoped to the cap's own page.

P3 (conf 4) — starts_paragraph accepted any line ending in a period, so
'as shown in Fig.', 'see e.g.', 'item 1.' and 'reviewed by Dr.' read as
paragraph boundaries and could let a continuation take the cap. Replaced
with ends_sentence(), which rejects internal-period abbreviations,
numeric and roman list markers, and a short abbreviation list.

Unchanged: Shannon reads 'THE recent development ...', 0 of 186
pdf-evals documents affected. 998 tests pass, clippy clean.
2026-08-07 19:33:21 -07:00
Abimael Martell b0b42c4949 review: gate on cap line-count and require a paragraph start
Three findings from the second review, all valid.

P1 — ordinary continuations could still take the cap. Rejecting only a
preceding hyphen treated any non-hyphenated context as a paragraph
start, so a continuation sharing the left edge became 'Tcontinuation'.
The target must now START a paragraph: either extra leading above it
(> 1.15x the local step) or a completed sentence on the line above.
Shannon's target has 18.6pt of leading above against a 12.1pt step.

P2 — the vertical-step bound was expressed as a fraction of the cap em,
but the step is the body leading and is independent of cap size. A 25pt
cap over 12pt leading is a genuine two-line cap yet failed 'step >= em/2'.
Recast as a line count: the cap must be at most 2.5 line-steps tall.
Shannon measures 1.53; the four-line initials this cannot place measure
3.5 and 4.0. Tall caps over tight leading now pass, as they should.

P2 — the hyphenation regression test did not exercise its own guard: at
a 12pt step under a 25pt cap the continuation was already rejected by
the vertical gate, so deleting the hyphen check would not have failed
it. Raised the step to 14pt so the hyphen guard is what does the work.

Unchanged: Shannon reads 'THE recent development ...', 0 of 186
pdf-evals documents affected, 996 tests pass, clippy clean.
2026-08-07 16:32:41 -07:00
Abimael Martell dd68cc221f review: scope drop-cap merging to genuine two-line caps
Addresses both cubic findings, and measuring the geometry changed what
this PR claims.

Finding 1 (target may be a continuation): real. Two guards now.

- The line above the target must not end on a hyphen, or the target
  resumes a split word (polkuja_ylakoulu: 'ylakou-' + 'lulaisten').
- The target and the cap's own line must share a left edge, since both
  clear the glyph; a continuation sits at the paragraph margin instead.

A third guard I tried and removed: rejecting targets that start
lowercase. That is backwards here — the cap takes the word's first
letter, so the paragraph's first line legitimately starts lowercase
('ver the course...' for 'Over').

Finding 2 (indent misread as a word boundary): real. Leading whitespace
now only marks a standalone-word cap when the cap is itself a
single-letter word, so an indented mid-word cap cannot yield 'T HE'.

The substantive change is scope. Measuring the two corpus documents
showed both use caps of 44-47pt over an 11-13pt leading — four-line
initials, not two-line. For those the paragraph's first line is several
lines up, and taking the line immediately above is a coin flip: right
for 275_41c50d3a, wrong for polkuja_ylakoulu, where it produced
'Ntulla'. Requiring the baseline step to be at least half the cap height
restricts this to genuine two-line caps, where the immediately preceding
line is the paragraph start by construction.

Consequences, stated plainly:

- Shannon still reads 'THE recent development ...' — the reported case.
- Corpus impact is now zero: 0 of 186 pdf-evals documents and no change
  on opendataloader beyond what #264 already contributes.
- The earlier +0.0033 mhs came from the unscoped version merging
  multi-line caps, which also introduced the polkuja corruption. That
  gain was not real and is withdrawn.
- Multi-line initials remain unhandled; locating their paragraph start
  needs a different approach than looking one line up.

1004 tests pass, clippy clean.
2026-08-07 16:16:43 -07:00
Abimael Martell 20c5a0a82a fix(markdown): place two-line drop caps at the paragraph start
A two-line drop cap's baseline aligns with the paragraph's SECOND line,
so Y-grouping puts the glyph at the start of that line rather than on a
line of its own. The existing merge_drop_caps only handled caps that
occupy their own line, so the embedded form survived into the output and
surfaced mid-sentence once the paragraph was joined.

Shannon's 'A Mathematical Theory of Communication' — the PDF that
prompted this work — opened with

    HE recent development of various methods of modulation such as PCM
    and PPM which exchange T bandwidth for signal-to-noise ratio ...

and now reads 'THE recent development ... which exchange bandwidth'.

Detection requires the cap to be a single uppercase glyph >= 1.8x body
size (bitmap Type3 caps report their glyph bbox rather than the em box,
so a two-line cap can measure as little as ~1.9x), followed on the same
line by a substantive body run, with the paragraph's first line directly
above in the same column and indented past the cap. The target must
itself read as body text, so headings, labels and table fragments that
merely fall in the geometric window are never rewritten.

Removing the cap from the line also stops it inflating heading tiers:
Shannon's title moves from h2 to h1, and 275_41c50d3a's heading levels
all shift up one, both correct.

Corpus impact is narrow — 2 of 186 pdf-evals documents:

- 275_41c50d3a: heading levels shift up one, as above.
- polkuja_ylakoulu: a wash. The cap is misplaced both before and after
  (main prefixes it to 'pelaaminen' inside a spurious heading, this
  version prefixes it to 'lulaisten'), but the spurious heading is gone
  and the paragraph joins correctly. Noted rather than tuned away — the
  target selection takes the immediately preceding line, which can be
  the wrong column on multi-column pages.

opendataloader-bench (200 docs, ground truth): overall +0.0012, mhs
+0.0036 against pre-#264 main, of which #264 contributed +0.0003 /
+0.0003 — so this change accounts for roughly +0.0009 overall and
+0.0033 mhs, the largest heading-metric gain measured in this series.

994 tests pass, clippy clean.
2026-08-07 15:51:27 -07:00
Abimael Martell 436af97038 fix(tables): exclude script attachments and tiny numeric fragments from detection (#264)
* fix(tables): exclude script attachments and tiny numeric fragments from detection

Split out of #242 (draft) so it can be reviewed on its own evidence.

Display equations with sub/superscripts form phantom small-font table
regions: the subscripts cluster with nearby small text (footnotes, axis
labels) into fake multi-column grids. Two guards:

- Script attachment: a small-font item horizontally adjacent to a
  larger-font item at a genuine baseline offset is a sub/superscript,
  not a table cell, and is excluded from candidates. A real baseline
  offset is required so a small cell beside a larger same-baseline
  label is never filtered. Attachment targets are indexed by Y and
  scanned through a bounded window rather than a full-page sweep.
  The body-font pass applies the same exclusion but only for
  heading-sized anchors (>= 1.15x base), so body-size table cells
  beside slightly larger labels are untouched.
- Tiny numeric fragments: a <=2-row grid whose every cell is a bare
  1-2 digit number carries no tabular information. Restricted to the
  small-font pass, where the pattern is overwhelmingly exponent
  clusters; body-font numeric grids are unaffected.

Corpus impact: 20 of 186 documents, measured against a control build of
main so main's own drift is excluded. Table rows fall in 17 of 18
inspected documents and no content is lost — 2103_07786 drops all 21
rows, every one a math fragment ('|X 42 43|1|||'); Stijn_SB_doc drops
173 rows of footnote text that had been shredded into cells, with word
count slightly UP and footnote markers intact. M2019_mordeste gains 11
rows from a 3-column grid re-detected as 2-column, neither clearly
better nor worse.

Note the 20 documents is far more than the 3 that per-change ablation
suggested: that figure measured sole-cause attribution inside the
original combined PR, where other heuristics changed the same files and
masked this one. Reach and sole-cause are different measurements.

805 unit + 148 integration tests pass, clippy clean, in-repo snapshots
unchanged.

* fix(tables): suppress script column evidence instead of dropping candidates

Reworked after reviewing the corpus diffs: the first approach removed
sub/superscripts from table candidates entirely, which had two failure
modes beyond the intended fix.

- Legitimate cell content was displaced. citizen-sr-282 is a calculator
  manual whose engineering-notation table lists M = 10^6, k = 10^3.
  Those exponents are superscripts, so they were dropped from the table
  and resurfaced elsewhere in the reading order ('9 mega 6 kilo = 10 3
  milli').
- Removing items changed the candidate geometry, so different spurious
  structure could form from what remained.

Scripts are now kept as candidates and excluded only from the geometry:
they cannot create a column (find_column_boundaries), cannot qualify a
region on their own (find_table_regions / _strict), but are still
assigned to cells. Column alignment is validated against ALL items
including scripts — validating only the non-script subset would let a
region manufacture alignment by ignoring its awkward items, which is
what block-diagram pages did.

Corpus: 20 of 186 documents, net -359 table rows, no content lost.
Token-level comparison shows the only text changes are merges in the
right direction: 'X' + '10' becomes 'X10', 'L' + 'g' becomes 'Lg' —
subscripts joining their base instead of floating free.

Remaining artifact: MCF5235RM (and its _nxp duplicate) gains a small
spurious table from a block-diagram label line, and M2019_mordeste
gains 11 rows from a 3-column grid re-detected as 2-column. Both are
borderline regions where the previous output was also wrong; documented
rather than tuned away.

805 unit + 148 integration tests pass, clippy clean.

* fix(tables): use a heading-anchored script mask in the body-font pass

Cubic review of #264: a single script mask computed with a 0.0 anchor
was applied to both passes, including body-font region qualification and
geometry. The body pass is supposed to require a heading-sized anchor —
that distinction existed before the geometry rework and was lost in it.

Why it matters: body-pass candidates are themselves body-sized
(0.85..1.05x base). A cell at the low end of that band, say 8.5pt,
sitting beside a 10.5pt label clears the inherent 'anchor >= 1.2x cell'
rule (10.2) and so was flagged as a script attachment. At body sizes a
slightly larger neighbour is a bold label or column header, not the base
of a superscript, so flagging it stripped real cells out of the region
evidence and column geometry and could lose the table entirely.

Two masks now: the small-font pass keeps the 0.0 anchor, the body pass
requires >= 1.15x base. Note the threshold only bites below base size —
for a cell at base, 1.2x-of-cell already exceeds 1.15x-of-base — which
is exactly the 0.85..1.0x band cubic identified.

Corpus: 20 documents, net -367 table rows (was -359 with the single
mask), so the body pass now keeps 8 rows of real table it had been
discarding. 958 tests pass, clippy clean.

* fix(markdown): reject headings that end on a relational verb

A heading candidate ending in 'equals', 'denotes', 'implies' and the
like is the first half of a sentence, not a title. This shows up when a
block dissolves and strands its lead-in ahead of the formula it
introduced — opendataloader 01030000000144 produced

    ## Note that the exact error equals
    M - Q(h) = e - 2.7525... = -0.0342....

Deliberately a very short list. Broader variants were tried and
measured, then rejected:

- Function words (of/and/for/the): a heading that WRAPS across lines
  ends on exactly those. Destroyed real IRS Publication 17 headings —
  'Casualty and' -> 'Casualty and Theft Losses', 'Rule 10. You Must Be
  at' -> '... At Least Age 25'. 52 documents affected, -619 headings.
- Copulas and auxiliaries (is/are/be/have): same failure. 'Rule 15.
  Your AGI Must Be', 'What Medical Expenses Are' and 'When Can a Roth
  IRA Be' are real wrapped headings, while 'the tax burden should be'
  is a genuine fragment. The trailing word cannot separate them; that
  needs the next line's context, which this text-only predicate lacks.

The verbs kept never end a heading in any register, so they are safe
without context. Standalone the guard is a no-op on both benchmarks
(0 documents on opendataloader, 4 on pdf-evals with no net heading
change) — its value is as a companion to the table filter in this PR,
which is what strands these lead-ins.

Combined effect on opendataloader (200 docs, vs a control build of
main), where the table filter alone regressed:

                 table filter    + this guard
    overall        -0.0003          +0.0003
    mhs            -0.0019          +0.0003
    doc ...144     -0.063           +0.053
    doc ...144 mhs -0.203           +0.028

* review: gate the dangling-verb veto on sentence case, drop 'yields'

Cubic review of a5a6e8f — both findings valid.

1. 'yields' is also a plural noun. 'Bond Yields', 'Crop Yields' and
   'Dividend Yields' are real section titles in financial documents,
   which this corpus contains. Removed from the list; my claim that
   these verbs 'never end a heading in any register' was wrong for it.

2. A wrapped title-case heading whose first line ends on one of these
   verbs would be suppressed if the heading preprocessor failed to
   merge it.

Both are fixed by the same gate, which is the discriminator I was
missing: case. A heading is title case ('Bond Yields', 'The Theorem
Implies'); a stranded lead-in is sentence case ('Note that the exact
error equals', 'the method yields'). The veto now applies only when
every content word is NOT capitalized, so titles are spared regardless
of their final word.

This is also why the earlier function-word and copula variants failed:
they had no way to tell 'Rule 15. Your AGI Must Be' from 'the tax
burden should be'. Case separates those two as well.

No measured cost. opendataloader is unchanged from the previous
revision — overall +0.0003, mhs +0.0003, doc 01030000000144 still
0.732 -> 0.785 — and pdf-evals still 20 documents. 963 tests pass,
clippy clean.

* review: exempt section-numbered lines from the dangling-verb veto

Valid ordering bug. heading.rs consults is_heading_fragment at line 282
and only applies its numbered-prefix allowance at line 288, so the veto
pre-empted it: '1. What the model implies' is sentence case and ends on
a listed verb, so it was discarded before numbering could vouch for it.

Numbering is independent evidence of a heading, so the veto now skips
any line opening with a section number.

Acceptance is deliberately a little broader than heading::parse_numbering
(which requires a trailing delimiter) because '2.3 Section Title' is
written without one, and being permissive in a veto exemption can only
avoid suppressing headings. Two guards keep it from swallowing prose:

- a bare single number needs a delimiter ('1.' yes, '3 apples' no)
- roman numerals always need one, since a leading 'I' is the pronoun far
  more often than a section number

Not reused from convert::starts_with_section_number, which deliberately
demands two components because it bypasses isolation checks — that would
reject the reviewer's single-'1.' case.

No measured change: opendataloader still overall +0.0003 / mhs +0.0003
with doc 01030000000144 at 0.732 -> 0.785, pdf-evals still 20 documents,
target case still suppressed. 964 tests pass, clippy clean.

* review: share roman_value so the veto exemption matches the parser

Valid. My numbering predicate accepted tokens heading::parse_numbering
rejects — lowercase 'iv)', alphabetical 'd)', over-long 'MMMM.' — because
it case-folded and allowed D and M. Anything the parser rejects is not
numbering, so exempting it let ordinary list items bypass the
dangling-verb veto and reach font-based heading promotion.

Rather than restate the grammar, roman_value is now pub(super) and the
exemption calls it, so the two cannot drift. Its rules apply as written:
uppercase I/V/X/L/C only, at most 8 characters, positive total.

Decimal numbering keeps its slightly broader acceptance (bare '2.3' with
no trailing delimiter), which is deliberate and documented — that form is
common in real headings and being permissive in a veto exemption cannot
manufacture a heading, only decline to suppress one. The roman case is
different because single letters collide with alphabetical list markers.

No measured change: opendataloader overall +0.0003 / mhs +0.0003, doc
01030000000144 still 0.732 -> 0.785. 964 tests pass, clippy clean.

* test: cover the roman length bound with a nine-character token

Valid P3. The 'MMMM.' case fails on the unsupported M, not on length, so
the 8-character bound in roman_value had no coverage and could regress
silently. Added a nine-'I' token, which is rejected only by the bound,
plus an eight-'I' token that must stay exempt to pin the boundary from
both sides.

* fix(tables): stop dropping body-band scripts from the candidate set

Valid: the body-font pass filtered scripts out of body_candidates
itself, so body_script_flags and its two downstream uses were dead. The
mask filters region_evidence and feeds detect_table_in_region's is_script
closure, but neither ever saw a script item because the candidate set no
longer contained any.

Consequences: a body-band sub/superscript attached to a heading-sized
anchor was dropped from the table outright rather than assigned to a
cell, so its text was lost — the opposite of what both the
body_script_flags comment ('they stay candidates') and the
detect_table_in_region docstring ('they remain eligible for cell
assignment') describe, and inconsistent with the small-font pass.

Root cause: the geometry rework removed the candidate-level filter from
the small-font pass, but the body one had been reflowed onto a single
line by rustfmt so the same edit missed it. Adding body_script_flags in
a later review then wired a mask that the surviving filter made
unreachable.

No measured change on either benchmark — pdf-evals still 20 documents
and -367 table rows, opendataloader still overall +0.0003 / mhs +0.0003
with one document changed — because the combination it affects (a
body-sized script attached to a heading-sized anchor) does not occur in
either corpus. The fix is for correctness and consistency between the
two passes, not for a score.

964 tests pass, clippy clean.
2026-08-07 09:41:46 -07:00
Abimael Martell f731e1191c fix(site): refresh benchmark results (#289) 2026-08-06 12:52:00 -07:00
5 changed files with 1032 additions and 18 deletions
+192
View File
@@ -171,6 +171,74 @@ pub(crate) fn is_toc_marker_heading(text: &str) -> bool {
/// equation and absent from name-plus-number headings. A bare trailing colon
/// is NOT a fragment signal either: real headings frequently end with colons
/// ("Procedure:", "Steps for Using the Microscope:").
/// True when the line opens with a section number ("3.", "2.1.4", "IV)").
///
/// Mirrors the acceptance of `heading::parse_numbering` rather than the
/// stricter `convert::starts_with_section_number`, which deliberately
/// requires two components because it bypasses isolation checks. Here a
/// single "1." counts: numbering is independent evidence of a heading, and
/// `heading.rs` applies its numbered-prefix allowance *after* consulting
/// `is_heading_fragment`, so without this exemption a numbered
/// sentence-case heading would be vetoed before that allowance can run.
fn starts_with_numbering_prefix(t: &str) -> bool {
let Some(first) = t.split_whitespace().next() else {
return false;
};
let has_delimiter = first.ends_with(['.', ')', ':']);
let token = first.trim_end_matches(['.', ')', ':']);
if token.is_empty() {
return false;
}
let parts: Vec<&str> = token.split('.').collect();
let decimal = parts
.iter()
.all(|p| !p.is_empty() && p.len() <= 3 && p.chars().all(|c| c.is_ascii_digit()));
if decimal {
// "1." / "2.1." carry a delimiter; "2.3 Title" is written without
// one, so a multi-component number is accepted bare. A bare single
// number ("3 apples") is not — that is ordinary prose.
return has_delimiter || parts.len() >= 2;
}
// Roman numerals go through the heading parser's own grammar so the two
// agree: uppercase I/V/X/L/C only, at most 8 characters. A looser rule
// here would exempt markers the parser rejects — "iv)" or "d)" from an
// alphabetical list — letting an ordinary list item bypass the veto and
// reach heading promotion.
//
// A delimiter is also required: a bare leading "I" is the pronoun far
// more often than a section number.
has_delimiter && crate::markdown::heading::roman_value(token).is_some()
}
/// True when the line reads as a title rather than a sentence: every
/// content word (ignoring minor words) starts uppercase. Used to spare real
/// headings from the dangling-verb veto — "Bond Yields" is a section title,
/// "the method yields" is a stranded clause, and only the casing tells them
/// apart.
fn looks_title_case(t: &str) -> bool {
const MINOR: &[&str] = &[
"a", "an", "the", "of", "and", "or", "for", "to", "in", "on", "at", "by", "with", "from",
"as", "is", "are", "that", "than", "into",
];
let mut content = 0usize;
let mut capitalized = 0usize;
for w in t.split_whitespace() {
let cleaned: String = w.chars().filter(|c| c.is_alphabetic()).collect();
if cleaned.is_empty() {
continue;
}
if MINOR.contains(&cleaned.to_lowercase().as_str()) {
continue;
}
content += 1;
if cleaned.chars().next().is_some_and(char::is_uppercase) {
capitalized += 1;
}
}
// A single content word ("Yields") is a title by default.
content == 0 || capitalized == content
}
pub(crate) fn is_heading_fragment(text: &str) -> bool {
let t = text.trim_end();
@@ -244,9 +312,133 @@ pub(crate) fn is_heading_fragment(text: &str) -> bool {
if t.ends_with(':') && t.split_whitespace().any(is_equation_number) {
return true;
}
// Dangling clause: a stranded sentence lead-in ends on a relational
// verb with no terminal punctuation — "Note that the exact error equals"
// left ahead of its formula when a phantom table dissolved.
//
// Gated on the line reading as prose rather than a title. Case is the
// discriminator the trailing word alone cannot provide: a heading is
// title case ("Bond Yields", "The Method Yields") while a stranded
// lead-in is sentence case ("the method yields"). Without this gate the
// veto eats real headings — "Bond Yields", "Crop Yields" and any wrapped
// title-case heading the preprocessor failed to merge.
if !t.ends_with(['.', '!', '?', ':', ';', ')', ']'])
&& !looks_title_case(t)
&& !starts_with_numbering_prefix(t)
{
if let Some(last) = t.split_whitespace().next_back() {
let word: String = last
.trim_matches(|c: char| !c.is_alphanumeric())
.to_lowercase();
// Relational verbs only, and only those with no common noun
// sense. "yields" was dropped for exactly that reason: "Bond
// Yields" is a real section title. Function words, copulas and
// auxiliaries were measured and rejected outright — a heading
// that wraps across lines ends on those, and suppressing them
// destroyed real IRS Publication 17 headings.
const DANGLING_TAIL: &[&str] =
&["equals", "denotes", "implies", "satisfies", "signifies"];
if DANGLING_TAIL.contains(&word.as_str()) {
return true;
}
}
}
false
}
#[cfg(test)]
mod fragment_heading_tests {
use super::is_heading_fragment;
#[test]
fn dangling_tail_marks_stranded_clause() {
// opendataloader 01030000000144: left behind when a phantom table
// dissolved, ahead of its formula on the next line.
assert!(is_heading_fragment("Note that the exact error equals"));
assert!(is_heading_fragment("The remainder term satisfies"));
assert!(is_heading_fragment("we conclude that the sum equals"));
}
#[test]
fn real_headings_survive() {
assert!(!is_heading_fragment("Introduction"));
assert!(!is_heading_fragment("Error Analysis"));
assert!(!is_heading_fragment("Materials and Methods"));
assert!(!is_heading_fragment("Results"));
assert!(!is_heading_fragment("3.2 Richardson Extrapolation"));
assert!(!is_heading_fragment("Discussion and Conclusions"));
// Terminal punctuation means the clause is complete.
assert!(!is_heading_fragment("What is a Derivative?"));
assert!(!is_heading_fragment("Procedure:"));
assert!(!is_heading_fragment("Note that this is important."));
}
#[test]
fn title_case_headings_ending_in_a_verb_survive() {
// "yields" is also a plural noun; these are real section titles.
assert!(!is_heading_fragment("Bond Yields"));
assert!(!is_heading_fragment("Crop Yields"));
assert!(!is_heading_fragment("Dividend Yields"));
assert!(!is_heading_fragment("Yields"));
// A wrapped title-case heading whose first line ends on a listed
// verb must survive even if the preprocessor failed to merge it.
assert!(!is_heading_fragment("The Theorem Implies"));
assert!(!is_heading_fragment("What This Denotes"));
}
#[test]
fn numbered_sentence_case_headings_survive() {
// heading.rs consults is_heading_fragment BEFORE applying its
// numbered-prefix allowance, so the veto must not pre-empt it.
assert!(!is_heading_fragment("1. What the model implies"));
assert!(!is_heading_fragment("2.3 How the estimator satisfies"));
assert!(!is_heading_fragment("IV) What this denotes"));
// Without numbering the same wording is still a stranded clause.
assert!(is_heading_fragment("What the model implies"));
// A bare leading number or pronoun is prose, not numbering.
assert!(is_heading_fragment("3 apples and what that implies"));
assert!(is_heading_fragment("I think the model implies"));
// Markers heading::parse_numbering rejects must not be exempted
// either, or an ordinary list item bypasses the veto: lowercase
// roman, alphabetical markers, and over-long tokens.
assert!(is_heading_fragment("iv) the estimator satisfies"));
assert!(is_heading_fragment("d) the value implies"));
// Unsupported character (M is outside the parser's I/V/X/L/C set).
assert!(is_heading_fragment("MMMM. the value implies"));
// Over-long token: nine valid characters, so this exercises the
// 8-character bound rather than the character set.
assert!(is_heading_fragment("IIIIIIIII. the value implies"));
// Eight is still within the bound and stays exempt.
assert!(!is_heading_fragment("IIIIIIII. What this implies"));
// Uppercase roman within the parser's grammar is still exempt.
assert!(!is_heading_fragment("IV. What this denotes"));
assert!(!is_heading_fragment("XII) What this implies"));
}
#[test]
fn wrapped_headings_are_not_fragments() {
// A heading that wraps across lines ends on a function word. These
// are real headings from IRS Publication 17 and must survive.
assert!(!is_heading_fragment("Casualty and"));
assert!(!is_heading_fragment("Rule 10. You Must Be at"));
assert!(!is_heading_fragment("Higher Standard Deduction for"));
assert!(!is_heading_fragment("Qualifying Child of"));
assert!(!is_heading_fragment("When Can I Withdraw or"));
// Copulas and auxiliaries also end real wrapped headings.
assert!(!is_heading_fragment("Rule 15. Your AGI Must Be"));
assert!(!is_heading_fragment("What Medical Expenses Are"));
assert!(!is_heading_fragment("Rule 13. You Must Have"));
assert!(!is_heading_fragment("When Can a Roth IRA Be"));
}
#[test]
fn dangling_check_is_case_insensitive() {
// All-caps is not sentence case, so the veto must not fire there.
assert!(!is_heading_fragment("THE REMAINDER EQUALS"));
}
}
/// Compute the Y-gap threshold for paragraph break detection.
///
/// Instead of using a fixed multiple of base_size (which fails for double-spaced
+3 -1
View File
@@ -127,7 +127,9 @@ fn visual_style(line: &TextLine) -> Option<VisualStyle> {
})
}
fn roman_value(token: &str) -> Option<u32> {
/// Shared with `analysis::starts_with_numbering_prefix` so the veto
/// exemption and the heading parser agree on what a roman numeral is.
pub(super) fn roman_value(token: &str) -> Option<u32> {
if token.is_empty() || token.len() > 8 {
return None;
}
+526
View File
@@ -150,6 +150,61 @@ pub(crate) fn merge_heading_lines(
/// Merge drop caps with the appropriate line.
/// A drop cap is a single large letter at the start of a paragraph.
/// Due to PDF coordinate sorting, the drop cap may appear AFTER the line it belongs to.
/// True when the text ends a sentence, as opposed to merely ending in a
/// period. An abbreviation or list marker ("e.g.", "Fig.", "Mr.", "1.")
/// closes with a period mid-sentence, so treating those as paragraph
/// boundaries would let a drop cap be prepended to a continuation.
fn ends_sentence(text: &str) -> bool {
let t = text.trim_end();
if t.ends_with(['!', '?']) {
return true;
}
let Some(stripped) = t.strip_suffix('.') else {
return false;
};
let last = stripped.split_whitespace().next_back().unwrap_or("");
if last.is_empty() {
return false;
}
// Abbreviations carry an internal period between very short segments
// ("e.g.", "i.e.", "U.S."). Domains and decimals have the same shape but
// longer or numeric segments ("example.com.", "3.14."), and those end
// sentences perfectly well, so require every segment to be short and
// alphabetic before reading the internal period as an abbreviation.
if last.contains('.')
&& last
.split('.')
.filter(|seg| !seg.is_empty())
// Characters, not bytes: a two-letter non-ASCII abbreviation
// ("т.е.", "ú.d.") measures four or more bytes and would
// otherwise be read as a completed sentence.
.all(|seg| seg.chars().count() <= 2 && seg.chars().all(char::is_alphabetic))
{
return false;
}
// Enumerators stand alone on their line ("1.", "ii.", "IV."). A number
// or numeral in the tail of a sentence does not — "published in 2020.",
// "He scored 5." and "after World War II." all end sentences, and
// treating them as markers would block a legitimate drop-cap merge.
if stripped.split_whitespace().count() == 1 {
let is_numeric = last.chars().all(|c| c.is_ascii_digit());
let is_roman = last
.chars()
.all(|c| matches!(c.to_ascii_uppercase(), 'I' | 'V' | 'X' | 'L' | 'C'));
if is_numeric || is_roman {
return false;
}
}
const ABBREVIATIONS: &[&str] = &[
"Fig", "No", "Mr", "Mrs", "Ms", "Dr", "St", "vs", "etc", "al", "Ed", "Eq", "Ch", "pp",
"Vol", "cf", "Prof", "Inc", "Ltd", "Jr", "Sr",
];
!ABBREVIATIONS.iter().any(|a| a.eq_ignore_ascii_case(last))
}
pub(crate) fn merge_drop_caps(lines: Vec<TextLine>, base_size: f32) -> Vec<TextLine> {
let mut result: Vec<TextLine> = Vec::with_capacity(lines.len());
@@ -169,6 +224,169 @@ pub(crate) fn merge_drop_caps(lines: Vec<TextLine>, base_size: f32) -> Vec<TextL
.map(|c| c.is_uppercase())
.unwrap_or(false);
// Embedded drop cap: a two-line cap's baseline aligns with the
// paragraph's SECOND line, so Y-grouping puts the glyph at the start
// of that line rather than on a line of its own. Left there it
// surfaces mid-sentence once the paragraph is joined — Shannon's
// "A Mathematical Theory of Communication" reads "...which exchange
// T bandwidth for signal-to-noise ratio...". Detect it, prepend the
// character to the paragraph's first line, and drop it from this one.
//
// The size gate is 1.8x rather than 2.5x because bitmap (Type3) caps
// report their glyph bbox rather than the em box, so a two-line cap
// can measure as little as ~1.9x the body size.
if line.items.len() > 1 {
let first = &line.items[0];
// The remainder must be a substantive body run: a lone label or
// math fragment beside a large glyph is not a drop-cap paragraph.
let rest_letters: usize = line.items[1..]
.iter()
.map(|i| i.text.chars().filter(|c| c.is_alphabetic()).count())
.sum();
let is_embedded_cap = first.font_size >= base_size * 1.8
&& first.text.trim().chars().count() == 1
&& first
.text
.trim()
.chars()
.next()
.is_some_and(char::is_uppercase)
&& line.items[1..]
.iter()
.all(|i| i.font_size < base_size * 1.5)
&& line.items[1..].iter().any(|i| i.x > first.x)
&& rest_letters >= 8;
if is_embedded_cap {
let drop_char = first.text.trim().chars().next().unwrap();
let cap_x = first.x;
let line_y = line.y;
// Text on the cap's own line, pushed right to clear the glyph.
let rest_x = line.items[1].x;
// Walk up the run of lines the cap has indented. A drop cap
// pushes every line it covers to the right of the glyph, so
// the paragraph's first line is the TOPMOST line sharing that
// indent — however many lines the cap spans. Using the indent
// rather than the cap's font size is what makes this work for
// three- and four-line initials as well as two-line ones;
// deriving a line count from the em size does not survive
// contact with real documents, where 36-47pt initials sit
// over 11-14pt leading.
//
// A cap in a different column has no such run (its neighbours
// sit at an unrelated x), so it is left alone — which is
// correct when the cap's own line already carries the rest of
// the word.
const INDENT_TOLERANCE: f32 = 2.0;
const MAX_CAP_LINES: usize = 8;
let max_step = base_size * 2.5;
let mut target_idx = result.len();
let mut expected_y = line_y;
while target_idx > 0 && result.len() - target_idx < MAX_CAP_LINES {
let cand = &result[target_idx - 1];
let step = cand.y - expected_y;
let shares_indent = cand
.items
.first()
.is_some_and(|i| (i.x - rest_x).abs() <= INDENT_TOLERANCE);
if cand.page != line.page || step <= 0.0 || step > max_step || !shares_indent {
break;
}
expected_y = cand.y;
target_idx -= 1;
}
// The topmost line of the run is the paragraph's first line.
// The line above THAT tells us whether it starts a paragraph.
let before_target = target_idx
.checked_sub(1)
.and_then(|i| result.get(i))
.filter(|l| l.page == line.page)
.map(|l| (l.text().trim_end().to_string(), l.y));
// Leading within the run: the step from the target down to the
// next line of the paragraph, which is the cap's own line when
// the run is a single line.
let run_step = result
.get(target_idx)
.map(|t| {
let below_y = result.get(target_idx + 1).map_or(line_y, |b| b.y);
t.y - below_y
})
.unwrap_or(0.0);
let step_for_gap = if run_step > 0.0 {
run_step
} else {
base_size * 1.2
};
let target = (target_idx < result.len())
.then(|| &mut result[target_idx])
.filter(|prev| {
let prev_text = prev.text();
let prev_trimmed = prev_text.trim();
// A hyphen on the line above means the target resumes
// a split word, so it continues a paragraph rather
// than starting one (polkuja_ylakoulu: "ylakou-" +
// "lulaisten").
//
// Case cannot serve as a continuation signal here: the
// target legitimately starts lowercase, because the
// cap removes the word's first letter and leaves
// "ver the course..." for "Over".
let continues_previous = before_target
.as_ref()
.is_some_and(|(b, _)| b.ends_with('-'));
// The target must START a paragraph: extra leading
// above it, a completed sentence on the line above, or
// nothing above it at all.
let starts_paragraph = match before_target.as_ref() {
None => true,
Some((text, y)) => {
y - prev.y > step_for_gap * 1.15 || ends_sentence(text)
}
};
!continues_previous
&& starts_paragraph
&& prev.page == line.page
&& prev.y > line_y
// Indented past the cap glyph, not merely to its
// right by an arbitrary amount.
&& prev
.items
.first()
.is_some_and(|i| i.x > cap_x && i.x - cap_x <= first.font_size * 2.0)
// Body text, so headings, labels and table
// fragments are never rewritten.
&& prev_trimmed
.chars()
.next()
.is_some_and(char::is_alphabetic)
&& prev_trimmed.chars().filter(|c| c.is_alphabetic()).count() >= 8
});
if let Some(prev_line) = target {
if let Some(first_item) = prev_line.items.first_mut() {
// A mid-word cap ("T" + "HE recent") joins directly.
// Leading whitespace only marks a word boundary when
// the cap is itself a single-letter word, since the
// paragraph's indent can also arrive as whitespace.
const SINGLE_LETTER_WORDS: &[char] = &['A', 'I', 'O', 'U', 'Y', 'E'];
let had_leading_ws = first_item.text.starts_with(char::is_whitespace)
&& SINGLE_LETTER_WORDS.contains(&drop_char);
let rest = first_item.text.trim_start().to_string();
first_item.text = if had_leading_ws {
format!("{} {}", drop_char, rest)
} else {
format!("{}{}", drop_char, rest)
};
}
let mut line = line.clone();
line.items.remove(0);
result.push(line);
continue;
}
}
}
if is_drop_cap {
let drop_char = trimmed.chars().next().unwrap();
@@ -598,6 +816,314 @@ mod tests {
}
}
fn make_item_at(text: &str, font_size: f32, x: f32) -> TextItem {
let mut item = make_item(text, font_size, None);
item.x = x;
item.width = text.len() as f32 * font_size * 0.5;
item
}
#[test]
fn embedded_drop_cap_moves_to_paragraph_start() {
// A two-line cap baseline-aligns with the paragraph's SECOND line,
// so it lands as that line's first item (Shannon entropy.pdf p.1).
let first_line = TextLine {
items: vec![make_item_at(
"HE recent development which exchange",
10.0,
90.0,
)],
// 16pt baseline step under a 25pt cap: a genuine two-line cap.
y: 716.0,
page: 1,
adaptive_threshold: 0.10,
};
let second_line = TextLine {
items: vec![
make_item_at("T", 25.0, 72.0),
make_item_at("bandwidth for signal-to-noise ratio", 10.0, 90.0),
],
y: 700.0,
page: 1,
adaptive_threshold: 0.10,
};
let result = merge_drop_caps(vec![first_line, second_line], 10.0);
assert_eq!(result.len(), 2);
assert!(
result[0].text().starts_with("THE recent"),
"cap should prepend to the paragraph start: {}",
result[0].text()
);
assert!(
result[1].text().starts_with("bandwidth"),
"cap must be removed from the second line: {}",
result[1].text()
);
}
#[test]
fn embedded_drop_cap_walks_a_multi_line_initial_to_the_paragraph_start() {
// A 47pt initial over 13pt leading covers four lines, so the
// paragraph's first line is three lines above the cap rather than
// immediately above it (polkuja_ylakoulu). The indented run, not the
// cap's em size, is what locates it.
let mut lines = vec![TextLine {
items: vec![make_item_at("Previous paragraph ends here.", 10.0, 72.0)],
y: 766.0,
page: 1,
adaptive_threshold: 0.10,
}];
for (i, text) in [
"rilaiset mediasisallot ovat tarkea osa",
"useimpien ylakoululaisten elamaa ja",
"muuta tekstia jatkuu tassa viela",
]
.iter()
.enumerate()
{
lines.push(TextLine {
items: vec![make_item_at(text, 10.0, 90.0)],
y: 753.0 - 13.0 * i as f32,
page: 1,
adaptive_threshold: 0.10,
});
}
lines.push(TextLine {
items: vec![
make_item_at("E", 47.0, 72.0),
make_item_at("loppuosa tekstista tassa", 10.0, 90.0),
],
y: 714.0,
page: 1,
adaptive_threshold: 0.10,
});
let result = merge_drop_caps(lines, 10.0);
assert!(
result[1].text().starts_with("Erilaiset"),
"cap belongs on the topmost line of the indented run: {}",
result[1].text()
);
assert!(
result[2].text().starts_with("useimpien"),
"intervening run lines must be untouched: {}",
result[2].text()
);
assert!(
result[4].text().starts_with("loppuosa"),
"cap must be removed from its own line: {}",
result[4].text()
);
}
#[test]
fn embedded_drop_cap_ignores_non_paragraph_neighbours() {
// Same geometry, but the preceding line is a short label rather than
// body text, so it must not be rewritten.
let label = TextLine {
items: vec![make_item_at("Fig. 2", 10.0, 90.0)],
y: 716.0,
page: 1,
adaptive_threshold: 0.10,
};
let second_line = TextLine {
items: vec![
make_item_at("T", 25.0, 72.0),
make_item_at("bandwidth for signal-to-noise ratio", 10.0, 90.0),
],
y: 700.0,
page: 1,
adaptive_threshold: 0.10,
};
let result = merge_drop_caps(vec![label, second_line], 10.0);
assert_eq!(result[0].text().trim(), "Fig. 2");
assert!(
result[1].text().starts_with('T'),
"cap stays put: {}",
result[1].text()
);
}
#[test]
fn embedded_drop_cap_keeps_a_space_for_standalone_word_caps() {
// Leading whitespace on the paragraph's first item marks the cap as
// a word of its own rather than the first letter of one.
let mut lead = make_item_at("long time ago in a galaxy far away", 10.0, 90.0);
lead.text = " long time ago in a galaxy far away".to_string();
let first_line = TextLine {
items: vec![lead],
y: 716.0,
page: 1,
adaptive_threshold: 0.10,
};
let second_line = TextLine {
items: vec![
make_item_at("A", 25.0, 72.0),
make_item_at("continued here with more body text", 10.0, 90.0),
],
y: 700.0,
page: 1,
adaptive_threshold: 0.10,
};
let result = merge_drop_caps(vec![first_line, second_line], 10.0);
assert!(
result[0].text().starts_with("A long time ago"),
"standalone-word cap keeps one space: {}",
result[0].text()
);
}
#[test]
fn embedded_drop_cap_skips_hyphenation_continuation_targets() {
// The line above the RUN ends on a hyphen, so the run's topmost line
// resumes a split word rather than starting a paragraph. It sits at
// the paragraph margin (x=72), outside the cap's indent, so it is not
// part of the run itself.
let split_word = TextLine {
items: vec![make_item_at(
"mediasisallot ovat osa useimpien ylakou-",
10.0,
72.0,
)],
y: 728.0,
page: 1,
adaptive_threshold: 0.10,
};
let run_top = TextLine {
items: vec![make_item_at(
"lulaisten elamaa ja muuta tekstia",
10.0,
90.0,
)],
y: 714.0,
page: 1,
adaptive_threshold: 0.10,
};
let cap_line = TextLine {
items: vec![
make_item_at("E", 25.0, 72.0),
make_item_at("jatkuu tassa lisaa leipatekstia", 10.0, 90.0),
],
y: 700.0,
page: 1,
adaptive_threshold: 0.10,
};
let result = merge_drop_caps(vec![split_word, run_top, cap_line], 10.0);
assert!(
result[1].text().starts_with("lulaisten"),
"a run resuming a split word must not receive the cap: {}",
result[1].text()
);
assert!(
result[2].text().starts_with('E'),
"cap stays put when no valid target exists: {}",
result[2].text()
);
}
#[test]
fn embedded_drop_cap_indent_is_not_a_word_boundary() {
// The paragraph's first line is indented to clear the cap, and that
// indent can arrive as leading whitespace. A mid-word cap must still
// join directly — "T HE recent" would be the defect this fixes.
let mut lead = make_item_at("HE recent development and more body text", 10.0, 90.0);
lead.text = " HE recent development and more body text".to_string();
let first_line = TextLine {
items: vec![lead],
y: 716.0,
page: 1,
adaptive_threshold: 0.10,
};
let cap_line = TextLine {
items: vec![
make_item_at("T", 25.0, 72.0),
make_item_at("bandwidth for signal-to-noise ratio", 10.0, 90.0),
],
y: 700.0,
page: 1,
adaptive_threshold: 0.10,
};
let result = merge_drop_caps(vec![first_line, cap_line], 10.0);
assert!(
result[0].text().starts_with("THE recent"),
"indent must not be read as a word boundary: {}",
result[0].text()
);
}
#[test]
fn ends_sentence_rejects_abbreviations_and_markers() {
use super::ends_sentence;
assert!(ends_sentence("This completes the thought."));
assert!(ends_sentence("Is that so?"));
assert!(ends_sentence("Stop!"));
// Periods that do not end a sentence.
assert!(!ends_sentence("as shown in Fig."));
assert!(!ends_sentence("see e.g."));
// Non-ASCII abbreviations. The two-CHARACTER segment is the case
// that distinguishes a character count from a byte count: "пр" is
// 2 chars but 4 bytes, so a byte-based bound would reject it and
// read the line as a completed sentence.
assert!(!ends_sentence("и т.пр."));
assert!(!ends_sentence("см. т.е."));
assert!(!ends_sentence("napr. ú.d."));
assert!(!ends_sentence("reviewed by Dr."));
// Standalone enumerators, any case.
assert!(!ends_sentence("1."));
assert!(!ends_sentence("IV."));
assert!(!ends_sentence("ii."));
assert!(!ends_sentence("xii."));
// Numbers and numerals that genuinely end a sentence must count,
// or a legitimate drop-cap merge is blocked.
assert!(ends_sentence("The paper was published in 2020."));
assert!(ends_sentence("He scored 5."));
assert!(ends_sentence("after World War II."));
assert!(ends_sentence("the constant equals 3.14."));
assert!(ends_sentence("documented at example.com."));
assert!(!ends_sentence("a trailing clause with no period"));
}
#[test]
fn embedded_drop_cap_allows_first_paragraph_on_a_new_page() {
// The line two back is on the previous page, so its y is unrelated
// and must not be used as leading evidence.
let prev_page_tail = TextLine {
items: vec![make_item_at(
"tail of the previous page body text",
10.0,
90.0,
)],
y: 90.0,
page: 1,
adaptive_threshold: 0.10,
};
let first_line = TextLine {
items: vec![make_item_at(
"HE recent development which exchange",
10.0,
90.0,
)],
y: 716.0,
page: 2,
adaptive_threshold: 0.10,
};
let cap_line = TextLine {
items: vec![
make_item_at("T", 25.0, 72.0),
make_item_at("bandwidth for signal-to-noise ratio", 10.0, 90.0),
],
y: 700.0,
page: 2,
adaptive_threshold: 0.10,
};
let result = merge_drop_caps(vec![prev_page_tail, first_line, cap_line], 10.0);
assert!(
result[1].text().starts_with("THE recent"),
"a page break must not suppress the merge: {}",
result[1].text()
);
}
#[test]
fn test_merge_struct_tree_headings() {
// Two consecutive lines tagged as H2 via struct tree, same font size as body
+308 -10
View File
@@ -435,6 +435,72 @@ fn revised_table_cell_indices(
.collect()
}
/// Index of candidate "body" items (larger-font attachment targets) sorted by
/// Y, so script-attachment checks scan a narrow Y window instead of the whole
/// page per candidate.
struct ScriptBodyIndex<'a> {
/// (y, item), sorted ascending by y
by_y: Vec<(f32, &'a TextItem)>,
/// widest vertical attachment window any body item can produce
max_window: f32,
}
impl<'a> ScriptBodyIndex<'a> {
fn new(items: &'a [TextItem]) -> Self {
// Smallest table-candidate font is 6pt, so any possible attachment
// target is at least 6 x 1.2 pt.
let mut by_y: Vec<(f32, &TextItem)> = items
.iter()
.filter(|i| i.font_size >= 6.0 * 1.2)
.map(|i| (i.y, i))
.collect();
by_y.sort_by(|a, b| a.0.total_cmp(&b.0));
let max_window = by_y
.iter()
.map(|(_, i)| i.font_size * 0.8)
.fold(0.0f32, f32::max);
Self { by_y, max_window }
}
/// True when a small-font item is horizontally attached to a larger-font
/// item at a script baseline offset — a sub/superscript in running text
/// or math (equation subscripts, footnote markers). Script attachments
/// are not table cells; without this filter, display equations with
/// sub/superscripts form phantom small-font table regions (e.g. TeX
/// papers where log subscripts cluster with footnote lines into a fake
/// 3-column table). A genuine baseline offset is required so same-line
/// table neighbours (a small cell beside a larger label cell) are never
/// classified as scripts.
///
/// `min_anchor_size` additionally constrains what counts as an
/// attachment target: the small-font pass accepts any sufficiently
/// larger item (0.0), while the body-font pass requires a heading-sized
/// anchor so a body-size table cell beside a slightly larger label with
/// baseline jitter is never treated as a script.
fn is_script_attachment(&self, small: &TextItem, min_anchor_size: f32) -> bool {
let attach_gap = small.font_size.max(4.0) * 0.6;
let lo = self
.by_y
.partition_point(|(y, _)| *y < small.y - self.max_window);
self.by_y[lo..]
.iter()
.take_while(|(y, _)| *y <= small.y + self.max_window)
.any(|(_, body)| {
let dy = (small.y - body.y).abs();
body.font_size >= small.font_size * 1.2
&& body.font_size >= min_anchor_size
&& dy > body.font_size * 0.05
&& dy <= body.font_size * 0.8
&& {
let gap_after_body = small.x - (body.x + body.width);
let gap_before_body = body.x - (small.x + small.width);
(-attach_gap..=attach_gap).contains(&gap_after_body)
|| (-attach_gap..=attach_gap).contains(&gap_before_body)
}
})
}
}
/// Detect tables in a set of text items from a single page
pub fn detect_tables(items: &[TextItem], base_font_size: f32, skip_body_font: bool) -> Vec<Table> {
detect_tables_with_page_width(items, base_font_size, skip_body_font, content_width(items))
@@ -483,6 +549,27 @@ pub(crate) fn detect_tables_with_page_width(
// === Pass 1: Small-font tables (existing behavior) ===
let table_font_threshold = base_font_size * 0.90;
// Mark sub/superscript attachments once per pass. They stay candidates —
// the masks only remove them from region qualification and column/row
// geometry.
//
// The two passes need different anchor thresholds. In the small-font pass
// any sufficiently larger neighbour is a plausible base for a script. In
// the body-font pass the candidates are themselves body-sized
// (0.85..1.05x), so a merely "slightly larger" neighbour is usually a bold
// label or an adjacent column header, not the base of a superscript —
// treating it as one would strip real cells out of the geometry and lose
// the table. Requiring a heading-sized anchor (>= 1.15x base) keeps the
// body pass to genuine scripts hanging off headings.
let script_index = ScriptBodyIndex::new(items);
let script_flags: Vec<bool> = items
.iter()
.map(|item| script_index.is_script_attachment(item, 0.0))
.collect();
let body_script_flags: Vec<bool> = items
.iter()
.map(|item| script_index.is_script_attachment(item, base_font_size * 1.15))
.collect();
let table_candidates: Vec<(usize, &TextItem)> = items
.iter()
.enumerate()
@@ -494,7 +581,14 @@ pub(crate) fn detect_tables_with_page_width(
.collect();
if table_candidates.len() >= 6 {
let regions = find_table_regions(&table_candidates);
// Qualify regions from non-script items: a cluster of sub/superscripts
// must not, on its own, mark out a table region.
let region_evidence: Vec<(usize, &TextItem)> = table_candidates
.iter()
.filter(|(idx, _)| !script_flags[*idx])
.cloned()
.collect();
let regions = find_table_regions(&region_evidence);
for (y_min, y_max) in regions {
let region_items: Vec<(usize, &TextItem)> = table_candidates
@@ -508,7 +602,9 @@ pub(crate) fn detect_tables_with_page_width(
}
if let Some(mut table) =
detect_table_in_region(&region_items, TableDetectionMode::SmallFont)
detect_table_in_region(&region_items, TableDetectionMode::SmallFont, &|i| {
script_flags[i]
})
{
// Try to recover body-font header row above the small-font table
recover_header_row(&mut table, items, table_font_threshold);
@@ -553,8 +649,20 @@ pub(crate) fn detect_tables_with_page_width(
body_font_low,
body_font_high,
);
// Scripts are NOT filtered out of the candidate set here, mirroring
// the small-font pass: they must stay eligible for cell assignment so
// a sub/superscript that belongs inside a table cell keeps its text.
// The heading-anchored `body_script_flags` mask removes them from
// geometry only.
if body_candidates.len() >= 6 {
let regions = find_table_regions_strict(&body_candidates);
// Same reasoning as the small-font pass: scripts do not qualify
// regions, but remain available for cell assignment within one.
let region_evidence: Vec<(usize, &TextItem)> = body_candidates
.iter()
.filter(|(idx, _)| !body_script_flags[*idx])
.cloned()
.collect();
let regions = find_table_regions_strict(&region_evidence);
log::debug!("body-font: {} strict regions found", regions.len());
for (y_min, y_max, _x_min, _x_max) in &regions {
@@ -580,7 +688,9 @@ pub(crate) fn detect_tables_with_page_width(
}
if let Some(table) =
detect_table_in_region(&region_items, TableDetectionMode::BodyFont)
detect_table_in_region(&region_items, TableDetectionMode::BodyFont, &|i| {
body_script_flags[i]
})
{
tables.push(table);
}
@@ -808,10 +918,30 @@ fn find_table_regions_strict(items: &[(usize, &TextItem)]) -> Vec<(f32, f32, f32
regions
}
/// Detect a table within a specific region
fn detect_table_in_region(items: &[(usize, &TextItem)], mode: TableDetectionMode) -> Option<Table> {
// Find column boundaries
let columns = find_column_boundaries(items, mode);
/// Detect a table within a specific region.
///
/// `is_script` marks items that are sub/superscript attachments. Those are
/// excluded from the *geometry* — they must not be able to create a column,
/// which is how equation subscript clusters used to fabricate phantom grids —
/// but they remain eligible for cell assignment, so legitimate cell content
/// (exponents in an engineering-notation table, footnote markers) stays in
/// the cell it belongs to instead of leaking out into the reading order.
fn detect_table_in_region(
items: &[(usize, &TextItem)],
mode: TableDetectionMode,
is_script: &dyn Fn(usize) -> bool,
) -> Option<Table> {
// Column geometry from non-script items only.
let geometry_items: Vec<(usize, &TextItem)> = items
.iter()
.filter(|(idx, _)| !is_script(*idx))
.cloned()
.collect();
// A region that is *entirely* scripts has no table structure at all.
if geometry_items.is_empty() {
return None;
}
let columns = find_column_boundaries(&geometry_items, mode);
let min_cols = 2;
if columns.len() < min_cols || columns.len() > 25 {
log::debug!(
@@ -822,8 +952,8 @@ fn detect_table_in_region(items: &[(usize, &TextItem)], mode: TableDetectionMode
return None;
}
// Find row boundaries
let rows = find_row_boundaries(items);
// Find row boundaries (geometry items only, same reasoning)
let rows = find_row_boundaries(&geometry_items);
let min_rows = 2;
if rows.len() < min_rows {
log::debug!(
@@ -842,6 +972,11 @@ fn detect_table_in_region(items: &[(usize, &TextItem)], mode: TableDetectionMode
);
// Verify this looks like a table: multiple items should align to columns
// Validate against ALL items, including scripts. Columns are derived from
// non-script geometry so scripts cannot *create* a column, but excluding
// them from validation too would let a region manufacture alignment: drop
// the awkward items and whatever remains looks like a tidy grid. Block
// diagrams did exactly that. Everything in the region must fit.
let col_alignment = check_column_alignment(items, &columns, mode);
let min_alignment = match mode {
TableDetectionMode::SmallFont => 0.5,
@@ -912,6 +1047,29 @@ fn detect_table_in_region(items: &[(usize, &TextItem)], mode: TableDetectionMode
cells.push(row_cells);
}
// Validation 0 (small-font pass only): reject tiny all-numeric
// fragments. A <=2-row grid whose every cell is a bare 1-2 digit number
// carries no tabular information — in practice these are
// exponent/subscript clusters from display math that happen to align.
// Body-font tables are not subject to this veto: their cells cannot be
// script glyphs.
if matches!(mode, TableDetectionMode::SmallFont) {
let nonempty_cells: Vec<&String> =
cells.iter().flatten().filter(|c| !c.is_empty()).collect();
if rows.len() <= 2
&& !nonempty_cells.is_empty()
&& nonempty_cells
.iter()
.all(|c| c.len() <= 2 && c.chars().all(|ch| ch.is_ascii_digit()))
{
log::debug!(
" validation 0 fail: tiny all-numeric fragment ({} cells)",
nonempty_cells.len()
);
return None;
}
}
// Validation 1: some rows should have content in first column.
// Use a lower threshold (25%) for tables with wrapped cells where
// continuation lines leave the first column empty.
@@ -1977,6 +2135,146 @@ fn try_add_label_column(
#[cfg(test)]
mod tests {
fn make_item(text: &str, x: f32, y: f32, font_size: f32, width: f32) -> TextItem {
TextItem {
text: text.to_string(),
x,
y,
width,
height: font_size,
font: "TestFont".to_string(),
font_size,
page: 1,
is_bold: false,
is_italic: false,
is_underline: false,
is_strikeout: false,
item_type: ItemType::Text,
mcid: None,
}
}
#[test]
fn script_attachment_detects_subscript_after_body_text() {
let body = make_item("log", 100.0, 500.0, 10.0, 15.0);
let sub = make_item("10", 115.5, 497.0, 7.0, 7.0);
let items = vec![body, sub.clone()];
assert!(ScriptBodyIndex::new(&items).is_script_attachment(&sub, 0.0));
}
#[test]
fn script_attachment_detects_superscript_footnote_marker() {
let body = make_item("Hartley", 200.0, 500.0, 10.0, 35.0);
let sup = make_item("2", 235.8, 504.0, 6.6, 3.5);
let items = vec![body, sup.clone()];
assert!(ScriptBodyIndex::new(&items).is_script_attachment(&sup, 0.0));
}
#[test]
fn script_attachment_ignores_small_cell_far_from_body_text() {
let body = make_item("Revenue", 100.0, 500.0, 10.0, 40.0);
let cell = make_item("1,234", 180.0, 500.0, 7.0, 20.0);
let items = vec![body, cell.clone()];
assert!(!ScriptBodyIndex::new(&items).is_script_attachment(&cell, 0.0));
}
#[test]
fn body_pass_anchor_spares_cells_beside_slightly_larger_labels() {
// A body-font table cell (10pt) sitting beside a slightly larger,
// NON-heading label (12.5pt) with a little baseline jitter. The
// small-font pass treats any larger neighbour as a possible script
// base, but the body pass must not: at body sizes a slightly larger
// neighbour is a bold label or column header, and flagging the cell
// would strip it out of the table geometry and lose the table.
// Cell at the low end of the body band (0.85x base) beside a 10.5pt
// label. 10.5 clears the inherent 1.2x-of-cell rule (10.2) but falls
// below the body pass's heading anchor (11.5), which is exactly the
// band where the two masks must disagree.
let label = make_item("Revenue", 100.0, 500.0, 10.5, 40.0);
let cell = make_item("1,234", 141.0, 496.5, 8.5, 22.0);
let items = vec![label, cell.clone()];
let index = ScriptBodyIndex::new(&items);
let base = 10.0;
assert!(
index.is_script_attachment(&cell, 0.0),
"small-font pass anchor should still see this as an attachment"
);
assert!(
!index.is_script_attachment(&cell, base * 1.15),
"body pass must not treat a cell beside a slightly larger label \
as a script — that removes real cells from the geometry"
);
// A genuine heading-sized anchor still qualifies in the body pass.
let heading = make_item("Section", 100.0, 500.0, 20.0, 60.0);
let sup = make_item("3", 161.0, 508.0, 10.0, 5.0);
let h_items = vec![heading, sup.clone()];
assert!(
ScriptBodyIndex::new(&h_items).is_script_attachment(&sup, base * 1.15),
"script hanging off a heading must still be excluded in the body pass"
);
}
#[test]
fn script_attachment_ignores_same_baseline_neighbor_cell() {
// A small cell beside a larger label on the SAME baseline is a table
// layout, not a subscript — a genuine baseline offset is required.
let label = make_item("Total", 100.0, 500.0, 10.0, 25.0);
let cell = make_item("42", 127.0, 500.0, 7.5, 9.0);
let items = vec![label, cell.clone()];
assert!(!ScriptBodyIndex::new(&items).is_script_attachment(&cell, 0.0));
}
#[test]
fn script_attachment_ignores_neighbor_on_different_line() {
let body = make_item("Header", 100.0, 500.0, 10.0, 30.0);
let cell = make_item("42", 131.0, 486.0, 7.0, 10.0);
let items = vec![body, cell.clone()];
assert!(!ScriptBodyIndex::new(&items).is_script_attachment(&cell, 0.0));
}
/// Equation-subscript + footnote layout from Shannon entropy.pdf page 1,
/// with real coordinates. Without the larger-font anchors the small items
/// alone DO form a phantom table — proving the layout reaches detection —
/// and adding the anchors must suppress it.
fn shannon_page1_small_items() -> Vec<TextItem> {
vec![
make_item("2", 267.4, 133.9, 7.4, 3.7),
make_item("10", 306.2, 133.9, 7.4, 7.4),
make_item("10", 342.7, 133.9, 7.4, 7.4),
make_item("10", 325.0, 118.9, 7.4, 7.4),
make_item("Bell System Technical Journal,", 295.7, 101.9, 8.0, 95.0),
make_item(
"April 1924, p. 324; Certain Topics in",
396.7,
101.9,
8.0,
130.0,
),
make_item("v. 47, April 1928, p. 617.", 250.9, 92.5, 8.0, 90.0),
make_item("Bell System Technical Journal,", 264.2, 82.6, 8.0, 95.0),
make_item("July 1928, p. 535.", 364.3, 82.6, 8.0, 65.0),
]
}
#[test]
fn equation_scripts_do_not_form_phantom_table() {
let bare = shannon_page1_small_items();
assert!(
!detect_tables(&bare, 10.0, false).is_empty(),
"test layout must form a phantom table when the filter cannot fire"
);
let mut items = shannon_page1_small_items();
items.push(make_item("log", 253.0, 137.0, 10.0, 13.5));
items.push(make_item("log", 291.5, 137.0, 10.0, 13.5));
items.push(make_item("log", 328.0, 137.0, 10.0, 13.5));
items.push(make_item("log", 310.3, 122.0, 10.0, 13.5));
let tables = detect_tables(&items, 10.0, false);
assert!(
tables.is_empty(),
"equation scripts + footnotes must not become a table: {tables:?}"
);
}
use super::*;
use crate::types::ItemType;
+3 -7
View File
@@ -1,16 +1,12 @@
Reprinted with corrections from *The Bell System Technical Journal,* Vol. 27, pp. 379423, 623656, July, October, 1948.
## A Mathematical Theory of Communication
# A Mathematical Theory of Communication
### By C. E. SHANNON
## By C. E. SHANNON
INTRODUCTION
HE recent development of various methods of modulation such as PCM and PPM which exchange
# Tbandwidth for signal-to-noise ratio has intensified the interest in a general theory of communication. A
basis for such a theory is contained in the important papers of Nyquist¹ and Hartley² on this subject. In the present paper we will extend the theory to include a number of new factors, in particular the effect of noise in the channel, and the savings possible due to the statistical structure of the original message and due to the nature of the final destination of the information. The fundamental problem of communication is that of reproducing at one point either exactly or ap- proximately a message selected at another point. Frequently the messages have *meaning*; that is they refer to or are correlated according to some system with certain physical or conceptual entities. These semantic aspects of communication are irrelevant to the engineering problem. The significant aspect is that the actual message is one *selected from a set* of possible messages. The system must be designed to operate for each possible selection, not just the one which will actually be chosen since this is unknown at the time of design. If the number of messages in the set is finite then this number or any monotonic function of this number can be regarded as a measure of the information produced when one message is chosen from the set, all choices being equally likely. As was pointed out by Hartley the most natural choice is the logarithmic function. Although this definition must be generalized considerably when we consider the influence of the statistics of the message and when we have a continuous range of messages, we will in all cases use an essentially logarithmic measure. The logarithmic measure is more convenient for various reasons:
THE recent development of various methods of modulation such as PCM and PPM which exchange bandwidth for signal-to-noise ratio has intensified the interest in a general theory of communication. A basis for such a theory is contained in the important papers of Nyquist¹ and Hartley² on this subject. In the present paper we will extend the theory to include a number of new factors, in particular the effect of noise in the channel, and the savings possible due to the statistical structure of the original message and due to the nature of the final destination of the information. The fundamental problem of communication is that of reproducing at one point either exactly or ap- proximately a message selected at another point. Frequently the messages have *meaning*; that is they refer to or are correlated according to some system with certain physical or conceptual entities. These semantic aspects of communication are irrelevant to the engineering problem. The significant aspect is that the actual message is one *selected from a set* of possible messages. The system must be designed to operate for each possible selection, not just the one which will actually be chosen since this is unknown at the time of design. If the number of messages in the set is finite then this number or any monotonic function of this number can be regarded as a measure of the information produced when one message is chosen from the set, all choices being equally likely. As was pointed out by Hartley the most natural choice is the logarithmic function. Although this definition must be generalized considerably when we consider the influence of the statistics of the message and when we have a continuous range of messages, we will in all cases use an essentially logarithmic measure. The logarithmic measure is more convenient for various reasons:
1. It is practically more useful. Parameters of engineering importance such as time, bandwidth, number of relays, etc., tend to vary linearly with the logarithm of the number of possibilities. For example, adding one relay to a group doubles the number of possible states of the relays. It adds 1 to the base 2 logarithm of this number. Doubling the time roughly squares the number of possible messages, or doubles the logarithm, etc.
2. It is nearer to our intuitive feeling as to the proper measure. This is closely related to (1) since we in- tuitively measures entities by linear comparison with common standards. One feels, for example, that two punched cards should have twice the capacity of one for information storage, and two identical channels twice the capacity of one for transmitting information.