Documentation
¶
Overview ¶
Package gofastcore defines the document model and extractor interface shared by every go-fast-* extraction library.
Every extractor, whatever its input format, produces a *Document:
Document ├── Source where the bytes came from and what format they were ├── Metadata title, authors, dates, ... ├── Outline[] the source's own table of contents, if it has one ├── Parts[] the format's natural top-level unit: page, slide, sheet, ... │ ├── Blocks[] content in reading order: heading, paragraph, table, ... │ └── Warnings[] what went wrong in this part ├── Children[] embedded documents: email attachments, archive members └── Warnings[] what went wrong for the document as a whole
The model is deliberately flat inside a part. Section hierarchy is not stored; it is implied by heading levels, which lets extractors emit blocks in a single pass and lets page workers run independently.
The shared model is the common denominator across formats. An extractor may offer a richer native API beside it (word boxes, fonts, glyph positions for PDF); those details do not belong here.
Contract for extractors ¶
- All strings are valid UTF-8 and follow the text conventions below.
- A block is at least a paragraph-sized unit, never a fragment of a line or word.
- Blocks appear in reading order. Where the format does not declare order (PDF), order is the extractor's best inference. Block.Origin does not cover order; it describes kind, level and boundaries only.
- A top-level document has at least one part. Formats with no natural unit (docx, html, txt) use a single PartBody.
- Part numbers are the 1-based ordinal of the part in the source and strictly increase. They need not be contiguous: extracting pages 40-60 yields parts numbered 40 to 60.
- A block that runs across a part boundary is either assigned to the part where it starts or split, with Continued set on the later piece. A table too large for one block is split by rows within its part, with Continued set on the later pieces.
- Partial extraction returns a Document with warnings, not an error. Errors are for input that yields nothing usable.
- Content the file declares not shown or not inked is extracted like any other and carries the reason (Display), never dropped. Nothing else about visibility is judged. Every extractor calls Part.Finish on each finished part.
- Lists that consumers iterate are never nil: Document.Parts, Part.Blocks and Table.Rows. JSON then has [] where a list is empty, never null, at no encoding cost. New and Part.Finish take care of the first two; a table has at least one row and one column.
- Output is deterministic: the same input and options give the same Document whatever Options.Workers is, including where a limit truncates it.
Text conventions ¶
- Text is in logical order, the order in which it is read and typed, also for right-to-left scripts. An extractor that cannot guarantee this for some input says so with a warning.
- Soft line breaks inside a paragraph are joined with a single space. A "\n" in Text means a hard break.
- End-of-line hyphenation is resolved only when the extractor is certain. Otherwise the hyphen stays and the lines are joined with no space: "inter-" + "national" gives "inter-national", so that a real compound such as "well-" + "known" comes out right.
- Presentation-form ligatures (U+FB00 to U+FB06) are written as their letters in every piece of text: block text, table cells, markers, part names, outline titles, alt text and the metadata's title, subject, authors and keywords. The output is for retrieval. Nothing wider is rewritten, and strings that identify or address something (a link target, an image ID, an anchor, a file name) are left as the source has them. See Ligature and ExpandLigatures.
- No string contains a control character (Unicode category Cc: NUL, form feed, carriage return, ...) other than "\n" and "\t".
- Block text is not empty and has no leading or trailing whitespace.
- Code blocks that the source declares as code are verbatim: the ligature and whitespace rules do not apply to them. Code that an extractor infers from layout has its ligatures expanded.
- Unicode normalization form is not guaranteed.
Document.Validate checks the mechanical parts of this contract and is intended to run in every extractor's test suite.
Index ¶
- Constants
- Variables
- func AppendLigatures(dst, src []byte) []byte
- func ExpandLigatures(s string) string
- func Ligature(r rune) string
- func ResolveLimit(v, def int64) int64
- func StoredKindNames() []string
- type Block
- type CellDetail
- type CellType
- type ChildFunc
- type DecodeBudget
- type Display
- type DisplayCells
- type Document
- func (d *Document) AllBlocks() iter.Seq2[*Part, *Block]
- func (d *Document) AllWarnings() iter.Seq2[*Part, Warning]
- func (d *Document) Markdown() string
- func (d *Document) Text() string
- func (d *Document) Validate() error
- func (d *Document) Walk(fn func(doc *Document, depth int) bool)
- func (d *Document) Warn(severity Severity, code, message string)
- func (d *Document) WriteMarkdown(w io.Writer, opts *RenderOptions) error
- func (d *Document) WriteText(w io.Writer, opts *RenderOptions) error
- type Extractor
- type Image
- type ImageMode
- type Kind
- type Limits
- type Location
- type Merge
- type Metadata
- type Options
- type Origin
- type OutlineItem
- type Part
- type PartKind
- type PartRange
- type Rect
- type RenderFlags
- type RenderOptions
- type Severity
- type Source
- type Span
- type Style
- type Table
- type TextBudget
- type Warning
Constants ¶
const ( // AttrNoteType says what a KindNote block is: one of the Note* // values. AttrNoteType = "type" // AttrAuthor is who wrote a note or made a tracked change, as the // source names them. AttrAuthor = "author" // AttrDate is when a note was written or a change made, as the // source writes it, normally ISO 8601. AttrDate = "date" // AttrLevel is the real level of a heading deeper than six, in // decimal ("8"). AttrLevel = "level" // AttrLanguage is the programming language of a KindCode block. AttrLanguage = "language" // AttrName is the name the source gives a table, a pivot table or a // chart ("SalesTable"). AttrName = "name" // AttrRole says what a block stands for when its kind alone does not // say: a table that is not a grid of cells the source shows as such, // the headers of a message, a block of a signature. One of the Role* // values. AttrRole = "role" // AttrChart is the type of a chart, lowercase as the source names it // ("bar", "line", "pie", "scatter"). AttrChart = "chart" // AttrAxisX and AttrAxisY are the titles of a chart's axes. AttrAxisX = "x_axis" AttrAxisY = "y_axis" // AttrStored says what kind of stored, never-shown data a block is: // one of the Stored* values. It records where the text came from; it // sets no Display reason. Such a block is usually in the stored part, // but stored data that belongs to a page, sheet or slide (a PDF page's // scripts) stays in that part. The renderers leave out every block // marked stored, wherever it is, unless RenderOptions.Stored is set. AttrStored = "stored" // AttrNotation is the notation of a KindFormula block: one of the // Notation* values. AttrNotation = "notation" // AttrField is the name the source gives the form field or control // whose value the block is (a PDF form field, a Word form field or // content control). AttrField = "field" )
Keys of Block.Attrs that mean the same in every format.
const ( // RoleChart: the table is the data of a chart, as the chart's source // stores it. A chart's title is a KindCaption block before it. RoleChart = "chart" // RolePivot: the table is a pivot table. RolePivot = "pivot" // RoleHeaders: the block is the headers of a message that a mail // program shows (From, To, Date, Subject). RoleHeaders = "headers" // RoleSignature: the block is part of a message's signature, the text // after a line "-- ". RoleSignature = "signature" )
Values of Attrs[AttrRole].
const ( // StoredPivotCache: the records a pivot table was built from, kept in // the file where the source data is gone. StoredPivotCache = "pivot_cache" // StoredDefinedName: a name a workbook defines for a value, a formula // or a range of cells. StoredDefinedName = "defined_name" // StoredDocumentVariable: a variable a document stores for fields and // macros to use (Word's document variables). StoredDocumentVariable = "document_variable" // StoredCustomXML: data a program stored in the file as XML of its // own. StoredCustomXML = "custom_xml" // StoredFieldCode: the instruction of a field (a NoteField note, an // RTF index or table-of-contents entry). Every field note carries it. StoredFieldCode = "field_code" // StoredMacro: the source code of a macro or script, read as text and // never run. StoredMacro = "macro" // StoredMarkupComment: a comment in the file's markup (an HTML or XML // <!-- --> comment), which no reader displays. It stays where it // stands. A reviewer's comment, which is displayed, is a NoteComment // note and is not stored. StoredMarkupComment = "markup_comment" // StoredFormField: a field of a form that is shown on no page, such as // a PDF form field with no widget. StoredFormField = "form_field" // StoredAfterEnd: data that follows the logical end of the file (after // an RTF document's closing brace, after a PDF's last %%EOF, appended // to a zip archive). The part also carries WarnInputTrailingData. StoredAfterEnd = "after_end" // StoredManifestItem: a resource a publication lists in its manifest // and no chapter shows, such as an EPUB's image that no page uses. StoredManifestItem = "manifest_item" // StoredStylesheet: the text of a style sheet (an HTML <style> // element). StoredStylesheet = "stylesheet" // StoredGenerator: the name of the program that wrote the file, where // the file records it as data (RTF \generator). StoredGenerator = "generator" // StoredCustomProperty: a property of the document that its author or // a program defined, with its name in Attrs[AttrName] (RTF // \userprops). StoredCustomProperty = "custom_property" // StoredShapeData: the data a shape of a drawing carries and does not // draw (Visio's shape data, a row per label), a table after the // shape's own text in its page. StoredShapeData = "shape_data" // StoredLinkedData: a copy the file keeps of data from an outside // source it links to (a Visio data recordset), a table in the stored // part. StoredLinkedData = "linked_data" )
Values of Attrs[AttrStored].
const ( NotationLaTeX = "latex" NotationUnicodeMath = "unicodemath" // the linear form Word uses NotationPlain = "plain" )
Values of Attrs[AttrNotation].
const ( // NoteComment is a reviewer's comment or annotation attached to the // content. NoteComment = "comment" // NoteDeletion is text removed by a tracked change. The document's // text is given as if the change were accepted; the removed text is // kept here. NoteDeletion = "deletion" // NoteSpeaker is the speaker's notes of a slide. NoteSpeaker = "speaker" // NoteField is the instruction of a field whose result is in the text // ("HYPERLINK ...", "MERGEFIELD Name"). It follows its paragraph. The // instruction is never shown, but that is what a field is, not a // declaration: the note sets no Display reason. It is stored data: // every field note is marked Attrs[AttrStored] = StoredFieldCode, so // the renderers leave it out unless RenderOptions.Stored or // StoredKinds asks for it. NoteField = "field" // NoteChoices is the list of values a control offers to choose from: // the drop-down of a spreadsheet cell (a data validation list), a // drop-down form field or content control, the options of a PDF choice // field. Its Text is the values, one per line, in the source's order. // A list the source takes from cells elsewhere is given as the // reference to them ("=Lists!$A$1:$A$12"), since the values are // already in the text where those cells are. It follows the block of // the control, or for a sheet stands at the place of the cells it is // for (Loc.Range), with the control's name in Attrs[AttrField] where // the source names it. The values are shown to a reader who opens the // list; the note sets no Display reason. NoteChoices = "choices" // NoteAttribute is text a markup element keeps in an attribute rather // than in its content, and which a reader meets only through assistive // technology or by pointing at it: aria-label, title, placeholder, an // image map area's alt. It stands at the element's place, with the // attribute's name in Attrs["attribute"]. No Display reason. NoteAttribute = "attribute" // NoteHeaders: the headers of a message that a mail program does not // show, one "Name: value" per line. No Display reason: the format // declares none. NoteHeaders = "headers" // NoteMIMEPreamble and NoteMIMEEpilogue: the text of a multipart // message body before its first part and after its last, which no mail // program shows. No Display reason: the format declares none. NoteMIMEPreamble = "mime_preamble" NoteMIMEEpilogue = "mime_epilogue" )
Values of Attrs[AttrNoteType].
const ( BlockCost = 128 CellCost = 16 )
BlockCost and CellCost are what a block, and a cell of a table, take from the text budget (Limits.MaxTextBytes) beyond their text. A file decides how many blocks and cells there are as freely as it decides how long a string is: a PDF page that draws one image a hundred thousand times needs six bytes of content for each, and a sheet can have a grid of empty cells. BlockCost is about what a block takes written down with no text (in the PDF corpus, a document's JSON is 157 bytes a block beyond its text); CellCost is what a cell takes in memory, more than it takes in JSON. At the default limit a document has at most two million blocks.
const ( // WarnPartFailed: the part could not be parsed. Its blocks are missing // or incomplete. Severity error. WarnPartFailed = "part.failed" // WarnPartNoText: the part was parsed and contains no text and no // images, e.g. a blank page or a page of vector drawing only. WarnPartNoText = "part.no_text" // WarnPartImageOnly: the part was parsed and contains no text, but // does contain image content. This is what a scanned page looks like. // It is reported whatever Options.Images is set to. WarnPartImageOnly = "part.image_only" // WarnTextUnmappedGlyphs: some text has no Unicode mapping in the // source and appears as U+FFFD or is absent. WarnTextUnmappedGlyphs = "text.unmapped_glyphs" // WarnTextControlCharactersRemoved: control characters (Unicode Cc) // with no meaning as text were removed from extracted text, as the // text conventions require: NUL, ESC, the C1 controls and the like. // Not counted are those the format reads as something: tab, line // ends (a carriage return), and white space or a break (a form feed // in HTML, or between pages). The message says how many. Severity // info. Every extractor that removes any raises it, once per part or // document with the count. WarnTextControlCharactersRemoved = "text.control_characters_removed" // WarnTextEncodingDetected: the input declares no character encoding // and is not valid UTF-8; it was read in the encoding its bytes were // recognised as, which the message names, with how to give one // instead. Severity warning: the encoding is not declared, though an // extractor uses one only where it is certain and refuses the input // otherwise. WarnTextEncodingDetected = "text.encoding_detected" // WarnTextTrackedChanges: the part has tracked changes. Its text is // given as if all were accepted; each deletion is kept as a note block // of type NoteDeletion. WarnTextTrackedChanges = "text.tracked_changes" // WarnHeadingLevelClamped: the part has headings deeper than six // levels. Each has Level 6 and its real level in Attrs[AttrLevel]. // Severity info: nothing is lost. WarnHeadingLevelClamped = "structure.heading_level_clamped" // WarnImageUnsupportedEncoding: image data was requested // (ImagesData) and an image uses an encoding the extractor cannot // deliver; its block is present without data. WarnImageUnsupportedEncoding = "image.unsupported_encoding" // WarnInputRepaired: the input was structurally damaged and was read // by a recovery path. Severity info if nothing is known to be lost. WarnInputRepaired = "input.repaired" // WarnInputUnreadContent: the input holds content of a kind the // extractor does not read (an equation, a sound or video clip, a // plug-in, a dialog sheet); the message names the kind and how many. // It is not in the output. Severity warning. WarnInputUnreadContent = "input.unread_content" // WarnInputStreamDamaged: a stream or member of the file other than // its main content (styles, numbering, notes, document properties, a // manifest, a VBA project, an embedded object) could not be read to // its end; what was read before the damage is used. The message names // it. "Stream" is a piece of the file, not a Part of the document. // Severity warning. WarnInputStreamDamaged = "input.stream_damaged" // WarnInputDecrypted: the input was encrypted and was decrypted, and // Metadata.Encrypted is set. The message names the scheme, and which // password (the caller's, or one the format defines for files meant to // open without one) or certificate opened it. Severity info. WarnInputDecrypted = "input.decrypted" // WarnInputActiveContent: the input contains something meant to be // run, or an instruction to run something: macros, scripts, an action // that starts a program or opens a file (a PDF Launch action). It is // not read and never run. An instruction that names a file or address // outside the input is also WarnInputExternalReference; the two are // separate facts. WarnInputActiveContent = "input.active_content" // WarnInputExternalReference: the input refers to a file or address // outside itself other than by an ordinary hyperlink: a remote // template, a linked picture, a linked object, an action that sends // form data to or loads data from an address. Nothing is fetched or // sent. WarnInputExternalReference = "input.external_reference" // WarnInputAmbiguous: the input can be read as two different // documents, depending on the program: an archive that names a member // twice in two ways, or has two members with one name. Which reading // this extractor takes is in its documentation. WarnInputAmbiguous = "input.ambiguous" // WarnInputTrailingData: data follows the logical end of the file // (after an RTF document's closing brace, after a PDF's last %%EOF, // appended to a zip archive). Its text is in the stored part with // Attrs[AttrStored] = StoredAfterEnd. The message says how many bytes // follow the end. WarnInputTrailingData = "input.trailing_data" // WarnTableRegionSplit: an area of a sheet whose cells are spread so // thinly that the rectangle around them is mostly empty was not // written as one table: each run of cells side by side in a row is a // table of one row. The message gives the sheet and the count. // Severity info: no cell is lost. WarnTableRegionSplit = "table.region_split" // WarnTableFormulaNoValue: cells hold formulas with no stored result // (a program wrote the file without calculating it), so they are // empty; formulas are not evaluated, and are in Table.Cells when // Options.Cells is set. One warning per part with the count. // Severity info. WarnTableFormulaNoValue = "table.formula_no_value" // WarnLimitExceeded: a limit was reached during extraction and the // output is cut or left out at that point. The limit is one of // Options.Limits or a fixed bound of the extractor (the longest field // instruction it keeps, the most columns of a table it reads); the // message says which, and what was left out. It covers anything that // would appear in the output: text, cells, notes, metadata values, // names, labels and addresses; a bound on data used only inside the // extractor needs no warning. Severity error, for every such cut. WarnLimitExceeded = "limit.exceeded" // WarnWarningsOmitted: more warnings were raised on the part or the // document than MaxWarnings, and the rest are counted here instead of // listed. Part.Warn and Document.Warn add it at the end of the list // (warnings appended to the list directly can follow it); extractors // do not emit it themselves. Its message begins with the // number of warnings it counts, and its severity is the highest of // theirs. WarnWarningsOmitted = "warnings.omitted" // WarnChildNotExtracted: an embedded document is listed in Children // with its name and size but was not extracted, because no child // extractor was supplied, the depth limit was reached, or the // extractor had nothing to hand over (a limit stopped it first). WarnChildNotExtracted = "child.not_extracted" // WarnChildUnsupported: no extractor handles the embedded document's // format, or it uses a feature that is not implemented. It is listed // in Children without content. WarnChildUnsupported = "child.unsupported" // WarnChildEncrypted: the embedded document is encrypted and was not // opened: no password was supplied, the one supplied does not open // it, or no key in Options.Keys matches a recipient it names. // Severity error. WarnChildEncrypted = "child.encrypted" // WarnChildFailed: extraction of an embedded document was attempted // and failed for any other reason. Severity error. WarnChildFailed = "child.failed" )
Warning codes shared by all extractors. Each describes an observed fact about the input or the output.
const DefaultMaxDepth = 4
DefaultMaxDepth is how deeply embedded documents are followed when Limits.MaxDepth is zero: an attachment inside an archive inside an email is depth 2.
const DefaultMaxTextBytes = 256 << 20
DefaultMaxTextBytes is the text a document and the documents embedded in it may hold when Limits.MaxTextBytes is zero. It is some ten times the text of a workbook of two million cells or of a book of a million and a half words.
const MaxWarnings = 1000
MaxWarnings is the number of warnings Part.Warn and Document.Warn keep on one part or one document. Past it, each further warning is counted in a single warning with the code warnings.omitted, added at the end of the list, whose severity is the highest of those it counts and whose message begins with their number. The count is read back from that warning, so it survives a copy of the part and a round trip through JSON. It stays last unless an extractor appends to Warnings directly after it; such appends are not bounded by MaxWarnings, and an extractor that makes many of them past the bound may get a second summary. The count stops at 999,999,999. Past the bound Warn adds no entry and updates the summary in place: Has does not see a warning that was only counted, code that remembers the index of a warning it raises must check it, and two copies of a part that share one Warnings array share the summary, or overwrite each other's. A summary copied in from another part's list counts on for this one. An extractor should still merge warnings that repeat, with a count, rather than rely on this bound.
const SchemaVersion = "0.2"
SchemaVersion identifies the shape of the serialized model. It changes when a field is removed or its meaning changes. Additions, including new block kinds, do not change it: decoders map names they do not know to the Unknown value of the enum.
0.2 (2026-11-20): Hidden became Display, with only the reasons a file declares ("hidden", "no_ink"); hidden_checked and the text.hidden warning were removed. Later in 0.2, two rules narrowed what an extractor may write without changing the shape: a thematic break is always native (Validate rejects an inferred one), and the values of Attrs["stored"], Attrs["type"] on a note and Attrs["role"] are closed sets.
The schema version is not the module version: module v0.1.0 writes schema 0.2.
Variables ¶
var ( // ErrPasswordRequired: the input is encrypted and no password was given. ErrPasswordRequired = errors.New("gofastcore: password required") // ErrWrongPassword: the input is encrypted and the password given does // not open it. ErrWrongPassword = errors.New("gofastcore: wrong password") // ErrKeyRequired: the input is encrypted for a certificate and no key // in Options.Keys matches a recipient it names. ErrKeyRequired = errors.New("gofastcore: private key required") // ErrUnsupported: the input is valid but uses a feature or variant the // extractor does not implement. ErrUnsupported = errors.New("gofastcore: unsupported input") // ErrMalformed: the input is not a readable file of the expected format. ErrMalformed = errors.New("gofastcore: malformed input") // ErrLimitExceeded: a limit stopped the extraction before there was // anything to return. That is always the case when the input exceeds // Limits.MaxInputBytes, and it is the case for any other limit that is // reached before the input could even be identified, such as a // decompression bomb in the part that says what the file is. A limit // reached once there is a document truncates it and adds // WarnLimitExceeded instead of failing. ErrLimitExceeded = errors.New("gofastcore: limit exceeded") // ErrNoPartsSelected: Options.Parts selects no part of the input, // because it lies beyond the last part or First is greater than Last. ErrNoPartsSelected = errors.New("gofastcore: part range selects no parts") )
Errors common to all extractors. Extractors wrap them, so test with errors.Is.
Functions ¶
func AppendLigatures ¶
AppendLigatures appends src to dst with every presentation-form ligature written as its letters, and returns the extended slice. It is ExpandLigatures for an extractor that assembles text in a buffer.
func ExpandLigatures ¶
ExpandLigatures returns s with every presentation-form ligature (U+FB00 to U+FB06) written as its letters. A string that has none is returned as it is, without allocating.
func Ligature ¶
Ligature returns the letters a presentation-form ligature (U+FB00 to U+FB06) stands for, and "" for any other character.
Every go-fast library writes these seven characters as their letters in all text it extracts, because the output is searched and compared: a reader looking for "office" must find a document that spells it with U+FB01. Nothing wider is done; this is not compatibility normalization. An extractor that builds text a character at a time calls Ligature, and one that has whole strings calls ExpandLigatures or AppendLigatures, so that no library keeps its own table.
func ResolveLimit ¶
ResolveLimit applies the Limits convention to one value: it returns def when v is zero, the largest int64 when v is negative, and v otherwise.
func StoredKindNames ¶
func StoredKindNames() []string
StoredKindNames returns every value of Attrs[AttrStored], for a command that takes kinds by name (RenderOptions.StoredKinds). The slice is the caller's.
Types ¶
type Block ¶
type Block struct {
// Kind is what the block is; it decides which other fields mean
// something (the table above).
Kind Kind `json:"kind"`
// Level is a heading's level, or the nesting depth of a list item or
// quote; other kinds do not use it.
Level uint8 `json:"level,omitempty"`
// Text is the block's text, following the package's text conventions.
// It is empty only for a table or a thematic break, and for an image
// with no alternative text.
Text string `json:"text,omitempty"`
// Origin says whether the block's kind, level and boundaries are
// declared by the source or were inferred by the extractor. It does
// not cover the block's position in the reading order: a PDF image is
// native (the file declares it and its box) even though where it falls
// among the text is inferred. The zero value is OriginNative, so an
// extractor that infers structure must set OriginInferred explicitly
// on every such block.
Origin Origin `json:"origin,omitempty"`
// Display lists every reason the file declares why content in this
// block is not shown or not inked; zero means it declares none, which
// says nothing about whether a reader can see the text. A reason that
// also appears on a span, or on a DisplayCells region of a table,
// applies only there; any other reason applies to the whole block. See
// DisplayWhole and DisplayedText. Such content is never dropped.
Display Display `json:"display,omitempty"`
// Continued marks a block that continues the nearest block of the
// same kind before it: the last one of the preceding part, as with
// the second half of a paragraph split by a page break, or the one
// before it in the same part, as with a table too long for one block
// and split by rows. A continued table has the columns of the table
// it continues; its HeaderRows count only header rows it repeats.
// Optional: an extractor that cannot tell leaves it false.
Continued bool `json:"continued,omitempty"`
// Ordered applies to list items.
//
// Marker is the label a reader sees in front of the block, as it
// appeared, when the source provides or defines one: the label of a
// list item ("3.", "(a)", "4.2.1"), the number of a numbered heading
// ("2.3"), the mark of a footnote ("1", "*"). It is content: a
// contract refers to "clause 4.2". It is kept out of Text, and the
// renderers put it back in front.
Ordered bool `json:"ordered,omitempty"`
Marker string `json:"marker,omitempty"`
// Spans carries inline formatting and links over Text, and marks the
// ranges the file declares not shown or not inked. Formatting and links
// are optional and only produced when Options.Spans is set; spans with
// Display set are always produced.
Spans []Span `json:"spans,omitempty"`
// Table is set exactly on a table block, Image exactly on an image
// block.
Table *Table `json:"table,omitempty"`
Image *Image `json:"image,omitempty"`
// Loc says where in the source the block came from.
Loc Location `json:"loc,omitzero"`
// Attrs is the escape hatch for format-specific facts. Keys are
// lowercase. Prefer a real field once two formats need the same key.
// The keys every format spells the same way are the Attr* constants.
Attrs map[string]string `json:"attrs,omitempty"`
}
Block is one unit of content in reading order.
Which fields are meaningful depends on Kind:
Kind Text Level Other KindHeading heading text 1-6 Marker KindParagraph paragraph text - - KindListItem item text, no marker nesting, from 1 Ordered, Marker KindTable empty - Table KindImage alt text / caption - Image KindCode code, verbatim - Attrs["language"] KindQuote quoted text nesting, from 1 - KindCaption caption text - - KindFootnote note text - Marker KindFormula the formula - Attrs["notation"] KindNote the note's text - Attrs: type, author, date, field KindHeader running header - - KindFooter running footer - - KindThematicBreak empty - -
A heading's Level is 1 to 6. A source with deeper levels (Word has nine) has them clamped to 6, with the real level, in decimal, in Attrs[AttrLevel]; the part then carries WarnHeadingLevelClamped.
KindHeader and KindFooter are page furniture (repeated titles, page numbers). They are kept so nothing is silently lost, and tagged so consumers can drop them.
KindThematicBreak marks a break between topics or scenes that the source declares (an HTML <hr>, a Markdown thematic break, Word's horizontal line, LibreOffice's Horizontal Line paragraph style). It is a boundary a chunker can split on. It has no text and is never Continued.
func (*Block) DisplayWhole ¶
DisplayWhole returns the reasons that apply to the whole block.
Block.Display lists every reason declared anywhere in the block. A reason that also appears on a span (or, for a table, on a DisplayCells region) applies only to those ranges; a reason that appears on none applies to the whole block.
func (*Block) DisplayedText ¶
DisplayedText returns the block's text without the content declared with one of the reasons in exclude: the empty string if such a reason applies to the whole block, otherwise Text with those ranges cut out.
type CellDetail ¶
type CellDetail struct {
Row int `json:"row"`
Col int `json:"col"`
// Href is where the cell links to: an address, or "#place" inside the
// document.
Href string `json:"href,omitempty"`
// Formula is the formula whose result the cell displays, as the
// source writes it, without a leading "=". It is never evaluated.
Formula string `json:"formula,omitempty"`
// Type is the kind of value the cell stores. Value is that value
// where the displayed text does not show it in full: a number its
// format rounds, a date's serial number. Value is set only with Type.
Type CellType `json:"type,omitempty"`
Value string `json:"value,omitempty"`
}
CellDetail is what one cell of a table holds besides its displayed text.
type CellType ¶
type CellType uint8
CellType is the kind of value a table cell stores (CellDetail.Type).
func (CellType) MarshalText ¶
func (*CellType) UnmarshalText ¶
type ChildFunc ¶
type ChildFunc func(ctx context.Context, name, mime string, r io.ReaderAt, size int64, opts *Options) (*Document, error)
ChildFunc extracts one embedded document. name is the attachment or member name and mime its declared media type; either may be empty. The function is expected to work out the format and route to the right extractor, passing opts through.
type DecodeBudget ¶
type DecodeBudget struct {
// contains filtered or unexported fields
}
DecodeBudget counts the bytes a document and the documents embedded in it may still decompress, against Limits.MaxDecodedBytes.
The limit on decompressed bytes is what stops a decompression bomb. An extractor counts against it as it reads, and each document has its own count. But a document can embed thousands of documents, each of them a bomb that stays just inside the limit: without more, the limit would hold for each and the whole would cost thousands of times as much. DecodeBudget makes the limit the document's and its embedded documents' together, as TextBudget does for text, and in the same way.
An extractor gets the budget of the document it is reading from WithDecodeBudget, and before it hands an embedded document to Options.ExtractChild sees to it that the budget says what the document has left (Take). It passes the context WithDecodeBudget returned. The child's extractor, of whatever library, gets from WithDecodeBudget a budget no larger than what its parent has left, reads within it, and on Close takes what it used from its parent; the parent then goes on with what is left. Embedded documents are extracted one after another.
How an extractor counts while it reads is its own affair: it may take from the budget as it goes, or keep a count of its own and settle with the budget (Settle) before each embedded document and at the end.
A nil *DecodeBudget has no limit. A DecodeBudget is safe for concurrent use.
func DecodeBudgetFrom ¶
func DecodeBudgetFrom(ctx context.Context) *DecodeBudget
DecodeBudgetFrom returns the budget ctx carries, or nil.
func WithDecodeBudget ¶
func WithDecodeBudget(ctx context.Context, limits Limits, def int64) (context.Context, *DecodeBudget)
WithDecodeBudget returns the budget for one reading of a document, and ctx carrying it. The budget is limits.MaxDecodedBytes (def if zero, none if negative; the default is the extractor's own), or what the document this one is embedded in has left, if ctx carries that and it is less.
func (*DecodeBudget) Close ¶
func (d *DecodeBudget) Close()
Close ends the reading: what the document took is taken from the budget of the document it is embedded in, if there is one. Later calls do nothing.
func (*DecodeBudget) Left ¶
func (d *DecodeBudget) Left() int64
Left returns the bytes not yet taken; a negative number once more was asked for than there was.
func (*DecodeBudget) Settle ¶
func (d *DecodeBudget) Settle(left int64) bool
Settle takes from the budget what is needed for Left to be at most left, and reports whether Left is then not negative. It is for an extractor that keeps a count of its own while it reads (left is what that count says the document has left) and settles with the budget before it hands an embedded document to Options.ExtractChild, and at the end. It never gives back: if the budget already has less than left, it is unchanged.
func (*DecodeBudget) Take ¶
func (d *DecodeBudget) Take(n int64) bool
Take takes n decompressed bytes from the budget and reports whether they were there to take.
type Display ¶
type Display uint16
Display is a set of reasons, each declared by the file, why content is not shown or not inked. The zero value means the file declares neither. In JSON it is a "+"-joined list of names, e.g. "hidden+no_ink".
A reason is declared when the file states it in one switch or one value of the content or of something containing it, including through the file's own inheritance (a style, an ancestor element). Anything that needs two values compared, or a threshold, is not a declaration and is not reported: colour against background, a size against a minimum, a box against the page or another box, the coverage of an image, an evaluated condition.
const ( // DisplayHidden: the file switches the content off. Hidden formatting // or the hidden attribute; a hidden sheet, row, column, slide, shape, // layer or annotation; display:none. DisplayHidden Display = 1 << iota // DisplayNoInk: the file declares the text drawn with no paint: no // fill, full transparency, PDF text render mode 3 or 7. The searchable // text layer of a scanned PDF page is drawn this way, so excluding // DisplayNoInk leaves out the text of scanned pages. DisplayNoInk // DisplayUnknown stands for reasons this version of the package does // not know. Unlike an unknown style, an unknown reason is kept on // decode, so that an older consumer never loses a declaration. DisplayUnknown Display = 1 << 15 // DisplayAny is every reason. It is meant for // RenderOptions.ExcludeDisplay. DisplayAny Display = 0xFFFF )
func (Display) MarshalText ¶
func (*Display) UnmarshalText ¶
type DisplayCells ¶
type DisplayCells struct {
Row int `json:"row"`
Col int `json:"col"`
RowSpan int `json:"row_span"`
ColSpan int `json:"col_span"`
Display Display `json:"display"`
}
DisplayCells marks a rectangular region of a Table whose cells the file declares not shown or not inked. Row and Col are 0-based; RowSpan and ColSpan are at least 1. A hidden column is one region the height of the table.
type Document ¶
type Document struct {
// SchemaVersion is the SchemaVersion of the package that wrote it.
SchemaVersion string `json:"schema_version"`
// Source says what the document was extracted from.
Source Source `json:"source"`
// Metadata holds the properties the source declares for the whole
// document.
Metadata Metadata `json:"metadata,omitzero"`
// Outline is the source's own table of contents, in its order.
Outline []OutlineItem `json:"outline,omitempty"`
// Parts are the format's natural units in source order: pages,
// slides, sheets, chapters, messages or one body, then the stored
// part if there is one. Never nil.
Parts []Part `json:"parts"`
// Children are the embedded documents, in the order the extractor met
// them; see Options.ExtractChild.
Children []*Document `json:"children,omitempty"`
// Warnings holds problems that concern the document as a whole.
// Problems local to a part are in Part.Warnings.
Warnings []Warning `json:"warnings,omitempty"`
}
Document is the output of every go-fast-* extractor.
func New ¶
New returns an empty Document for the given format with the schema version set. Its Parts list is empty but not nil, so that it is written to JSON as [] and never as null.
func (*Document) AllBlocks ¶
AllBlocks iterates over every block of the document in reading order, together with the part that holds it. Children are not visited.
func (*Document) AllWarnings ¶
AllWarnings iterates over the document-level warnings, for which the part is nil, and then over each part's warnings. Children are not visited.
func (*Document) Markdown ¶
Markdown renders the document (not its children) as Markdown with default options.
func (*Document) Text ¶
Text renders the document (not its children) as plain text with default options, for consumers such as embedding pipelines that do not want Markdown syntax. Blocks are separated by blank lines, tables are tab-separated, and images contribute their alt text.
func (*Document) Validate ¶
Validate checks that the document obeys the model's structural contract and the mechanical text conventions (valid UTF-8, no control characters, no unexpanded ligatures in text, trimmed non-empty block text) and returns every violation found, joined with errors.Join. It also checks that Part.Finish was called on every part, that the lists consumers iterate are not nil, and that every Attrs["stored"], note Attrs["type"] and Attrs["role"] is one of the package's values.
It is a check on producers. It walks the whole document, so call it from tests rather than on the hot path, and it rejects the Unknown enum values that only arise when decoding output from a newer extractor.
func (*Document) Walk ¶
Walk calls fn for d and then for every descendant in Children, depth first. It stops early if fn returns false.
func (*Document) Warn ¶
Warn appends a document-level warning. It keeps at most MaxWarnings of them, as Part.Warn does. It is not safe for concurrent use; workers should warn on their own Part instead.
func (*Document) WriteMarkdown ¶
func (d *Document) WriteMarkdown(w io.Writer, opts *RenderOptions) error
WriteMarkdown renders the document's parts to w as Markdown.
Text that would be read as Markdown structure at the start of a line ("# ", "> ", "- ", "1. ") is escaped, so a paragraph stays a paragraph. Inline characters are not escaped. Of Spans, links are rendered, as [text](<address>), and so are the links of table cells; formatting is not.
type Extractor ¶
type Extractor interface {
// Formats lists the format names this extractor handles, as they
// appear in Source.Format: "pdf", or "docx", "pptx", "xlsx".
Formats() []string
// Extract reads size bytes from r and returns the document. io.ReaderAt
// is used because the container formats (PDF, zip, OLE) need random
// access; an *os.File, a bytes.Reader and a memory map all satisfy it.
//
// opts may be nil. A partially readable input yields a Document with
// warnings. An error means nothing usable was extracted, and wraps one
// of the Err* values where one applies. Extract must return promptly
// with ctx.Err() once ctx is cancelled.
Extract(ctx context.Context, r io.ReaderAt, size int64, opts *Options) (*Document, error)
}
Extractor turns one or more input formats into the shared document model. Every go-fast-* library provides one, so that a dispatcher can treat all formats alike.
Implementations must be safe for concurrent use: a pipeline calls Extract from many goroutines, one document each.
type Image ¶
type Image struct {
// ID identifies the image resource within the document. Equal IDs
// mean equal bytes, and several blocks may share one ID (a logo on
// every page). It is not a per-block identifier.
ID string `json:"id,omitempty"`
MIME string `json:"mime,omitempty"`
// Width and Height are in pixels, 0 if unknown.
Width int `json:"width,omitempty"`
Height int `json:"height,omitempty"`
// Data holds the encoded image bytes when the extractor was asked for
// them. Serialized as base64. When several blocks share an ID, Data is
// guaranteed only on the first of them in document order; later ones
// may leave it nil.
Data []byte `json:"data,omitempty"`
}
Image describes an image referenced by a KindImage block.
type ImageMode ¶
type ImageMode uint8
ImageMode selects how much image information an extractor produces.
const ( // ImagesMeta, the default, emits a block for every image, with what // the source says of it: its place, its dimensions, its alternative // text, and an ID by which the same image is known wherever it // occurs. An image is content: where it stands gives context, and // its alternative text is text its author wrote. ImagesMeta ImageMode = iota // ImagesData additionally fills Image.Data with the encoded bytes, // for a caller that looks at the pictures. ImagesData // ImagesNone emits no image blocks: the alternative text of images // is then not in the document. WarnPartImageOnly is still reported. // For callers that want text only and know what they leave out. ImagesNone )
type Kind ¶
type Kind uint8
Kind is the type of a Block.
const ( // KindInvalid is the zero value: a block whose kind was never set. KindInvalid Kind = iota // KindUnknown is a kind this version of the package does not know. // Consumers should treat it as a paragraph. KindUnknown // The kinds of content. What each uses of Block's fields is in the // table in Block's documentation. KindParagraph KindHeading KindListItem KindTable KindImage KindCode KindQuote KindCaption KindFootnote KindFormula KindNote KindHeader // KindThematicBreak is a break between topics or scenes that the // source marks as such: an HTML <hr>, a Markdown thematic break, // Word's horizontal line, an empty paragraph in LibreOffice's // Horizontal Line paragraph style. It has no text and is always OriginNative: // a bordered or ruled paragraph, a drawn line or a row of asterisks is // formatting, not a declared break, and no break is inferred from it. // Page, column and section breaks are layout and are not emitted as // blocks. KindThematicBreak )
func (Kind) MarshalText ¶
func (*Kind) UnmarshalText ¶
type Limits ¶
type Limits struct {
// MaxInputBytes bounds the input size. Exceeding it is
// ErrLimitExceeded before any work is done.
MaxInputBytes int64
// MaxDecodedBytes bounds the total bytes produced by decompression
// (zip members, PDF streams), the defense against decompression bombs.
MaxDecodedBytes int64
// MaxTextBytes bounds the text a document holds: the text of its
// blocks and the cells of its tables, each counted as often as it
// occurs, in the document and the documents embedded in it together,
// and BlockCost for every block and CellCost for every cell besides.
// It is the defense against a small file that says a long text many
// times over (one string that every cell of a sheet refers to, a
// form drawn on every page), which the decompression limit does not
// see: what is repeated is stored once. Text outside blocks counts
// too where the file decides both its length and how often it
// occurs (outline titles, a name made for every part, list markers,
// link targets), unless the extractor holds it to the length of a
// name. When the limit is reached, the part being read is cut off
// there with WarnLimitExceeded. The default is DefaultMaxTextBytes.
// See TextBudget.
MaxTextBytes int64
// MaxParts bounds the number of parts extracted. When the input has
// more, the first MaxParts parts of the requested range are returned
// with WarnLimitExceeded, also where the count is known up front.
MaxParts int
// MaxDepth bounds how deeply embedded documents are followed. The
// default is DefaultMaxDepth.
MaxDepth int
}
Limits bounds the work an extractor will do for one input. For every field, zero means the extractor's default and a negative value means no limit.
type Location ¶
type Location struct {
// BBox is the block's bounding box in the coordinate space of its
// part as displayed: origin top-left, y increasing downward, units as
// in Part.Width/Height. A box drawn at these coordinates on a rendered
// image of the part encloses the block.
BBox Rect `json:"bbox,omitzero"`
// Range is a cell range in A1 notation for blocks from a sheet,
// e.g. "B2:F40".
Range string `json:"range,omitempty"`
// Offset and Length give the block's byte span in the source for
// plain-text formats (txt, md, html).
Offset int64 `json:"offset,omitempty"`
Length int64 `json:"length,omitempty"`
// Anchor is an identifier the source itself gives the block, stable
// for as long as the source is: a Word paragraph id, an HTML id
// attribute, the fragment of an e-book link. It is what a citation
// points at in a format that has no pages and no byte offsets.
Anchor string `json:"anchor,omitempty"`
}
Location pins a block to its place in the source so that a retrieval hit can be cited and shown in context. Every field is optional; the part a block belongs to is given by its position in Document.Parts.
type Merge ¶
type Merge struct {
Row int `json:"row"`
Col int `json:"col"`
RowSpan int `json:"row_span"`
ColSpan int `json:"col_span"`
}
Merge is a merged cell region. Row and Col are 0-based; RowSpan and ColSpan are at least 1 and at least one of them is greater than 1.
type Metadata ¶
type Metadata struct {
Title string `json:"title,omitempty"`
// Authors has one entry per author the source declares. A source with
// a single free-text author field (PDF) yields one entry, verbatim;
// extractors must not split a string on guesswork.
Authors []string `json:"authors,omitempty"`
Subject string `json:"subject,omitempty"`
// Keywords follows the same rule as Authors: a single free-text
// keywords field yields one entry, verbatim.
Keywords []string `json:"keywords,omitempty"`
Language string `json:"language,omitempty"` // BCP 47, e.g. "en", "pt-BR"
// Created and Modified are the dates the source declares for the
// document; zero where it declares none.
Created time.Time `json:"created,omitzero"`
Modified time.Time `json:"modified,omitzero"`
// Application is the software that produced the file.
Application string `json:"application,omitempty"`
// Encrypted reports that the input was encrypted (and was decrypted).
Encrypted bool `json:"encrypted,omitempty"`
// Extra carries format-specific properties that have no field above,
// e.g. email "from"/"to"/"message-id", PDF "producer". Keys are
// lowercase.
Extra map[string]string `json:"extra,omitempty"`
}
Metadata holds document-level properties. Every field is optional.
type Options ¶
type Options struct {
// Workers bounds the goroutines used inside a single document
// (e.g. PDF pages). 0 means runtime.GOMAXPROCS(0). Pipelines that
// already parallelize across documents should set 1.
Workers int
// Images selects how much image information to extract. The zero
// value is ImagesMeta: every image is a block.
Images ImageMode
// Spans asks for inline formatting and links in Block.Spans. Spans
// that carry a Display reason are produced whether or not this is set.
Spans bool
// Password is tried on encrypted input. It is also passed down to
// embedded documents, which is what opens an encrypted attachment of
// an unencrypted email.
Password string
// Keys are private keys tried on input encrypted for a certificate
// (an Office file encrypted for a certificate, a PDF with the
// public-key security handler): the key whose public half matches a
// recipient the file names is used. A crypto.Decrypter may keep its
// key in hardware or in another process. Passed down to embedded
// documents, as Password is.
Keys []crypto.Decrypter
// Cells asks for the formulas of table cells, and the type and the
// stored value of a cell where its displayed text does not show the
// value in full, in Table.Cells. On a sheet of numbers that is an
// entry for every cell, so it is not given unless asked for.
Cells bool
// Parts restricts extraction to a range of part numbers. The zero
// value extracts every part. A range that selects nothing is
// ErrNoPartsSelected.
Parts PartRange
// Limits guards against hostile or oversized input.
Limits Limits
// Child extracts embedded documents (email attachments, archive
// members, files embedded in a PDF). It is how a dispatcher that
// knows every format is injected into an extractor that knows one,
// without the extractors importing each other. When nil, embedded
// documents are listed in Children but not extracted.
//
// Extractors do not call Child directly; they call ExtractChild.
Child ChildFunc
// Name is recorded as Source.Name.
Name string
// Depth is the nesting depth of the document being extracted: 0 for
// a top-level document. ExtractChild maintains it; callers leave it
// zero.
Depth int
}
Options are the settings common to all extractors. The zero value asks for text, structure and a block for every image, for the whole input, using all CPUs.
Settings that only one format understands (for PDF: memory mapping, a cache budget) do not belong here. They are fields on that library's extractor value, e.g. (&gofastpdf.Extractor{...}).Extract(...).
func (*Options) ExtractChild ¶
func (o *Options) ExtractChild(ctx context.Context, name, mime string, r io.ReaderAt, size int64) *Document
ExtractChild extracts one embedded document on behalf of an extractor and always returns a Document to append to Children, so that every embedded file is at least listed with its name and size.
The returned document has no parts and a single warning when the child was not extracted. The warning code says why:
WarnChildNotExtracted no ChildFunc was supplied, the depth limit was reached, or r is nil
(the extractor has nothing to hand over, as when a limit stopped it)
WarnChildUnsupported the ChildFunc returned ErrUnsupported
WarnChildEncrypted the ChildFunc returned ErrPasswordRequired, ErrWrongPassword or ErrKeyRequired
WarnChildFailed the ChildFunc returned any other error
ExtractChild may be called on a nil *Options.
type Origin ¶
type Origin uint8
Origin says how a block's structure (its kind, level and boundaries) was determined. It says nothing about where the text came from.
const ( // OriginNative: the source declares the structure. A docx style, an // HTML tag, a tagged-PDF structure element, a PDF outline entry. OriginNative Origin = 0 // OriginInferred: the extractor deduced the structure from geometry, // fonts or other heuristics. A consumer that needs certainty should // treat such blocks as plain text and chunk by size. OriginInferred Origin = 1 // OriginUnknown is an origin this version of the package does not know. OriginUnknown Origin = 255 )
func (Origin) MarshalText ¶
func (*Origin) UnmarshalText ¶
type OutlineItem ¶
type OutlineItem struct {
Title string `json:"title"`
// Level is the nesting depth, from 1.
Level int `json:"level"`
// Part is the Number of the part the entry points to, 0 if the target
// is unknown. The part may be absent from Parts when only a range was
// extracted.
Part int `json:"part,omitempty"`
// Y is the vertical position of the target within the part, in the
// part's coordinate space, 0 if unknown.
Y float64 `json:"y,omitempty"`
}
OutlineItem is one entry of the source's own table of contents: a PDF bookmark, an epub nav point. It is structure the source declares, so it is reliable even where block structure is inferred.
type Part ¶
type Part struct {
// Kind is the kind of unit: page, slide, sheet, chapter, message,
// body or stored.
Kind PartKind `json:"kind"`
// Number is the 1-based ordinal of this part in the source.
Number int `json:"number"`
// Name is what people call the part: the sheet name, slide title,
// chapter title, or a PDF page label ("iv", "A-3") where it differs
// from Number. Optional.
Name string `json:"name,omitempty"`
// Width and Height give the part's coordinate space for Block.Loc.BBox,
// as the part is displayed. For PDF: the CropBox after /Rotate and
// UserUnit are applied, in points. Zero when the part has no geometry.
Width float64 `json:"width,omitempty"`
Height float64 `json:"height,omitempty"`
// Display gives the reasons the file declares for the whole part: a
// hidden sheet or slide. Every block of the part carries the same
// reasons (Finish copies them).
Display Display `json:"display,omitempty"`
// Blocks are the part's content in reading order. Never nil once
// Finish has been called.
Blocks []Block `json:"blocks"`
// Warnings are the problems local to this part.
Warnings []Warning `json:"warnings,omitempty"`
}
Part is a format's natural top-level unit of content.
A part is self-contained: a worker can fill one without touching any shared state, and a part handed on by itself carries its own warnings.
func (*Part) Finish ¶
func (p *Part) Finish()
Finish completes a part. An extractor calls it once per part, after the part's blocks are final. It:
- copies Part.Display onto every block, so that "b.Display != 0" is the only test a consumer needs;
- makes Blocks an empty list instead of nil when the part has no blocks (a failed or blank page), so that JSON has [] and not null.
It touches only the part, so page workers can call it concurrently. It is idempotent.
func (*Part) Markdown ¶
Markdown renders a single part as Markdown with default options. Those leave out stored data and running headers and footers, so a stored part renders as "". To render one with other options, render a Document holding it.
type PartKind ¶
type PartKind uint8
PartKind is the type of a Part.
const ( PartInvalid PartKind = iota // PartUnknown is a part kind this version of the package does not know. PartUnknown // PartBody is the single part of a format with no natural division: // docx, odt, html, txt, md, rtf. PartBody PartPage // pdf PartSlide // pptx, odp PartSheet // xlsx (and xlsb), ods PartChapter // epub PartMessage // eml, msg; one per message in an mbox // PartStored holds what belongs to the file as a whole and to no // page, sheet or slide, and is shown on none: macro code, document // variables, custom XML data, defined names. A document has at most // one, after its other parts and numbered after them. It carries no // part-level Display reason: being stored says where text came from, // not what the file declares about its display. The renderers leave it // out unless RenderOptions.Stored is set. Options.Parts // selects it only with the whole document (the zero range); a reader // that gives parts one at a time gives it last, after the others. PartStored )
func (PartKind) MarshalText ¶
func (*PartKind) UnmarshalText ¶
type PartRange ¶
type PartRange struct {
First int // the first part number selected; 0 means from the first
Last int // the last part number selected; 0 means through the last
}
PartRange selects parts by number, both ends inclusive. A zero First means from the first part; a zero Last means through the last.
type Rect ¶
type Rect struct {
X0 float64 `json:"x0"`
Y0 float64 `json:"y0"`
X1 float64 `json:"x1"`
Y1 float64 `json:"y1"`
}
Rect is an axis-aligned rectangle with (X0,Y0) top-left and (X1,Y1) bottom-right.
type RenderFlags ¶
type RenderFlags struct {
// contains filtered or unexported fields
}
RenderFlags are the command-line flags every go-fast command offers for RenderOptions, with the same names, values and meaning in each:
-furniture Furniture -stored[=kinds] Stored, StoredKinds -part-markers PartMarkers -exclude-display[=reasons] ExcludeDisplay -children (default true) Children
A command defines them with AddRenderFlags and, after parsing, sets its RenderOptions with Apply.
func AddRenderFlags ¶
func AddRenderFlags(fs *flag.FlagSet) *RenderFlags
AddRenderFlags defines the shared render flags on fs and returns them.
func (*RenderFlags) Apply ¶
func (f *RenderFlags) Apply(o *RenderOptions)
Apply sets the fields of o that the render flags control, and leaves the others.
type RenderOptions ¶
type RenderOptions struct {
// Furniture includes running headers and footers, which are dropped
// by default.
Furniture bool
// Stored includes stored data: the stored part (macro code, defined
// names, document variables and other data the file shows nowhere),
// and blocks of other parts whose Attrs[AttrStored] is set, such as
// the scripts of a PDF page. Both are left out by default.
Stored bool
// StoredKinds includes only the stored data of the kinds named (values
// of Attrs[AttrStored], such as StoredMarkupComment or
// StoredFieldCode), wherever it is: in the stored part or in any other
// part. A block of the stored part with no kind is included only by
// Stored. Stored includes every kind, whatever StoredKinds says.
StoredKinds []string
// PartMarkers emits a line before each part so that positions survive
// in the rendered text: "<!-- page 3 -->" in Markdown, "[page 3]" in
// plain text.
PartMarkers bool
// ExcludeDisplay leaves out content the file declares with any of the
// given reasons. The default is to include everything. Excluding
// DisplayNoInk also leaves out the searchable text layer of scanned
// PDF pages, which would then render empty.
ExcludeDisplay Display
// Children renders the documents in Document.Children after the
// document's own parts, depth first, each after a line that names it:
// "<!-- child 2: report.pdf -->" in Markdown, "[child 2: report.pdf]"
// in plain text. A nested child is numbered by its path ("child 2.1").
// A child that was listed but not extracted gives its line only. The
// same options apply to every child. Children nested more than 64
// deep are not rendered: no extractor nests them so deep, and the
// bound stops a tree built by hand with a cycle in it.
Children bool
}
RenderOptions controls Markdown and plain-text output. The zero value is the default.
type Severity ¶
type Severity uint8
Severity says how a warning affects the output. Values are ordered, so "w.Severity >= SeverityError" is meaningful; an unknown severity sorts highest.
const ( // SeverityInvalid is the zero value: a severity that was never set. SeverityInvalid Severity = 0 // SeverityInfo: something notable happened; the output is complete. SeverityInfo Severity = 1 // SeverityWarning: the output is present but incomplete or degraded, // or it is one of more than one way the input can be read. SeverityWarning Severity = 2 // SeverityError: content is missing or untrustworthy. SeverityError Severity = 3 // SeverityUnknown is a severity this version of the package does not // know. SeverityUnknown Severity = 255 )
func (Severity) MarshalText ¶
func (*Severity) UnmarshalText ¶
type Source ¶
type Source struct {
// Format is the short lowercase format name: "pdf", "docx", "eml", ...
// It is empty only for a child that was listed but not extracted.
Format string `json:"format,omitempty"`
// Name is the file name, URL, or, for a child document, the attachment
// or archive member name. Optional.
Name string `json:"name,omitempty"`
// MIME is the media type if known.
MIME string `json:"mime,omitempty"`
// Size is the input size in bytes, 0 if unknown.
Size int64 `json:"size,omitempty"`
}
Source describes the input the document was extracted from.
type Span ¶
type Span struct {
Start int `json:"start"`
End int `json:"end"`
Style Style `json:"style,omitempty"`
Href string `json:"href,omitempty"`
// Display gives the reasons declared for this range when they apply to
// only part of the block. Every reason here is also in Block.Display.
Display Display `json:"display,omitempty"`
}
Span marks the range [Start, End) of Block.Text with inline styling, a link target, or the reasons the file declares that range not shown or not inked. Spans may overlap.
Start and End are byte offsets into the UTF-8 text, not character offsets, and always fall on character boundaries. A consumer in a language that indexes strings by code point must convert; in Python:
text.encode("utf-8")[start:end].decode("utf-8")
type Style ¶
type Style uint8
Style is a set of inline text styles. In JSON it is a "+"-joined list of names, e.g. "bold+italic". Names this version does not know are ignored on decode.
func (Style) MarshalText ¶
func (*Style) UnmarshalText ¶
type Table ¶
type Table struct {
// HeaderRows is the number of leading rows that are column headers.
HeaderRows int `json:"header_rows,omitempty"`
Rows [][]string `json:"rows"`
Merges []Merge `json:"merges,omitempty"`
// Display marks the cells the file declares not shown or not inked
// when that is only part of the table: a hidden row or column. Every
// reason here is also in Block.Display.
Display []DisplayCells `json:"display,omitempty"`
// Cells holds what some cells have besides the text they display, in
// order of row, then column; a cell with nothing more has no entry.
// Links come with Options.Spans; formulas, types and stored values
// with Options.Cells. Everything here counts against
// Limits.MaxTextBytes. The renderers write links, never formulas or
// values: a formula can hold text that nobody sees on the sheet.
Cells []CellDetail `json:"cells,omitempty"`
// RowLocs says where each row came from, for a source that can say it: a
// byte span, an anchor the source gives the row, a box on the page. It is
// empty, or has one entry per row in the order of Rows; a row with
// nothing to say has a zero Location. Block.Loc still covers the whole table.
RowLocs []Location `json:"row_locs,omitempty"`
}
Table is a rectangular grid of cell text. Every row has the same number of columns; a merged region stores its text in its top-left cell, leaves the other covered cells empty, and is listed in Merges.
Extractors should split very large sheets into several table blocks (each with its own Loc.Range) rather than emit one giant table.
type TextBudget ¶
type TextBudget struct {
// contains filtered or unexported fields
}
TextBudget counts the text a document may still produce, against Limits.MaxTextBytes.
A file can be small and say a great deal: one long string that every cell of a sheet refers to, a form drawn on every page. What is repeated is stored once, so the limit on decompressed bytes does not see it, and the document that results holds, or writes out, the text as often as it occurs. The budget is what bounds that.
An extractor gets the budget of the document it is reading from WithTextBudget, takes from it BlockCost and the bytes of the text of every block, CellCost and the bytes of every table cell it produces, and when Take reports false stops reading the part, keeps what it has and raises WarnLimitExceeded there. It calls Close when the document is done.
Text outside blocks is taken from the budget as well, wherever the file decides both how long it is and how often it occurs: outline titles, a name made for every part, list markers, link targets. A string the extractor holds to the length of a name need not be. The outline is counted before the first part and a part's name with the part, so that the place of the cut does not depend on timing.
The budget is the document's and its embedded documents' together. The context WithTextBudget returns carries the budget; an extractor passes that context to Options.ExtractChild, and the child's extractor, of whatever library, gets from WithTextBudget a budget of its own that is no larger than what its parent has left, and on Close takes what it used from its parent. Embedded documents are extracted one after another, so what each may use does not depend on timing.
A nil *TextBudget has no limit. A TextBudget is safe for concurrent use.
func TextBudgetFrom ¶
func TextBudgetFrom(ctx context.Context) *TextBudget
TextBudgetFrom returns the budget ctx carries, or nil.
func WithTextBudget ¶
WithTextBudget returns the budget for one reading of a document, and ctx carrying it. The budget is limits.MaxTextBytes (DefaultMaxTextBytes if zero, none if negative), or what the document this one is embedded in has left, if ctx carries that and it is less.
func (*TextBudget) Close ¶
func (b *TextBudget) Close()
Close ends the reading: what the document took is taken from the budget of the document it is embedded in, if there is one. Later calls do nothing.
func (*TextBudget) Exhaust ¶
func (b *TextBudget) Exhaust()
Exhaust spends what is left, so that Spent reports true and every later Take reports false: for an extractor that has stopped at the limit by a count of its own (an outline already cut at the limit) and so has nothing left for what follows. It gives nothing back if more was taken than there was.
func (*TextBudget) Left ¶
func (b *TextBudget) Left() int64
Left returns the bytes not yet taken; a negative number once more was asked for than there was.
func (*TextBudget) Reset ¶
func (b *TextBudget) Reset()
Reset gives back everything taken, for an extractor that reads the document again from the start (as one that reads parts side by side may, to cut the document at the same place whatever the number of workers).
func (*TextBudget) Return ¶
func (b *TextBudget) Return(n int64)
Return gives back n bytes that were taken, for an extractor that reads a part again and will take them a second time.
func (*TextBudget) Spent ¶
func (b *TextBudget) Spent() bool
Spent reports whether Take has reported false.
func (*TextBudget) Take ¶
func (b *TextBudget) Take(n int) bool
Take takes n bytes of text from the budget and reports whether they were there to take. Once it has reported false the budget is spent: the extractor keeps what it had before the call and stops. A negative n is taken as 0: Take never gives back (Return does), so Take(0) only reports whether the budget is spent.
type Warning ¶
type Warning struct {
// Code is a stable machine-readable identifier. The codes shared by
// all extractors are the Warn* constants; an extractor may add its own
// under a format prefix, e.g. "pdf.font_missing".
Code string `json:"code"`
// Severity says how the problem affects the output.
Severity Severity `json:"severity"`
// Message is free text for people. Programs should switch on Code.
Message string `json:"message,omitempty"`
}
Warning records a non-fatal problem encountered during extraction.
A warning states what happened. It never recommends what to do next: the go-fast libraries do no OCR and call no external service, so a code says "this part has images and no text", not "this part needs OCR". The caller decides what follows from the fact.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package cfb reads compound files, the container of the legacy Office formats, and writes them.
|
Package cfb reads compound files, the container of the legacy Office formats, and writes them. |
|
cfbtest
Package msbintest is the test harness of go-fast-msbin: it builds the files the library reads, so that each behaviour has a small file with exactly known content.
|
Package msbintest is the test harness of go-fast-msbin: it builds the files the library reads, so that each behaviour has a small file with exactly known content. |
|
Package charset decodes text in the character encodings documents use to UTF-8.
|
Package charset decodes text in the character encodings documents use to UTF-8. |
|
Package clean turns bytes read from a file into strings that obey the text conventions of the shared document model: valid UTF-8, no control characters other than line feed and tab, and for prose no surrounding white space and no presentation-form ligatures.
|
Package clean turns bytes read from a file into strings that obey the text conventions of the shared document model: valid UTF-8, no control characters other than line feed and tab, and for prose no surrounding white space and no presentation-form ligatures. |
|
Package hidden has what readers share in placing what the file declares about the display of text (hidden, no ink) on blocks and spans.
|
Package hidden has what readers share in placing what the file declares about the display of text (hidden, no ink) on blocks and spans. |
|
Package inflate decompresses deflate streams (RFC 1951) held in memory: raw, as zip members are; in zlib's wrapping (RFC 1950), as PDF streams are; and in gzip's (RFC 1952).
|
Package inflate decompresses deflate streams (RFC 1951) held in memory: raw, as zip members are; in zlib's wrapping (RFC 1950), as PDF streams are; and in gzip's (RFC 1952). |
|
Package label writes the labels a reader sees in front of list items: bullets, and numbers as letters and Roman numerals.
|
Package label writes the labels a reader sees in front of list items: bullets, and numbers as letters and Roman numerals. |
|
Package numfmt renders a spreadsheet cell's value the way the cell shows it: through its number format.
|
Package numfmt renders a spreadsheet cell's value the way the cell shows it: through its number format. |
|
Package opc reads the container of the formats built on the Open Packaging Conventions (ECMA-376 Part 2): a zip archive holding parts, a table of their content types, and relationship parts that link them.
|
Package opc reads the container of the formats built on the Open Packaging Conventions (ECMA-376 Part 2): a zip archive holding parts, a table of their content types, and relationship parts that link them. |
|
Package symbol translates the characters of symbol fonts to Unicode.
|
Package symbol translates the characters of symbol fonts to Unicode. |
|
Package vba reads the source code of a VBA project: the modules of macros an Office file carries in a storage of its compound file (a presentation, in a compound file of its own within its stream).
|
Package vba reads the source code of a VBA project: the modules of macros an Office file carries in a storage of its compound file (a presentation, in a compound file of its own within its stream). |
|
vbatest
Package vbatest builds VBA projects for tests ([MS-OVBA]): compressed containers and the streams of a project, in a compound file.
|
Package vbatest builds VBA projects for tests ([MS-OVBA]): compressed containers and the streams of a project, in a compound file. |
|
Package xmlscan is a streaming pull tokenizer for XML.
|
Package xmlscan is a streaming pull tokenizer for XML. |
|
Package ziprecover opens a zip archive, and one cut short in transit whose directory is lost, the same way for every go-fast library.
|
Package ziprecover opens a zip archive, and one cut short in transit whose directory is lost, the same way for every go-fast library. |