Documentation
¶
Overview ¶
Package layout infers roles from geometry and typography, for the documents that declare none.
Most PDFs are untagged, so for most PDFs there is no structure tree to read a heading rank out of. extract deliberately stops short of guessing: it marks every non-artifact block RoleParagraph and leaves rank to whichever package has the most evidence. Where a tree exists that is sectionize. Where none does it is here.
Why not "bold and larger means heading" ¶
The obvious rule is falsified by the corpus, and this package is shaped by how it fails. Measured over the untagged fixtures:
- pymupdf/v110-changes.pdf sets 8.04pt *bold* as 48.8% of its characters, against 49.4% at 9.96pt — so the body wins on size by half a point of margin while bold is not emphasis in that document at all, and a weight-implies-heading rule marks half of it. (Measured on the character tally rather than reached through this package: the file's headings fuse into the paragraphs after them, so nothing there is a candidate — see uniformStyle.)
- pymupdf/2201.00069.pdf (arXiv) and adobe-samples/autotagPDFInput.pdf set their headings *plain* — 11.96pt and 28pt respectively — and use bold only as inline emphasis, 0.3% and 0.5% of characters. A rule that requires bold finds nothing.
- pymupdf/dotted-gridlines.pdf has a table row at body size in bold, 41 characters of it. It is typographically indistinguishable from a real heading.
- testdata/reference/headings.pdf sets its third level at *body size* in bold, so a rule that requires a larger size loses the deepest level of the one fixture written to test heading depth.
So size and weight together cannot separate a heading from a bold table row, and neither can the space above it: on dotted-gridlines the gap above that row is 1.68 times the body size, inside the 1.60–1.96 range the reference headings occupy.
What the document states rather than implies ¶
A numbered heading carries its own rank. "4.2.1 Nested subclause" is level three because the document says so, not because 9.96pt happens to sit third in a size ladder. That inverts the usual arrangement: typography is the *gate* that admits a block as a candidate, and the section number is what assigns the level. An annex number does the same job with a letter for its first component — "B.2.3" is level three — which annexLevel reads and numberedLevel cannot.
Ranking by position in the size ladder was measured and rejected. pymupdf's mupdf_explored.pdf has five distinct above-body sizes — 24.79 chapter titles, 20.66 "Chapter 1" labels, 17.22 the book title, 14.35 sections, 11.96 the author line and part entries — of which only some are heading levels at all. Ranking by ladder position disagreed with the document's own numbering on 296 of 296 numbered headings, because it counts rungs that are not levels. Numbering is not a heuristic about the document; it is the document's statement, so it wins.
For a long time the cost was that unnumbered headings stayed paragraphs: the fixtures showed no signal in the candidate itself that admits "Preface" without also admitting a bold table row. The section after next is what closed that.
Two candidate signals for that limit were measured and rejected, which is worth stating so neither is proposed again as though it were untried. *Recurrence* — promote a style that heads a block on many pages, not on one — was ADR 0008's own suggestion, and the corpus falsifies it in both directions: of the 151 unnumbered above-body candidates on the untagged path, 9 occur once and include real titles ("MARKET SUMMARY & PLAN", chinese-tables.pdf's "第七章 企业资信状况"), while the repeated ones include mupdf_explored.pdf's "Robin Watts" and "September 5, 2022" at 9 occurrences over 7 pages. Rank and repetition are independent of each other here. A *size ratio* threshold fails the same way: joined to what producers declare, the 287 unnumbered above-body candidates on the tagged corpus peak at 73.2% precision around 1.17 and fall to 6% by 1.63, because a title page's 3.4x masthead is not a heading and a 1.08x subclause is. There is no gap in that distribution to put a threshold in.
What follows an unnumbered heading ¶
Both rejected signals look at the candidate. What separates a heading from a bold table row is what comes after it. A heading heads body text: a long paragraph in lighter type that starts where the heading does. A table row is followed by a row, a masthead by an author line, and a "Chapter 1" label by the chapter's title. headsBody is that test, and it may pass over numbered subheadings on the way to the body.
Measured against the producers' declarations on the tagged corpus, it promotes unnumbered headings at 0.914 precision, where promoting every candidate scored 0.116 (ADR 0031). Its level comes from the numbered headings set in its style, or else from its style's rank.
Index ¶
- Variables
- func Decoration(im doc.Image) string
- func Footnotes(d *doc.Document) int
- func Furniture(d *doc.Document) int
- func Hyphens(d *doc.Document) int
- func ImageBlocks(im *doc.Image) []doc.Block
- func ImageSlot(blocks []doc.Block, box geom.Rect) int
- func Keep(d *doc.Document) [][]bool
- func PageBreaks(d *doc.Document) int
- func PlaceImage(p *doc.Page, im *doc.Image)
- type ImageStats
- type ListStats
- type Options
- type Stats
- type TableStats
Constants ¶
This section is empty.
Variables ¶
var DefaultOptions = Options{MaxHeading: 80, MaxLevel: 6, ListStep: 1.0}
DefaultOptions is inference as the CLI runs it.
ListStep of 1.0 sits in the middle of an empty band rather than at a tuned point. Measured over every PDF on disk, a marker run contains only eight distinct left-edge gaps in total: six at 0.011 type sizes, one at 0.241, and one at 2.403. The first seven are the same tier — float noise in a shared margin, and ISO 32000-2's PDFDocEncoding table where two adjacent rows open with an em dash and an en dash of different widths — while the last is reference/lists.pdf's genuine `itemize` nesting. Anything from roughly 0.3 to 2.4 yields the same result, so 1.0 is a statement that nesting indents by about a character, not a threshold fitted to a trough.
Functions ¶
func Decoration ¶ added in v1.0.0
Decoration says why im is decoration on its own, whatever page it is on: "artifact", "small" or "fill", or "" when it is not. The tagged path asks it too, so a structure tree that tags a swatch as a Figure does not put it in the output.
func Footnotes ¶ added in v1.0.0
Footnotes finds an untagged page's footnotes, in place, and returns how many it found.
A footnote is two pieces of text far apart: a mark raised above the line it sits in and set smaller, and a note at the foot of the page that opens with the same mark, raised and smaller in its own turn. Either alone is weak evidence. A raised small digit is as often an exponent or a unit, and a small paragraph at the foot is as often a caption or an address. So a note is taken only where the page has both:
- a block below all the page's other text whose lines open with marks, cut into one note at each such line;
- a mark in the page's text with the same label, the first one not already taken.
A raised mark sits a quarter of its line's size or more above the line's foot, and is set at no more than 0.8 of the line's size. In reference/footnotes.pdf that is 4.2pt up in a 9.96pt line, at 6.97pt, and the same shape one size down in the notes (ADR 0036).
A note becomes a RoleFootnote whose Note is its label and Marker its mark, the mark taken from its text; the mark in the text keeps its own characters and gains the label in Span.Note. A label is the mark's number, with its page added where an earlier page used the number already. A mark that is not a number becomes "fn" and a count, since a GFM label of "*" would be read as emphasis.
Runs before PageBreaks, which passes over notes, so a paragraph continued past a page with footnotes is still joined.
func Furniture ¶ added in v1.0.0
Furniture marks an untagged document's running headers, running footers and folios as artifacts in place, and returns how many blocks it marked.
A tagged producer wraps its furniture in an Artifact, and extract drops it. An untagged page says nothing about it, but the document does: furniture is text in the top or bottom margin that recurs from page to page, changing only its numbers. So a block lying wholly in a margin band is furniture when its text, with each number made one symbol, is found in the same band on another page.
Measured against the tagged corpus, whose producers mark their furniture as artifacts (ADR 0033): 3538 of 3572 artifact blocks found, and 11 blocks marked that are not. A band of 15% of the page admitted 399 more false ones, and making every digit one symbol, rather than every number, joined footnotes whose URLs differ only in digits and split folios set in roman numerals.
One page is no evidence, so a one-page document keeps everything. A block already an artifact, as md -artifacts keeps a tagged producer's, is neither counted nor marked again. Runs before the other passes, so a header is never a heading and a folio never a cell.
func Hyphens ¶ added in v1.0.0
Hyphens removes the hyphens a typesetter put at line ends, in place, and returns how many it removed.
Extract keeps every hyphen that ends a line after a letter, and joins the next line to it with no space (dashHoldsTheWord), because it cannot tell "exten-|sive" from "cross-|reference" and a hyphen deleted in error is not recoverable from the output. The document can tell them apart, because it is the only dictionary there is. A hyphen before a lower-case letter is dropped when either of these holds:
- the document spells the joined word elsewhere, and never the hyphenated one: "configura-| tion" against "configuration";
- neither half is a word anywhere in the document: "exten-|sive". A compound's halves are words, "machine-|readable" aside.
Otherwise it stays, as the ambiguous case does (ADR 0035). Over the corpus the pass takes 249 hyphens from 11 files. Of the words that changed in md's output, 2 are compounds it wrongly joined, "machine-readable" and "sub-clauses", whose halves appear nowhere else in their documents. Four of the tagged standards mark their typesetter's hyphens with /ActualText, which sectionize already applies; the pass takes all 15 of those on its own. The case it leaves alone is a break with a word for either half, such as "over-|lap" or "insert-|ing", which no reading of the document can tell from a compound.
A soft hyphen at a line end is a typesetter's by definition, and always goes.
The words counted leave out any that crosses a line start, so a hyphen being judged is not its own evidence, and running the pass again, after PageBreaks has made line starts of its own, judges the rest the same way.
func ImageBlocks ¶ added in v1.0.0
ImageBlocks is what stands in for im (ADR 0046): the paragraphs or the cells read off it, for text and a table; its line, "[tag: description]", for a picture; its line and then its table of values for a chart; and "image" when nothing was read. The tagged path asks it too.
func ImageSlot ¶ added in v1.0.1
ImageSlot is where an image at box goes among one page's blocks, in their reading order: the index of the first block below the image's top that shares its columns, or the one after the last block above it that does, or the end. The tagged path asks it too, for an image no structure element claims, so that both paths put one image in one place.
func Keep ¶ added in v1.0.0
Keep reports, for each page and each of its images, whether Images places it: what is worth reading off the page, since what is decoration is not (ADR 0046).
func PageBreaks ¶ added in v1.0.0
PageBreaks joins a paragraph that a page break cut in two, in place, and returns how many it joined.
It is extract's column rule (ADR 0030) at a page break, which extract cannot apply itself: a page is extracted alone, and an untagged page's running header stands between the halves until Furniture has marked it. So it runs after the other passes, and asks the same questions of the last paragraph before the break and the first after it, skipping artifacts:
- the first starts flush with its page's text, and is set at the same size;
- the last is at the foot of its page's text;
- and either the first starts lower case, or the last's last line runs to its page's right edge and the first starts in the face the last ends in.
The face is for a running header Furniture cannot see, because no other page repeats it: mupdf_explored.pdf's one page of chapter 27 sets its header flush, at the body's size, in italic, after a page that ends on a full line (ADR 0034).
The second half's spans join the first's block, each keeping its own Page, as the model carries a block across a break, and the break is a wrap: extract.WrapSpace decides the space. A paragraph across three pages, the middle one holding nothing else, is one block. The second half ends where one of its lines repeats the indent the first half opened with; see splitAtIndent.
Types ¶
type ImageStats ¶ added in v1.0.0
type ImageStats struct {
Placed, Artifacts, Small, Fills, Furniture, Read int
}
ImageStats counts what Images did.
func Images ¶ added in v1.0.0
func Images(d *doc.Document) ImageStats
Images places each image a page paints as a RoleImage block among the page's text blocks, before the first block whose top lies below the image's top and that shares its columns, and after every block above it. An image is left out when it is decoration:
- painted inside an /Artifact, the producer's statement that it is;
- under imageMinSide on its shorter side, or of imageMinSamples or fewer samples;
- furniture: the same size at the same place on 3 pages or more and half of them, a logo in a running header, where it covers under a quarter of the page, since every page of a scan is one image in the same place;
- already read: a scan under an invisible text layer, an OCR'd PDF, whose text is what the image says. Any invisible text over the image is the sign, since that is what an invisible text layer is for: pymupdf's two OCR'd fixtures lay 5 and 6 lines over a full-page scan, a few percent of it.
type ListStats ¶
type ListStats struct {
// Runs counts maximal sequences of consecutive list items.
Runs int
// Items counts blocks promoted to RoleListItem.
Items int
// MaxLevel is the deepest nesting assigned. One on every corpus fixture except
// reference/lists.pdf, which is the only document on disk with a nested list.
MaxLevel int
}
ListStats reports what Lists did. Quiet failure is the same risk as for Headings: a run that promotes nothing has not errored, and neither has one that promotes a table.
func Lists ¶
Lists promotes untagged blocks to RoleListItem in place, and reports what it did.
A block is a list item when it opens with a marker glyph as its own token. That is a weaker signal than the section number Headings runs on, and the reason it is usable anyway is that a bullet is not a character anyone sets in prose: measured over the corpus, of 1442 blocks opening with one of doc's marker glyphs, reading every ambiguous case leaves 5 that are not list items — all of them rows of ISO 32000-2's glyph tables in Annex A and D, where an em dash or en dash *is* the row's subject ("— 132 0x84 0204 U+2014 EM DASH"). At 5 in 1442 the population is 288:1 in favour of promoting, which is the inverse of the ratio that made DESIGN.md's lost-space defect not worth a rule.
The marker is removed, here and not in the sink ¶
Promoting a block to RoleListItem is the statement that its marker is structure rather than text, so the marker leaves the spans with it — into Block.Marker, which is where a sink that can render a label finds it. Leaving it in the text would mean every sink re-deriving the glyph allowlist to know which leading rune was the marker — the same split doc.Block warns against for space inference, half the policy in the model and half in the producer. It would also double the marker on the one sink that exists: markdown writes its own "- ".
Block.StripMarker does it, in doc rather than here, because this is no longer the only producer of a list item's marker: sectionize reads one the structure tree declares, and two copies of the allowlist is the same split one package further out. This is still the only place in *this* package that edits a block's text rather than its role.
Levels, and what was rejected ¶
Depth comes from the left edge, ranked within a maximal run of consecutive marker blocks. Ranking within the run rather than the page is what keeps two unrelated lists in different columns from being read as one nested list.
A minimum run length was measured and rejected. Requiring two consecutive marker blocks looks like the obvious guard against a stray table row, and it costs far too much: it drops 136 promotions across the corpus, and reading them shows they are overwhelmingly genuine — single-item lists, and multi-item lists that extract fused into one block ("■ machine-readable text presented in a declared language; ■ appropriate…"). It would have rejected 136 to catch about 3.
The fusion in that second group is a segmentation defect in extract rather than anything a role rule should paper over, and it was investigated rather than left as a suspicion: 98 line pairs across 6 files, of which exactly one reaches the emitted output, because every other affected file is tagged and sectionize splits its items from the structure tree before a sink sees them. Both fixes that suggest themselves are dead — the vertical step before a bullet line (1.220 to 1.486 line heights) overlaps ordinary wraps (1.100 to 1.500) completely, the bullet sits flush with the block margin rather than outdented from it at the 25th through 90th percentile, and breaking a block where the marked-content identifier changes would cost 6911 splits to buy 8. So the run minimum stays rejected on the 136-to-3 arithmetic and not pending a segmentation fix. DESIGN.md §10 carries the numbers and the larger defect the measurement did find, which is on the tagged path.
func OrderedLists ¶ added in v1.0.0
OrderedLists promotes a run of consecutively numbered paragraphs to list items.
Why this needs a run where Lists does not ¶
ADR 0011 rejected ordered lists, and its objection was exact: a numbered item is a paragraph opening with a number, which is also what a numbered heading is and what a table row is, and nothing distinguishes them. That is true of one block, which is all Lists ever looks at — a bullet glyph is evidence by itself, so a single "• item" is promotable. A number carries no such evidence, so the evidence has to come from somewhere else, and the only place left is the neighbours: "1." then "2." then "3.", consecutive blocks at one left edge, incrementing by one. That is a claim about a sequence, and no heading or table row makes it accidentally.
This is why the run minimum Lists rejected on a 136-to-3 count is *required* here. The two rules are asymmetric because their evidence is: Lists pays 136 genuine single-item lists to catch 3 stray rows and refuses; here there is no promotion at all without the run, because without it there is nothing to separate an item from prose that starts with a number.
What the delimiter separates, and what the corpus contains ¶
The label must carry a delimiter — "1." or "[1]", never a bare "1" — and doc.OrderedLabel requires it. That is what keeps a numbered heading out: "7.4 Filters" and "1 Scope" are a clause number followed by space. A dotted number cannot form a run at all, since it has no single value to increment, so ADR 0008's rule and this one cannot collide over the same block.
Measured over all 50 documents on disk, the rule promotes 70 runs of 260 items, and reading every one shows what they are: algorithm steps ("a) Accumulate a sequence…"), bibliography entries ("[1] ISO/IEC 8825-1…"), and RFC reference lists. Forms are "a)" 174, "n." 43, "[n]" 21, "n)" 17, "a." 5; lengths 2 to 11, with 25 runs of exactly 2. 4 runs are tables of contents ("1. Introduction 1"), which are the only false positives on disk — and all 4 are in *tagged* documents, where pdfspec.InferRoles never runs because sectionize read the structure tree instead. On the untagged path this pass actually serves, the effect is 5 runs of 25 items, all in mupdf_explored.pdf, all genuine. A TOC guard was measured anyway and would catch 3 of the 4 at zero cost to a genuine item; it is not here, because a guard that cannot fire on any file this code runs on is untested code, and the honest place for the measurement is this comment.
The strongest check available is a producer's own declaration, the same one ADR 0011's glyph allowlist rests on. Of the tagged list items that declare a /Lbl holding an ordered label, doc.OrderedLabel reads the same form off the item's own text in 16 of 16, disagreeing in 0.
What is not attempted ¶
Nesting. Lists ranks depth by left edge within a run; here every promoted item is level 1, because an indented ordered sub-list is not on disk and a tier rule fitted to no positive case is fitted to noise — ADR 0011's own reason for stating ListStep rather than tuning it.
That is also why opt is accepted and not read, which a reviewer should see as deliberate rather than forgotten. Options carries three settings and none applies: MaxHeading and MaxLevel bound a heading, and ListStep is the *nesting* step, which needs tiers this pass does not produce — its negative "flatten" case is already what every item gets. sameEdge's tolerance is not ListStep under another name: one asks how far apart two edges must be to mean different depths, the other how close they must be to mean the same margin. The parameter stays for the signature the other three passes share, so pdfspec.InferRoles calls them uniformly; adding a knob for the tolerance instead would be configurability no caller asked for and no measurement wants, since the value sits in an empty band.
A run that crosses a page break. The loop is per page, so "a)…d)" ending one page and "e)…g)" opening the next promote as two runs rather than one. That is a real limitation and not a preference: it was measured. 5 such continuations exist in the corpus — all of them in *tagged* documents, so 0 reach this pass, and there is nothing on the untagged path to fix. It also costs a sink nothing today, because each item carries its own label and the markdown sink emits every label rather than counting; a sink that renumbered from the first item would need this closed first. Joining across the break would mean carrying run state between pages, which is state no other pass in this package keeps, bought for no measured case.
type Options ¶
type Options struct {
// ListStep is how far a list item's left edge must sit right of the tier above it
// to count as nested, as a multiple of the run's type size. Zero means the default;
// a negative value disables nesting, leaving every item at level 1.
ListStep float64
// MaxHeading bounds a heading's length in runes. A heading is short; a numbered
// paragraph is not, and specifications are full of them ("4.2.1 The value shall
// be…"). Without a bound, every numbered clause body in a standard becomes a
// heading. Measured against the fixtures: the longest true heading found is 44
// runes, so 80 leaves room without admitting prose. Zero means the default.
MaxHeading int
// MaxLevel bounds the depth a section number may assign. Markdown has six
// heading levels and deeper numbering exists — ISO clause 7.11.4.2.1 is five —
// so the cap is where the dialect's, not the document's. Zero means the default.
MaxLevel int
}
Options configures inference.
type Stats ¶
type Stats struct {
// BodySize is the size, in points, of the dominant text cluster.
BodySize float64
// BodyBold reports whether that dominant cluster is bold — that is, whether
// weight carries any heading signal in this document. False on every fixture in
// the corpus; v110-changes.pdf comes closest and still misses, its 8.04pt bold
// holding 48.8% of characters against a 9.96pt plain body that wins on size.
BodyBold bool
// Candidates counts blocks that passed the typographic gate.
Candidates int
// Headings counts blocks promoted to RoleHeading.
Headings int
}
Stats reports what inference did. The failure modes here are quiet — a run that promotes half a document has not errored, and neither has one that promotes nothing — so the numbers are the only way to see it.
func Headings ¶
Headings promotes untagged blocks to RoleHeading in place, and reports what it did.
In place rather than returning a new document because the caller already owns one and the change is per-block: a Role and a Level, on blocks that extract left as paragraphs. Building a doc.Outline here would duplicate sectionize, whose level stack already turns a linear (level, title, content) sequence into a tree — that is the next step on this path, not this one.
A document with no text, or one whose blocks are all artifacts, is left alone and reports zero. That is not an error: a page holding one image has no headings.
type TableStats ¶ added in v1.0.0
type TableStats struct {
// Tables counts the grids found, Rows their rows and Cells their cells. Over the 51
// untagged PDFs on disk: 19 tables, 113 rows, 573 cells. The band reader over drawn rules
// alone finds 13, 76 and 352, the lattice brings that to 14, 86 and 399 (ADR 0037), and
// extract's gutters to these (ADR 0038).
Tables, Rows, Cells int
// Joined counts the tables that continued from the page before, their header row
// repeated, and were made one with it.
Joined int
}
TableStats reports what Tables did. The failure modes are quiet in both directions — a run that finds nothing has not errored, and neither has one that reads a page of prose as a grid — so the counts are the only way to see it.
func Tables ¶ added in v1.0.0
func Tables(d *doc.Document, opt Options) TableStats
Tables promotes a page's spans to RoleTableCell where the page's own strokes say a table is drawn, and reports what it did.
Why the strokes and nothing else ¶
The gap between two cells and the gap between two words are the same measurement. Over all 117499 inferred spaces on disk the ratio of gap to nominal space width is continuous from the 0.40 the SpaceFrac threshold itself imposes out to 1303, with no quarter-width band empty below 5 and the largest jump anywhere below 200 — 4529 ratios below 0.50, 14530 between 1.75 and 2.00, then a long thin tail of 11 past 200 — so no threshold on the gap separates a column boundary from wide word spacing. Over the 12 documents in docs/ alone the shape is the same: 46917 spaces, 2738 below 0.50, 14337 between 1.75 and 2.00. Twelve is the whole directory, not the eleven specifications the tolerance figures in geom are denominated in — docs/ also holds LightOnOCR's paper — and the denominator is named because a later reading taken over eleven would not reproduce these three numbers and would look like drift. That is the measurement that rules out the gap clustering pdfplumber and markitdown use, and it is why extract carries doc.Page.Rules at all: a stroke drawn between two glyphs is the producer's own statement that they are in different cells, where a gap is a statistic about them.
extract has already acted on that statement — splitAtRules divided the row's text into one span per cell, because a block's spans carry one box each and text merged into a single span cannot be taken apart later without re-measuring glyphs. What is left here is the grid: which spans are a row, which rows are one table, and which column each cell sits in.
Everything here is a sort or a comparison, never an arithmetic threshold ¶
Columns come from x-overlap: two cells share a column when their boxes overlap on x. That deliberately has no tolerance in it, for the reason listTiers gives — the numbers compared are glyph extents the extractor measured, not quantities this package computed, so two cells either overlap or they do not.
The alternative was to key a row by the positions of the rules that split it, and it is wrong in a way worth recording: adobe-samples/autotagPDFInput.pdf draws its header row's column rule at x=158.88 and its body rows' at x=158.94, so an exact key reads one table as two, and pymupdf/dotted-gridlines.pdf draws 2048 verticals of a dotted grid where which one is found first depends on the width of the text either side of it. Cell overlap is invariant to both.
What a row minimum would cost ¶
Measured over the 6 untagged documents on disk — the only ones this runs on, since all 11 corpus specifications are tagged — the gate finds 21 runs, 12 of them a single row. A one-row table is emitted by GFM as a header and a delimiter with no body, which is how "HB | pencil (very complex)" and "Generate a | launch" would read. They are dropped by requiring two rows, and that drop is not free: chinese-tables.pdf sets four genuine one-row tables of a rating history. Two rows is kept because a single row cannot distinguish a table from a line of text that happens to have a rule through it, which is what the other eight are.