doc

package
v1.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 23, 2026 License: MIT Imports: 5 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package doc is the domain model every other package converges on: what a document looks like after it has been read and before it has been written out.

Nothing here parses, positions, classifies, or renders. That is deliberate and it is the reason the package exists. The extractor, the layout heuristics, the OCR engine, and the structure-tree walker all produce this model, and the Markdown and OKF sinks all consume it — so a page recovered from glyph positions and a page recovered from a vision model are interchangeable by the time a sink sees them. Without a shared model in the middle, each producer and each sink would need to know about the others, which is how the libraries in §1 of docs/DESIGN.md ended up as one package that does everything.

The only dependency is geom, which is itself stdlib-only. geom owns Rect, Matrix, and the tolerance policy; re-declaring them here would give the repo two rectangles that must be kept in agreement, so the layout in DESIGN.md §4 listing them under doc is satisfied by using geom's.

Section is in section.go, and its shape came from measuring ISO 32000-2 rather than from anticipating it — see that file for what the measurement changed.

Index

Constants

View Source
const Unmapped = "�"

Unmapped stands for a glyph the file gives no Unicode value to, one character per glyph: the replacement character, which the Markdown sink writes as [err] (ADR 0042).

Variables

This section is empty.

Functions

func IsMarker added in v1.0.0

func IsMarker(s string) bool

orderedForms are the ordered-label shapes a producer writes.

A closed list of shapes rather than "a number then punctuation", because the risk here is not which glyph follows the number — it is what else in a document opens with one.

These five are exactly the forms the corpus contains, and the tally is the whole justification: of the 260 items layout.OrderedLists promotes across all 50 documents, "a)" is 174, "n." 43, "[n]" 21, "n)" 17 and "a." 5. Parenthesized labels — "(1)" and "(a)" — look like obvious siblings of "[1]" and were written, measured at **zero occurrences**, and removed. Admitting a sixth form on the strength of it seeming plausible is the speculative code this repo does not keep: no fixture could reach it, so nothing would catch it going wrong. If one turns up, the evidence arrives with it.

The delimiter is required and is what does the separating. A numbered *heading* is "7.4 Filters" or "1 Scope" — a clause number followed by space, no delimiter — and a dotted number has no single sequence value to increment, which is why "N.N" cannot form a run at all and needs no exclusion. Measured over every document on disk, no dotted clause number chains under layout.OrderedLists' rule. IsMarker reports whether s, spaces aside, is a list marker standing alone: a bullet ListMarker admits, or a label OrderedLabel reads, with nothing after it. A column of these is a list set with its markers in a column of their own, as extract's gutters ask.

func ListMarker added in v0.2.0

func ListMarker(txt string) rune

ListMarker returns the marker rune txt opens with, or zero.

It trims the text itself rather than trusting a caller to, which is what makes the two conditions below sufficient: on trimmed text a marker followed by whitespace must have something after that whitespace, since the last rune is not one. A separate "and content follows" check reads like the third requirement and is unreachable — a mutation removing it survives every test, which is how it was found.

The separator is what distinguishes a marker from the same glyph used as a character: every bullet-initial block in the corpus has it and none is glued to its text — 1305 of 1305 over every block on disk — while the excluded "-" is glued in 12 of its 13 block-initial occurrences. Both figures are the all-blocks population, which is the one to state here because this vocabulary serves both producers; the untagged paragraphs layout.Lists alone sees are a small subset of it, and marker_test.go records the per-glyph split for the five excluded glyphs because there the two populations disagree. The length requirement is the other measured case — mupdf_explored.pdf has blocks that are a lone Wingdings square with no text, which are decoration and not items.

Exported because the decision to promote a block and the act of stripping it are separate steps in layout: a block that will not be promoted must not have its text edited, so the test has to be available without the mutation.

func OrderedLabel added in v1.0.0

func OrderedLabel(txt string) (string, int)

OrderedLabel returns the ordered label txt opens with and its sequence value, or "" and 0.

The value is what makes a run checkable: 1 for "1." and for "a.", so a rule can require that consecutive items increment by one. Letters are single and lowercase only — "aa." is not a form on disk, and an uppercase letter opens far too much prose ("A. " begins a sentence) to admit on this evidence.

The separator requirement is the same one ListMarker makes and it matters more here, because the label is far more common as ordinary text than a bullet glyph is: "1.5" and "Figure 1." must not read as labels, and neither does, the first for having no separator and the second for not being at the start.

Exported for the same reason ListMarker is: deciding to promote a block and editing its text are separate steps, and a block that will not be promoted must not be edited.

Types

type Block

