extract

package
v0.51.2 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2026 License: MIT Imports: 25 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 extract is the parse stage: one extractor per media type, each turning an item's bytes into units, such as a thread's post and comments or a book's pages. A registry keyed by media type picks the extractor, so an item parses the same whatever source sent it.

An extractor registers by joining builtin. One written in Go sets Extract. One whose library is not Go is a Program from the worker image, run through isolatedprocess. One whose item holds no bytes, such as a video, reads the item at its source, and the source registers it through Register. Each output is keyed by item, extractor and version, so a changed extractor takes a new version and its outputs write beside the old. A media type holds one primary extractor, which landing queues, and may hold secondary ones, whose parse another stage's write queues and writes beside the primary's.

Index

Constants

View Source
const (
	BlockHeading   = "heading"
	BlockParagraph = "paragraph"
	BlockListItem  = "list item"
	BlockTableRow  = "table row"
	BlockQuote     = "quote"
	BlockCode      = "code"
)

The kinds of block that ArticleTrafilatura labels its units with.

View Source
const AudioWhisperTimeout = 12 * time.Hour

AudioWhisperTimeout bounds one parse by AudioWhisper. The longest memo that the push route takes is the recording that server.MaxMemoBytes holds. A run measures well under the audio's length with `/usr/bin/time -v audio-whisper < <the audio>`, so the bound leaves room past it.

View Source
const DoclingPins = "e919138066e6"

DoclingPins is the first 12 hex digits of the SHA-256 of the pin of each library in doclingLibraries' closure in release/python-requirements.txt, in the lock's order, then every model pin in release/download-docling-models, one a line. The closure is each of those libraries and every library that the lock's via lines say one in the closure needs. Each shapes Docling's markdown, and a test fails until this equals them.

View Source
const DoclingTimeout = 3 * time.Hour

DoclingTimeout bounds one run of pdf-docling. A 1,245-page PDF, the longest that sections selected when this was measured, took 34 minutes under `/usr/bin/time -v pdf-docling < <the PDF>` on a busy desk of 16 CPUs, 1.6 s a page. A node with half those CPUs takes about twice that, and the bound leaves more than twice that again.

View Source
const DoclingVersion = "2.153.0"

DoclingVersion is the Docling that release/python-requirements.txt pins, and that the worker image installs for pdf-docling.

View Source
const FasterWhisperVersion = "1.2.1"

FasterWhisperVersion is the faster-whisper that release/python-requirements.txt pins, and that the worker image installs for audio-whisper.

View Source
const MediaTypeHTML = "text/html"

MediaTypeHTML is a web page's media type, as a feed's entry lands one.

View Source
const MediaTypeMarkdown = "text/markdown"

MediaTypeMarkdown is a markdown document's media type.

View Source
const MediaTypePDF = "application/pdf"

MediaTypePDF is a PDF's media type, as a folder connector lands one.

View Source
const ProgramDir = "/usr/local/libexec/ingestion/extractors"

ProgramDir is where the worker image installs each extractor program.

View Source
const ProgramTimeout = 30 * time.Minute

ProgramTimeout is a program extractor's Timeout unless its registration sets another.

View Source
const PyMuPDFVersion = "1.28.2"

PyMuPDFVersion is the PyMuPDF that release/python-requirements.txt pins, and that the worker image installs for the PDF programs.

View Source
const ReadAttempts = 4

ReadAttempts is how many claims a parse makes of a read that fails boundedly before it fails. A claim that ended waiting is not among them.

View Source
const ReadWaitCeiling = 48 * time.Hour

ReadWaitCeiling is how long a parse waits on its source in all before it fails, counted from the source's first answer to wait. It outlasts the longest pause that ypl declares, a day, so only a source that never frees fails a parse this way.

View Source
const SlotGroupHeavy = "heavy"

SlotGroupHeavy is the slot group of each parse whose run holds gigabytes, such as Docling's and Whisper's.

View Source
const TrafilaturaPins = "f242083fb35b"

