Documentation
/ Reference
hive-prep
Raw documents to atomic markdown. Package hiveprep, CLI hiveprep.
Narrative version: building a corpus.
What still uses hive-prep
hive-prep is not deprecated. It stays as the tool library and for scripted runs, and no
command of it warns. Where an assistant session drives the ingest, use
hive-ingest instead: it keeps its own file ledger and
reads no curation plan. It makes records, not atomic markdown,
so it replaces no hive-prep command in a scripted run.
| Uses it | What it uses | Why it stays |
|---|---|---|
| a scripted run | every command; normalize, route, transform and stamp take the curation plan as --plan |
a run with no assistant session has no other way from documents to atomic markdown |
the release smoke test, tools/smoke-installed.py |
validate-atomic, and stamp with a plan |
it proves the installed distribution |
hive-gen |
reads the atomic markdown, in the re-topic pass, the product facet stamp and the deprecated model stages | the re-topic pass and the facet stamp are not deprecated, and the stages work until removed |
| legacy Office sources | normalize converts .doc, .ppt and .xls with LibreOffice |
hive-ingest does not yet extract DOC |
No released package imports hiveprep. hive-ingest carries its own copy of the
boilerplate rules it started from.
Commands
A chain of Click subcommands, run in order. Each writes files the next reads, so the pipeline is resumable and every intermediate state is inspectable on disk.
| Command | Does |
|---|---|
scan |
walk a tree, produce a file inventory CSV with folder-derived hints |
dups |
report byte-identical duplicate sets |
dedup-formats |
collapse same-document format variants, such as X.doc alongside X.docx |
validate-plan |
validate the curation plan before execution (gate 1) |
normalize |
normalise the plan's includes to PDF intermediates |
route |
report the text, vision and passthrough tier split, without using a GPU (gate 2) |
transform |
convert to atomic markdown |
stamp |
stamp plan metadata into atomic frontmatter |
validate-atomic |
validate the corpus: unique slugs, enums, links |
hiveprep <command> --help for arguments.
Only one step involves a model: the curation pass that produces the plan. Everything else is deterministic.
Two gates
Gate 1, after validate-plan. The curation plan lists every source document with a proposed
decision: include, exclude, duplicate-of, supersedes, plus derived metadata. Validation checks the
plan is well formed. It cannot check that it is right, and nothing downstream will notice that
you meant to exclude a directory.
product is required on every include and has no default. It leads every slug, so a missing one
cannot be guessed; validate-plan reports every offending entry here and lists the products
declared in the profile's curation.products. A plan that reaches route, transform or stamp
with a product-less include is refused there too, before any work: each exits with the message
alone, naming the offending entry and pointing back at validate-plan for the vocabulary, rather
than with a traceback. The platform and product vocabularies are otherwise checked only when the
profile declares them - an empty vocabulary means "not configured", not "reject everything".
Gate 2, after route. route is a GPU-free precheck reporting how many files will go through
each conversion tier. Approving it before transform is what stops a surprise vision-model bill.
Modules
| Module | Purpose |
|---|---|
cli.py |
Click command group wiring each stage to a subcommand |
config.py |
typed environment-backed settings |
profile.py |
the corpus profile, as far as this package needs it: the folder-name aliases mapping a directory segment to a product |
scanner.py |
recursive walk to a streaming inventory CSV |
folder_parser.py |
classification hints from folder segments |
dups.py |
SHA-256 duplicate grouping |
curation_plan.py |
load and validate the plan; collapse format variants |
slugs.py |
folder-qualified, collision-safe slug identity |
libreoffice.py |
headless conversion to PDF with isolated profiles |
striptrim.py |
strikethrough and tracked-change removal at the document XML level |
normalize.py |
route each source to a PDF intermediate |
docling_client.py |
HTTP client for the document converter |
vision.py |
OpenAI-compatible vision client, page image to markdown |
transform.py |
PDF profiling, tier routing, atomic markdown with frontmatter |
stripper.py |
YAML regex boilerplate scrubbing |
stripper_rules/*.yaml |
the rule sets |
stamp.py |
stamp plan metadata into frontmatter, matched by slug |
validate.py |
validate the atomic corpus and derive relations |
Conversion tiers
Three, chosen per file.
Text. A document converter service, when DOCLING_BASE is set and PREFER_DOCLING is true.
normalize converts Office formats (DOCX, PPTX, XLSX and legacy .doc, .ppt, .xls) to PDF
first, and transform sends the normalized PDFs to the converter for layout and tables, falling
back to local pymupdf4llm on converter failure.
Vision. A vision model, for pages that yield almost no extractable text: scans and image-only
slides. A page producing fewer than VISION_MIN_CHARS characters routes here.
Passthrough. Already-text sources, copied with frontmatter added.
LibreOffice runs locally during normalize to produce PDFs; LO_JOBS sets concurrency.
If the vision model is unavailable for a vision-tier document, transform captures a per-document
failure (TransformResult(ok=False)), writes no atomic markdown file for that document, and
continues the batch. That keeps one unreachable vision endpoint or broken file from aborting a
batch. At the end it prints only a count of the errors: it names no failed document, shows no error
message and still exits with status 0.
Boilerplate stripping
Regex rules in hiveprep/stripper_rules/<product>.yaml, selected by STRIP_PRODUCT, disabled with
STRIP_BOILERPLATE=false. Each rule is line-oriented: matching lines are deleted, then blank-line
runs collapse. Never applied to fenced code blocks.
product: default
patterns:
- type: regex
pattern: "^\\s*Page \\d+ of \\d+\\s*$"
flags: MULTILINE
Note the doubled backslashes. These are YAML double-quoted scalars, where a lone \s is an invalid
escape and fails to parse.
The product ships only default.yaml: page footers, copyright lines, rights notices. Vendor
rule sets are corpus-side and belong with your corpus.
Anchor rules to footer and header form, never to a vendor name alone. In a corpus of one vendor's manuals, that name appears in thousands of legitimate sentences, and a rule matching the bare name deletes content while looking like it is working. The test suite covers this case specifically.
Internals
Module-level detail: the algorithms, thresholds and failure behaviour.
scanner.py, folder_parser.py, dups.py
scanner walks a tree and streams an inventory CSV rather than building a list, so a corpus
larger than memory still scans. folder_parser derives classification priors from folder segments,
which the curation agent treats as hints rather than facts. dups groups by SHA-256, so it finds
byte-identical files under different names and misses near-duplicates by design; near-duplicate
judgment is the curation agent's job.
curation_plan.py
Loads the plan and validates it deterministically: enum membership, path existence, no duplicate
slugs. Also collapses same-stem format variants family-aware: .doc/.docx/.docm are one
family, .ppt/.pptx another, .xls/.xlsx another. Same stem across families stays distinct,
because Spec.docx and Spec.xlsx are usually two documents, not two renderings of one.
slugs.py
Slugs are folder-qualified and collision-safe. Identity is the slug, so a collision silently merges two documents into one atomic file; the qualification is what prevents it.
libreoffice.py, striptrim.py, normalize.py
libreoffice converts office formats to PDF headlessly, each job with an isolated user profile
directory, because concurrent headless LibreOffice instances sharing a profile corrupt each other.
LO_JOBS sets concurrency.
striptrim removes strikethrough and tracked-change text at the document XML level, before
conversion. Doing it afterwards is not equivalent: once a .docx is a PDF, deleted text that was
still visible is indistinguishable from live text.
normalize routes each source to a PDF intermediate: strike-trim then convert for .docx,
LibreOffice for other office formats, straight copy for PDFs.
transform.py, the converter core
The most consequential module. Three parts.
Profiling. pdf_text_profile reports pages, average extractable characters per page, and
img_page_frac, the fraction of pages dominated by one large image.
The dominant-image test uses each page's largest single image, not the sum of its images. Summing inflates the fraction on any page carrying several small recurring logos, which would route text-rich pages to the vision tier and quietly multiply the GPU bill.
Routing. route_tier is deliberately simple:
avg_chars >= VISION_MIN_CHARS (100) -> text
otherwise, img_page_frac >= VISION_MIN_IMG_PAGES (0.5) -> vision
otherwise -> text
A page counts as image-dominated when its largest image covers IMG_DOMINANT_FRAC (0.5) of the
page. Text is the default in both undecided branches: a thin text extraction is a cheap, visibly
short file, whereas a wrong vision route is expensive and looks fine.
An explicit per-slug force_tier from a routing override beats the automatic decision.
Conversion. The text tier calls extract_text_markdown, which prefers the document converter
and falls back to local pymupdf4llm on any converter error or empty result, so the pipeline
runs with no GPU and no converter service. _clean_text_md strips data-URI images, collapses
four-or-more dot leaders, and squeezes blank-line runs.
The vision tier renders pages with pdftoppm -png at a configured DPI and concatenates per-page
descriptions. passthrough_markdown fences already-text sources with a language hint.
Text and vision output both pass through the boilerplate stripper. Passthrough never does: you do not regex-scrub fenced code.
Two behaviours that matter when a run goes wrong:
- Resumable.
transform_planskips any slug whose atomic file already exists (skip_existing), reporting it withtier="skip". Re-running after a partial failure converts only what is missing. - Failures are captured, not raised. A per-document error becomes a flagged
TransformResult(ok=False, error=…)and the run continues. One unreadable file in three thousand does not abort the batch, and the failures are listed at the end.
route_plan is the same profiling without any conversion. That is gate 2: it tells you the tier
split before you pay for it.
stamp.py, validate.py
stamp writes plan metadata into atomic frontmatter, matched by slug, filling only missing
fields unless overwrite is set, so a hand-corrected value survives a re-stamp. Every invocation
requires --atomic to name the directory to stamp. It never reads ATOMIC_DIR from the environment
or .env, and never falls back to ./hive-work/atomic: a shared hive-gen setting may name an
entire corpus rather than the output for this plan. Missing, blank, nonexistent and non-directory
scope values refuse with --atomic guidance before any documents change.
hiveprep stamp --plan curation.yaml --atomic ./hive-work/atomic
For existing scripts that relied on ATOMIC_DIR, add --atomic with the intended directory.
A valid directory with no matching files still reports "0 files stamped", as does a correct
re-run over an already-stamped corpus.
validate checks unique slugs, doc_type enum membership and resolvable links, and derives
relations.yaml. It exits non-zero on any error, which is what makes it usable as a gate in CI.
Tests
Fakes only. The Docling and vision clients are injected, so the suite runs with no network, no GPU
and no converter service. Tests that need LibreOffice skip with a stated reason when it is absent.
Use uv run pytest --collect-only -q in tooling/hive-prep/ for the current inventory rather than
a count written down here.
Configuration
See configuration.
Gotchas
WORK_DIR gets large. It holds intermediate conversions for the whole corpus. It is scratch and
safe to delete between runs.
Duplicate detection is content-hashed; scanning is path-based. scan writes one CSV row per
file path, whereas dups groups .pdf, .docx, .pptx and .xlsx files by SHA-256, so the same
document under two names appears in one duplicate group with both paths. Usually what you want,
occasionally surprising.
A bad plan refuses to run. Deliberate: a plan that half-applies is harder to reason about than one that does not start.