type Block struct {
	// Role is what this block is.
	Role Role

	// Level is the heading depth for RoleHeading (1-6) or the nesting depth for
	// RoleListItem (1-based). Zero for everything else.
	Level int

	// Marker is a list item's label with the item's own text — the bullet glyph a
	// page draws, or the number or letter an ordered list counts. Empty for
	// everything that is not a list item, and for an item whose label is neither
	// declared nor drawn. A RoleFootnote's label as the page writes it is here too,
	// "1)" or "*", which is the text the page draws and so the text a conservation count
	// asks for.
	//
	// It is a field rather than a prefix on the text for the reason Docling's
	// ListItem separates the two: a marker kept inside the text has to be re-found
	// by every sink, using a glyph allowlist each one would have to re-derive, and
	// on the one sink that exists it doubles — markdown writes its own "- ". Kept
	// rather than dropped because a bullet is losable and a label is not: "[1]" and
	// "a." are text the page says, and Markdown has no syntax that restates them, so
	// a sink that wants them needs to know they existed. Enumerated is that
	// distinction, derived from this.
	Marker string

	// Note is a RoleFootnote's label, the one its mark's Span.Note names, and empty for
	// every other role. It is an identifier, not page text: "1" for a mark set "1)", "fn1"
	// for one set "*", which GFM would read as emphasis, and "1-2" for the second note a
	// document numbers 1. Marker holds what the page says.
	Note string

	// Cell places a RoleTableCell in its table, and is nil for every other role.
	// See Cell for why the position is on the block rather than the blocks being
	// nested inside a table block.
	Cell *Cell

	// Spans are the block's styled runs in reading order.
	Spans []Span

	// Box is the block's bounding rectangle in one page's coordinate space.
	//
	// One page's, because a block has a Box and no page range while a Section has FirstPage
	// and LastPage — so a block that spans a break cannot say so, and sectionize does rebuild
	// such blocks: a paragraph continuing past a page break is one structure element naming
	// two pages. Unioning across it would give a rectangle bounding two coordinate spaces,
	// which locates nothing in either. Its spans each carry their own Span.Page, so the page
	// this rectangle belongs to is the Page of the first span that has one, and the later
	// pages' text is still reachable through the spans.
	Box geom.Rect

	// Lines are the block's lines in reading order, as the extractor drew them. A span runs
	// on across lines whenever its style does, so the spans cannot say where a line ended,
	// and a pass that asks whether a paragraph's last line is full, or its first flush, needs
	// that. Empty for a block no extractor drew.
	//
	// They describe Spans as they are, so a writer that edits the spans' text keeps the starts
	// in step, as StripMarker and layout.Hyphens do, or empties Lines, as a table cell cut from
	// its row's spans does. Stale lines index past a block's spans: that is what made
	// layout.Hyphens panic on every table before TestBlockLinesDescribeTheirSpans existed.
	Lines []Line

	// Lang is a language override from the structure tree, when the block declares
	// one different from the document's.
	Lang string

	// Alt is /Alt: a description of the content for a reader who cannot see it.
	// It does not replace the spans, and a sink that treats it as replacement text
	// deletes page text — see Replacement, and the two are separate fields for
	// exactly that reason.
	//
	// For a RoleFigure with no spans it is the only text available, which is why it
	// is carried on the block rather than dropped once the spans are read.
	Alt string

	// Image is the painted image a RoleImage block stands for, nil on every other block.
	Image *Image

	// Replacement is /ActualText: what the content *is* where the glyphs do not
	// spell it — an image of a word, a ligature drawn as artwork, a decorative
	// capital. It replaces the spans, because that is what §14.9.4 defines it as.
	//
	// Split from Alt because §14.9.3 and §14.9.4 are opposite operations and one
	// field cannot say which it holds. Merged, a sink had to pick one behaviour for
	// both, and it picked substitution: PDF20_AN001-BPC.pdf's illustration carries
	// an /Alt paraphrasing three captions that are real text on the page inside the
	// same Figure, and all three were dropped — 129 characters, the one occurrence
	// in the 50-document corpus. Picking description for both instead would have
	// broken the case /ActualText exists for, so the fix is the field, not the rule.
	//
	// Empty on every block the corpus produces, and not because /ActualText is rare:
	// there are 4803 of them across the 51 PDFs on disk, and all 4803 are on inline
	// Span elements, which sectionize does not lift into blocks. So this field is a
	// correct model of §14.9.4 that nothing on disk currently fills, and the sinks'
	// substitution rule rests on unit tests rather than on the corpus. Reading those
	// spans is separate work — the values are a line break, a bullet and a soft
	// hyphen, and each one is a text defect of its own where the glyphs differ.
	Replacement string

	// MCIDs are the marked-content identifiers this block was assembled from, on
	// the block's page. Carried for diagnosis: when tagged text comes out in the
	// wrong order, the question is always which MCIDs went where, and answering it
	// without this means re-running the extraction.
	//
	// Not the join key for a structure element. A block is a *layout* unit and an
	// element is a *logical* one, and the two disagree often enough to matter: on
	// Well-Tagged-PDF-WTPDF-1.0.pdf, 12% of headings share a block with the body text
	// that follows them, because the extractor's paragraph heuristic saw one paragraph
	// where the tree declares a heading and a definition. Joining on this set resolves
	// such a heading's title to the heading plus the definition. Span.MCID is the key
	// that does not have that failure.
	MCIDs []int
}

Block is a run of content that a sink emits as one unit.

A block holds Spans rather than a string because style changes inside a paragraph carry meaning that Markdown can express — an italic term, a code identifier in prose — and flattening to a string at extraction time discards it irreversibly. The spans are also where the space-inference decisions land, so keeping them lets a defect be traced to the glyph run that caused it.

func (Block) Enumerated added in v0.2.0

func (b Block) Enumerated() bool

Enumerated reports whether the block's marker is an ordered label — a number or a letter — rather than a bullet.

Derived from Marker rather than stored beside it, because the two cannot disagree: the marker either is a single glyph from the allowlist or it is something a producer counted. Docling carries this as its own field; here a second field could be set inconsistently with the first, and there is nothing it could express that this does not.

It exists because a sink cannot render what it cannot distinguish. Markdown has no syntax for "[1]" as a list marker, so a sink emitting "- " has to put an ordered label back into the line, and dropping it instead would lose text the page draws.