TrafilaturaPins is the first 12 hex digits of the SHA-256 of the pin of each library in trafilaturaLibraries' closure in release/python-requirements.txt, in the lock's order, one a line. Each shapes the text that trafilatura finds, and a test fails until this equals them.

View Source
const TrafilaturaVersion = "2.4.0"

TrafilaturaVersion is the trafilatura that release/python-requirements.txt pins, and that the worker image installs for article-trafilatura.

View Source
const WhisperModel = "large-v3-turbo"

WhisperModel is the model that audio-whisper runs, whose files release/download-whisper-model pins.

View Source
const WhisperPins = "a764b748ef26"

WhisperPins is the first 12 hex digits of the SHA-256 of the pin of each library in whisperLibraries' closure in release/python-requirements.txt, as DoclingPins reads its own, then every model pin in release/download-whisper-model, then ffmpeg's version and SHA-256 in release/install-tools, one a line. Each shapes a transcript, and a test fails until this equals them.

View Source
const WhisperProgram = ProgramDir + "/audio-whisper"

WhisperProgram is where the worker image installs audio-whisper, which transcribes the audio it reads on stdin with faster-whisper.

View Source
const WhisperVersion = "1+faster-whisper-" + FasterWhisperVersion + "-" + WhisperModel + "-" + WhisperPins

WhisperVersion names the transcription that audio-whisper makes, so a transcript by other libraries, weights or decoding writes beside the old. A change to the program's own settings raises the leading number.

Variables

View Source
var ArticleTrafilatura = func() Extractor {
	e := Program("article-trafilatura", "2+trafilatura-"+TrafilaturaVersion+"-"+TrafilaturaPins, MediaTypeHTML, ProgramDir+"/article-trafilatura")
	e.FetchesPage = true
	e.LabelMeaning = LabelIsKind
	return e
}()

ArticleTrafilatura reads a web page's main text with trafilatura, one unit per block of trafilatura's XML in the page's order, labeled with the block's kind as ReadArticleLabel reads it. A code block stays whole. It keeps the page's tables and leaves out its comment section. It runs in no slot group, so a page never waits behind a book or a memo.

Its version names trafilatura's and TrafilaturaPins, so a parse by other libraries writes beside the old one. A change to the program's own reading raises the leading number. It fetches the page of an item that landed no bytes, as a pushed link does.

AudioWhisper is the primary extractor of a memo's audio, in each container that the push route lands a memo as. It runs audio-whisper over the item's bytes in SlotGroupHeavy, so a memo, a video's audio and a book's Docling parse never run at once on one worker.

View Source
var MarkdownSections = Extractor{
	Name: "markdown-sections", Version: "1", MediaType: MediaTypeMarkdown,
	Extract: func(_ context.Context, body io.Reader) (Read, error) {
		raw, err := io.ReadAll(body)
		if err != nil {
			return Read{}, err
		}
		if !utf8.Valid(raw) {
			return Read{}, fmt.Errorf("the document is not UTF-8")
		}
		return Read{Units: markdownSections(strings.ReplaceAll(string(raw), "\r\n", "\n"))}, nil
	},
}

MarkdownSections parses a markdown document into one unit per ATX heading: the heading's line and every line below it up to the next heading, labeled by the heading's text. The text before the first heading is one unit with no label. A line inside a fenced code block is code, so a shell comment there opens no section. Each unit keeps its heading's line, so the parse's text reads as the document does.

View Source
var PDFDocling = func() Extractor {
	e := Program("docling", "1+docling-"+DoclingVersion+"-"+DoclingPins, MediaTypePDF, ProgramDir+"/pdf-docling")
	e.Positional, e.Secondary, e.Timeout, e.SlotGroup = true, true, DoclingTimeout, SlotGroupHeavy
	return e
}()

PDFDocling reads a PDF with Docling's standard pipeline, one unit per PDF page, so unit n is PDF page n, a blank page included. A unit's text is the page's markdown, with each code block fenced and each table's rows kept, and its label is the page's printed label, as PDFText reads it. Docling drops every formula, so it reads only the books whose profile sections.FontShares.CodeHeavyMathLight picks.

