Skip to Content
Recodocs

Document readers and ingestion

Optional format-specific readers, chunking, snapshots, feeds and publication pipelines with caller-owned limits and no root re-exports.

7 min read

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.

NameKindWhat it does
chunks.TextChunkdataclassOne page text slice with offsets and a fingerprinted identifier
chunks.chunk_pagesfunctionSplit page strings with overlap and versioned chunk IDs
pdf.PdfLimitsdataclassPositive byte, page and text bounds plus empty-page policy
pdf.PdfRejectedexceptionStable rejection codes for PDF reads
pdf.read_pdf_pagesfunctionPer-page text from a local .pdf path
pdf.read_pdf_bytesfunctionIn-memory PDF read with password and layout mode options
pdf.read_pdf_textfunctionJoin pages with PAGE markers under the text limit
pymupdf.PdfPagedataclassPhysical page text with source hash and page count
pymupdf.read_pagesfunctionSelected PyMuPDF pages under byte and page caps
pymupdf.render_pagefunctionPNG raster of one admitted page
pdf_structure.inspect_pdffunctionText pages plus optional native layout evidence
pdf_structure.DocumentStructureReportdataclassFull structure report container
docx.DocxLimitsdataclassZIP and paragraph bounds for DOCX
docx.read_docx_textfunctionTop-level body paragraphs after bounded checks
docx.read_docx_bodyfunctionBody 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.DocumentLimitsdataclassInput, page and structured output bounds
docling.DocumentRejectedexceptionRefused conversion with optional native result
docling.ParsedDocumentdataclassSource receipt around a native ConversionResult
docling.DoclingParserclassWrap a caller-owned DocumentConverter and parser_id
docling_knowledge.DoclingDocumentIndexclassIndex, search and cite one Docling document
docling_knowledge.DoclingChunkingclassNative hybrid chunking policy binding
docling_knowledge.ChunkingPolicydataclassToken budget and overflow handling
docling_knowledge.DocumentCitationdataclassVerified quote over native items
html.html_textfunctionVisible text without script or style
html.html_documentfunctionTitle and block-structured text from local HTML
tables.TableLimitsdataclassCSV file and dimension bounds
tables.read_csvfunctionUTF-8 CSV to row records
tables.table_recordsfunctionHeader and row width validation
workbooks.read_workbookfunctionBounded XLSX cell decode without formula execution
feeds.FeedEntrydataclassUntrusted feed fields
feeds.parse_feedfunctionParse bytes or a local path only
web_snapshot.SnapshotFetcherclassAllowlisted HTTP fetch with manifest storage
web_snapshot.SourceSnapshotdataclassURL, time and content record
web_snapshot.read_snapshotfunctionVerified read from a manifest path
web_snapshot.ExtractionPlandataclassDeclared HTML regions to extract
web_snapshot.extract_postfunctionExtract post records from a snapshot
source_files.LocalSourceFilesclassBounded discovery and reads under one root
source_sync.LocalSourceSyncclassSerialized multi-format sync with deletion proposals
ingestion_jobs.IngestionJobsclassContent-addressed staging on the job queue
feed_ingestion.FeedIngestorclassFeed through snapshot, chunk, embed and index
search_pipeline.bind_policyfunctionAttach document policy to publication inputs
search_pipeline.publish_textfunctionPublish text into recoverable knowledge
search_pipeline.publish_native_filefunctionNative file lane into publication
search_tools.DocumentSearchToolsclassGoverned hybrid search over published passages
search_tools.HybridSearchLanesdataclassKeyword and dense results from one caller-authorized publication snapshot
chunking.ChunkdataclassVersioned chunk record with fingerprint id
chunking.ChunkerprotocolChunker contract
chunking.FixedCharacterChunkerclassFixed-size character chunks
chunking.SlidingWindowChunkerclassOverlapping window chunks
chunking.SentenceChunkerclassSentence-bounded chunks
chunking.SectionChunkerclassSection-aware sentence chunking
chunking.AdaptiveChunkerclassBudget-driven chunk size selection
chunking.normalize_textfunctionOpt-in normalization with receipt
chunking.score_queryfunctionQuery complexity scoring
chunking.trim_conversationfunctionTrim turns under a token policy
chunking.benchmarkmoduleCorpus chunker comparison and winner selection
chunking.experimentmoduleSQLite-backed chunk experiment artifacts
chunking.answering.answer_questionfunctionCited answer via a TextClient (model step)
chunking.answering.assess_groundednessasync functionGroundedness 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.docling leaves docling and torch unloaded; parse imports 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_pages rejects the whole file on unreadable pages when require_text_each_page is true; there is no OCR fallback in pdf or pymupdf.
  • Docling publication gate. Only ConversionStatus.SUCCESS publishes; partial native results raise DocumentRejected with code conversion_incomplete. Serialized output must fit max_output_bytes.
  • Identity fields. Empty identifier, source_id, or source_version raise ValueError; parser_id must 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_feed accepts bytes or Path, 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_pages fingerprints include text and parameters; overlap must satisfy 0 <= overlap_chars < max_chars.
  • Model steps are isolated. Answering calls TextClient and LLMGrader; 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_sync may propose deletions; hosts execute them through owning publication services. feed_ingestion requires a new index_identity when 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