The vocabulary here is declaredMarkers and not listMarkers, because this asks whether a marker already in hand is a bullet, not whether a block's text should be read as having one. Either producer's bullet is a bullet, and asking the narrower map made the hyphen StripDeclaredMarker had just recovered come back as "- \- text" — the doubling the marker field exists to stop, one escape further along. There is no false positive to weigh: layout cannot set a marker this map admits and the shared one does not, and that follows from the setters rather than from a convention. On the undeclared path Marker comes from StripMarker, whose rune is in listMarkers by construction, or from StripOrderedLabel, whose label is more than one rune and so returns above on the length test without reaching either map. SetMarker is the only other setter and only sectionize calls it. The two maps differ by exactly the hyphen, which is the one rune neither of those two can produce.

func (Block) IsEmpty

func (b Block) IsEmpty() bool

IsEmpty reports whether the block would emit nothing. A block with no text, no Alt and no Replacement is a positioned rectangle a producer left behind, and every stage from sectionize onward has to skip it. An image is never empty: it emits "image" when nothing else.

func (*Block) SetMCIDs added in v1.0.0

func (b *Block) SetMCIDs()

SetMCIDs rebuilds b.MCIDs as the union of its spans' identifiers, which is what the field is documented to be.

It lives here, beside the field, because the invariant was stated on the field and implemented separately at each of four write sites — and two of the four built something else. The extractor deduplicated and skipped -1; layout's mcidsOf did both; sectionize's emitItem did neither, and its unplaced filtered -1 without deduplicating, so an adopted listing indent emitted [1 1 2 2] where the union is [1 2]. Measured over every block the tagged pipeline produces for the 12-file corpus — page blocks, preamble, sections and unplaced — 34364 of the entries on 7406 of 46722 blocks were duplicates and 88 were the absent value, and nothing downstream reads a single one: the field is carried for diagnosis, so the cost was a diagnostic that lies rather than wrong output. A contract asserted in a comment and re-implemented per caller is a contract that holds wherever someone remembered it.

-1 is excluded because it is the absent value, not an identifier: a span drawn outside marked content was assembled from no MCID at all. Order is first appearance, which is reading order for every writer here and is what makes the field answer "which MCIDs went where". Linear scan rather than a map: the largest block in the corpus holds 106 spans (ISO/TS 32005), so the set is small enough that a map's allocation costs more than the scan it saves, and this runs once per block.

A fresh slice rather than a truncated reuse of the old one. A struct copy of a Block shares the array behind MCIDs — which is the whole reason sectionize.detach exists — so writing into b.MCIDs[:0] would edit a sibling copy's set through storage they share, and the sibling would keep its own length and read the values written for this block.

func (*Block) SetMarker added in v0.2.0

func (b *Block) SetMarker(marker string)

SetMarker records a marker the producer declared, and closes the gap its removal leaves in the text.

For the producer that has a declaration to read: sectionize takes the label's spans out of the item before gathering it, so there is no marker left in the text to find — but there is usually whitespace where it was. Measured over every tagged list item on disk that declares a /Lbl, dropping the label's spans leaves the item's text opening with whitespace in 139 of 153 cases, which a sink writing its own "- " renders as two spaces.

The trim is the same one StripMarker does after the marker, and stops at the first span with content left for the same reason: it must not reach into the item's own prose.

func (*Block) StripDeclaredMarker added in v1.0.0

func (b *Block) StripDeclaredMarker() bool

StripDeclaredMarker is StripMarker for a block the producer already declared a list item, and differs only in vocabulary: declaredMarkers rather than listMarkers.

A separate method rather than a parameter on StripMarker, because the choice of vocabulary is not a caller's option to pass — it follows from whether a declaration exists, which only sectionize knows. layout has no declaration to read and must never reach the wider map; a boolean argument would let it, and the compiler would not care.

Callers: sectionize.markItem, on the path where the producer declared RoleListItem and omitted the /Lbl. declaredMarkers documents which glyphs this adds and what each is measured at.

func (*Block) StripMarker added in v0.2.0

func (b *Block) StripMarker() bool

StripMarker moves a leading marker glyph out of the block's spans into Marker, and reports whether it found one.

For the producer that has no declaration to read: the marker is only in the drawn text, so recognizing it and removing it are the same act. ListMarker gates it, so the separator and length requirements apply here too — a lone bullet with no text is page decoration and keeps its glyph.

A producer that declared the role but not the label wants StripDeclaredMarker, which is this walk over a wider vocabulary.

The span walk is not simply "edit the first span". A block's text is its spans concatenated with no separator, so the marker and the whitespace after it can be split across spans in three ways, each of which occurs on disk: the marker with its separator in one span, the marker alone with the separator opening the next (a bold en dash followed by a roman body, which is testdata/reference/lists.pdf's nested item), and a leading span holding nothing but whitespace with the marker in the one after it. Stopping at the first non-empty span leaves "- • Item." in the output.

unicode.IsSpace rather than a byte cutset: producers separate a marker from its text with U+00A0 routinely, and ListMarker admits the block on that basis, so the strip must accept the same separators the gate did.

A span the strip empties stays in place rather than being removed, so the span indices a caller holds stay valid and Span.MCID survives for diagnosis; an empty span writes nothing.

func (*Block) StripOrderedLabel added in v1.0.0

func (b *Block) StripOrderedLabel() bool

StripOrderedLabel moves a leading ordered label out of the block's spans into Marker, and reports whether it found one.

Separate from StripMarker rather than folded into it, because the two remove different shapes and only one of them is a single rune. A bullet is one glyph, so StripMarker can decode a rune and trim; a label is up to five ("[100]") and may be split across spans by a style change on the delimiter — a producer setting the number bold and the bracket roman gives "1" and ") text" — so this consumes a rune count across as many spans as it takes.