It is secondary, so landing never queues it. The write that ends such a book's structure task queues it, and its parse writes beside PDFText's. It runs in SlotGroupHeavy, whose limit bounds its parses and Whisper's together. Its version names Docling's and DoclingPins, so a parse by other libraries or weights writes beside the old one. A change to the program's own reading raises the leading number.

View Source
var PDFText = func() Extractor {
	e := Program(store.ExtractorPDFText, "1+pymupdf-"+PyMuPDFVersion, MediaTypePDF, ProgramDir+"/"+store.ExtractorPDFText)
	e.Positional = true
	e.TakesFetchedPages = true
	return e
}()

PDFText reads a PDF's text with PyMuPDF, one unit per PDF page, so unit n is PDF page n, a blank page included. A unit's label is the page's printed label where the PDF declares page labels, and null where it declares none. Its version names PyMuPDF's, so a library upgrade writes its pages beside the old ones.

View Source
var SlotGroups = map[string]int{SlotGroupHeavy: 1}

SlotGroups holds each slot group's default limit, which a [worker.slot_limits] key naming the group overrides. heavy runs one parse at a time, because a worker's memory holds one.

View Source
var ThreadText = Extractor{
	Name: "thread-text", Version: "1", MediaType: redditexport.MediaTypeSave,
	Extract: func(ctx context.Context, body io.Reader) (Read, error) {
		units, err := threadText(ctx, body)
		return Read{Units: units}, err
	},
}

ThreadText parses a Reddit save: its post, then each comment of its thread depth first, in the order Reddit sorted them. A comment that its author deleted or a moderator removed is left out, and its replies are kept. Each unit's label is its author.

Functions

func AfterParse added in v0.29.0

func AfterParse(written, deferred []server.AfterStage) server.AfterStage

AfterParse runs in the write that ends a parse task done, and routes on the output that the task's extractor wrote: written runs where the parse holds text, and deferred where it handed the item to another extractor. A task whose extractor this build does not name runs written.

func Capability

func Capability(e Extractor) string

Capability is the capability of e's parse tasks, so a worker claims only the tasks of extractors it runs.

func QueueDeferredParse added in v0.29.0

func QueueDeferredParse(ctx context.Context, tx *store.Tx, task store.Task) error

QueueDeferredParse runs where AfterParse finds a parse deferred. It queues a parse by the extractor that the task's extractor's DefersTo names, unless one is queued or leased, or a done one at its version is held. So a parse replay over a deferred item queues the other extractor's parse again only where it has not read the item at its version, and an item whose other parse failed is read again.

func Register added in v0.29.0

func Register(extractors ...Extractor)

Register adds extractors to the builtin registry, as a source registers the ones that read its items, from its own init.

func RegisterLabelMeaning added in v0.46.0

func RegisterLabelMeaning(producer string, meaning LabelMeaning)

RegisterLabelMeaning declares what the labels of producer's parses hold, from the init of a producer that is no extractor, such as a stage that writes another parse's units again.

func SourceHandler added in v0.29.0

func SourceHandler(e Extractor, api string, client *http.Client, log *slog.Logger) (worker.Handler, bool)

SourceHandler is the worker handler of e, an extractor that ReadsURL, whose reader reaches its source at api through client. It is false where e's program is not installed here, so the worker claims none of its tasks.

func SpanLabel added in v0.37.0

func SpanLabel(startMs, endMs int64) string

SpanLabel is the label of a stretch of audio from startMs to endMs: each end as mm:ss, or h:mm:ss from an hour on, joined by an en dash, such as 01:05–01:12.

Types

type ArticleBlock added in v0.46.0

type ArticleBlock struct {
	Kind string
	// Level is a heading's, 1 to 6.
	Level int
	// Language is the language that the page names for a code block, and
	// empty where it names none.
	Language string
}

ArticleBlock is what an ArticleTrafilatura unit's label says of its block.

func ReadArticleLabel added in v0.46.0

func ReadArticleLabel(label *string) (ArticleBlock, bool)

ReadArticleLabel reads label as ArticleTrafilatura writes it: a kind, a heading's kind and level, as "heading 2", or a code block's kind and language, as "code python". It is false for any other label, such as the null of a parse at an older version.

