Document readers and ingestion
Optional format-specific readers, chunking, snapshots, feeds and publication pipelines with caller-owned limits and no root re-exports.
The recohut_kit.documents namespace groups optional document libraries behind explicit submodule imports. Importing the package root loads no third-party parsers. The layer turns local bytes into bounded text, structure reports, versioned chunks and publication-ready artifacts. Hosts select parsers, models, original-file storage and policy; allowlisted snapshot fetch and snapshot files are implemented in web_snapshot. It does not schedule crawls or infer deletions from partial listings.
Purpose
A document reader transforms source bytes into text and structure an application can use. Keep the source location and version attached to the extracted material so later answers can be checked.
The documents layer owns bounded reading and staging: pypdf-backed text PDFs, optional PyMuPDF text and rasterization, DOCX paragraphs and ordered body text with table cells after ZIP checks, strict local CSV tables, offline RSS/Atom bytes, local HTML visible text, allowlisted web snapshots, optional Docling conversion with source receipts, page-preserving character chunks, an experimentation-oriented chunking subpackage, feed ingestion and multi-format local source sync, and glue into governance-aware publication and vector targets.
It deliberately does not fetch arbitrary URLs inside table or feed parsers, enable OCR without a caller-composed Docling converter, execute workbook formulas, sanitize HTML for security, bound peak CPU or memory as a hard sandbox, or choose embedding providers. URLs and remote acquisition sit outside DoclingParser.parse. Native models may download weights on first use; OCR and other model options stay on the caller-supplied converter.
Public API
Import submodules explicitly; recohut_kit.documents re-exports nothing.
| Name | Kind | What it does |
|---|---|---|
chunks.TextChunk | dataclass | One page text slice with offsets and a fingerprinted identifier |
chunks.chunk_pages | function | Split page strings with overlap and versioned chunk IDs |
pdf.PdfLimits | dataclass | Positive byte, page and text bounds plus empty-page policy |
pdf.PdfRejected | exception | Stable rejection codes for PDF reads |
pdf.read_pdf_pages | function | Per-page text from a local .pdf path |
pdf.read_pdf_bytes | function | In-memory PDF read with password and layout mode options |
pdf.read_pdf_text | function | Join pages with PAGE markers under the text limit |
pymupdf.PdfPage | dataclass | Physical page text with source hash and page count |
pymupdf.read_pages | function | Selected PyMuPDF pages under byte and page caps |
pymupdf.render_page | function | PNG raster of one admitted page |
pdf_structure.inspect_pdf | function | Text pages plus optional native layout evidence |
pdf_structure.DocumentStructureReport | dataclass | Full structure report container |
docx.DocxLimits | dataclass | ZIP and paragraph bounds for DOCX |
docx.read_docx_text | function | Top-level body paragraphs after bounded checks |
docx.read_docx_body | function | Body paragraphs and table cells in document order. Table rows use tab separators with CSV-style quoting. Cell paragraphs count toward the paragraph limit, and merged cell text appears once. |
docling.DocumentLimits | dataclass | Input, page and structured output bounds |
docling.DocumentRejected | exception | Refused conversion with optional native result |
docling.ParsedDocument | dataclass | Source receipt around a native ConversionResult |
docling.DoclingParser | class | Wrap a caller-owned DocumentConverter and parser_id |
docling_knowledge.DoclingDocumentIndex | class | Index, search and cite one Docling document |
docling_knowledge.DoclingChunking | class | Native hybrid chunking policy binding |
docling_knowledge.ChunkingPolicy | dataclass | Token budget and overflow handling |
docling_knowledge.DocumentCitation | dataclass | Verified quote over native items |
html.html_text | function | Visible text without script or style |
html.html_document | function | Title and block-structured text from local HTML |
tables.TableLimits | dataclass | CSV file and dimension bounds |
tables.read_csv | function | UTF-8 CSV to row records |
tables.table_records | function | Header and row width validation |
workbooks.read_workbook | function | Bounded XLSX cell decode without formula execution |
feeds.FeedEntry | dataclass | Untrusted feed fields |
feeds.parse_feed | function | Parse bytes or a local path only |
web_snapshot.SnapshotFetcher | class | Allowlisted HTTP fetch with manifest storage |
web_snapshot.SourceSnapshot | dataclass | URL, time and content record |
web_snapshot.read_snapshot | function | Verified read from a manifest path |
web_snapshot.ExtractionPlan | dataclass | Declared HTML regions to extract |
web_snapshot.extract_post | function | Extract post records from a snapshot |
source_files.LocalSourceFiles | class | Bounded discovery and reads under one root |
source_sync.LocalSourceSync | class | Serialized multi-format sync with deletion proposals |
ingestion_jobs.IngestionJobs | class | Content-addressed staging on the job queue |
feed_ingestion.FeedIngestor | class | Feed through snapshot, chunk, embed and index |
search_pipeline.bind_policy | function | Attach document policy to publication inputs |
search_pipeline.publish_text | function | Publish text into recoverable knowledge |
search_pipeline.publish_native_file | function | Native file lane into publication |
search_tools.DocumentSearchTools | class | Governed hybrid search over published passages |
search_tools.HybridSearchLanes | dataclass | Keyword and dense results from one caller-authorized publication snapshot |
chunking.Chunk | dataclass | Versioned chunk record with fingerprint id |
chunking.Chunker | protocol | Chunker contract |
chunking.FixedCharacterChunker | class | Fixed-size character chunks |
chunking.SlidingWindowChunker | class | Overlapping window chunks |
chunking.SentenceChunker | class | Sentence-bounded chunks |
chunking.SectionChunker | class | Section-aware sentence chunking |
chunking.AdaptiveChunker | class | Budget-driven chunk size selection |
chunking.normalize_text | function | Opt-in normalization with receipt |
chunking.score_query | function | Query complexity scoring |
chunking.trim_conversation | function | Trim turns under a token policy |
chunking.benchmark | module | Corpus chunker comparison and winner selection |
chunking.experiment | module | SQLite-backed chunk experiment artifacts |
chunking.answering.answer_question | function | Cited answer via a TextClient (model step) |
chunking.answering.assess_groundedness | async function | Groundedness judgement via LLMGrader (model step) |
How it composes
Kit imports are submodule-specific. From recohut_kit.json, fingerprint is imported by chunks, docling, docling_knowledge, source_sync, feed_ingestion and chunking contracts and strategies; canonical_json and as_json_value are imported by docling_knowledge. search_pipeline imports Document; search_tools imports Passage; docling_knowledge and chunking answering import Passage, Citation and cite. search_pipeline uses publication units and DocumentPolicy; search_tools uses publication units and governance scope types. Vector contracts support feed ingestion, the chunking experiment and the benchmark; SQLiteVectorIndex is used by the experiment and the benchmark. concurrency.jobs supports ingestion jobs and source sync; files and storage.sqlite support source sync. recohut_kit.objects supports ingestion_jobs and docling_knowledge local stores. Chunking benchmark and answering pull in recohut_kit.retrieval, recohut_kit.retrieval_sparse, recohut_kit.retrieval_benchmark, and recohut_kit.evals (judge, RAG metrics, suites). recohut_kit.providers supplies TextClient for generation; groundedness grading uses LLMGrader. recohut_kit._lazy_build resolves lazy artifacts in docling_knowledge. Chunking experiment reads usage receipts, and answering carries the provider receipt on AnswerRun. recohut_kit.tokens.Tokenizer is used by chunking strategies.
pypdf, pymupdf, docx, docling, feedparser, openpyxl (workbooks), and optional NLTK or spaCy segmenters are imported inside the reader, parser or segmenter call that uses them, not when the kit submodule is imported.
Minimal usage
Install the docx extra from your Kit checkout with uv pip install '.[docx]'. Generate a synthetic document and read a paragraph followed by a table row.
from pathlib import Path
from tempfile import TemporaryDirectory
from docx import Document
from recohut_kit.documents.docx import DocxLimits, read_docx_body, read_docx_text
limits = DocxLimits(
max_bytes=100_000, max_uncompressed_bytes=2_000_000,
max_paragraphs=10, max_chars=200,
)
with TemporaryDirectory() as directory:
path = Path(directory) / "report.docx"
document = Document()
document.add_paragraph("Monthly report")
row = document.add_table(rows=1, cols=2).rows[0]
row.cells[0].text = "Status"
row.cells[1].text = "Ready"
document.save(path)
assert read_docx_text(path, limits=limits) == "Monthly report"
assert read_docx_body(path, limits=limits) == "Monthly report\nStatus\tReady"For structured conversion with DoclingParser, install the docling extra and pass a configured native DocumentConverter, a source path, identity fields, and DocumentLimits. Converter configurations that use models can download model files on first use.
Limits and gotchas
- No root imports. Importing
recohut_kit.documents.doclingleavesdoclingandtorchunloaded;parseimports Docling. - Limits are not sandboxes. PDF docstrings bound accepted input and output, not peak memory or time; DOCX and Docling docstrings say their limits are not a CPU or memory sandbox; HTML limits bound input and extracted text. Hostile files still need a process sandbox.
- PDF text only.
read_pdf_pagesrejects the whole file on unreadable pages whenrequire_text_each_pageis true; there is no OCR fallback inpdforpymupdf. - Docling publication gate. Only
ConversionStatus.SUCCESSpublishes; partial native results raiseDocumentRejectedwith codeconversion_incomplete. Serialized output must fitmax_output_bytes. - Identity fields. Empty
identifier,source_id, orsource_versionraiseValueError;parser_idmust change when converter options or model revisions change. - Untrusted evidence. HTML and feed fields are untrusted; HTML parsing does not emulate CSS visibility or strip instruction-like content.
- Feeds and tables.
parse_feedaccepts bytes orPath, never a URL. Malformed XML and entries without links raise. - Web snapshots. The fetcher checks exact allowed hostnames, including redirects, and relies on trusted DNS for those hosts. Default reuse skips network unless
refetch=True. Publication remains a host decision. - Chunk IDs.
chunk_pagesfingerprints include text and parameters; overlap must satisfy0 <= overlap_chars < max_chars. - Model steps are isolated. Answering calls
TextClientandLLMGrader; NLTK and spaCy load when those segmenters are constructed; feed ingestion and search call the caller-supplied embedding adapter; Docling model use follows the converter you pass. - Sync and jobs.
source_syncmay propose deletions; hosts execute them through owning publication services.feed_ingestionrequires a newindex_identitywhen an index is recreated.
Verification
The example checks both paragraph-only text and body text with a table row. See Verify the examples.
How is this page?
Last updated on