Marker holds the label with its delimiter and without the separator ("1.", "[3]", "a)"), which is what a sink needs: Block.Enumerated reads it to tell an ordered item from a bullet, and the markdown sink reads the digits back out to write CommonMark's own syntax. The separator goes because it is spacing rather than content, exactly as in StripMarker.

An empty span left behind stays in place rather than being removed, for StripMarker's reason: span indices a caller holds stay valid, and Span.MCID survives for diagnosis.

func (Block) Text

func (b Block) Text() string

Text returns the block's text, spans concatenated with no separator.

No separator because a span boundary is a style change, not a word boundary: the space between "an" and "italic" belongs to one span or the other, and inserting one here would double it. Space inference happens once, in the extractor, against font metrics — doing any of it in this package would put half the policy in the model and half in the producer.

type Cell added in v1.0.0

type Cell struct {
	// Table numbers the table within its document, from 1, so two adjacent tables do
	// not merge into one grid. A number rather than a pointer because doc is a data
	// model that has to survive being written to JSON and read back.
	Table int

	// Row is the 0-based row and Col the 0-based column, both counting the cells the
	// tree declares rather than any geometric position. A ragged row — 46 of 788
	// tables have one — therefore numbers its own cells consecutively and stops short,
	// which is what lets a sink pad it to the table's width.
	//
	// Col is an ordinal among the row's own kids, so a producer that put a cell
	// somewhere other than directly under its TR has no column and gets no Cell at all.
	// All 17482 cells on disk are direct children, and the spec does not require it.
	//
	// Row counts through THead, TBody and TFoot without restarting, because those group
	// rows rather than renumbering them — 4540 of the corpus's 4650 rows are inside one.
	Row int
	Col int

	// Header reports a TH rather than a TD. 773 of 788 tables on disk have an all-TH
	// first row, which is the shape a Markdown header row expresses; 598 also carry a
	// TH below row 0, which no Markdown syntax can mark, so a sink emits those as
	// ordinary cells and this field is what records that it had to.
	Header bool
}

Cell is a table cell's position in its table.

It is a field on the cell block rather than a Table block holding rows holding cells, and that is the load-bearing decision here. A doc.Page is a flat list of blocks in reading order, and every stage after extraction — the space accounting, the character-conservation tests, the OKF sink, the unplaced-content report — walks that list. Nesting tables would make a block's text reachable by two different paths, and the invariant that a page's characters are the sum of its blocks' is what this repo's accounting tests rest on. A sink that wants the grid regroups on Table and Row, which is a scan of consecutive blocks because a tree's reading order puts one table's cells together.

Spans are not modeled. Of 17482 cells on disk, 69 declare /ColSpan greater than 1 and 43 declare /RowSpan — about 1%, concentrated in ISO/TS 32005 — and no Markdown table syntax can express either, so a sink pads the row instead. Reading them would let a sink place a spanning cell's text under only its first column, which is what GFM renders anyway; recording that they exist and are unrepresentable is the honest state, and tag.Elem does not read /A at all.

type Document

type Document struct {
	// Meta is what the file says about itself, for frontmatter and for OKF
	// provenance.
	Meta Metadata

	// Pages are in document order, and every page the file declares is present
	// even when nothing could be extracted from it. A missing page would shift
	// every page number after it, and page numbers are what a reader checks a
	// conversion against.
	Pages []Page
}

Document is one PDF, read.

func (*Document) Text

func (d *Document) Text() string

Text returns the whole document's text, pages joined by a blank line.

The same measurement rendering as Page.Text, for the same reason.

type Image added in v1.0.0

type Image struct {
	// Box is the image's extent in page coordinates: the unit square through the CTM at the
	// paint, bounded.
	Box geom.Rect

	// Width and Height are the image's size in samples, as its dictionary declares.
	Width, Height int

	// Mask reports a stencil mask (/ImageMask true): one bit a sample, painted in the fill
	// colour, which is how a producer draws a glyph, a rule or a logo as a bitmap.
	Mask bool

	// MCID is the marked-content identifier the image was painted inside, or -1, and Artifact
	// reports that it was painted inside an /Artifact, a producer's statement that it is
	// decoration.
	MCID     int
	Artifact bool

	// Read is what was read off the image, nil when nothing was (ADR 0046).
	Read *ImageRead
}

Image is one painted image: where it stands on the page and what it is.

type ImageRead added in v1.0.0

type ImageRead struct {
	// Kind is what the image holds: "text", "table", "chart" or "picture".
	Kind string

	// Blocks stand in for the image, in page coordinates: a text image's paragraphs, a table
	// image's cells, a chart's table of its values.
	Blocks []Block

	// Alt is a model's description of a picture or a chart, "tag: description".
	Alt string

	// By names what read it, "tesseract 5.5.3 eng" and the model, for the page report.
	By string
}

ImageRead is what an image was read as, and the content that stands in its place.

type Line added in v1.0.0

type Line struct {
	Box    geom.Rect
	Page   int
	Size   float64
	Space  float64
	Span   int
	Offset int
}

Line is one line of a block: the box of its glyphs in its page's coordinates, the 1-based page, the size most of its characters are set in, the widest space advance among its fonts, which is the unit extract measures indents and line ends in, and where its text starts: byte Offset of Spans[Span].Text, since a span runs on across lines whenever its style does.

type Metadata