type AudioAnswer added in v0.37.0

type AudioAnswer struct {
	Model string `json:"model"`
	TranscriptInfo
	Segments int     `json:"segments"`
	StartsMs []int64 `json:"starts_ms"`
}

AudioAnswer is what an AudioWhisper parse keeps as its answer: the model, what audio-whisper reported of the audio, how many segments it heard, and where each unit starts in the audio, in milliseconds, by the unit's order.

type Extractor

type Extractor struct {
	// Name names the extractor in each output it writes, such as thread-text.
	Name string
	// Version is written beside each output, so a changed extractor takes a
	// new one.
	Version   string
	MediaType string
	// AlsoReads names each other media type that the extractor is primary
	// for, such as each audio container that a memo arrives in.
	AlsoReads []string
	// Program is the absolute path of the extractor's program, and empty for
	// one written in Go. A worker runs it only where the program is installed.
	Program string
	// Extract reads body and answers its units in order, with the answer
	// that its parse keeps, such as what a transcript heard.
	Extract func(ctx context.Context, body io.Reader) (Read, error)
	// Timeout bounds one run of Extract, and none where it is zero. A run
	// past it fails its task, so a program that hangs on one item's bytes
	// frees its worker slot and the item waits in review.
	Timeout time.Duration
	// LabelMeaning is what the extractor's unit labels hold, a title unless
	// it says otherwise.
	LabelMeaning LabelMeaning
	// Positional keeps a unit with no text in its place, so unit n is the
	// artifact's own part n, such as a book's PDF page n. Otherwise such a
	// unit is dropped and the rest are numbered again.
	Positional bool
	// Secondary marks an extractor that landing never queues and a parse
	// replay never picks, because another stage's write queues its parse, as
	// the structure's queues PDFDocling's.
	Secondary bool
	// SlotLimit caps the extractor's parses that one worker runs at once,
	// where [worker.slot_limits] names no limit for it. Zero leaves them
	// uncapped. An extractor in a slot group sets none.
	SlotLimit int
	// SlotGroup names the slot group whose limit the extractor's parses share
	// with every other extractor in it, such as SlotGroupHeavy. SlotGroups
	// holds the group's limit.
	SlotGroup string
	// ReadsURL marks an extractor whose item holds no bytes, so it reads the
	// item at its source through the reader that Open opens on that source's
	// client. A source registers it, and a worker runs its parses only where
	// it opened that source. It sets no Extract.
	ReadsURL bool
	// Open opens the reader of an extractor that ReadsURL, which reaches its
	// source at api through client, carrying the source client's token.
	Open func(api string, client *http.Client) Reader
	// DefersTo names the secondary extractor whose parse the write that ends a
	// deferred parse of this one queues, such as Whisper for a video whose
	// captions hold no track.
	DefersTo string
	// LinkKind is the kind of item key, as itemkey names it, whose link this
	// extractor reads at its source, such as youtube. A pushed link of that
	// kind lands as the extractor's media type, under the URL that LinkURL
	// makes. Only a primary extractor that ReadsURL sets it.
	LinkKind string
	// LinkURL is the URL that the source names an item under, from the id in
	// the item's key, as its poll lands it. An extractor with a LinkKind sets
	// it, so an item's URL is the same whichever connector landed it first.
	LinkURL func(id string) string
	// FetchesPage marks the extractor of a web page whose parse, where its
	// item holds no bytes, GETs the page at the item's URL through publicweb
	// and keeps it as the item's bytes before reading it. A pushed link that
	// keys as a url lands as its media type with no bytes, so the service
	// stores only the page that it fetched. Only one primary extractor that
	// reads bytes sets it.
	FetchesPage bool
	// TakesFetchedPages marks an extractor whose media type a fetched page
	// may answer in place of a web page, such as a PDF that a pushed link
	// names. The parse that fetched it keeps it, and hands the item to this
	// extractor's parse under this media type. Only a primary extractor that
	// reads bytes sets it.
	TakesFetchedPages bool
}

