ocr

package
v1.0.1 Latest Latest
Warning

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

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

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

Documentation

Overview

Package ocr recovers text from pages whose content stream does not carry it.

It is the fallback path, and naming it that is the whole design. A scanned page has an image and no text; a born-digital page has text and the extractor already read it. Reading the second kind from pixels produces a worse answer than the one already in hand — the content stream states its glyphs, while OCR infers them — so the decision of *which* pages to send is worth more than any engine choice. That decision is Route.

Words, with a confidence

An Engine returns the words it read, each with its box and its confidence. Page builds the same doc.Page the extractor produces from them, so every sink downstream is unchanged, and a document can be part scanned and part digital without the caller knowing which pages were which. doc.Page.Rasterized is the record of that.

The confidence is what the issue (#9) asked for and what DocTags could not give: a model's transcription states every word with the same assurance, right or wrong. A word below the threshold is written [err] (ADR 0042) instead of a guess.

The interface is this repo's, and no backend's type appears in it: the consuming package owns the interface and adapters live in subpackages, as with objects/pdfcpu and render/pdfium. ocr/tesseract is the one adapter (ADR 0043).

Index

Constants

View Source
const DefaultThreshold = 0.05

DefaultThreshold is the coverage below which a page is sent to OCR.

5% rather than 0. A pure scan is exactly zero and any positive threshold catches it, so the number is really about the mixed page: a scan whose only digital text is a stamped page number, a header, or a Bates number occupies a percent or two, and at a threshold of zero every one of those pages silently yields one line instead of the page. Set well below what a page of real prose reaches — a single-column page of body text covers a third of its box or more — so the two populations are not close to each other and the exact value is not load-bearing.

View Source
const PageMinConf = 80

PageMinConf is the mean confidence below which a page's reading is not taken as text.

A photo is read as a few words of noise: the spike's three image-only fixtures gave 1 to 4 words at a mean of 32 to 74, "eee eee eee eee" among them. Pages of text read at 84.0 to 95.7, the lowest a scan-like page of a dense paper (ADR 0043). 80 sits between.

View Source
const SureConf = 90

SureConf is the confidence from which a word is taken on Tesseract's reading alone: at 90 and over, 99.4% of the spike's 6,769 words were right; under it, 79% of 712 (ADR 0043).

Variables

View Source
var ErrRefused = errors.New("the reader refused its answer")

ErrRefused is a reader's refusal of one answer, its guard's verdict: a disagreement, where any other error is the reader failing.

Functions

func Adds added in v1.0.0

func Adds(orig, read doc.Page) bool

Adds reports whether read, a page built from OCR, adds to orig, the page the extractor found with its artifacts: whether it holds at least addsFactor times orig's words with a character read.

The file's own text comes first, and OCR only adds to it. Route sends a page by its coverage, and a born-digital page can cover very little: the reference fixtures set a few lines on a full page, under the 5% threshold. Read again, such a page gives back the words it already had, now inferred from pixels, and replacing it cost every enforced bench dimension: tables fell from 0.875 to 0.375 and style from 0.960 to 0.560 (ADR 0043).

func Cells added in v1.0.0

func Cells(words []Word, xs, ys []int) [][]string

Cells places words in the grid xs and ys bound: each in the cell its box's centre falls in, joined in reading order. A word of nothing but "|" is a rule read as text and is dropped, as is a word outside the grid.

func Confirm added in v1.0.0

func Confirm(ctx context.Context, img image.Image, words []Word, r Reader) ([]Word, Confirmation, error)

Confirm asks r for a second reading of each word under SureConf, cropped from img by its box, and marks the word Agreed where the two readings match (ADR 0044).

Agreement is the rule because it is what the spike measured: of the 712 words Tesseract read under 90, it and Gemma agreed on 494, and 488 of those were right, 98.8%. Where they disagreed the right reading was either one's about as often as neither's, so neither is taken, and Page writes the word as [err]. A reading that fails its guard is a disagreement.

A reader that fails outright, the daemon gone mid-page, stops the asking: the error is returned with the words as they are, and the caller reads the page without a second opinion.

func Cover added in v1.0.0

func Cover(words []Word, bounds image.Rectangle) float64

Cover is the share of bounds the words' boxes cover, overlaps counted once each word.

func Coverage added in v1.0.0

func Coverage(p doc.Page) float64

Coverage is the page's coverage by the blocks that hold a character the extractor read. A block of glyphs the file gives no value to, each written [err] (ADR 0042), covers the page as a scan's image does: with text nobody has read. Counted, it would keep the page from the one engine that could read it.

func Deskew added in v1.0.0

func Deskew(img image.Image) (image.Image, float64)

Deskew estimates img's skew and returns it rotated back level, with the angle it found in degrees, the turn rotate undoes. The angle is the one whose projection of the page's ink onto rows is most peaked: lines of type and a table's rules lie along rows only when the page is level (ADR 0047). A page skewed less than deskewMin is returned as it is.

func Filled added in v1.0.0

func Filled(cells [][]string) bool

Filled reports a grid with words in two rows and two columns of its cells, which a table is and a photograph with lines in it, read as a few words, is not: test-rewrite-images.pdf's "Never look back!" fell in one column of a grid its photograph's edges drew (ADR 0046).

func Grid added in v1.0.0

func Grid(img image.Image) (xs, ys []int, ok bool)

Grid finds a ruled table's lines in img: the rows of pixels a horizontal rule runs along and the columns a vertical one does, each rule's centre once. ok is false unless there are three of each, a frame with a line inside it both ways, which a chart's frame alone is not.

func IsText added in v1.0.0

func IsText(ws []Word) bool

IsText reports whether a page's words read as text: at a mean confidence of PageMinConf or more.

func IsTextImage added in v1.0.0

func IsTextImage(words []Word, bounds image.Rectangle) bool

IsTextImage reports whether words, read from an image of the given bounds, make it an image of text: read as text at all (IsText), of textMinWords or more, covering textCover of it.

func MeanConf added in v1.0.0

func MeanConf(ws []Word) float64

MeanConf is the words' confidence weighted by their length, so a page is not judged by its stray one-character fragments; 0 for no words.

func Page added in v1.0.0

func Page(words []Word, n int, box geom.Rect, img image.Rectangle, minConf float64) doc.Page

Page builds page n from the words an engine read in its image, as the extractor would have built it from glyphs: a block per paragraph, a span and a doc.Line per line, in page coordinates.

box is the page's rectangle in points and img the image's bounds, which span it. A word read below minConf, and not Agreed by a second reader, is written doc.Unmapped, which the sink tags [err] (ADR 0042): one for the word, since how many characters an engine could not read is not something it says.

Lines are joined by extract.WrapSpace, the extractor's own rule for a wrapped line, so a word broken at a hyphen reaches layout.Hyphens as the extractor's words do.

func ReadAgain added in v1.0.0

func ReadAgain(ctx context.Context, img image.Image, w Word, r Reader) (string, error)

ReadAgain is r's reading of the word w in img, cropped as Confirm crops it.

func Route

func Route(p doc.Page, threshold float64) bool

Route reports whether a page should be sent to an Engine.

The rule is coverage: the fraction of the page's crop box covered by the text blocks the extractor found. A scanned page has an image spanning the page and no text blocks at all, so its coverage is zero; a born-digital page has text spread across most of it. The threshold separates them, and the reason it is a coverage ratio rather than a character count is the case that motivates the whole router — a scanned page carrying a single line of digital text in a header. Counting characters says "this page has text, skip it" and loses the entire scan. Coverage says a page whose text occupies 2% of it has essentially none.

doc.Page.Coverage was written for this and documents itself as "the numerator of the OCR router's coverage rule", including the two defensive cases that matter here: a block outside the crop box clamps rather than pushing coverage above 1, and a zero-area page box yields 0, so a defective page routes to OCR rather than being silently accepted as complete.

A page already marked Rasterized is never routed again — it came from OCR, so sending it back would ask the engine to read its own output.

func Same added in v1.0.0

func Same(a, b string) bool

Same reports whether two readings have the same letters and digits, in NFKC, the comparison the spike scored by: "(e.g.," and "e.g." are one reading, "IoU" and "loU" are two.

func SameGlyph added in v1.0.0

func SameGlyph(a, b string) bool

SameGlyph reports whether two readings of one glyph read alone are the same character, in NFKC. Not Same: a glyph alone is as often a symbol as a letter, "$" or "•", and Same compares letters and digits only (ADR 0048).

func Stroke added in v1.0.0

func Stroke(img image.Image, r image.Rectangle) float64

Stroke measures the median width of the horizontal runs of ink in r in img, ink being a luma under 128. On the gold set's scans at 200 dpi, body type's strokes are 2 pixels on every line and bold type's 3 to 5.

Types

type Confirmation added in v1.0.0

type Confirmation struct {
	Reader                 string
	Asked, Agreed, Refused int
}

Confirmation is what Confirm did: the words it asked about, how many the reader agreed with, and how many of its answers it refused. Every word asked about and not agreed with is [err].

type Engine

type Engine interface {
	// Read returns the words in img, in reading order.
	Read(ctx context.Context, img image.Image) ([]Word, error)

	// Name identifies the engine and its model, for the page report: "tesseract 5.5.3 eng".
	Name() string
}

Engine reads the words in one page image.

One page per call: a page is the unit the router decides about, and the unit a failure is confined to, so a fifty-page scan with one unreadable page yields forty-nine. Implementations need not be safe for concurrent use.

type Fill added in v1.0.0

type Fill struct {
	// At is the run of doc.Unmapped, a byte range of the text.
	At [2]int

	// Text is what was read in its place.
	Text string

	// Words are the indices of the words it was read from.
	Words []int

	// Alone is a run that is a word of one glyph, read by its shape alone. Tesseract reads a
	// bullet as "e" as surely as a "$" as "$", so its confidence does not say which it is.
	Alone bool
}

A Fill is what a reading gives one run of glyphs with no value in a line's text (ADR 0048).

func Fills added in v1.0.0

func Fills(text string, words []Word) []Fill

Fills reads, from the words read off a line's image, the text of each run of glyphs in it with no value. No glyph is guessed: a run is filled only where the line's own text pins its place.

  • The line's words with no run in them are matched to the reading's, in order, and what lies between two matches on one side is read against what lies between them on the other.
  • Between them, word for word where the two have as many words, a word with a run must read as its mapped letters around the run, "crea" and "ng" around "ti", and a run of n glyphs as n characters, or as up to 3n letters, a glyph being one character or a ligature.
  • A word of nothing but a run of n glyphs, with no letters of its own to place it, must read as a word of n characters.
  • A gap that is all one such word, a line set wholly in a font with no values, takes the words between whose characters, spaces included or not, number n.
  • A line of one glyph and nothing else is not filled: nothing places it, and every reading of one character has its count. A symbol set alone, in a formula, is what one is.

The words' confidence is the caller's to judge.

type Reader added in v1.0.0

type Reader interface {
	Read(ctx context.Context, img image.Image, maxRunes int) (string, error)
	Name() string
}

Reader gives a second reading of the text in a crop: inferd's vision model, in ocr/gemma. maxRunes bounds the reply; a reader refuses rather than answer longer.

type Table added in v1.0.0

type Table struct {
	Box    image.Rectangle
	XS, YS []int
	Cells  [][]string
	Words  []int
}

Table is a ruled table found on a page image: its box, the lines of its grid in the page image's pixels, its cells' text, and which words went into it.

func Tables added in v1.0.0

func Tables(img image.Image, words []Word, dpi float64) []Table

Tables finds the ruled tables on a page image read at dpi: rules of the same extent stacked three deep or more, whose region Grid confirms and whose cells words fill in two rows and two columns. Each word inside a table is placed in its cells (Cells) and named in Words, so that the caller writes it there and not again as text (ADR 0047).

type Word added in v1.0.0

type Word struct {
	// Text is the word as read.
	Text string

	// Box is the word's extent in the image's pixels.
	Box image.Rectangle

	// Conf is the engine's confidence in Text, from 0 to 100.
	Conf float64

	// Block, Par and Line number the word's block, paragraph and line within the image, as
	// the engine segmented it. Words sharing all three are one line, in reading order.
	Block, Par, Line int

	// Agreed reports that a second reader read the word as the engine did (Confirm), which
	// Page takes as the engine's reading confirmed, whatever its confidence.
	Agreed bool

	// Stroke is the median width, in pixels, of the word's horizontal runs of ink: how thick its
	// strokes are drawn, which tells a bold word, since Tesseract reads no weight (ADR 0047).
	// Zero where the engine did not measure it.
	Stroke float64
}

Word is one word an Engine read.

Directories

Path Synopsis
Package gemma asks inferd's vision model what only a model can answer: a second reading of a word Tesseract is unsure of, a description of a picture, and the values of a chart (ADR 0044).
Package gemma asks inferd's vision model what only a model can answer: a second reading of a word Tesseract is unsure of, a description of a picture, and the values of a chart (ADR 0044).
Package tesseract reads page images with the tesseract CLI, run as a subprocess when it is installed (ADR 0043).
Package tesseract reads page images with the tesseract CLI, run as a subprocess when it is installed (ADR 0043).

Jump to

Keyboard shortcuts

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