type Metadata struct {
	// Path is the source file as given on the command line. Kept because a
	// converted document with no record of where it came from cannot be
	// regenerated or checked.
	Path string

	// Title, Author, Subject, Keywords, Creator, and Producer come from the
	// document information dictionary (ISO 32000-2 §14.3.3) or from XMP.
	Title    string
	Author   string
	Subject  string
	Keywords string
	Creator  string
	Producer string

	// Created and Modified are as written in the file, not parsed into a time.
	// PDF date strings are frequently malformed, and a sink that emits the string
	// it found is more useful than one that drops a date it could not parse.
	Created  string
	Modified string

	// Lang is the document's /Lang, which OKF and Markdown frontmatter both want
	// and which is also the only reliable hint for hyphenation and casing rules.
	Lang string

	// Version is the PDF version, as reported by objects.Store.
	Version string

	// Tagged reports whether the file has a structure tree. It decides which
	// extraction path ran, so it belongs in the output: a conversion that silently
	// fell back to layout heuristics should be legible as such.
	Tagged bool

	// Encrypted reports an /Encrypt dictionary. A file may be readable and still
	// report true, since empty-password encryption is common.
	Encrypted bool
}

Metadata is the document-level information a sink can put in frontmatter.

Every field is optional, because every one of them is optional in the file. The zero value is a document that said nothing about itself, which is common and is not an error.

type Outline

type Outline struct {
	// Meta is the source document's metadata, carried so a sink emitting one file
	// per clause can attribute each of them without also being handed the Document.
	Meta Metadata

	// Sections are the top-level sections in document order.
	Sections []*Section

	// Preamble holds content that appeared before the first heading — a title page,
	// a copyright notice. It is kept rather than dropped because dropping content is
	// never the right default for an extractor, and it is separate from Sections
	// because it belongs to no clause.
	Preamble []Block

	// Unplaced holds text the reconstruction could not attribute to any section,
	// grouped by the page it was found on. It is Pages rather than Blocks because
	// without the page number this content cannot be checked against the original,
	// and Page is the type that already carries one.
	//
	// It exists because the alternative to keeping this is one of two worse things.
	// ISO 32000-2 draws the whole of clause 1 outside any marked-content sequence, so
	// no structure element names it: dropping it loses a normative clause, and
	// attaching it to the nearest preceding section files the Scope under "0.4
	// Changes introduced in ISO 32000-2:2020" — a wrong attribution in a bundle a
	// model will later read as fact, which is worse than an unattributed one.
	// Measured at 0.23% of the specification's text and 0% of ISO/TS 32005.
	//
	// Recovering such content as a *clause* needs a heading that the tree does not
	// contain, which is the layout path's job and not this one's.
	Unplaced []Page
}

Outline is a document's sections: the top-level ones, in document order.

A slice rather than a synthetic root, because a document does not have one heading at the top. ISO 32000-2 opens with Foreword and Introduction at the same level as clause 1, and inventing a root to hold them would put a section in the tree that no heading in the file corresponds to — which a clause-per-file sink would then have to emit or special-case.

func (*Outline) Count

func (o *Outline) Count() int

Count returns the total number of sections at every level, which is the acceptance measurement for the tagged path: docs/DESIGN.md §8 puts ISO 32000-2 at roughly 981, and a run producing single digits has reverted to container-driven segmentation.

func (*Outline) Walk

func (o *Outline) Walk(fn func(*Section) bool)

Walk calls fn for every section in the outline in document order, depth first.

type Page