Extractor turns the bytes of one media type into a parse's units.

func AudioWhisperAt added in v0.37.0

func AudioWhisperAt(program string) Extractor

AudioWhisperAt is AudioWhisper, run by the audio-whisper program at program. Each segment that holds speech becomes one unit, labeled by its span as SpanLabel writes it, and the parse keeps an AudioAnswer.

func Named added in v0.29.0

func Named(name string) (Extractor, bool)

Named is the builtin or registered extractor called name, and false where none is.

func Program

func Program(name, version, mediaType, path string, args ...string) Extractor

Program is an extractor that runs the program at path with args, such as one whose library is Python. The program reads the item's bytes on stdin, and writes one JSON line per unit on stdout, in order:

{"label": "Chapter 1", "text": "It was a bright cold day…"}

label may be null or left out, and any other field is refused. A run that exits non-zero fails its task, with the end of its stderr kept, and so does a run past ProgramTimeout. The program runs through isolatedprocess, so it holds none of the worker's credentials.

type Item added in v0.29.0

type Item struct {
	Key       string
	URL       *string
	MediaType string
}

Item is what an extractor that ReadsURL reads: the item's key, its URL and its media type.

type LabelMeaning added in v0.46.0

type LabelMeaning int

LabelMeaning is what a parse's unit labels hold. A reader of any parse, such as the review card, asks LabelMeaningOf rather than naming producers.

const (
	// LabelIsTitle titles its unit, such as a PDF page's printed label, a
	// comment's author or a video's chapter. It is every producer's default.
	LabelIsTitle LabelMeaning = iota
	// LabelIsSpan is the stretch of audio that the unit holds, as SpanLabel
	// writes it.
	LabelIsSpan
	// LabelIsKind is the kind of block that the unit is, as ReadArticleLabel
	// reads it.
	LabelIsKind
)

func LabelMeaningOf added in v0.46.0

func LabelMeaningOf(producer string) LabelMeaning

LabelMeaningOf is what the labels of a parse by producer hold: an extractor's LabelMeaning, a meaning that a producer registered, or a title.

type Read added in v0.29.0

type Read struct {
	Units []Unit
	// Deferred says the source holds no text of its own for the item, so its
	// parse hands the item to the extractor that DefersTo names, such as a
	// video with no caption track.
	Deferred bool
	// Answer is kept as the output's answer, such as the caption track that
	// a read used.
	Answer json.RawMessage
}

Read is what a Reader found.

type Reader added in v0.29.0

type Reader func(ctx context.Context, item Item) (Read, error)

Reader reads one item at its source, as an extractor that ReadsURL does.

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

Registry picks the primary extractor for an item by its media type, and for a pushed link by its key's kind. It holds every extractor that a worker runs.

func Builtin

func Builtin() *Registry

Builtin is the registry of every extractor that ingestion holds, and every one that a source registered.

func NewRegistry

func NewRegistry(extractors ...Extractor) (*Registry, error)

NewRegistry registers extractors. It refuses one with no name, version, media type or way to run, two of one name, two primary ones of one media type or one link kind, and one that defers to an extractor it does not hold as secondary. It refuses a link kind on an extractor that is secondary or reads bytes, and a page fetch on one that is secondary or reads its item at its source, or beside another. It refuses a fetched page's hand-off to one that is secondary or reads its item at its source. It refuses a slot group that SlotGroups does not hold, and a SlotLimit beside a slot group, whose limit is the group's.

func (*Registry) For

func (r *Registry) For(mediaType string) (Extractor, bool)

For is the primary extractor that reads mediaType, and false where none does.

func (*Registry) Handlers

func (r *Registry) Handlers(client *worker.Client, pages publicweb.Reader, log *slog.Logger) []worker.Handler

Handlers is a worker handler for each extractor of r that reads an item's bytes and runs here: each written in Go, and each whose program is installed. The extractor that FetchesPage GETs a page through pages, which answers a page of each type that an extractor TakesFetchedPages for too. An extractor that ReadsURL runs through its source's handlers, as SourceHandler opens it. A worker claims only these extractors' tasks.

