scikitplot.corpus#

scikitplot.corpus#

Tools for turning files, URLs, media, and text sources into canonical CorpusDocument evidence that can be transformed, embedded, stored, searched, adapted, and exported.

Choose the API that matches the job#

CorpusPipeline

Direct stage control for one source or an explicit batch.

CorpusBuilder

High-level build/search/adapt convenience for end-to-end corpus workflows.

FluentCorpus

Immutable, reusable configuration. Chained setter order describes what is configured; it does not define execution order.

RuntimeCorpus

The operational form of a validated Fluent plan. Materialization constructs runtime components; source processing starts only with run() or add().

RetrievalIndex / VectorIndexBackend

Lower-level retrieval and vector-backend extension APIs.

The common processing picture is:

Source
  -> Read
  -> Chunk / Normalize / Enrich
  -> Embed
  -> Store
  -> Index
  -> Retrieve
  -> Adapt / Export

Examples

Direct pipeline control:

>>> from pathlib import Path
>>> from scikitplot.corpus import CorpusPipeline, ParagraphChunker
>>> pipeline = CorpusPipeline(chunker=ParagraphChunker())
>>> result = pipeline.run(Path("article.txt"))
>>> print(f"{result.n_documents} chunks from {result.source}")

The dependency-free default sentence backend is REGEX. Passing a spaCy model name explicitly selects the spaCy shorthand instead:

>>> from scikitplot.corpus import SentenceChunker
>>> portable = SentenceChunker()
>>> spacy_chunker = SentenceChunker("en_core_web_sm")

High-level builder:

>>> from scikitplot.corpus import CorpusBuilder, BuilderConfig
>>> builder = CorpusBuilder(
...     BuilderConfig(
...         chunker="paragraph",
...         normalize=True,
...         enrich=True,
...         build_index=True,
...     )
... )
>>> result = builder.build("./data/")
>>> results = builder.search("quantum computing")

Reusable declarative configuration:

>>> from scikitplot.corpus import FluentCorpus
>>> fluent = FluentCorpus().chunker("paragraph").storage("memory")
>>> fluent.validate()
[]

Materialization is explicit and performs no source read by itself:

>>> from scikitplot.corpus import RuntimePolicy
>>> with fluent.materialize(policy=RuntimePolicy(allow_network=False)) as runtime:
...     len(runtime.documents)
0

A configured source becomes operational only when run() is called:

>>> runtime_fluent = (
...     FluentCorpus().source("article.txt").chunker("paragraph").storage("memory")
... )
>>> with runtime_fluent.materialize() as runtime:
...     result = runtime.run()

Network and optional-capability examples:

Live URLs, OCR, ASR, spaCy, NLTK resource-backed NLP, model embeddings, and native vector backends depend on the corresponding environment capability. User-facing examples should not fabricate results when a capability is absent. Documentation/gallery examples should either use a portable executed path or report a clear skip while keeping the optional configuration visible.

URL ingestion:

>>> result = pipeline.run_url("https://en.wikipedia.org/wiki/Python")

YouTube transcript:

>>> result = pipeline.run(
...     "https://www.youtube.com/watch?v=rwPISgZcYIk"
... )

Image OCR:

>>> from scikitplot.corpus import DocumentReader
>>> reader = DocumentReader.create(Path("scan.png"))
>>> docs = list(reader.get_documents())

With model embeddings:

>>> from scikitplot.corpus import EmbeddingEngine
>>> engine = EmbeddingEngine(backend="sentence_transformers")

Dependency-free local helpers:

>>> from scikitplot.corpus import HAMLET_TEXT, HashEmbedder, SimpleEnricherSpec
>>> HashEmbedder(dimension=32)([HAMLET_TEXT[:120]]).shape
(1, 32)
>>> FluentCorpus().enricher(SimpleEnricherSpec()).validate()
[]

HashEmbedder is a deterministic lexical hashing baseline, not a learned semantic model. HAMLET_TEXT is bundled convenience sample data rather than an authoritative scholarly edition.

See scikitplot/corpus/README.md for the user-oriented API map, runtime policy boundary, retrieval modes, and optional-capability guidance.

User guide. See the Corpus User Guide section for further details.

Adapter layer#

Class inheritance

Inheritance diagram of LangChainCorpusRetriever, MCPCorpusServer

to_langchain_documents

Convert CorpusDocument instances to LangChain Document.

to_langgraph_state

Convert documents to a LangGraph-compatible state dict.

to_mcp_resources

Convert documents to MCP resources/read response format.

to_mcp_tool_result

Format documents as an MCP tools/call response.

to_huggingface_dataset

Convert documents to a HuggingFace Dataset.

to_rag_tuples

Convert documents to (text, metadata, embedding) tuples.

to_jsonl

Yield documents as newline-delimited JSON strings.