type Page struct {
	// Number is the 1-based page number.
	Number int

	// Box is the page's visible area in user space — the crop box where one is
	// present, otherwise the media box. Blocks are positioned in the same space.
	Box geom.Rect

	// Rotate is /Rotate in degrees, a multiple of 90. Carried rather than applied:
	// a sink emitting text does not need it, and a rasterizer does, so folding it
	// into coordinates here would force the sink to undo it.
	Rotate int

	// Blocks are the page's content in reading order. Order is the producer's
	// responsibility — the structure tree's logical order when tagged, geometry
	// when not — because it is the one thing a sink cannot recover.
	Blocks []Block

	// Rasterized reports that this page's content came from OCR rather than from
	// the content stream. It travels with the page so a sink can mark inferred
	// text as inferred, which matters for a knowledge bundle a model will later
	// read as fact.
	Rasterized bool

	// Failed reports that this page could not be read, so its emptiness is a loss and
	// not a fact about the document.
	//
	// It travels with the page for the same reason Rasterized does: a consumer has to be
	// able to tell an inference from a reading, and a blank page from a page that is
	// blank. extract.Document substitutes an empty page for one it cannot parse — one
	// malformed page must not cost the other 999 — and without this field that
	// substitution is indistinguishable from a genuinely empty page to every sink, every
	// accounting test and every reader. It was: ISO/TS 32002's cover page was absent from
	// every conversion this repo produced and every check reconciled, because they all
	// measure what was read.
	//
	// Carries no reason, on purpose. The error belongs to the extractor that met it and
	// is available from extract.Extractor.Failed; what a sink needs is the one bit that
	// says do not present this page as content.
	Failed bool

	// Rules are the page's axis-aligned straight strokes and fills, in the order
	// drawn. They are the only evidence an untagged ruled table leaves behind, which
	// is why they are carried at all: measured over every inferred space on disk, the
	// gap that separates two cells and the gap that separates two words occupy one
	// continuous distribution from 0.25 to 1300 space widths with no empty band
	// anywhere, so no threshold on the gap alone can tell a column boundary from wide
	// word spacing. A rule between two glyphs can, and it is the producer's own
	// statement rather than a statistic about it.
	//
	// On the page rather than on a block because a rule belongs to no block: one rule
	// bounds the cells on both sides of it, so attributing it to either is a choice
	// the producer never made. Marked content cannot decide it either. Of ISO
	// 32000-2's 72,002 painting operators, 71,194 sit inside an /Artifact with no MCID
	// and 15 outside any marked content at all — a producer usually declares a rule
	// not to be content — but 793 sit inside a Span, a P or a Figure carrying a real
	// identifier, which is how page 205 paints the fraction bars extract reads. Nor
	// are they painted ahead of the text they enclose: of the 647 pages that both
	// paint and show text, exactly one paints first.
	//
	// Nothing downstream of layout reads these, and no accounting test counts them:
	// they carry no characters, so they cannot affect the conservation invariant that
	// every other field here is subject to.
	//
	// Empty for a page that draws none, which is the minority — 658 of ISO 32000-2's
	// 1,023 draw at least one, 284,866 rules in all, and 9 of the 11 reference
	// fixtures draw none.
	//
	// This comment said 580 pages before, and that is a corrected mismeasurement
	// rather than a quantity that moved: nothing in the rule-collection path has
	// changed the segments it records, only the width it records beside them. 658
	// and 284,866 are what a walk of every page reports.
	Rules []Rule

	// Gutters are verticals the extractor inferred where a table with no rules holds its
	// columns apart by white space alone, running down the rows they divide. The row text is
	// already split into cells at each. Kept apart from Rules because a rule is the
	// producer's own statement and a gutter is a reading of the page; layout's band reader
	// takes both, and its lattice, which needs a drawn frame, takes only Rules.
	Gutters []Rule

	// Images are the images the page paints, in the order painted: image XObjects and inline
	// images, inside forms too. Recorded where they stand, so that what an image holds can
	// be read off the rendered page (ADR 0045); the samples themselves are the image path's.
	Images []Image

	// Recovered are the runs of glyphs with no value in the file that were read off the
	// rendered page, each with the engine that read it and its confidence (ADR 0048). The
	// text the run was written as, doc.Unmapped, is replaced in its span.
	Recovered []Recovery
}

Page is one page's content in reading order.

func (Page) Coverage

func (p Page) Coverage() float64

Coverage returns the fraction of the page box its text occupies, from 0 to 1.

Zero for a page with no text or no box. A zero-area box is a defective page dictionary rather than a full page, so reporting no coverage routes it to the rasterizer, which is the outcome that recovers something.

func (Page) Text

func (p Page) Text() string

Text returns the page's text with one newline between blocks.

This is for measurement, not for output: the §9 benchmark counts characters, space ratio, and word lengths, and those numbers must come from one agreed rendering or they are not comparable across runs. Markdown formatting — heading markers, list bullets, paragraph spacing — is the sink's job, and a sink that called this would be reformatting a string instead of walking the model.

func (Page) TextBounds

func (p Page) TextBounds() geom.Rect

TextBounds returns the union of every block's rectangle, or the zero Rect when the page has no text.

This is the numerator of the OCR router's coverage rule: a page whose text covers too little of its box is a scan with no text layer, or one with a text layer so sparse that rasterizing it will do better. Expressed as a bounding union rather than a sum of areas because overlapping blocks would double-count and push a scanned page's coverage above the threshold.

type Recovery added in v1.0.0

type Recovery struct {
	// Box is the line the run is in, in page coordinates.
	Box geom.Rect

	// Glyphs is how many glyphs the run is, and Text what they were read as.
	Glyphs int
	Text   string

	// Engine names what read it, "tesseract 5.5.3 eng", or the second reader that agreed
	// with a reading Tesseract was unsure of. Conf is Tesseract's confidence, 0 to 100,
	// the lowest of the words it was read from.
	Engine string
	Conf   float64
}

Recovery is one run of glyphs with no value, read off the page's image.

type Role

type Role string

Role is what a block is, in the vocabulary a Markdown or OKF sink can act on.

It is a deliberately smaller set than tag.Role, and the reduction is the point. ISO 32000-2 §14.8.4 defines around fifty structure types; Markdown can express perhaps eight of them. Mapping down happens once, where the structure tree is read, rather than in each sink — otherwise every sink grows its own opinion about whether a TOCI is a list item, and two sinks disagree about the same document.

The set is also what layout/ and ocr/ have to produce. A vision model emits prose and headings, not TBody, so a vocabulary any narrower than this could not carry a tagged document's structure, and any wider could not be filled from an untagged one.

const (
	// RoleParagraph is body text, the default and the overwhelming majority.
	RoleParagraph Role = "paragraph"

	// RoleHeading is a heading; its depth is in Block.Level.
	RoleHeading Role = "heading"

	// RoleListItem is one item of a list. Nesting is in Block.Level, so a sink can
	// indent without reconstructing a tree.
	RoleListItem Role = "list_item"

	// RoleTableCell is one cell; Block.Cell says where in which table it sits.
	RoleTableCell Role = "table_cell"

	// RoleCode is preformatted text, where the extractor must not collapse
	// whitespace. The spec corpus is full of it.
	RoleCode Role = "code"

	// RoleQuote is a block quotation.
	RoleQuote Role = "quote"

	// RoleCaption is a figure or table caption. Separate from RoleParagraph
	// because a caption belongs with its figure when sections are stitched, and a
	// sink that cannot tell them apart puts it in the following paragraph.
	RoleCaption Role = "caption"

	// RoleFigure is a figure with no text of its own. Its Alt carries the
	// description, which for an accessible document is the only text there is.
	RoleFigure Role = "figure"

	// RoleImage is an image the page paints, where it stands among the text (ADR 0045).
	// Block.Image is its placement. Alt, when set, is what was read off it, "tag:
	// description"; a sink writes it as "[tag: description]", and as "[image]" when nothing
	// was.
	RoleImage Role = "image"

	// RoleArtifact is page furniture — a running header, a folio, a rule. Kept
	// rather than dropped at extraction, because "is this a header" is a judgement
	// and the evidence for it is here; a sink omits them, and probe can count them.
	RoleArtifact Role = "artifact"

	// RoleFootnote is a note's text, set apart from the body and pointed at by a mark
	// in it. Block.Note is its label, and the span that marks it carries the same label
	// in Span.Note, so a sink can link the two: Markdown writes them as a GFM footnote
	// reference and its definition. Block.Marker is the label as the page writes it.
	RoleFootnote Role = "footnote"
)