func (*Registry) LinkArrival added in v0.31.0

func (r *Registry) LinkArrival(key string) (mediaType, link string, ok bool)

LinkArrival is the media type and URL that a pushed link keyed key lands with, as the extractor that reads the key's kind names them, and false where no extractor reads a link of that kind. A child's key names no link.

func (*Registry) LinkKinds added in v0.31.0

func (r *Registry) LinkKinds() []string

LinkKinds names, in order, each kind of key whose link an extractor reads.

func (*Registry) LinkLanding added in v0.40.0

func (r *Registry) LinkLanding(key, link string) server.LinkLanding

LinkLanding is how the link keyed key lands, where link is its canonical URL. An extractor that reads the key's kind reads it at its source, as LinkArrival names it. A url link lands as a page where an extractor FetchesPage. A site whose items an extractor reads hosts no such page, as a channel's page names no single video. Any other link does not land.

func (*Registry) PageMediaType added in v0.40.0

func (r *Registry) PageMediaType() (string, bool)

PageMediaType is the media type that a pushed link to a web page lands as, with no bytes, so that the extractor that FetchesPage GETs the page in its parse. It is false where no extractor fetches pages.

func (*Registry) QueueParse

func (r *Registry) QueueParse(ctx context.Context, tx *store.Tx, item store.Item) error

QueueParse queues a parse task for item where an extractor reads its media type. Landing calls it in the write that adds the item, so every item lands with its parse queued. Landing calls it again where a write gives the item bytes or a new type. There, a parse by the extractor that is queued, leased or done stands, and a failed one is queued again to read the new bytes.

func (*Registry) Replayable

func (r *Registry) Replayable() server.Replayable

Replayable is the parse stage as a replay runs it again: a task for each item whose media type an extractor reads.

type RetryError added in v0.29.0

type RetryError struct {
	Err     error
	After   time.Duration
	Bounded bool
}

RetryError is a read that may succeed if made again, and its parse queues again after After. A bounded one fails once its task's claims reach ReadAttempts, such as when the source gave no answer. Where the source asked the read to wait, as while it is busy, the parse waits: it spends no claim, and fails once it has waited ReadWaitCeiling.

func (*RetryError) Error added in v0.29.0

func (e *RetryError) Error() string

func (*RetryError) Unwrap added in v0.29.0

func (e *RetryError) Unwrap() error

type Segment added in v0.29.0

type Segment struct {
	StartMs    int64  `json:"start_ms"`
	DurationMs int64  `json:"duration_ms"`
	Text       string `json:"text"`
}

Segment is one stretch of timed text, such as a caption or a run of speech: when it starts and how long it runs, in milliseconds, and its text on one line.

type Transcript added in v0.29.0

type Transcript struct {
	Info     TranscriptInfo
	Segments []Segment
}

Transcript is what audio-whisper heard.

func Transcribe added in v0.29.0

func Transcribe(ctx context.Context, program string, audio io.Reader) (Transcript, error)

Transcribe runs the program at program, as audio-whisper, over audio. The program reads the audio on stdin in any container that ffmpeg reads. It writes its TranscriptInfo as its first line on stdout, then one Segment a line in order. It runs through isolatedprocess, so it holds none of the worker's credentials. A run that exits non-zero answers an error with the end of its stderr, and one that exits zero with no info line answers an error of its own.

type TranscriptInfo added in v0.29.0

type TranscriptInfo struct {
	Language            string  `json:"language"`
	LanguageProbability float64 `json:"language_probability"`
	DurationMs          int64   `json:"duration_ms"`
	VoicedMs            int64   `json:"voiced_ms"`
}

TranscriptInfo is what audio-whisper reports of the audio before its segments: the language it heard and how sure it is, how long the audio runs, and how much of it the voice-activity filter kept.

type Unit

type Unit struct {
	// Label is the unit's own heading, such as a comment's author or a
	// chapter's title.
	Label *string
	Text  string
}

Unit is one part of a parse, as an extractor writes it. The parse numbers its units from 1 in their order.

Jump to

Keyboard shortcuts

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