to_numpy_arrays

Convert documents to a dict of NumPy arrays suitable for batch ML.

to_tensorflow_dataset

Convert documents to a tf.data.Dataset.

to_torch_dataloader

Convert documents to a torch.utils.data.DataLoader.

LangChainCorpusRetriever

LangChain-compatible retriever backed by RetrievalIndex.

MCPCorpusServer

MCP server adapter for corpus search.

Agentic Retrieval Session#

AgenticRetrievalSession

Ephemeral state for one investigation.

BudgetPolicy

Deterministic, decrementing limits on an investigation.

InvestigationOutcome

The result of a bounded investigation.

InvestigationStatus

How an investigation finished.

RoutePlan

A deterministic decision about which evidence paths to use.

StopReason

Why the loop stopped.

SufficiencySignals

The seven deterministic signals, computed before any model judgement.

route

Choose evidence paths by deterministic rule (autonomy level A1).

run_investigation

Run the bounded retrieve/evaluate/refine loop (autonomy level A2).

RoutingPolicy

An ordered set of RoutingRule, one per shape.

RoutingRule

One shape: the words that reveal it and the evidence paths it needs.

QueryShape

The built-in shapes of DEFAULT_ROUTING_POLICY.

DEFAULT_ROUTING_POLICY

An ordered set of RoutingRule, one per shape.

query_tokens

Return the words a routing rule matches against.

Archive within Archive Handler#

extract_archive

Extract an archive to a destination directory.

is_archive

Check if a file path has a supported archive extension.

Artifact Handler#

ANNIndexArtifact

A persisted vector index together with its provenance.

ArtifactError

Raised when an artifact is missing, malformed or incompatible.

Base Classes#

Class inheritance

Inheritance diagram of DocumentReader, DummyReader

ChunkerBase

Abstract base class for all text chunkers.

CodeAwareFilter

Keep code that is not blank; filter everything else as prose.

DefaultFilter

Standard noise filter ported and improved from remarx's include_sentence.

NonBlankFilter

Keep every document whose text holds a non-whitespace character.

DocumentReader

Abstract base class for all format-specific document readers.

DummyReader

A no-op reader that validates source existence and accessibility.

FilterBase

Abstract base class for corpus document filters.

PipelineGuard

Wrap any document stream with resilience, deduplication, and checkpointing.

ReadCoverage

What one read of a source covered: parts read, empty and skipped.

Capability Status#

CapabilityStatus

Why a capability is or is not usable.

capability_snapshot

Return a read-only snapshot of the runtime corpus capabilities.

distribution_version

Return the installed version of a distribution, or None if absent.

probe_backend

Classify one backend's availability.

CapabilityRegistry

Explicit, side-effect-free registry for component readiness probes.

CapabilityReport

Read-only readiness state for one optional component.

CapabilitySpec

Declarative probe specification for one optional component.

capability_report

Probe one registered component capability.

component_capabilities

Return JSON-compatible readiness records for components.

default_capability_registry

Return the built-in component readiness registry.

Component Spec#

ComponentCatalog

An immutable snapshot of every registered component.

ComponentSpec

Everything the catalog knows about one component.

DiscoveryOutcome

What happened when one source was asked for its components.

DiscoveryStatus

Terminal outcome of asking one source what components it has.

component_catalog

Build a snapshot of every registered component.

Chunkers#

ChunkedTextList

A list subclass that carries per-chunk metadata alongside (int, str) pairs.

ChunkerBridge

Adapter that wraps a new-style chunker as a ChunkerBase- compatible object.

FixedWindowChunkerBridge

Bridge for FixedWindowChunker → ChunkerBase contract.

ParagraphChunkerBridge

Bridge for ParagraphChunker → ChunkerBase contract.

ProtocolChunkerBridge

Bridge for any chunker satisfying ChunkerProtocol (R3-1).

SemanticChunkerBridge

Bridge for SemanticChunker → ChunkerBase contract.

SentenceChunkerBridge

Bridge for SentenceChunker → ChunkerBase contract.

WordChunkerBridge

Bridge for WordChunker → ChunkerBase contract.

bridge_chunker

Wrap chunker in a bridge if it is a new-style chunker.

register_bridge

Register a custom bridge for a user-defined chunker class.

unregister_bridge

Remove a previously registered bridge for chunker_class.

TokenizerProtocol

Structural protocol for word tokenizers.

SentenceSplitterProtocol

Structural protocol for sentence segmenters.

StemmerProtocol

Structural protocol for word stemmers.

LemmatizerProtocol

Structural protocol for word lemmatizers.

FunctionTokenizer

Wrap any Callable[[str], list[str]] as a TokenizerProtocol.

FunctionSentenceSplitter

Wrap any Callable[[str], list[str]] as a SentenceSplitterProtocol.

FunctionStemmer