type Rule added in v1.0.0

type Rule struct {
	// Vertical reports the axis. A rule is one or the other by construction — a
	// segment that is neither is discarded rather than snapped to the nearer axis.
	Vertical bool

	// Pos is the coordinate on the axis the rule is perpendicular to: x for a
	// vertical rule, y for a horizontal one.
	Pos float64

	// From and To bound the rule along its own axis, From <= To.
	From, To float64

	// Width is the rule's thickness perpendicular to itself, in page units, when
	// it came from a stroked line; zero when it is one edge of a filled region.
	//
	// The two cases are not interchangeable and a consumer needs to tell them
	// apart. A filled rectangle has area, so its thickness is the distance between
	// the two edges reported here — both of them are. A stroked line has none: it
	// is reported once and its thickness is only this number. That is a difference
	// in the producer, not in the mark: ISO 32000-2 draws a fraction bar as a
	// filled rectangle and pdfTeX strokes the same bar, so a reader that measures
	// thickness one way sees it in one document and not the other.
	//
	// Zero is therefore ambiguous at the bottom end, deliberately: a hairline
	// "0 w" stroke and a filled edge both report zero. Both are the thinnest mark
	// the page can make, and distinguishing them would need a flag carrying no
	// information about the geometry.
	//
	// A path that is filled *and* stroked reports the stroke's width on all four
	// edges of its rectangle, so the two cases above are not exhaustive: "re B"
	// makes every edge both a filled region's boundary and a stroke of its own.
	//
	// Two producer habits are not read at all, and a consumer that measures a mark
	// should know it. A line width set through an ExtGState — "/GS0 gs" with /LW —
	// is not seen, so this value may be whatever the last "w" set or the initial 1;
	// and a skewed transformation has no single perpendicular extent for the
	// thickness to be, so the number would be wrong rather than absent.
	Width float64
}

Rule is one axis-aligned straight stroke or fill edge, in page coordinates.

Kept as a segment rather than a full line because extent is what distinguishes a table's edge from a page decoration: a horizontal rule spanning the text measure is a header underline, and one spanning a single column is a cell edge. A consumer needs both endpoints to tell them apart.

Curves are deliberately absent. A Bézier says nothing about where a table's edge runs, and the corpus draws 421 diagonal segments, all of them inside artwork.

func (Rule) Length added in v1.0.0

func (r Rule) Length() float64

Length returns the rule's extent along its own axis.

type Section

type Section struct {
	// Title is the heading text. It is resolved from page content joined on
	// (page, MCID), not from the structure element's /T: every heading in ISO
	// 32000-2 has an empty /T, so /T is an optimization when present and never the
	// source of truth.
	Title string

	// Level is the heading depth, 1-based. It comes from the declared heading role
	// — H1..H6, or a bare H's nesting depth per ISO 32000-2 §14.8.4.4 — on the
	// tagged path, and from font-size clustering on the untagged one. It is the
	// hierarchy: a section's parent is the nearest preceding section of lower level.
	Level int

	// Number is the clause number parsed off the front of the title, "7.5.8" for
	// "7.5.8 Filters", or empty when the title does not begin with one. It is kept
	// separate because it is what a cross-reference names and what a stable URI is
	// built from, and recovering it from the title at every use would mean parsing
	// it in several places.
	Number string

	// Blocks are the section's own content in reading order, excluding the heading
	// itself and excluding everything belonging to a subsection.
	Blocks []Block

	// Kids are subsections in document order.
	Kids []*Section

	// Parent is the enclosing section, nil at the top level.
	Parent *Section

	// Pages is the 1-based page range the section's content was found on, inclusive.
	// Both are 0 for a section whose content could not be anchored to any page. This
	// is a range and not a number on purpose: the median clause fits on one page and
	// the ones that matter do not.
	FirstPage, LastPage int
}

Section is one clause of a document: a heading, the content under it, and the subsections nested beneath.

The shape here follows a measurement rather than an expectation. An earlier draft of docs/DESIGN.md had a clause as "one contiguous subtree", which would have made Section a thin view over the structure tree. ISO 32000-2 has 7 Sect elements against 981 headings, with a single Part holding 13,442 direct children in a flat H1 P P P … stream, so 966 of those headings have no element children at all: a clause's body is its heading's *following siblings*, not its descendants. Section is therefore a real tree that sectionize builds, not a projection of one that already exists.

Two consequences visible in the fields. Blocks holds the content directly rather than referencing pages, because a clause has no page — clause 7.5.8 running from page 412 to 414 is one section whose blocks came from three pages, and there is nothing to stitch since the structure tree was never page-scoped to begin with. And Pages records where the content was found rather than where the section "is", because that is a range and a reader checking a conversion needs it.

