Documentation
¶
Overview ¶
Package liteparse is a Go binding for LiteParse (https://github.com/run-llama/liteparse), a fast local PDF/document parser with spatial text extraction, bounding boxes, markdown output, screenshots and optional OCR.
The binding needs no cgo: it loads the liteparse FFI shared library and PDFium at runtime via purego. See Load for how they are located.
p, err := liteparse.New(liteparse.WithOutputFormat(liteparse.FormatMarkdown))
if err != nil { ... }
defer p.Close()
res, err := p.ParseFile(ctx, "doc.pdf")
fmt.Println(res.Text)
Index ¶
- Constants
- Variables
- func Load(opts LoadOptions) error
- func Version() (string, error)
- type Annotation
- type AttributeValue
- type Config
- type CropBox
- type DocumentMetadata
- type Error
- type FormField
- type Headers
- type Image
- type ImageMode
- type LayoutBlock
- type LayoutCell
- type LayoutComplexity
- type LoadOptions
- type Option
- func WithConfig(cfg Config) Option
- func WithDPI(dpi float32) Option
- func WithMaxPages(n int) Option
- func WithOCR(enabled bool) Option
- func WithOCRLanguage(lang string) Option
- func WithOCRServer(url string, headers Headers) Option
- func WithOutputFormat(f OutputFormat) Option
- func WithPassword(pw string) Option
- func WithQuiet(quiet bool) Option
- func WithTargetPages(pages string) Option
- type OutputFormat
- type Page
- type PageComplexity
- type PageError
- type PageOrientation
- type Parser
- func (p *Parser) Close() error
- func (p *Parser) Config() Config
- func (p *Parser) IsComplexBytes(ctx context.Context, data []byte) ([]PageComplexity, error)
- func (p *Parser) IsComplexFile(ctx context.Context, path string) ([]PageComplexity, error)
- func (p *Parser) ParseBytes(ctx context.Context, data []byte) (*Result, error)
- func (p *Parser) ParseFile(ctx context.Context, path string) (*Result, error)
- func (p *Parser) ScreenshotBytes(ctx context.Context, data []byte, pages string) ([]Screenshot, error)
- func (p *Parser) ScreenshotFile(ctx context.Context, path, pages string) ([]Screenshot, error)
- type Rect
- type Result
- type Screenshot
- type ScreenshotRect
- type StructureElement
- type StructureTree
- type TextItem
- type VectorGraphics
- type VectorLine
- type VectorShape
- type WordBox
- type XFAPacket
Constants ¶
const ( // EnvLibPath names the liteparse FFI shared library file, or a directory // containing it. EnvLibPath = "LITEPARSE_LIB_PATH" // EnvPDFiumPath names the directory containing the PDFium shared library. // It is read by the native side; set it before the first parse. EnvPDFiumPath = "PDFIUM_LIB_PATH" )
Environment variables consulted when locating the native libraries.
const ( ReasonScanned = "scanned" ReasonNoText = "no-text" ReasonSparseText = "sparse-text" ReasonEmbeddedImages = "embedded-images" ReasonGarbled = "garbled" ReasonVectorText = "vector-text" ReasonAnnotationText = "annotation-text" ReasonMultiColumn = "multi-column" ReasonTableLikely = "table-likely" ReasonDenseGraphics = "dense-graphics" )
Complexity reasons. New values may appear in later liteparse versions.
Variables ¶
var ( ErrLibraryNotFound = errors.New("liteparse: native library not found") ErrInvalidArgument = errors.New("liteparse: invalid argument") ErrConfig = errors.New("liteparse: invalid config") ErrPDF = errors.New("liteparse: pdf error") ErrIO = errors.New("liteparse: io error") ErrOCR = errors.New("liteparse: ocr error") ErrConversion = errors.New("liteparse: conversion error") ErrCanceled = errors.New("liteparse: canceled") ErrPanic = errors.New("liteparse: native panic") ErrClosed = errors.New("liteparse: parser is closed") )
Sentinel errors. Match them with errors.Is; the returned *Error carries the native message.
Functions ¶
func Load ¶
func Load(opts LoadOptions) error
Load locates and loads the native libraries. Calling it is optional: every API loads lazily with default options on first use. Only the first call has any effect; later calls return the first call's result.
The liteparse FFI library is searched in order: opts.LibPath, $LITEPARSE_LIB_PATH, the executable's directory, <exe dir>/lib, ./lib, then the system loader's search path.
PDFium is loaded from opts.PDFiumPath when set. Otherwise, if a PDFium library sits next to the liteparse FFI library it is used; failing that, the native side searches $PDFIUM_LIB_PATH and the system loader's path.
Types ¶
type Annotation ¶
type Annotation struct {
Subtype string `json:"subtype"`
Contents string `json:"contents,omitempty"`
Created string `json:"created,omitempty"`
Modified string `json:"modified,omitempty"`
Title string `json:"title,omitempty"`
Rect *Rect `json:"rect,omitempty"`
QuadpointRects []Rect `json:"quadpoint_rects,omitempty"`
URI string `json:"uri,omitempty"`
}
Annotation is a PDF page annotation (Config.ExtractAnnotations).
type AttributeValue ¶
AttributeValue is a scalar structure attribute: exactly one field is set.
func (*AttributeValue) UnmarshalJSON ¶
func (v *AttributeValue) UnmarshalJSON(b []byte) error
UnmarshalJSON decodes an untagged bool, number or string.
type Config ¶
type Config struct {
// OCRLanguage is the Tesseract language code ("eng", "fra", ...).
OCRLanguage string `json:"ocr_language"`
// OCREnabled runs OCR on text-sparse pages and embedded images. It needs
// an engine: OCRServerURL, or a native library built with Tesseract.
OCREnabled bool `json:"ocr_enabled"`
// OCRServerURL points at an HTTP OCR server (liteparse OCR API spec).
OCRServerURL string `json:"ocr_server_url,omitempty"`
// OCRServerHeaders are sent with every OCR server request.
OCRServerHeaders Headers `json:"ocr_server_headers,omitempty"`
// TessdataPath is the tessdata directory (Tesseract builds only).
TessdataPath string `json:"tessdata_path,omitempty"`
// MaxPages caps the number of pages parsed.
MaxPages int `json:"max_pages"`
// TargetPages selects pages, e.g. "1-5,10".
TargetPages string `json:"target_pages,omitempty"`
// ExtractScreenshots renders parsed pages into Result.Screenshots.
ExtractScreenshots bool `json:"extract_screenshots"`
// ContinueOnPageError reports page failures in Result.PageErrors instead
// of failing the parse.
ContinueOnPageError bool `json:"continue_on_page_error"`
// DPI for OCR rasters and screenshots.
DPI float32 `json:"dpi"`
// OutputFormat selects the rendering of Result.Text.
OutputFormat OutputFormat `json:"output_format"`
// PreserveVerySmallText keeps text normally filtered as too small.
PreserveVerySmallText bool `json:"preserve_very_small_text"`
// Password for encrypted documents.
Password string `json:"password,omitempty"`
// Quiet suppresses native progress logging to stderr. New defaults it to
// true.
Quiet bool `json:"quiet"`
// NumWorkers is the number of concurrent OCR workers.
NumWorkers int `json:"num_workers"`
// ImageMode controls image references in markdown.
ImageMode ImageMode `json:"image_mode"`
// ExtractImages fills Result.Images with embedded image bytes.
ExtractImages bool `json:"extract_images"`
// ImageOutputDir also writes extracted images to this directory.
ImageOutputDir string `json:"image_output_dir,omitempty"`
// ExtractLinks renders hyperlinks as [text](url) in markdown.
ExtractLinks bool `json:"extract_links"`
KeepHeadersFooters bool `json:"keep_headers_footers"`
// ExtractAnnotations fills Page.Annotations.
ExtractAnnotations bool `json:"extract_annotations"`
// ExtractFormFields fills Page.FormFields.
ExtractFormFields bool `json:"extract_form_fields"`
// ExtractStructureTree fills Page.StructureTree for tagged PDFs.
ExtractStructureTree bool `json:"extract_structure_tree"`
// ExtractBlocks fills Page.Blocks with classified layout blocks.
ExtractBlocks bool `json:"extract_blocks"`
// ExtractContentBounds fills Page.ContentBounds.
ExtractContentBounds bool `json:"extract_content_bounds"`
// ExtractXFAPackets fills Result.XFAPackets.
ExtractXFAPackets bool `json:"extract_xfa_packets"`
// ExtractDocumentMetadata fills Result.DocMeta.
ExtractDocumentMetadata bool `json:"extract_document_metadata"`
// DetectScreenshotRects fills Screenshot.Rects.
DetectScreenshotRects bool `json:"detect_screenshot_rects"`
// RenderFormFields draws form field appearances into rasters. This runs
// the document's form JavaScript actions.
RenderFormFields bool `json:"render_form_fields"`
// OCRFailureFatal aborts the parse on systemic OCR failure.
OCRFailureFatal bool `json:"ocr_failure_fatal"`
// OCRHedgeDelaysMS is the HTTP OCR request-hedging schedule.
OCRHedgeDelaysMS []uint64 `json:"ocr_hedge_delays_ms,omitempty"`
// EmitWordBoxes fills TextItem.Words.
EmitWordBoxes bool `json:"emit_word_boxes"`
// ExtractTextMetadata fills the rich TextItem metadata fields.
ExtractTextMetadata bool `json:"extract_text_metadata"`
// CropBox restricts output to a page sub-region.
CropBox *CropBox `json:"crop_box,omitempty"`
// SkipDiagonalText drops text rotated off the right angles.
SkipDiagonalText bool `json:"skip_diagonal_text"`
// PageOrientationCorrections counter-rotates the listed pages.
PageOrientationCorrections []PageOrientation `json:"page_orientation_corrections,omitempty"`
// IncludeComplexity fills Page.Complexity.
IncludeComplexity bool `json:"include_complexity"`
// ExtractVectorGraphics fills Page.VectorGraphics.
ExtractVectorGraphics bool `json:"extract_vector_graphics"`
}
Config mirrors liteparse's LiteParseConfig. Start from DefaultConfig, or let New do it, then override what you need. Empty optional fields keep liteparse's defaults.
func DefaultConfig ¶
DefaultConfig returns liteparse's defaults as reported by the native library, with Quiet set to true.
type CropBox ¶
type CropBox struct {
Top float32 `json:"top"`
Right float32 `json:"right"`
Bottom float32 `json:"bottom"`
Left float32 `json:"left"`
}
CropBox restricts output to a page sub-region. Each field is the fraction cropped away from that side, in [0, 1].
type DocumentMetadata ¶
type DocumentMetadata struct {
CreationDate string `json:"creation_date,omitempty"`
ModDate string `json:"mod_date,omitempty"`
FileVersion *int `json:"file_version,omitempty"`
IsEncrypted *bool `json:"is_encrypted,omitempty"`
SecurityHandlerRevision *int `json:"security_handler_revision,omitempty"`
Permissions *uint64 `json:"permissions,omitempty"`
EOFSectionCount *uint32 `json:"eof_section_count,omitempty"`
StartxrefCount *uint32 `json:"startxref_count,omitempty"`
TrailerIDPairDiffers *bool `json:"trailer_id_pair_differs,omitempty"`
RawFileSize *uint64 `json:"raw_file_size,omitempty"`
XMP string `json:"xmp,omitempty"`
XMPTruncated *bool `json:"xmp_truncated,omitempty"`
SignatureCount *uint32 `json:"signature_count,omitempty"`
SignatureByteRangeReachesEOF *bool `json:"signature_byte_range_reaches_eof,omitempty"`
}
DocumentMetadata is document provenance (Config.ExtractDocumentMetadata).
type FormField ¶
type FormField struct {
ID string `json:"id"`
Type string `json:"type"`
Page int `json:"page"`
AnnotationIndex int `json:"annotation_index"`
WidgetIndex int `json:"widget_index"`
ObjectNumber *int `json:"object_number,omitempty"`
Name string `json:"name,omitempty"`
AlternateName string `json:"alternate_name,omitempty"`
Value string `json:"value,omitempty"`
ExportValue string `json:"export_value,omitempty"`
FieldFlags int `json:"field_flags"`
ControlCount *int `json:"control_count,omitempty"`
ControlIndex *int `json:"control_index,omitempty"`
Checked *bool `json:"checked,omitempty"`
Rect *Rect `json:"rect,omitempty"`
Options []string `json:"options,omitempty"`
SelectedOptions []string `json:"selected_options,omitempty"`
}
FormField is an AcroForm widget (Config.ExtractFormFields).
type Headers ¶
Headers are extra HTTP headers sent to the OCR server.
func (Headers) MarshalJSON ¶
MarshalJSON encodes headers as the [name, value] pairs liteparse expects, sorted by name for deterministic output.
func (*Headers) UnmarshalJSON ¶
UnmarshalJSON decodes [name, value] pairs.
type Image ¶
type Image struct {
ID string `json:"id"`
Name string `json:"name"`
Path string `json:"path,omitempty"`
Page int `json:"page"`
BBox Rect `json:"bbox"`
Width int `json:"width"`
Height int `json:"height"`
Rotation float32 `json:"rotation"`
Format string `json:"format"`
DuplicateOf string `json:"duplicate_of,omitempty"`
// Data is the encoded image (JPEG or PNG per Format).
Data []byte `json:"data,omitempty"`
}
Image is an embedded raster image (Config.ExtractImages).
type ImageMode ¶
type ImageMode string
ImageMode controls how raster images surface in markdown output.
type LayoutBlock ¶
type LayoutBlock struct {
Kind string `json:"kind"`
Text string `json:"text,omitempty"`
Level int `json:"level,omitempty"`
Bold bool `json:"bold,omitempty"`
Italic bool `json:"italic,omitempty"`
Ordered *bool `json:"ordered,omitempty"`
Marker string `json:"marker,omitempty"`
Lines []string `json:"lines,omitempty"`
Lang string `json:"lang,omitempty"`
Header []LayoutCell `json:"header,omitempty"`
Rows [][]LayoutCell `json:"rows,omitempty"`
HeaderRows int `json:"header_rows,omitempty"`
ID string `json:"id,omitempty"`
Format string `json:"format,omitempty"`
BBox *Rect `json:"bbox,omitempty"`
}
LayoutBlock is a classified block (Config.ExtractBlocks). Kind is one of heading, paragraph, list_item, code, table, merged_table, grid_fallback, rule, figure.
type LayoutCell ¶
type LayoutCell struct {
Text string `json:"text"`
BBox *Rect `json:"bbox,omitempty"`
Colspan int `json:"colspan,omitempty"`
Rowspan int `json:"rowspan,omitempty"`
}
LayoutCell is one table cell.
type LayoutComplexity ¶
type LayoutComplexity struct {
ColumnCount int `json:"column_count"`
RuledTableCount int `json:"ruled_table_count"`
RuledTableCoverage float32 `json:"ruled_table_coverage"`
TextTableRunCount int `json:"text_table_run_count"`
FigureCount int `json:"figure_count"`
FigureCoverage float32 `json:"figure_coverage"`
IsComplex bool `json:"is_complex"`
Reasons []string `json:"reasons"`
}
LayoutComplexity carries layout-difficulty signals (columns, tables, graphics). None of them imply OCR.
type LoadOptions ¶
type LoadOptions struct {
// LibPath is the liteparse FFI shared library file (libliteparse_ffi.dylib,
// libliteparse_ffi.so or liteparse_ffi.dll).
LibPath string
// PDFiumPath is the PDFium shared library file (libpdfium.dylib,
// libpdfium.so or pdfium.dll).
PDFiumPath string
}
LoadOptions overrides native library discovery. Zero values fall back to the default search (see Load).
type Option ¶
type Option func(*Config)
Option mutates a Config. Any func(*Config) works as an Option.
func WithOCRLanguage ¶
WithOCRLanguage sets the OCR language code.
func WithOCRServer ¶
WithOCRServer enables OCR through an HTTP OCR server.
func WithOutputFormat ¶
func WithOutputFormat(f OutputFormat) Option
WithOutputFormat sets the output format.
func WithPassword ¶
WithPassword sets the password for encrypted documents.
func WithTargetPages ¶
WithTargetPages selects pages, e.g. "1-5,10".
type OutputFormat ¶
type OutputFormat string
OutputFormat selects how Result.Text is rendered.
const ( FormatJSON OutputFormat = "json" FormatText OutputFormat = "text" FormatMarkdown OutputFormat = "markdown" )
type Page ¶
type Page struct {
PageNumber int `json:"page_number"`
PageLabel string `json:"page_label,omitempty"`
Width float32 `json:"width"`
Height float32 `json:"height"`
ContentBounds *Rect `json:"content_bounds,omitempty"`
// Text is the page's layout-preserved plain text.
Text string `json:"text"`
// Markdown is set when OutputFormat is FormatMarkdown.
Markdown string `json:"markdown,omitempty"`
TextItems []TextItem `json:"text_items"`
Complexity *PageComplexity `json:"complexity,omitempty"`
VectorGraphics *VectorGraphics `json:"vector_graphics,omitempty"`
Annotations []Annotation `json:"annotations,omitempty"`
FormFields []FormField `json:"form_fields,omitempty"`
StructureTree *StructureTree `json:"structure_tree,omitempty"`
Blocks []LayoutBlock `json:"blocks,omitempty"`
}
Page is one parsed page.
type PageComplexity ¶
type PageComplexity struct {
PageNumber int `json:"page_number"`
TextLength int `json:"text_length"`
TextCoverage float32 `json:"text_coverage"`
HasSubstantialImages bool `json:"has_substantial_images"`
ImageBlockCount int `json:"image_block_count"`
ImageCoverage float32 `json:"image_coverage"`
LargestImageCoverage float32 `json:"largest_image_coverage"`
FullPageImage bool `json:"full_page_image"`
UncoveredVectorArea *float32 `json:"uncovered_vector_area,omitempty"`
IsGarbled bool `json:"is_garbled"`
PageArea float32 `json:"page_area"`
NeedsOCR bool `json:"needs_ocr"`
Reasons []string `json:"reasons"`
Layout *LayoutComplexity `json:"layout,omitempty"`
}
PageComplexity signals whether a page needs OCR or heavier parsing.
type PageOrientation ¶
PageOrientation tells liteparse that a page's content appears rotated clockwise by Angle (0, 90, 180 or 270) so it can counter-rotate it.
type Parser ¶
type Parser struct {
// contains filtered or unexported fields
}
Parser parses documents with a fixed configuration. It is safe for concurrent use. PDFium itself is single-threaded, so the PDFium portion of concurrent calls is serialized natively; OCR and layout run in parallel.
func (*Parser) Close ¶
Close releases the native parser. It waits for in-flight calls and is safe to call more than once.
func (*Parser) IsComplexBytes ¶
IsComplexBytes computes per-page complexity signals for an in-memory document.
func (*Parser) IsComplexFile ¶
IsComplexFile cheaply computes per-page complexity signals for the document at path, without a full parse. Use it to route documents to OCR or a heavier pipeline.
func (*Parser) ParseBytes ¶
ParseBytes parses an in-memory document.
func (*Parser) ParseFile ¶
ParseFile parses the document at path. Non-PDF inputs (DOCX, XLSX, PPTX, images) are converted first, which requires LibreOffice for office formats.
func (*Parser) ScreenshotBytes ¶
func (p *Parser) ScreenshotBytes(ctx context.Context, data []byte, pages string) ([]Screenshot, error)
ScreenshotBytes renders pages of an in-memory document as PNG.
func (*Parser) ScreenshotFile ¶
ScreenshotFile renders pages of the document at path as PNG. pages is a selection such as "1-3,7"; empty renders every page. Config.DPI sets the resolution.
type Rect ¶
type Rect struct {
X float32 `json:"x"`
Y float32 `json:"y"`
Width float32 `json:"width"`
Height float32 `json:"height"`
}
Rect is an axis-aligned box.
type Result ¶
type Result struct {
// TotalPages in the source document, before TargetPages/MaxPages.
TotalPages int `json:"total_pages"`
// Text is the whole document rendered in the configured OutputFormat
// (plain text, or markdown for FormatMarkdown).
Text string `json:"text"`
Pages []Page `json:"pages"`
PageErrors []PageError `json:"page_errors,omitempty"`
Images []Image `json:"images,omitempty"`
Screenshots []Screenshot `json:"screenshots,omitempty"`
ImageErrorCount int `json:"image_error_count"`
// FormType is set when form-field extraction ran: 0 none, 1 AcroForm,
// 2 XFA full, 3 XFA foreground.
FormType *int `json:"form_type,omitempty"`
Creator string `json:"creator,omitempty"`
Producer string `json:"producer,omitempty"`
DocMeta *DocumentMetadata `json:"doc_meta,omitempty"`
XFAPackets []XFAPacket `json:"xfa_packets,omitempty"`
}
Result is the outcome of a parse.
type Screenshot ¶
type Screenshot struct {
PageNumber int `json:"page_number"`
Width int `json:"width"`
Height int `json:"height"`
PNG []byte `json:"png"`
// IsSolidFill reports a blank (single-color) render.
IsSolidFill bool `json:"is_solid_fill"`
Rects []ScreenshotRect `json:"rects,omitempty"`
}
Screenshot is a rendered page.
type ScreenshotRect ¶
type ScreenshotRect struct {
X float32 `json:"x"`
Y float32 `json:"y"`
Width float32 `json:"width"`
Height float32 `json:"height"`
// Color is ARGB hex, e.g. "ff1a2b3c".
Color string `json:"color"`
IsLine bool `json:"is_line"`
}
ScreenshotRect is a solid rectangle or line found in a rendered page.
type StructureElement ¶
type StructureElement struct {
Type string `json:"type"`
ID string `json:"id,omitempty"`
ActualText string `json:"actual_text,omitempty"`
AltText string `json:"alt_text,omitempty"`
Title string `json:"title,omitempty"`
Attributes map[string]AttributeValue `json:"attributes,omitempty"`
MarkedContentIDs []int32 `json:"marked_content_ids"`
Children []StructureElement `json:"children"`
Annotations []Annotation `json:"annotations"`
}
StructureElement is one tagged-PDF structure element. Attribute values are bool, float64 or string.
type StructureTree ¶
type StructureTree struct {
Roots []StructureElement `json:"roots"`
}
StructureTree is a page's tagged-PDF logical structure (Config.ExtractStructureTree).
type TextItem ¶
type TextItem struct {
Text string `json:"text"`
X float32 `json:"x"`
Y float32 `json:"y"`
Width float32 `json:"width"`
Height float32 `json:"height"`
Rotation float32 `json:"rotation"`
FontName string `json:"font_name,omitempty"`
FontSize float32 `json:"font_size,omitempty"`
// Confidence is the OCR confidence (0-1); nil for native PDF text.
Confidence *float32 `json:"confidence,omitempty"`
// Link is the hyperlink target covering this item, if any.
Link string `json:"link,omitempty"`
// Words is set with Config.EmitWordBoxes (or markdown output).
Words []WordBox `json:"words,omitempty"`
FontHeight *float32 `json:"font_height,omitempty"`
FontAscent *float32 `json:"font_ascent,omitempty"`
FontDescent *float32 `json:"font_descent,omitempty"`
FontWeight *int32 `json:"font_weight,omitempty"`
TextWidth *float32 `json:"text_width,omitempty"`
FontIsBuggy *bool `json:"font_is_buggy,omitempty"`
MCID *int32 `json:"mcid,omitempty"`
FillColor string `json:"fill_color,omitempty"`
StrokeColor string `json:"stroke_color,omitempty"`
CharCodes []uint32 `json:"char_codes,omitempty"`
TrailingSpaceGenerated *bool `json:"trailing_space_generated,omitempty"`
}
TextItem is a run of text with its bounding box. The metadata block is populated only with Config.ExtractTextMetadata.
type VectorGraphics ¶
type VectorGraphics struct {
Shapes []VectorShape `json:"shapes"`
Lines []VectorLine `json:"lines"`
}
VectorGraphics holds page vector paths (Config.ExtractVectorGraphics).
type VectorLine ¶
type VectorLine struct {
X1 float32 `json:"x1"`
Y1 float32 `json:"y1"`
X2 float32 `json:"x2"`
Y2 float32 `json:"y2"`
Stroke bool `json:"stroke"`
StrokeWidth *float32 `json:"stroke_width,omitempty"`
StrokeColor string `json:"stroke_color,omitempty"`
Fill bool `json:"fill"`
FillColor string `json:"fill_color,omitempty"`
}
VectorLine is a merged horizontal or vertical path segment.
type VectorShape ¶
type VectorShape struct {
BBox Rect `json:"bbox"`
Stroke bool `json:"stroke"`
StrokeColor string `json:"stroke_color,omitempty"`
Fill bool `json:"fill"`
FillColor string `json:"fill_color,omitempty"`
HasCurve bool `json:"has_curve"`
}
VectorShape is one path object's paint state and bounds.