Wrap any Callable[[str], str] as a StemmerProtocol.

FunctionLemmatizer

Wrap any Callable[[str, Optional[str]], str] as a LemmatizerProtocol.

CustomTokenizerRegistry

Thread-safe module-level registry for named custom components.

register_tokenizer

Register a named TokenizerProtocol implementation.

get_tokenizer

Retrieve a registered tokenizer by name.

register_sentence_splitter

Register a named SentenceSplitterProtocol implementation.

get_sentence_splitter

Retrieve a registered sentence splitter by name.

register_stemmer

Register a named StemmerProtocol implementation.

get_stemmer

Retrieve a registered stemmer by name.

register_lemmatizer

Register a named LemmatizerProtocol implementation.

get_lemmatizer

Retrieve a registered lemmatizer by name.

ScriptType

Dominant Unicode script detected in a text sample.

detect_script

Detect the dominant Unicode script in text.

is_cjk_char

Return True if ch is a CJK / Japanese / Korean character.

is_rtl_char

Return True if ch belongs to a right-to-left script.

split_cjk_chars

Split text into individual CJK character tokens.

MULTI_SCRIPT_SENTENCE_RE_PATTERN

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

ScriptSpan

A contiguous span of text in a single Unicode script.

ScriptSegmenter

Segment NFC-normalised text into contiguous Unicode script spans.

FixedWindowChunker

Produce fixed-size sliding-window chunks over a document.

FixedWindowChunkerConfig

Configuration for FixedWindowChunker.

WindowUnit

Unit of measurement for window size and step.

ISO_TO_NLTK

ISO_TO_NAME

NLTK_TO_ISO

NLTK_STOPWORD_LANGUAGES

frozenset() -> empty frozenset object frozenset(iterable) -> frozenset object

BUILTIN_LANG_STOPWORDS

coerce_language

Normalise any language specifier into a list of canonical NLTK names.

resolve_stopwords

Return a frozenset of stopwords for one or more languages.

iso_to_nltk

Resolve an ISO 639-1/639-3 code to a canonical NLTK language name.

nltk_to_iso

Resolve a canonical NLTK language name to its primary ISO 639-1 code.

MultilangConfig

Multilang feature flags for any chunker.

MultilangMixin

Shared multilang analysis mixin for all five chunkers.

ParagraphChunker

Split a document into paragraph-level Chunk objects.

ParagraphChunkerConfig

Configuration for ParagraphChunker.

ParentChildChunker

Large parents for context, small children for retrieval, linked.

ParentChildChunkerConfig

Configuration for ParentChildChunker.

RecursiveChunker

Split text by a separator hierarchy until each piece fits a budget.

RecursiveChunkerConfig

Configuration for RecursiveChunker.

SemanticBackend

Semantic chunking backend selector.

SemanticChunker

Embedding-aware, writing-system-aware semantic chunker (Layer 3).

SemanticChunkerConfig

Configuration for SemanticChunker.

SentenceBackend

Supported sentence-splitting backends.

SentenceChunker

Split a document into sentence-level Chunk objects.

SentenceChunkerConfig

Configuration for SentenceChunker.

StructureChunker

Chunk Markdown or reStructuredText by its headings and code blocks.

StructureChunkerConfig

Configuration for StructureChunker.

LemmatizationBackend

Lemmatization backend.

StemmingBackend

Stemming algorithm.

StopwordSource

Stopword list source.

TokenizerBackend

Word tokenisation backend.

WordChunker

Process a document at word level, producing normalised token chunks.

WordChunkerConfig

Configuration for WordChunker.

ArabicMorphologicalStrategy

Arabic and Hebrew morphological segmentation strategy.

CJKCharacterStrategy

Character-level segmentation for Han (Chinese logograph) script.

DeterminativeGroupStrategy

Egyptian Hieroglyph segmentation into determinative groups.

DictionaryBoundaryStrategy

Dictionary-based word boundary detection for no-space scripts.

EthiopicStrategy

Ethiopic (Amharic, Tigrinya) segmentation strategy.

GraphemeClusterStrategy

Grapheme-cluster-level fallback strategy for any script.

IndicAksharaStrategy

Grapheme-cluster segmentation for Indic scripts.

JapaneseStrategy

Multi-tier Japanese segmentation strategy.

KoreanSyllableStrategy

Space-delimited word segmentation for Korean Hangul.

MongolianStrategy

Traditional Mongolian segmentation strategy.

SegmentationStrategy

Protocol for per-script text segmentation strategies.

SpacePunctuationStrategy

Whitespace-and-punctuation segmentation for space-delimited scripts.

TibetanStrategy

Tibetan segmentation strategy.

WritingSystemAdapter

Dispatch per-script segmentation to the correct strategy.

WritingSystemAdapterConfig

Configuration for WritingSystemAdapter.

Corpus Builder#

Class inheritance

Inheritance diagram of CorpusBuilder

BuildResult

Result of a corpus build operation.

BuilderConfig

Configuration for CorpusBuilder.

CorpusBuilder

Unified corpus builder — end-to-end pipeline orchestrator.

Custom Hooks#

BuilderFactories

Component factory callables for FactoryCorpusBuilder.

CustomChunker

Wrap any callable as a ChunkerBase.

CustomEnricherConfig

Custom backend callables for CustomNLPEnricher.

CustomFilter

Wrap any callable as a FilterBase.

CustomNLPEnricher

NLPEnricher extended with fully-replaceable NLP backends.

CustomNormalizer

Wrap any callable as a NormalizerBase.

CustomRetrievalIndex

RetrievalIndex extended with a fully-replaceable custom scorer callable.

FactoryCorpusBuilder

CorpusBuilder extended with pluggable component factories.

HookableCorpusPipeline

CorpusPipeline extended with per-stage lifecycle hooks.

PipelineHooks

Lifecycle callbacks for HookableCorpusPipeline.

Diagnostic Error Record#

ErrorCategory

Coarse classification of a diagnostic, for counting and filtering.

ErrorRecord

One structured, serialisable diagnostic.

Downloader#

Class inheritance

Inheritance diagram of BaseDownloader, AnyDownloader

AnyDownloader

Auto-dispatching downloader with multi-URL and per-parameter list support.

BaseDownloader

Abstract base class for all format-specific URL downloaders.

CustomDownloader

Wraps a user-supplied callable as a BaseDownloader.

DownloadResult

Immutable result object returned by every BaseDownloader.

GitHubDownloader

GitHub URL downloader with automatic blob → raw normalisation.

GoogleDriveDownloader

Google Drive share-link downloader.

WebDownloader

Generic HTTP/HTTPS file downloader.

YouTubeDownloader

YouTube content downloader.

DownloadPlan

Side-effect-free dispatch plan for one URL.

DownloadPolicy

Transport/resource policy shared by Corpus downloaders.

download_policy

Resolve an object, named preset or mapping without hidden global state.

Embeddings#

CachePolicy

How EmbeddingEngine uses its disk cache.

CacheStatus

What one cached embedding call did.

CachedEmbeddings

The result of EmbeddingEngine.embed_cached.

resolve_hub_revision

Return the Hugging Face Hub commit a model id currently points to.

DEFAULT_CACHE_DIR

Path subclass for non-Windows systems.

DEFAULT_MODEL

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

EmbeddingEngine

Multi-backend sentence embedding engine with SHA-256 file caching.

HashEmbedder

Embed text with deterministic signed feature hashing.

DEFAULT_AUDIO_MODEL

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

DEFAULT_IMAGE_MODEL

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

DEFAULT_TEXT_MODEL

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

LLMTrainingExporter

Export a corpus with embeddings to LLM training formats.

MultimodalEmbeddingEngine

Unified embedding engine for any CorpusDocument modality — text, image, audio, video, or multimodal.

Embedding Manifest#

EmbeddingManifest

Identity of one embedding generation.

IncompatibleEmbeddingsError

Raised when vectors from incompatible generations would be combined.

Enricher#

BUILTIN_STOPWORDS

frozenset() -> empty frozenset object frozenset(iterable) -> frozenset object

EnricherConfig

Configuration for NLPEnricher.

NLPEnricher

Pipeline component that populates NLP enrichment fields on CorpusDocument.

SimpleEnricherSpec

Declarative configuration for SimpleFrequencyEnricher.

SimpleFrequencyEnricher

Populate tokens and deterministic frequency-ranked keywords.

Evaluation: Retrieval and Answer Metrics, Scorers#

Class inheritance

Inheritance diagram of EvaluationComparison, MetricComparison, QueryEvaluation, RetrievalEvaluation, ScorerBackendInfo

hit_rate_at_k

Fraction of queries with at least one relevant identifier in the first k.

mean_average_precision

Mean average precision (MAP), normalised by all relevant identifiers.

mean_reciprocal_rank

Mean of 1 / rank of the first relevant identifier (MRR).

ndcg_at_k

Normalised discounted cumulative gain (nDCG@k) over graded judgments.

precision_at_k

Fraction of the first k ranked identifiers that are relevant.

r_precision

Precision at |R|, the number of relevant identifiers of each query.

ranking_metrics

Compute several ranking metrics in one validated pass.

recall_at_k

Fraction of the relevant identifiers found in the first k.

binary_log_loss

Mean negative log-likelihood of binary outcomes under the probabilities.

brier_score

Mean squared difference between probabilities and binary outcomes.

calibration_report

Every calibration measure for one set of labelled probabilities.

expected_calibration_error

Count-weighted mean absolute gap between prediction and observation.

reliability_table

Per-bin mean predicted probability against observed relevance frequency.

CALIBRATION_STRATEGIES

Built-in immutable sequence.

anls_score

Average normalised Levenshtein similarity (ANLS).

edit_similarity

Return 1 - levenshtein(a, b) / max(len(a), len(b)).

edit_similarity_score

Mean normalised edit similarity between predictions and references.

exact_match_score

Fraction of predicted answers equal to a reference after normalisation.

normalize_answer

Normalise an answer string for comparison.

token_f1_score

Token-overlap F1 between predicted and reference answers (SQuAD style).

ScorerBackendInfo

Which base class the corpus scorers use in this process.

get_corpus_scorer

Return a new scorer for a metric name.

get_corpus_scorer_names

Return the names get_corpus_scorer accepts.

make_corpus_scorer

Make a scikit-learn compatible scorer from a corpus metric.

scorer_backend_info

Report which base class corpus scorers use in this process.

EvaluationComparison

Paired comparison of two evaluations of the same queries.

MetricComparison

One metric of an EvaluationComparison.

QueryEvaluation

One query of a RetrievalEvaluation.

RetrievalEvaluation

Result of evaluate_retrieval.

evaluate_retrieval

Run retriever on every query and score the rankings.

UndefinedMetricWarning

A metric is undefined for some queries and was scored by zero_division.

ranked_ids

Return the identifiers of retrieval results, in rank order.

Evaluation: LLM Judges, Answer Harness, Agreement#

Class inheritance

Inheritance diagram of AnswerEvaluation, AnswerItem, Completion, JudgeResult, LLM, LLMJudge, PreferenceEvaluation

CacheError

The response cache failed (a configuration problem, not a model failure).

Completion

One model response.

IncompleteCompletionError

A completion that did not end normally (cut off, filtered, refused).

LLM

A language model behind one call shape; made by make_llm.

make_llm

Make an LLM for OpenAI, Anthropic, Gemini or a callable.

JudgeParseError

A judge's response that is not a valid verdict.

JudgeResult

One judged score.

LLMJudge

Judge answers and contexts with a language model.

context_texts

Return the texts of retrieved contexts, in order.

parse_verdict

Parse a judge response strictly.

AnswerEvaluation

Result of evaluate_answers.

AnswerItem

One item of an AnswerEvaluation.

PreferenceEvaluation

Result of evaluate_preference.

evaluate_answers

Evaluate a system's answers with text metrics and LLM judges.

evaluate_preference

Judge two systems' answers head to head, in both orders.

cohen_kappa

Cohen's kappa between two raters of the same items.

fleiss_kappa

Fleiss' kappa for any number of raters with nominal labels.

krippendorff_alpha

Krippendorff's alpha for any number of raters, with missing ratings.

Export#

export_documents

Export a list of documents to output_path in the given format.

load_documents

Load CorpusDocument instances from a previously exported file.

Filter (backend-neutral) Expressions#

And

All sub-expressions must match.

Eq

field == value.

Exists

The field is present and not None.

Filter

Base class for filter expressions.

FilterCapability

A backend's declared answer for the operators in one expression.

In

field in values.

Not

Negates a sub-expression.

NotEq

field != value.

NotIn

field not in values; a missing field does not match.

Or

At least one sub-expression must match.

Range

lo <= field <= hi, with either bound optional.

SecurityFilter

A scope bound to an index and AND-ed with every query's own filter.

UnsupportedOperatorError

Raised when a backend is asked to evaluate an operator it rejects.

filter_from_dict

Rebuild a filter expression from its JSON form, refusing anything off contract.

filter_to_dict

Return the JSON form of a filter expression.

filterable_fields

Return the document fields a filter may name.

validate_filter

Return expression checked and frozen to the JSON-able form.

Generator Index#

IndexGeneration

Identity of one built index.

derive_generation

Derive the generation identity for a set of documents.

Document Identity#

DocIdScheme

How a corpus build names its documents.

IDENTITY_HEX_WIDTH

int([x]) -> integer int(x, base=10) -> integer

IncompatibleSchemaError

Raised for data written by another generation of the document schema.

UUID7Generator

Monotonic generator of RFC 9562 UUID version 7 identifiers.

assign_doc_ids

Return documents named by scheme, with parent links kept intact.

doc_id_scheme_of

Return the scheme that produced doc_id, judged by its exact form.

uuid7

Return a new RFC 9562 UUID version 7 from this process's generator.

uuid7_unix_ms

Return the Unix time in milliseconds that a UUID version 7 carries.

Graph Node#

EdgeTrust

How an edge came to exist.

GraphEdge

One relationship, with the provenance every edge must carry.

GraphNode

One node in the derived graph.

GraphQuery

A bounded traversal request.

GraphResponse

The outcome of a traversal, including why it stopped.

NodeKind

What a graph node represents.

RelationType

The kind of relationship an edge asserts.

derive_graph

Build the G0 view from document fields.

Hierarchy Report#

HierarchyReport

Outcome of validating a document hierarchy.

ancestors

Return the chain from doc_id's parent up to the root.

children

Return the direct children of doc_id.

descendants

Yield all descendants of doc_id, breadth-first.

validate_hierarchy

Check referential integrity, cycles and depth of the hierarchy.

Metadata#

CollectionManifest

Descriptor for a named corpus collection.

CorpusStats

Aggregate statistics over a CorpusDocument collection.

compute_stats

Compute aggregate statistics over a document collection.

provenance_from_filename

Extract provenance metadata from a source filename using heuristics.

Normalizers#

DedupLinesNormalizer

Remove exact duplicate lines while preserving first-occurrence order.

GraphemeClusterNormalizer

Normalize text to NFC and compute grapheme cluster boundaries.

HTMLStripNormalizer

Remove HTML and XML tags from the document text.

LanguageDetectionNormalizer

Detect document language and set CorpusDocument.language.

LowercaseNormalizer

Convert the document text to lowercase.

NormalizationPipeline

Apply a sequence of normalisers in order.

NormalizerBase

Abstract base class for all text normalisers.

UnicodeNormalizer

Apply Unicode normalisation (NFC, NFD, NFKC, or NFKD).

WhitespaceNormalizer

Collapse runs of whitespace and optionally strip leading/trailing space.

TextNormalizer

Pipeline component that populates normalized_text on CorpusDocument instances.

TextNormalizerConfig

Configuration for TextNormalizer.

normalize_text

Normalise text according to config.

Pipeline#

Class inheritance

Inheritance diagram of CorpusPipeline, PipelineResult

CorpusPipeline

Orchestrates the full corpus ingestion pipeline.

PipelineResult

Immutable summary of a single pipeline run.

create_corpus

Create and export a corpus from a single source file.

Plan Fluent Facade#

Class inheritance

Inheritance diagram of CorpusPlan, FluentCorpus

CONFIG_DOMAINS

Built-in immutable sequence.

ConfigConflictError

Raised when one domain is configured twice without an explicit intent.

CorpusPlan

An immutable, canonical description of a corpus configuration.

FluentCorpus

Immutable fluent builder over a CorpusPlan.

Readers#

Class inheritance

Inheritance diagram of MarkdownReader, CustomReader

ALTOReader

ALTO XML reader for scanned document archives.

AudioReader

Text extraction from audio files via companion transcript/lyrics parsing, Whisper ASR, and optional audio classification.

CHMReader

Read a Compiled HTML Help (.chm) file into chunks, page by page.

CodeReader

Read a source code or configuration file in blocks of whole lines.

LANGUAGES

CustomReader

Fully user-customizable reader for any file extension and resource type.

normalize_extractor_output

Coerce an extractor return value to a list of raw chunk dicts.

ImageReader

OCR-based text extraction from raster image files.

LEAN_FLAGS

LeanReader

Read a Lean source file one command at a time, each chunk naming its declaration.

MHTMLReader

Read a saved web page (.mhtml, .mht) into one chunk per element.

NotebookReader

Read a Jupyter notebook (.ipynb) into one chunk per cell.

OfficeReader

Read office documents: Office Open XML and OpenDocument.

PDFReader

PDF document reader with pdfminer.six → pypdf cascade.

JSONReader

Read JSON (.json) and JSON Lines (.jsonl, .ndjson).

TOMLReader

Read TOML (.toml).

YAMLReader

Read YAML (.yaml, .yml), every document of a stream.

SubtitleReader

Read a subtitle or caption file into timed chunks.

CSVReader

Read a delimited text table into chunks of rows.

MarkdownReader

Markdown document reader.

ReSTReader

reStructuredText document reader.

TextReader

Plain-text document reader.

VideoReader

Text extraction from video files via subtitle parsing and/or automatic speech recognition.

HTMLReader

Read a local HTML file into one chunk per text element, offline.

WebReader

Fetch a web page and extract structured text via BeautifulSoup.

YouTubeReader

Extract the transcript of a YouTube video using youtube-transcript-api.

TEIReader

TEI/XML document reader with dramatic structure extraction.

XMLReader

Generic XML document reader with configurable XPath.

ArchiveBudgetError

Raised when the members of an archive tree inflate past its extraction budget.

ArchiveNestingError

Raised when archive nesting exceeds max_depth (nested-archive bomb).

ZipReader

Generic ZIP archive reader — dispatches each member to its natural reader.

TarReader

Read a tar archive (plain, gzip, bzip2 or xz) or a single compressed file.

Registry#

ComponentRegistry

Central look-up table for corpus pipeline components.

registry

Central look-up table for corpus pipeline components.

Retrieval Response#

LegKind

Which evidence path a leg represents.

LegOutcome

How one evidence path fared.

LegStatus

Outcome of one evidence path.

RetrievalResponse

Hits plus the story of how they were obtained.

RetrievalStatus

Outcome of a retrieval operation as a whole.

Retriever#

DenseRetriever

Vector-similarity evidence path.

FusedItem

One item of a fused ranking.

FusionContribution

One leg's share of a fused item's score.

FusionPolicy

Weighted reciprocal rank fusion with one tie-break and returned contributions.

GraphRetriever

Relationship-traversal evidence path.

LegContribution

One leg's contribution to a fused hit.

LegResult

What one leg produced, and how it went.

LexicalRetriever

Keyword / BM25 evidence path.

LogOddsContribution

One leg's evidence for one fused item.

LogOddsFusedItem

One item of a probability-fused ranking.

LogOddsFusion

Pool calibrated legs as log-odds evidence into probabilities of relevance.

LogOddsFusionResult

A fused ranking and the diagnostics needed to trust it.

CUT_MODES

Built-in immutable sequence.

CachedSearch

Exact, bounded cache in front of one retrieval index.

CutPolicy

A rule for how many ranked hits to keep.

CutResult

Where a list was cut, and why.

PROBABILITY_FUSION_LEGS

Built-in immutable sequence.

ProbabilityFusion

Opt-in probability fusion for hybrid search: a policy and a calibrator per leg.

Retriever

Base class for an independent evidence path.

fuse_by_rank

Combine leg results by weighted reciprocal rank fusion.

Retrieval Execution Plan#

CharBudgetCompressor

Keep each hit's text, best first, until a character budget is spent.

ContextPassage

The context a compressor kept from one hit.

ExecutionResult

Ranked hits plus the account of every stage.

PlannedHit

One ranked hit of a plan, with the score of each stage that ranked it.

RetrievalExecutionPlan

Run retrieval through typed, bounded stages.

StageBudget

Deterministic limits on the retrieve stage.

StageKind

One stage of a plan, in execution order.

StageOutcome

How one stage fared.

StageStatus

Outcome of one stage.

Corrective Retrieval#

CorrectionResult

The returned hits, the verdict, and every round.

CorrectionRound

One round: the query run, how it was graded, what came back.

CorrectionVerdict

What the corrective retrieval came to.

CorrectiveRetrieval

Grade, then accept, retry with a rewritten query, or abstain (CRAG).

EvidenceGrade

How a grader judged one round's hits.

GradeResult

One grader's judgement of one round.

TermCoverageGrader

Grade hits by the share of the query's words their text contains.

Runtime Policy#

RuntimeCorpus

Materialized operational view of a validated CorpusPlan.

RuntimePolicy

Execution-boundary policy applied by RuntimeCorpus.

materialize_plan

Resolve a validated CorpusPlan into runtime components.

runtime_policy

Resolve a runtime policy object, preset name, or mapping.

CorpusPolicyBundle

Typed composition of the independent Corpus policy dimensions.

corpus_policy_bundle

Resolve a policy bundle object, named preset, or mapping.

Optional Backend Policy#

BackendCandidate

One lazy backend attempt.

BackendOutcome

Structured, serialisable outcome from run_backend_chain.

BackendPlan

Side-effect-free preflight of candidate ordering and policy eligibility.

BackendPolicy

Policy for selecting and exhausting optional backend chains.

BackendSkip

Why a backend was not executed under the resolved policy.

BackendStatus

Outcome of one ordered backend operation.

backend_policy

Resolve an object, named preset or mapping without hidden global state.

plan_backend_chain

Resolve backend order/readiness without executing a backend.

run_backend_chain

Try candidates in order and return a structured outcome.

ASRBackend

User-defined ASR backend adapter.

ASRRequest

Stable immutable request passed to user-provided ASR backends.

WHISPER_MODELS

Built-in immutable sequence.

asr_segment_metadata

Return user/backend metadata without allowing core-field shadowing.

plan_whisper_backends

Plan the exact ASR chain without importing/loading/running a model.

transcribe_whisper

Transcribe media with a shared, policy-driven ASR backend chain.

Samples for Corpus Usage#

HAMLET_TEXT

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Schema#

SectionType

Semantic label for the role of a text chunk within its source document.

ChunkingStrategy

Describes how a CorpusDocument was segmented from raw text.

ExportFormat

Supported serialisation targets for a completed corpus.

SourceType

Semantic label for the kind of source from which a document was read.

MatchMode

Search mode for intertextual matching queries against a corpus index.

Modality

Primary content modality of a CorpusDocument.

ErrorPolicy

Per-document error handling behaviour for PipelineGuard.

CorpusDocument

Canonical representation of a single text chunk in a processed corpus.

documents_to_pandas

Convert a list of CorpusDocument instances to a pandas.DataFrame.

documents_to_polars

Convert a list of CorpusDocument instances to a polars.DataFrame.

Similarity Backend#

Class inheritance

Inheritance diagram of LevenshteinRanker, PairwiseRanker

DEFAULT_BACKEND_ORDER

Built-in immutable sequence.

AnnoyBackend

ANN backend over a scikit-plots Annoy Index (default backend).

BruteForceBackend

Exact cosine similarity via a normalised dot product.

FaissBackend

ANN backend over a FAISS IndexFlatIP on normalised vectors.

FallbackRefusedError

A fallback was needed and allow_fallback=False refused it (R2-5).

VectorIndexBackend

Uniform contract for a dense vector index.

VoyagerBackend

ANN backend over a Voyager cosine-space index.

list_available_backends

Return the canonical names of currently importable backends.

select_backend

Construct an ANN backend by name.

RetrievalConfig

Configuration for similarity search.

RetrievalHit

A single search result.

RetrievalIndex

Multi-mode similarity index over CorpusDocument collections.

LevenshteinRanker

Ranker by normalised Levenshtein similarity, with backend provenance.

PairwiseRanker

Ranker built from a pairwise relevance function.

make_levenshtein_ranker

Make a CustomRetrievalIndex ranker by Levenshtein similarity.

make_pairwise_ranker

Make a CustomRetrievalIndex ranker from a pairwise function.

Source#

CorpusSource

Declarative descriptor for one or more document sources.

SourceEntry

A single resolved source entry yielded by CorpusSource.iter_entries.

SourceKind

Discriminant for the kind of source an entry represents.

Storage#

Class inheritance

Inheritance diagram of InMemoryStorage, SQLiteStorage

FilterSupport

How a backend handled one requested filter.

InMemoryStorage

Thread-safe in-memory dict store.

JSONLStorage

Append-friendly JSONL (newline-delimited JSON) flat-file store.

QueryResult

Result container returned by StorageBase.query.

SQLiteStorage

SQLite-backed corpus store with FTS5 full-text search.

StorageBase

Abstract base class for all corpus storage backends.

StorageQuery

Query parameters for StorageBase.query.

Type Contracts#

MetadataDict

CharOffset

TokenId

BowVector

EmbeddingVector

DocumentStatus

Lifecycle state of a CorpusDocument in the corpus pipeline.

ContentType

MIME-style content type for raw document payloads.

StorageBackend

Storage backend identifiers for the corpus store.

NormalizerType

Normalisation step identifiers for pipeline ordering.

Chunk

A single unit of text produced by a chunker.

ChunkResult

Container returned by every ChunkerProtocol implementation.

ChunkerConfig

Abstract base configuration for all chunker implementations.

SourceConfig

Abstract base configuration for document source implementations.

NormalizerConfigBase

Abstract base configuration for text normaliser implementations.

StorageConfig

Abstract base configuration for storage backend implementations.

PipelineStep

Descriptor for a single step in a PipelineConfig.

PipelineConfig

Full pipeline configuration composed of ordered steps.

EmbeddedChunk

A Chunk decorated with a dense embedding vector.

RetrievalQuery

A query submitted to the corpus retrieval layer.

ChunkHit

A single result returned from the corpus retrieval layer.

CorpusRecord

A persisted record combining a Chunk with storage metadata.

ChunkerProtocol

Structural interface every chunker must satisfy.

NormalizerProtocol

Structural interface every text normaliser must satisfy.

SourceProtocol

Structural interface every document source must satisfy.

StorageProtocol

Structural interface every storage backend must satisfy.

ChunkerRegistration

An entry in the ChunkerRegistry.

ValidationError

A single validation failure raised during corpus processing.

ValidationResult

Aggregate result of a validation pass.

TrainingExample

A single example in an LLM fine-tuning dataset.

TrainingDataset

A named collection of TrainingExample objects.

ToolCallInput

Input payload for a Model Context Protocol tool call.

ToolCallResult

Result returned from a Model Context Protocol tool call.

SemantemeInfo

Rich semantic unit descriptor attached to each multilang chunk.

PreprocessingStep

Record of a single preprocessing transformation applied to raw text.

PreprocessingTrace

Ordered audit trail of all preprocessing transformations.

MultilangChunkMeta

Per-chunk multilang analysis bundle — stored in chunk.metadata.

URL Handler#

URLKind

Classification of a URL for routing to the correct handler.

classify_url

Classify a URL into one of the known URLKind categories.

download_url

Download a URL to a local file.

infer_extension

Infer a file extension from HTTP response headers and URL path.

probe_url_kind

Probe a URL with a HEAD request to classify by Content-Type.

resolve_url

Resolve a provider-specific URL to a direct-download URL.