func (*Section) Path

func (s *Section) Path() []string

Path returns the section's ancestry titles from the top level down to and including its own, which is what OKF tags and a breadcrumb both need.

func (*Section) Text

func (s *Section) Text() string

Text returns the section's own blocks as text, one block per line, excluding subsections. A blank line separates blocks, matching what a sink would emit, so that a description extracted from this reads the same as the rendered document.

func (*Section) Walk

func (s *Section) Walk(fn func(*Section) bool) bool

Walk calls fn for every section in this subtree in document order, depth first, including the receiver. A fn returning false stops the traversal.

type Span

type Span struct {
	// Text is the run's characters. Several characters may come from one glyph — a
	// ligature — and one character may come from several glyphs.
	Text string

	// Style is how the run was drawn.
	Style Style

	// Box is the run's bounding rectangle in page coordinates.
	Box geom.Rect

	// Page is the 1-based number of the page Box is measured on, or 0 when the span
	// carries no geometry.
	//
	// Page coordinates are per page, so a Box alone is not a position: two spans on
	// different pages can hold the same rectangle and be a page apart on paper. A
	// consumer that regroups spans has to know that, and one does — sectionize joins
	// spans in the order a structure element lists its content, and a paragraph
	// continuing past a page break is one element whose references name two pages, so
	// its geometric rules were comparing a Y0 from page n against one from page n+1.
	// See sectionize's sameLine, which is where that comparison is refused.
	//
	// Only a span the extractor drew has one. Every other producer fabricates spans to
	// carry text with no position — a declared label, an /ActualText substitution, an
	// inferred break — and 0 is the statement of that, chosen as the zero value because
	// "no geometry" is what a hand-built Span should mean. Page numbers are 1-based
	// (Page.Number), so 0 cannot collide with a real page the way MCID 0 collides with a
	// real identifier.
	//
	// Not the same question as MCID -1, which is the tempting shortcut and is wrong: a
	// drawn span can have no marked-content identifier. PDF-Declarations draws its contents
	// leaders outside any marked content, and those 5 spans are ordinary rectangles on a
	// real page — a walk that read -1 as "no geometry" would call them page 0 and be wrong
	// about five real positions. An empty Box is what says there is no position; this field
	// says which page a non-empty one belongs to.
	Page int

	// Link is the URI the run links to, read from the page's link annotations, or empty.
	// Only a URI a reader follows, http, https, mailto or ftp, is carried (ADR 0041).
	Link string

	// Note is the label of the footnote this run marks, or empty for a run that marks
	// none. The run keeps the mark's own text, a raised "1" or "*", so a sink that
	// cannot link a note still says what the page says; one that can writes a
	// reference in its place.
	Note string

	// MCID is the marked-content identifier this run was drawn inside, or -1 when it
	// was drawn outside any marked-content sequence. Combined with the page number it
	// is the join key between page text and a structure element.
	//
	// It is on the span rather than only on the block because a span never crosses a
	// marked-content boundary while a block routinely does — the extractor starts a
	// new run at every MCID change, so this is exact where Block.MCIDs is a union. On
	// Well-Tagged-PDF-WTPDF-1.0.pdf that distinction is 12% of the headings.
	//
	// Zero is a valid MCID, so the absent value is -1 and cannot be the zero value of
	// the field. Constructing a Span by hand therefore leaves it claiming MCID 0; the
	// extractor always sets it, and a consumer joining on it should treat a page with
	// no marked content as having no join at all rather than trusting a 0.
	MCID int
}

Span is a run of text sharing one style.

type Style

type Style struct {
	// Font is the /BaseFont name with any subset prefix stripped.
	Font string

	// Size is the effective on-page size in user-space units, after the text
	// matrix and CTM. Not the Tf operand: a Tf of 1 with a matrix scaling by 12 is
	// how many producers set 12-point type, and reporting 1 makes every size-based
	// heading heuristic useless.
	Size float64

	// Bold and Italic are as declared by the font descriptor's flags and weight.
	Bold   bool
	Italic bool

	// Mono reports a fixed-pitch font, from the descriptor's flag. It is the signal
	// that distinguishes a code block from a paragraph in an untagged document,
	// where nothing else does.
	Mono bool

	// Strike reports a line drawn through the run, which extract reads from a rule set at the
	// height of the letters' lower body (ADR 0040). GFM writes it as ~~.
	Strike bool

	// Hidden reports rendering mode 3 or 7 — invisible, or clip-only. This is the
	// text layer under a scanned page, which is exactly the text an extractor
	// wants, so it is reported rather than filtered. A sink emits it; a coverage
	// calculation counts it; only a renderer skips it.
	Hidden bool
}

Style is the typographic identity of a span.

Font stays alongside the Bold and Italic flags rather than being replaced by them, because the two disagree and each has a consumer. The flags are what the descriptor asserts, and a font named "Arial-BoldMT" whose descriptor forgot the flag is ordinary — so the extractor sets the flags from both sources. A consumer grouping runs into blocks still needs the exact font name, which no pair of booleans can stand in for.

func (Style) SameRun

func (s Style) SameRun(o Style, t geom.Tolerance) bool

SameRun reports whether two styles are close enough that their spans can be merged into one.

Size is compared with a tolerance because it is computed from a matrix, so two glyphs set in the same type can differ in the last bits. Without the tolerance a paragraph becomes one span per glyph, which is correct and useless.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL