Everything a new user needs to go from a fresh checkout of
pipeline/ to a converted file, without reading any other
tab first. This folder is self-contained: it does not import,
reference, or depend on anything else in the surrounding repository
(see the portability note at the bottom of this tab), so these steps
work regardless of where pipeline/ lives on disk.
Python 3.10 or newer. The core package (pdf_pipeline, Layers 1-7) has
zero required third-party dependencies -- pdfminer.six is
vendored in-tree and PDF writing is a first-party implementation. Everything below is
optional, and every optional subsystem has its own isolated requirements.txt
so installing one never pulls in another.
| Subsystem | requirements file | What it unlocks |
|---|---|---|
| requirements.txt | empty by design -- only needed for encrypted-PDF support (pip install -e ".[encrypted]") | Core conversion: PDF/image/text/office/tabular parsing, JSON/Markdown/HTML/text/annotated-PDF output |
| surya-tailored/requirements.txt | installed after a one-time python setup_offline.py weight download (~2GB, license-gated -- see below) | OCR for standalone image files, and optional Surya-routed PDF parsing |
| models/requirements.txt | sentence-transformers, keybert, gliner, chonky, torch, scikit-learn | Keyword/entity extraction, topology clustering, semantic chunk splitting, and the embedding/reranking models Layer 9 needs |
| vectorstore/requirements.txt | lancedb, pyarrow | The embedded vector store Layer 9 indexes chunks into and queries against |
| requirements-dev.txt | pytest | Running the test suite |
pipeline/rag/ (BM25, fusion, query orchestration) and pipeline/storage/
(snapshots, embedding cache, audit log) are pure-stdlib -- no requirements file needed at all.
cd pipeline
pip install -e .
That alone is enough to convert PDFs and text-like files to JSON/Markdown/HTML/text. Add the optional extras only as you need them:
# Encrypted PDFs
pip install -e ".[encrypted]"
# Retrieval-augmented generation stack (embeddings, reranking, vector store)
pip install -r models/requirements.txt
pip install -r vectorstore/requirements.txt
# Image OCR / Surya (see the license note below before enabling)
cd surya-tailored
python setup_offline.py
pip install -r requirements.txt
cd ..
Three entry points, from simplest to most complete:
# Single file, from the CLI
python -m pdf_pipeline input.pdf -o out/ --markdown --json --html --text
# A whole folder, unattended (Windows: double-click run_batch.bat instead
# and answer its prompts)
python -m pdf_pipeline.batch_cli -i "path/to/input" -o "path/to/output"
# Local dashboard -- interactive, gated pipeline diagram + live progress
# (Windows: double-click run_dashboard.bat instead)
python -m pdf_pipeline.dashboard.server
# opens http://127.0.0.1:8765
The dashboard is the easiest way to explore what this pipeline can do: every checkbox in its diagram maps 1:1 to an option documented in this reference (see each layer's "What you can choose" box), and disabled options show a tooltip explaining exactly which prerequisite is missing.
pip install -r requirements-dev.txt
pytest tests/ -v
The core suite needs no optional weights at all. Tests under models/tests/,
and any test that imports pipeline/vectorstore/ or exercises a real
SentenceTransformer/LanceDB call, are skipped automatically if the matching weights or
packages aren't present -- nothing fails loudly just because an optional extra wasn't
installed.
surya-tailored/'s own code is Apache-2.0, but the model weights it downloads
carry a separate, non-standard license with real commercial-use restrictions (revenue/funding
thresholds, a no-compete-with-datalab.to clause). Read
surya-tailored/MODEL_LICENSE
yourself before using it commercially. Every Surya code path additionally requires an explicit,
per-run opt-in (--enable-surya --surya-accept-license, or the dashboard's
Enable + license-acknowledgment checkboxes) -- with it left off, image files still convert,
just without OCR text.
MODELS.md's onboarding content. The full
per-model license table, hardware notes, and research rationale for each optional model now
live in MODEL_ROUTES.md (Layer 9) and each layer's own file table below; this tab
is deliberately just "how do I get something running," not a second copy of the design
brainstorm docs.
Every layer below has its own tab: what feeds into it, what options you as a user can choose (checkboxes/CLI flags -- covered before any Python file names), a diagram of its internal sub-pipeline, and a full file-by-file reference. The Dashboard is a separate product surface built on top of everything below it -- its backend is one more layer in the chain, but its frontend (the actual webpage) is documented completely independently, since it only ever talks to the backend's HTTP API and knows nothing about PDFs, Surya, or chunking internals itself.
Kept intentionally small -- one box per layer, not per function -- so it renders reliably. Each layer's own tab has a second, more detailed diagram of just that layer's internals. Notice Layer 8 plugs in sideways (dashed arrows) rather than sitting in the main chain, and Layer 9 is fed directly by Layer 5's chunks, not by Layer 7 -- Output Writers and the RAG index are two independent consumers of upstream data, not a straight line.
pdf_pipeline package) has zero third-party Python
dependencies for its core, deterministic path -- PDF parsing uses a
vendored copy of pdfminer.six (pdf_pipeline/_vendor/), and PDF
output writing uses a first-party COS/PDF writer (pdfio/).
Optional backends (pypdfium2 for page rasterization, Surya/PIL/torch for
image OCR) are always imported lazily and degrade gracefully when absent.
Two more vendored, stdlib-only parsers -- _vendor/docparse
(docx/pptx) and _vendor/tableparse (csv/tsv/xlsx, plus
json/xml/yaml/xbrl/Avro/X12-EDI's shared knowledge-graph-building code) --
are wrapped respectively by office_parser.py,
tabular_parser.py, avro_parser.py, and
edi_parser.py. All four hold the exact same
zero-third-party-dependency invariant as pdf_parser.py --
see Parsing (Layer 3) for the grid-shaped vs. graph-shaped split between
them. Layer 8 is the only place allowed to import both
pdf_pipeline and the optional ML/RAG subsystems -- nothing in
Layers 1-7 ever imports pipeline/models/,
pipeline/vectorstore/, or pipeline/rag/, not
even lazily. Those three subsystems are themselves independently
optional siblings of each other, each with (or, for
pipeline/rag/, deliberately without) its own
requirements.txt -- pipeline/vectorstore/ is the
only genuinely new third-party dependency the RAG feature
introduces (lancedb, pyarrow);
sentence-transformers was already required by
pipeline/models/requirements.txt, and
pipeline/rag/ (BM25, reciprocal rank fusion, query
orchestration) is pure Python with no dependencies of its own. A fourth
sibling, pipeline/storage/ (vector-store+weights snapshots,
a query-embedding cache, and a human-readable Q&A audit log), is
stdlib-only (json, os, shutil, datetime), with no
requirements.txt of its own, under the same "never imports
pdf_pipeline, only reachable through Layer 8" rule.
The shared data model and configuration objects every other layer builds on. Nothing here is a "stage" a document passes through -- it's the vocabulary the rest of the pipeline is written in: one dataclass-based config object, one content-tree class hierarchy, and a handful of cross-cutting utilities (logging, memory tracking, string sanitization) that every later layer calls into rather than reimplementing.
ConversionConfig object, and the IObject/BoundingBox class hierarchy that Layers 3-7 all read and write. Consumed directly by every other layer -- there is no "next layer" arrow here, this is the substrate.| File | Depends on | Used by | Key classes / functions | Input → Output |
|---|---|---|---|---|
| config.py | stdlib only (re, dataclasses, typing) | pipeline.py, batch.py, image_parser.py, every outputs/* and processors/* module, dashboard/* |
|
Raw kwargs (+ user-selected format/Surya/chunking flags) → validated config object (raises ValueError eagerly on bad values) |
| models.py | stdlib only (dataclasses, enum, itertools, typing) | literally every other module in the package |
|
Defines the pages: List[List[IObject]] shape -- the single lingua franca between Parsing, Structure, and Output Writers |
| context.py | config.py (IMAGE_FORMAT_PNG) |
pipeline.py, outputs/images.py | PipelineContext -- image embed/output-dir/format settings + a shared sequential image-index counter |
Per-run settings (incl. user-selected image-embed mode) → threaded by reference through one convert_pdf()/convert_image() call so every image writer shares one counter |
| logging_utils.py | stdlib (logging, time, os) | batch.py, pipeline.py, dashboard/server.py | new_run_id(), build_logger(), _ListCaptureHandler, capture_third_party_warnings() (context manager), tail_lines() |
Run id + log dir (user-selected --logs-dir) → logger + captured-warnings list + logs/run_<id>.log file |
| memory_utils.py | stdlib (sys) + platform-specific POSIX/Windows RSS reads | batch.py (per-file memory delta), scouting.py (dashboard memory estimate) | current_rss_bytes(), format_bytes() |
Process handle → resident memory in bytes / human string |
| text_sanitize.py | stdlib (re) | models.py (IObject.sanitize_description(), used by SemanticPicture/EnrichedImageChunk) |
sanitize_description(), sanitize_description_strip_pua() |
Raw description string → angle-tag/PUA-stripped safe string for JSON/HTML/Markdown |
Discovers files under an input folder, decides output paths (mirroring
the input folder structure), builds one ConversionConfig per
file, and drives every file through Parsing -- either directly (CLI) or
via a background thread (Dashboard Backend, Layer 10).
pipeline.convert_file() per discovered file, plus a BatchRunSummary (per-file status/error/chunk-count) and a run log file. → feeds Layer 3 (Parsing).| File | Depends on | Used by | Key classes / functions | Input → Output |
|---|---|---|---|---|
| batch.py | image_parser.py, text_parser.py, eml_parser.py, office_parser.py, tabular_parser.py, avro_parser.py, edi_parser.py, config.py, logging_utils.py, memory_utils.py, pipeline.py (convert_file) |
batch_cli.py, dashboard/server.py, scouting.py (reuses discover_pdfs) |
discover_pdfs(), discover_input_files() (matches every parser's own extension-set constant across PDF/image/text/eml/office/tabular/structured-data/avro/edi -- stubbed/EDIFACT files are deliberately included too, so they're discovered and reported as unsupported rather than silently invisible), FileRunResult, BatchRunSummary, run_batch() |
input_dir + format/model-hook kwargs (user selections, threaded through from the CLI or dashboard) → mirrored output_dir tree + BatchRunSummary |
| batch_cli.py | batch.py, config.py, optional pipeline/model_hooks.py (via sys.path insert) | invoked as python -m pdf_pipeline.batch_cli |
build_arg_parser(), main() -- accepts --no-native-output (mirrors --no-structure's pattern; flips ConversionConfig.generate_native_output off) |
CLI args (user flags) → calls run_batch(), prints a summary table |
| cli.py | config.py, pipeline.py (convert_file) |
__main__.py (python -m pdf_pipeline <file>) |
build_arg_parser(), main() |
CLI args → single-file conversion |
| scouting.py | vendored pdfminer (cheap page-count parse, no full extraction), batch.py (discover_pdfs) |
dashboard/server.py (pre-run ETA) | _cheap_page_count(), FileScoutResult, ScoutResult, scout_input_folder(), estimate_memory_mb(), load_benchmarks()/update_benchmarks(), estimate_time_seconds() |
Input folder → file/page counts + a persisted-benchmark-derived time estimate |
Known gap: this still walks the folder via the legacy discover_pdfs(), so images, txt/md/log/ini/cfg/eml files, and the newer office/tabular/structured-data/Avro/EDI formats (docx/pptx/csv/tsv/xlsx/json/xml/yaml/xbrl/avro/edi) are all invisible to the pre-run scout/ETA summary -- they convert correctly (see Parsing, Layer 3) but don't count toward the file/page estimate shown before a run starts. Pre-existing behavior, left as-is rather than scope-creeping into the scouting system for this change.
|
||||
| __main__.py / __init__.py | cli.py / config.py + pipeline.py | python -m pdf_pipeline entry point; package public API | re-exports ConversionConfig, ConversionResult, convert_pdf, FilterConfig, SanitizationRule |
— |
Turns raw file bytes into the shared pages: List[List[IObject]]
tree -- for most formats. Five independent routes converge on that same
shape or deliberately diverge from it, depending on whether the format
is page-shaped or graph-shaped. This is the one layer every other file
format's quirks get absorbed into, which is why it has the most moving
parts of any layer in this pipeline.
.eml, office (docx/pptx), tabular (csv/tsv/xlsx), or structured-data (json/xml/yaml/xbrl/avro/edi) file path + ConversionConfig (from Ingestion, Layer 2).pages: List[List[IObject]] + page sizes/boxes → feeds Layer 4 (Structure) when structure/chunks are requested, and Layer 7 (Output Writers) directly for json/markdown/html/text/annotated-image output. For graph-shaped formats: a native output manifest (_vendor/tableparse's own txt/md/json/chunks.jsonl files) plus a derived Markdown preview string, written directly by office_parser.py/tabular_parser.py/avro_parser.py/edi_parser.py without routing through Layers 4/5/9.
Native PDF output additionally passes through a 9-step heuristic
pipeline in processors/ (table detection → reading order
→ line/list/paragraph grouping → header/footer detection →
heading classification → caption linking → nesting levels) --
or, if config.use_struct_tree is set, struct_tree_extraction.py
reads the PDF's own accessibility structure tree instead of running the
heuristics. The text/email route takes a third path entirely: it never
runs the heuristic pipeline or the struct-tree route at all, since these
formats carry no real glyph coordinates to reconstruct layout from --
text_parser.py/eml_parser.py build final
high-level nodes (SemanticHeading, SemanticParagraph,
PDFList/ListItem) directly against a synthetic
single-page, US-Letter BoundingBox placeholder. Structure
(Layer 4) and every Output Writer (Layer 7) already pattern-match on
these exact node types regardless of how the flat per-page list was
produced, so nothing downstream needed to change for any of these
routes to work.
office_parser.py wraps the vendored _vendor/docparse
parser (docx/pptx, zero third-party dependencies) and tabular_parser.py
wraps the vendored _vendor/tableparse parser (csv/tsv/xlsx, plus a
detect-and-report stub for legacy .xls/.parquet that
raises UnsupportedFormat rather than guessing at a binary layout)
for the grid-shaped half of the new formats. Both build a real
pages: List[List[IObject]] tree against real page/slide geometry
-- docx section/paragraph/table/image provenance with best-effort page numbers,
pptx exact EMU bounding boxes, spreadsheet cells folded into
TableBorder grids (one heading node per sheet) -- and hand it to
the same downstream Structure/Chunking/Output-Writer machinery every PDF or
image already uses. Nothing in Layers 4-7 needed to change for this route to
work either.
tabular_parser.py's other half (json/ndjson/xml/yaml/xbrl), plus
avro_parser.py (Avro Object Container files -- a hand-rolled,
stdlib-only binary decoder, since no avro/fastavro
package is available) and edi_parser.py (X12 EDI envelopes --
ISA/GS/ST segment hierarchy -- with EDIFACT detected up front and cleanly
rejected via EDIFACTNotSupported rather than mis-parsed as X12),
cover formats that are graph- or record-shaped rather than
page-shaped: nested objects, nulls, repeated arrays, cross-references between
entities. Forcing these onto a synthetic page would either flatten real
structure or invent page geometry that was never there, so this route stops
short of Structure/Chunking/Embedding on purpose -- it is a deliberate,
documented scope boundary, not an oversight. All three modules share two
helpers factored out of tabular_parser.py:
build_dataset_from_object(root, source, fmt) -> Dataset (turns
any nested dict/list/scalar into a _vendor/tableparse
Dataset, reusing its entity-detection and knowledge-graph-building
code for free) and write_native_and_preview(ds, output_dir, stem, fmt)
(writes the native txt/md/json/chunks.jsonl manifest via
_vendor/tableparse's own emitter, plus a derived Markdown preview
string so the result still shows up alongside every other format's
markdown/text output in the dashboard and CLI). Bridging
_vendor/tableparse's own Chunk dataclass into this
package's chunking/Chunk for the same LanceDB index (Layer 9) is
separate future work, not attempted in this pass.
| File | Depends on | Used by | Key classes / functions | Input → Output |
|---|---|---|---|---|
| pdf_parser.py | _vendor/pdfminer_six/*, models.py | pipeline.convert_pdf() | parse_pdf(), _ChunkBuilder, _extract_image(), _extract_page(), _classify_rect_or_line(), _normalize_color() |
PDF path + password → pages + page_sizes (per-character glyph runs → TextChunk/LineChunk/LineArtChunk/ImageChunk) |
| image_parser.py | surya_backend.py, config.py (user's enable_surya/surya_license_acknowledged checkboxes gate every call), models.py, processors/levels.py, outputs/annotate.py (lazy) |
pipeline.convert_image()/convert_file() |
|
Image file (or Surya-rasterized PDF pages) → pages (same shape as pdf_parser's) + per-page annotated overlay PNG bytes |
| surya_backend.py | surya-tailored/pipeline.py (sibling folder; optional torch/transformers/PIL, imported lazily, only reached if the user's Surya checkbox is on) | image_parser.py only | is_available()/can_load_images()/check_assets(), get_engine(), load_input_file(), analyze_images(), ocr_image_bytes() (Tier 3), strip_html_tags()/parse_table_html()/parse_list_items()/parse_form_fields() |
PIL images + Surya spec (user-selected weights/device/tasks/mode/dpi) → per-page OCR/layout/table/form result dicts with per-block bbox + confidence |
| struct_tree_extraction.py | pdfio/reader_shim.py, config.py (only reached when the user sets use_struct_tree=True), models.py |
pipeline.convert_pdf() when use_struct_tree=True |
extract_from_struct_tree(), _walk(), _page_index_for_elem() |
PDF's own /StructTreeRoot → pages (alternate to the heuristic route) |
| text_parser.py | models.py (stdlib only otherwise -- configparser from the standard library) |
pipeline.convert_text_like()/convert_file(), batch.py (discovery) |
|
Plain-text file → final SemanticHeading/SemanticParagraph/PDFList nodes on one synthetic US-Letter page (bypasses the heuristic pipeline entirely) |
| eml_parser.py | models.py (stdlib only otherwise -- email, html.parser from the standard library) |
pipeline.convert_text_like()/convert_file(), batch.py (discovery) |
|
.eml file → final SemanticParagraph/SemanticHeading nodes (subject as heading, body as paragraphs, attachment names listed) on one synthetic page |
| office_parser.py | _vendor/docparse/* (vendored, stdlib only), models.py, text_parser.py | pipeline.convert_office()/convert_file(), batch.py (discovery) |
|
.docx/.pptx file → real pages (docx page/section provenance, pptx exact EMU bboxes) + docparse's own native txt/md/json/chunks.jsonl/media export |
| tabular_parser.py | _vendor/tableparse/* (vendored, stdlib only), models.py | pipeline.convert_tabular_grid()/convert_structured_data()/convert_file(), batch.py (discovery), avro_parser.py + edi_parser.py (shared helpers) |
|
Grid formats → real pages (TableBorder grids, one heading per sheet) + native output. Structured-data formats → native output + Markdown preview only (no pages, skips Layers 4/5/9) |
| avro_parser.py | stdlib only (json, os, struct, zlib), tabular_parser.py (build_dataset_from_object/write_native_and_preview) |
pipeline.convert_structured_data()/convert_file(), batch.py (discovery) |
|
.avro file (OCF: magic + JSON schema + sync-marked, optionally deflate-compressed blocks) → decoded records → native output + Markdown preview via tabular_parser.py's shared helpers |
| edi_parser.py | stdlib only (os, typing), tabular_parser.py (build_dataset_from_object/write_native_and_preview) |
pipeline.convert_structured_data()/convert_file(), batch.py (discovery) |
|
X12 EDI file (ISA-delimited segments) → parsed interchange/group/transaction hierarchy → native output + Markdown preview via tabular_parser.py's shared helpers |
| processors/content_filter.py | models.py, processors/text_processing.py | pipeline._heuristic_pipeline() step 1 | run_content_filter(), filter_page_contents() |
Raw page contents (+ user's FilterConfig selections) → filtered contents (hidden text/out-of-page/tiny text/OCG removed per config) |
| processors/table_detection/border.py | models.py | pipeline._heuristic_pipeline() step 3/4a | detect_table_borders(), assign_cell_contents(), merge_spanning_cells(), set_next_page_link() |
LineChunks → TableBorder nodes with assigned cell contents |
| processors/reading_order.py | models.py | pipeline._heuristic_pipeline() (before line/list/paragraph grouping) | sort_reading_order() (recursive XY-cut), density_ratio() |
Raw content-stream order → visual reading order (multi-column aware) |
| processors/text_lines.py | models.py | pipeline._heuristic_pipeline() step 4e; image_parser.py's analogue | group_chunks_into_lines(), link_bullet_line_art() |
TextChunks → TextLines |
| processors/header_footer.py | models.py | pipeline._heuristic_pipeline() step 5a | detect_headers_and_footers() |
TextLines (cross-page) → SemanticHeaderOrFooter nodes |
| processors/lists.py | models.py | pipeline._heuristic_pipeline() step 5b/6b/9a | detect_lists(), stitch_cross_page_lists() |
TextLines → PDFList/ListItem nodes, stitched across page breaks |
| processors/paragraphs.py | models.py | pipeline._heuristic_pipeline() step 6a | group_lines_into_paragraphs() |
TextLines → SemanticParagraph nodes |
| processors/headings.py | models.py | pipeline._heuristic_pipeline() step 6c/9c | classify_headings(), ModeWeightStatistics |
Whole-document font-size statistics → SemanticHeading nodes with a level |
| processors/captions.py | models.py | pipeline._heuristic_pipeline() step 8; image_parser.py's _link_captions (adapted) |
wrap_images_as_pictures(), detect_captions(), link_captions() |
Images + nearby text → SemanticPicture/TableBorder linked to a SemanticCaption |
| processors/levels.py | models.py | pipeline._heuristic_pipeline() step 9d; image_parser.py directly | assign_levels() |
Flat content list → nesting-level annotations on ListItem/PDFList/SemanticHeading |
| processors/text_processing.py | models.py | processors/content_filter.py | replace_undefined_characters(), filter_tiny_text(), merge_close_text_chunks(), remove_same_text_chunks(), remove_text_decoration_images() |
Character-level cleanup helpers used inside content filtering |
← Ingestion | Next layer: Structure → | Also feeds: Output Writers →
Turns the flat pages IObject list into a nested
DocumentNode hierarchy (Document > Section >
Heading/Paragraph/Table/Figure/Formula/...) and a citation/concept/
cross-reference Graph over that hierarchy. Only built when
generate_structure or generate_chunks is
requested -- Chunking (Layer 5) needs the same tree, so it's built once
and shared rather than duplicated.
pages: List[List[IObject]] + document_info (from Parsing, Layer 3).DocumentNode tree + a Graph object. → feeds Layer 5 (Chunking) and Layer 6 (Concepts) directly in-memory, and structure.json/graph.json via Layer 7 (Output Writers) when generate_structure=True.| File | Depends on | Used by | Key classes / functions | Input → Output |
|---|---|---|---|---|
| structure/tree.py | models.py (BoundingBox, IObject) | build.py, graph.py, export.py, chunking/* (view_a/view_e/enrich/*) | DocumentNode + NODE_* type constants (SECTION, HEADING, PARAGRAPH, TABLE, FIGURE, FORMULA, ...) |
Defines the tree-node shape every downstream chunk/graph builder walks |
| structure/build.py | tree.py, models.py | pipeline.py (both convert_pdf/convert_image) | build_document_tree(), _dispatch(), _wrap_list(), _reparent_captions(), _node_text() |
pages (flat IObject list) → DocumentNode tree |
| structure/graph.py | tree.py | pipeline.py, concepts/__init__.py (k_hop_neighbors) |
Graph/GraphNode/GraphEdge, build_graph(), extract_citations()/extract_concept_phrases()/extract_cross_references(), k_hop_neighbors(), nodes_by_id() |
DocumentNode tree → Graph (citation/concept/cross-reference/next-prev/shares-notation edges) |
| structure/export.py | graph.py, tree.py | pipeline.py (when generate_structure=True, a user selection) |
to_tree_json()/to_tree_dict(), to_graph_json()/to_graph_dict() |
DocumentNode tree / Graph → structure.json / graph.json text |
Builds retrieval-ready Chunk objects from the DocumentNode
tree (View A: hierarchical section/paragraph chunks; View E: sentence-
window micro-chunks), then enriches every chunk with cheap, model-free
metadata (provenance, bibliography/boilerplate classification, editorial
environment detection, math-awareness, lexical BM25 tokens/acronyms).
Three enrichers are model-backed and stay inert (fields left at their
default) unless the Optional ML Bridge (Layer 8) supplies a hook.
DocumentNode tree (from Structure, Layer 4) + optional keyword_extractor/entity_extractor/topology_fn hooks (from the ML Bridge, Layer 8).List[Chunk]. → chunks.json via Layer 7 (Output Writers), chunk texts feed Layer 6 (Concepts) for similarity matching, and (when a chunk_indexer hook is supplied by the ML Bridge, Layer 8) the same chunks are embedded and written into Layer 9's LanceDB table.| File | Depends on | Used by | Key classes / functions | Input → Output |
|---|---|---|---|---|
| chunking/models.py | stdlib (hashlib, dataclasses) | every file in this layer | Chunk dataclass, compute_chunk_id(), GRANULARITY_*/VIEW_* constants | Defines the Chunk shape (text, provenance, enrichment dict) |
| chunking/provenance.py | structure/tree.py | view_a.py, view_e.py | own_heading_node(), full_heading_trail(), provenance_from() | DocumentNode(s) → page numbers, node ids, bounding boxes for a chunk |
| chunking/tables.py | models.py | view_a.py | table_to_markdown() | TableBorder → Markdown table text for table chunks |
| chunking/text_utils.py | stdlib (re) | view_a.py, view_e.py | word_count(), split_sentences() | Raw text → word count / sentence list |
| chunking/view_a.py | structure/tree.py, chunking/models.py, provenance.py, tables.py, text_utils.py | pipeline._generate_chunks() | build_view_a_chunks() (+ word-budget packing / optional semantic-splitter hook) | DocumentNode tree → hierarchical section/paragraph Chunks |
| chunking/view_e.py | structure/tree.py, chunking/models.py, provenance.py, text_utils.py | pipeline._generate_chunks() when chunk_view_e=True (user checkbox) | build_view_e_chunks() | DocumentNode tree → sentence-window micro-Chunks |
| chunking/export.py | chunking/models.py | pipeline._generate_chunks() | to_chunks_dict()/to_chunks_json() | List[Chunk] → chunks.json text |
| chunking/enrich/__init__.py | every enrich/* submodule below | pipeline._generate_chunks() | enrich_chunks() -- the orchestrator | List[Chunk] (+ optional hooks) → same list, mutated with .enrichment fields |
| chunking/enrich/structural.py | chunking/models.py | enrich/__init__.py | enrich_provenance(), enrich_structural() (sibling-group hashing) | Chunk → provenance + structural-position metadata |
| chunking/enrich/bibliographic.py | chunking/models.py | enrich/__init__.py | enrich_bibliographic(), _classify_heading() | Chunk → bibliography-section classification |
| chunking/enrich/boilerplate.py | chunking/models.py, structure/tree.py | enrich/__init__.py | enrich_boilerplate(), _boilerplate_type() | Chunk → boilerplate-type flag (running header/footer/TOC/...) |
| chunking/enrich/editorial.py | chunking/models.py | enrich/__init__.py | enrich_editorial(), _detect_environment() | Chunk → textbook-environment tag (Theorem/Example/Exercise/...) |
| chunking/enrich/math_aware.py | chunking/models.py, structure/tree.py | enrich/__init__.py | enrich_math() | Chunk → formula-density/notation metadata |
| chunking/enrich/lexical.py | chunking/models.py | enrich/__init__.py | bm25_tokens(), extract_acronyms(), enrich_lexical() (+ optional KeyBERT keyword_extractor hook, present only if the user has KeyBERT weights downloaded) | Chunk text → BM25 tokens + acronym map (+ keyphrases if the hook is supplied) |
| chunking/enrich/topology.py | chunking/models.py | enrich/__init__.py | enrich_topology() (+ optional HDBSCAN topology_fn hook) | All chunk texts → cluster label + nearest-neighbor ids + medoid flag per chunk |
| chunking/enrich/entities.py | chunking/models.py, structure/tree.py | enrich/__init__.py | enrich_entities() (+ optional GLiNER entity_extractor hook), _should_skip_smart_skip() | Chunk text → named entities (if the hook is supplied) |
← Structure | Next layer: Concepts → | Optional hooks from: ML Bridge → | Also feeds: Embedding, Vector Store & RAG →
Resolves a user-supplied list of concept strings (concepts.txt)
against a document's own chunks and citation graph, producing one
provenance-tracked result file per concept -- "every place this document
talks about X, and how confident/close that match is." Only runs when
concepts_path is set AND a concepts_resolver hook
(Layer 8) is supplied; otherwise this layer is skipped entirely.
concepts.txt path + List[Chunk] (Layer 5) + Graph (Layer 4) + a concepts_resolver hook (embedding similarity, from the ML Bridge, Layer 8).concepts/<doc>/ -- written directly by this layer itself (an exception to Output Writers, Layer 7, being the only file-writing layer, kept here since concept results are keyed by concept name, not by output format).| File | Depends on | Used by | Key classes / functions | Input → Output |
|---|---|---|---|---|
| concepts/__init__.py | chunking/models.py (Chunk), structure/graph.py (Graph, GraphNode, nodes_by_id), structure/tree.py (NODE_SECTION) | pipeline._generate_chunks() |
|
concepts.txt (user-supplied) + chunks + graph + similarity indices/scores (from the resolver hook) → one result file per concept |
← Chunking & Enrichment | Next layer: Output Writers → | Resolver hook from: ML Bridge →
The only layer that writes files into the user's output directory.
Everything upstream (Parsing/Structure/Chunking/Concepts) only ever
builds in-memory objects; this layer serializes them to disk in whichever
formats ConversionConfig requested.
pages (Layer 3), DocumentNode/Graph (Layer 4), List[Chunk] (Layer 5) -- whichever the requested formats need.output_dir: .json/.md/.html/.txt/.annotated.pdf/.tagged.pdf/.structure.json/.graph.json/.chunks.json, images/<doc>/img_NNN.ext + page_NNN.annotated.png.| File | Depends on | Used by | Key classes / functions | Input → Output |
|---|---|---|---|---|
| outputs/json_writer.py | models.py | pipeline.py (generate_json, user checkbox) | generate_json(), _node_to_json(), _extraction_tier() | pages → <doc>.json (includes extractionTier 1/2 + ocrConfidence when Tier 3 ran) |
| outputs/markdown_writer.py | config.py, models.py | pipeline.py (generate_markdown, user checkbox) | generate_markdown(), _render_node(), _render_table(), _render_list() | pages → <doc>.md |
| outputs/html_writer.py | config.py, models.py | pipeline.py (generate_html, user checkbox) | generate_html(), _render_node(), _render_table(), _render_list() | pages → <doc>.html |
| outputs/text_writer.py | config.py, models.py | pipeline.py (generate_text, user checkbox) | generate_text(), _render_node() | pages → <doc>.txt |
| outputs/annotated_pdf.py | models.py, pdfio/* | pipeline.py (PDF-only, generate_pdf=True, user checkbox) | generate_annotated_pdf(), _build_overlay_content_stream(), _color_for() | original PDF + pages → <doc>.annotated.pdf (colored debug overlay boxes in a toggleable OCG layer) |
| outputs/tagged_pdf.py | models.py, pdfio/* | pipeline.py (PDF-only, generate_tagged_pdf=True, user checkbox) | generate_tagged_pdf(), _tag_for() | original PDF + pages → <doc>.tagged.pdf (PDF/UA accessibility structure tree) |
| outputs/images.py | context.py, models.py, rasterize/pdfium_backend.py (Tier 2, optional) | pipeline.py (both convert_pdf/convert_image) | write_extracted_images(), _write_one(), _walk(), _try_rasterize() | pages → images/<doc>/img_NNN.ext files + written_path/is_rasterized stamped back onto each node |
| outputs/annotate.py | rasterize/png_encoder.py only (pure stdlib) | image_parser.py (image-mode overlay), pipeline.py (PDF-page overlay) | Canvas, draw_rect(), draw_text() (built-in 5x7 bitmap font), Box, render_annotated_page(), color_for_label() | Raw RGB pixel buffer + a list of boxes(label/color) → annotated PNG bytes. Zero third-party dependencies -- deliberately not PIL-based, so a native-PDF-only run stays dependency-free. |
| pdfio/cos.py | stdlib only | reader_shim.py, writer.py, content_stream.py callers | Name, Ref, Dictionary, Array, StreamObject | Defines the PDF COS object primitives |
| pdfio/content_stream.py | stdlib only | annotated_pdf.py, tagged_pdf.py | rect_stroke(), invisible_text_span(), marked_content_wrap(), escape_pdf_string() | Geometry/text → raw PDF content-stream bytes |
| pdfio/reader_shim.py | _vendor/pdfminer_six/* | annotated_pdf.py, tagged_pdf.py, struct_tree_extraction.py | open_document(), get_page_refs(), walk_struct_tree(), get_raw_dict(), extract_mcid_text_map(), PageRef, _McidTextDevice | PDF path → page refs / raw COS dicts / MCID-to-text maps, read via the vendored pdfminer parser |
| pdfio/writer.py | pdfio/cos.py, _vendor/pdfminer_six/* | annotated_pdf.py, tagged_pdf.py | PdfWriter, serialize_value(), _contiguous_runs(), format_number() | New/updated COS objects → an incrementally-updated PDF file (original content untouched) |
| rasterize/pdfium_backend.py | models.py (BoundingBox), rasterize/png_encoder.py, optional pypdfium2 | outputs/images.py (Tier 2 crops), pipeline.py (page-level overlay) | rasterize_region() (Tier 2 crop), rasterize_full_page() (whole-page render for the bbox overlay), _bitmap_to_rgb_buffer(), _bitmap_to_png_bytes(), is_available() | PDF path + page/bbox → PNG bytes or raw RGB buffer; returns None gracefully if pypdfium2 isn't installed |
| rasterize/png_encoder.py | stdlib only (struct, zlib) | pdfium_backend.py, outputs/annotate.py | encode_png(), _chunk() | Raw pixel buffer → valid PNG bytes (single IDAT, no filtering/palette -- correctness over size) |
← Concepts | Terminal layer -- writes to disk.
pipeline/model_hooks.py is the single sanctioned file allowed
to import both pdf_pipeline (Layers 1-7, zero third-party
dependencies) and the optional ML/RAG subsystems --
pipeline/models/ (sentence-transformers, KeyBERT, GLiNER,
HDBSCAN/scikit-learn), pipeline/vectorstore/ (LanceDB), and
pipeline/rag/ (BM25/fusion/query orchestration, pure Python).
Nothing in Layers 1-7 ever imports any of those three itself, not even
lazily -- every model or retrieval interaction is a plain optional
Callable built here and threaded through as a keyword
argument.
batch_cli.py) or Dashboard Backend (Layer 10), which call model_hooks.build_*() once per run.Callable hooks (keyword_extractor, entity_extractor, topology_fn, concepts_resolver) passed into Layer 5 (Chunking & Enrichment) and Layer 6 (Concepts); plus two more for Layer 9 -- chunk_indexer (embeds + writes each document's chunks into LanceDB, passed into Layer 2's run_batch()/convert_file()) and a query function returned by build_query_fn() (embeds a live query, runs hybrid search + optional reranking, called directly by Dashboard Backend). All hooks are absent entirely (stay None) if a model's weights aren't downloaded or its package isn't installed.| File | Depends on | Used by | Key classes / functions | Input → Output |
|---|---|---|---|---|
| pipeline/model_hooks.py | pipeline/models/loaders.py, topology.py, concepts.py; pipeline/vectorstore/store.py; pipeline/rag/query.py + pdf_pipeline's own public API |
batch_cli.py, dashboard/server.py |
|
device/model/path string (user selections, threaded from the dashboard's Retrieval settings panel) → a Callable hook (or None + a reason string if the model/package isn't ready) |
| pipeline/models/loaders.py | optional sentence-transformers, keybert, gliner (each imported lazily) | model_hooks.py |
|
Model name + device (user selection) → a loaded model object, forced offline (never phones home for weights) |
| pipeline/models/topology.py | optional numpy, scikit-learn (HDBSCAN) | model_hooks.py (build_topology_fn), verify/evidence.py (reused for claim clustering) |
cluster_chunk_embeddings(), embed_and_cluster_chunks(), _top_m_neighbors_from_similarity(), _compute_medoid_flags(), _l2_normalize() |
Chunk (or claim) texts → cluster labels + top-M neighbor indices + medoid flags |
| pipeline/models/concepts.py | optional numpy + topology.py's _l2_normalize |
model_hooks.py (build_concepts_resolver) |
top_k_similar(), embed_concepts_and_chunks(), resolve_concepts_by_similarity() |
Concept strings + chunk texts → top-k similarity indices/scores per concept |
| pipeline/models/setup_offline.py | argparse, pathlib; downloads weight files | run manually by a developer, not imported by the pipeline itself | ModelTarget, list_targets(), is_downloaded(), download_one(), main() |
CLI invocation (developer picks which model target) → downloads/verifies weight files into pipeline/models/weights/ |
Feeds hooks into: Chunking & Enrichment | and Concepts | and Embedding, Vector Store & RAG →
The final stage of the straight-line pipeline, and the most internally complex layer in this
reference -- broken into four sub-pipelines below (Indexing, Query, Evidence Breakdown,
Storage), each with its own diagram, rather than one combined one. Embeds retrieval
Chunks (Layer 5) into a shared on-disk LanceDB table (no server process), then
answers a live user query by combining dense vector search with BM25 keyword search
(reciprocal rank fusion), then optionally reranking the fused shortlist with a cross-encoder
before returning the top-k chunks. Four independent sibling packages implement this, bridged
into the rest of the pipeline only through Layer 8 (pipeline/model_hooks.py) --
none of them imports pdf_pipeline itself: pipeline/vectorstore/ (the
LanceDB wrapper), pipeline/rag/ (BM25, fusion, query orchestration -- pure Python),
pipeline/storage/ (snapshots, embedding cache, audit log -- also pure Python), and
pipeline/verify/ (the evidence-breakdown step, also pure Python plus the same
embedder/clustering machinery Layer 5 already uses).
List[Chunk] (Layer 5) + a chosen embedding model, via the chunk_indexer hook (Layer 8), called once per document during a batch run. Query path: a free-text user query, via a build_query_fn()-returned closure (Layer 8), called on demand by the Dashboard Backend (Layer 10) -- optionally paired with a previously-cached embedding vector (see Storage below), which skips the embedding-model call for that query entirely.doc_id's slice of the shared LanceDB chunks table. Query path: a dict of up to top_k (default 10) chunks (text, heading trail, page numbers, source file, relevance score) plus the resolved query_vector and embedding_model used -- consumed directly by the Dashboard Frontend's Query panel (Layer 11), or by any other caller of rag.query.answer_query().
The reranker is optional and, when enabled, only rescores the small
fused shortlist (default 30 candidates) rather than the full vector
candidate pool (default 50) -- a cross-encoder is far more accurate than
a second round of cosine similarity for the same pair (query and
candidate are encoded together, in one forward pass, so the model can
attend across both texts) but far too slow to run over an entire corpus.
MODEL_ROUTES.md's researched Routes B (mxbai-rerank-large-v2), C1
(Qwen3-Reranker-0.6B), and D (bge-reranker-v2-m3) are wired in as opt-in
alternatives to the default bge-reranker-base, paired with the matching
embedding route above via loaders.py's
_EMBED_MODEL_REGISTRY/_RERANKER_MODEL_REGISTRY name-keyed
registries; build_query_fn()'s model_name/reranker_model_name
parameters thread the choice all the way through to vector-snapshot save/load, so a saved
snapshot bundles the weights folder actually in use.
An opt-in step strictly AFTER answer_query() returns, implemented by a fourth
sibling package, pipeline/verify/, per RAG_ANSWER_EVALUATION_BRAINSTORM.md's
Tier 1 (Phases 1-3). Reports four independently-inspectable scores instead of one collapsed
relevance number, plus an explicit distinct_sources_in_result meta-field so a
single-source result set can't masquerade as strong consensus. The pre-existing
single-score path is completely untouched by this -- it's an additive, gated
step.
A third sibling package, pipeline/storage/, adds
persistence around this layer without changing anything about how
indexing or querying itself works. It lets a finished vector store (and
the model weights that built it) be saved once and reloaded later
without re-running Ingestion → Chunking → Embedding at all, lets a
single query's own embedding vector be cached and replayed without a
second embedding-model call, and keeps a plain-text, human-readable log
of every question asked and every answer returned. Every saved name is
unique by construction: a YYYYMMDD_HHMMSS timestamp, with a
numeric suffix appended on the rare same-second collision.
storage/query_logs.py runs alongside every query
unconditionally -- unlike the snapshot save and the embedding-cache
save above, both opt-in per request, the audit log has no on/off
checkbox, matching the user's own request that this record always be
kept. One =====-delimited, plain-text entry per question is
appended to storage/query_logs/qa_<YYYYMMDD>.log (one
file per calendar day, not one file per query and not one unbounded
file), holding the question, the settings used, and each returned
chunk's rank/score/source/page numbers/truncated text snippet -- built
to be opened directly in a text editor for a manual audit, no tooling
required. When evidence breakdown ran, the same entry also gains an
EVIDENCE BREAKDOWN section (consensus/minority/contradiction/conclusion).
| File | Depends on | Used by | Key classes / functions | Input → Output |
|---|---|---|---|---|
| vectorstore/__init__.py | vectorstore/store.py | model_hooks.py | Re-exports VectorStore, is_available() |
— |
| vectorstore/store.py | optional lancedb, pyarrow (imported lazily) | model_hooks.py (build_chunk_indexer, build_query_fn) |
|
Chunks + embedding vectors + doc_id → LanceDB table rows; query vector → ranked nearest-neighbor rows |
| vectorstore/requirements.txt | — | pip install target | lancedb>=0.13.0, pyarrow>=14.0.0 |
The only genuinely new third-party packages this whole RAG feature introduces |
| rag/__init__.py | rag/query.py | model_hooks.py | Re-exports answer_query() |
— |
| rag/bm25.py | stdlib only (pure Python, no dependencies) | rag/query.py | tokenize() (byte-identical to chunking/enrich/lexical.py's bm25_tokens()), class BM25Index, build_bm25_index(corpus_rows) |
Corpus rows + a query → Okapi BM25 relevance scores per chunk_id |
| rag/fusion.py | stdlib only | rag/query.py | reciprocal_rank_fusion(rankings, k=60) |
Multiple ranked id lists (vector, BM25) → one fused ranking |
| rag/query.py | rag/bm25.py, rag/fusion.py (duck-types VectorStore/Embedder/Reranker -- no direct import of vectorstore/ or models/) |
model_hooks.py (build_query_fn) |
process_query(), vector_search_ranking(), hybrid_search_ranking(corpus_rows, vector_hits, query, bm25_k), rerank(), answer_query(query_text, *, store, embedder, reranker=None, top_k=10, vector_k=50, bm25_k=50, hybrid_k=30, query_vector=None) -- query_vector: supply a cached vector (user's saved-embedding picker) to skip re-embedding query_text |
Query text (+ optional pre-computed vector) + a store/embedder/optional reranker → top-k ranked chunks with scores |
| verify/__init__.py | verify/claims.py, verify/evidence.py | model_hooks.py (build_evidence_verifier) |
Re-exports evaluate_evidence() |
— |
| verify/claims.py | stdlib only (re) | verify/evidence.py | split_sentences() (abbreviation-aware regex splitter), claims_from_results(results, min_words=4) |
Retrieved chunk results → candidate claim sentences (short fragments below min_words dropped), each back-referencing its parent chunk_id/doc_id/source_file/score |
| verify/evidence.py | verify/claims.py, models/topology.py (cluster_chunk_embeddings, reused as-is) |
model_hooks.py (build_evidence_verifier), dashboard/server.py (when OPT_QUERY_EVIDENCE_BREAKDOWN is checked) |
evaluate_evidence(results, *, embedder, nli_verifier=None) -- orchestrates claim splitting, clustering, consensus/minority split, contradiction flagging (only if an nli_verifier hook is supplied), and composite ranking; degrades gracefully to an "error" field (not an exception) if clustering is unavailable (e.g. scikit-learn not installed) |
Top-k query results + an embedder (+ optional NLI verifier) → consensus/minority/contradictions/conclusion dict, plus distinct_sources_in_result and nli_ran meta-fields |
| storage/__init__.py | storage/snapshots.py, storage/query_embeddings.py, storage/query_logs.py | model_hooks.py | Re-exports every public function from the three submodules below | — |
| storage/paths.py | stdlib only (os, datetime) | storage/snapshots.py, query_embeddings.py, query_logs.py | STORAGE_ROOT, VECTOR_SNAPSHOTS_DIR, QUERY_EMBEDDINGS_DIR, QUERY_LOGS_DIR, timestamp_to_the_second(), unique_dir(), unique_file() |
— → a collision-safe YYYYMMDD_HHMMSS-named path (numeric suffix disambiguates same-second collisions) |
| storage/snapshots.py | storage/paths.py; lazy, function-body-only imports into models/loaders.py (weights copy) and a best-effort vectordb row count | model_hooks.py (save_vector_snapshot/list_vector_snapshots/load_vector_snapshot/delete_vector_snapshot) |
save_snapshot(), list_snapshots(), load_snapshot(), delete_snapshot() |
A live vector store path + embedding model (user's "save as snapshot" button, with an "include weights" checkbox) → one self-contained, timestamped snapshot folder; loading one back stamps a weights_root onto the manifest so a snapshot's own weights can be loaded independent of the shared pipeline/models/weights/ |
| storage/query_embeddings.py | storage/paths.py | model_hooks.py (save_query_embedding_record/list_query_embedding_records/load_query_embedding_record/delete_query_embedding_record) |
save_query_embedding(), list_query_embeddings() (metadata only, no vectors), load_query_embedding(), delete_query_embedding() |
A query's text + embedding vector (user's "save embedding" checkbox) → one timestamped JSON record; reloaded later and passed straight into rag.query.answer_query()'s query_vector parameter |
| storage/query_logs.py | storage/paths.py | model_hooks.py (append_qa_log) |
append_qa_entry(), list_log_files(), tail_log() |
A question + its ranked answer chunks (+ evidence breakdown, if run) → one human-readable entry appended to today's plain-text log file (qa_<YYYYMMDD>.log) |
rag/query.py, vectorstore/store.py's
non-LanceDB logic, and verify/'s claim-splitting/ranking
orchestration) was exercised directly in this sandbox using fake
store/embedder/reranker/NLI doubles and confirmed correct. The real LanceDB
calls in vectorstore/store.py and the real
SentenceTransformer/CrossEncoder calls in
models/loaders.py's Embedder/Reranker/NLIVerifier
could not be executed here -- no network access to install
lancedb/pyarrow/sentence-transformers/
torch in this environment. Each call follows the libraries'
own documented Python APIs; treat as strongly evidenced, not proven,
until a real pip install -r pipeline/vectorstore/requirements.txt
(and the existing pipeline/models/requirements.txt) plus a
live batch run + query confirms it on your machine.
VISUAL_RAG_BRAINSTORM.md) covers an optional, entirely parallel
image-based retrieval pipeline (ColQwen + Qwen-VL + Qdrant) -- not part of this
layer's shipped code, and not this document's concern; see
pipeline/VISUAL_RAG_BRAINSTORM.md directly.
← Chunking & Enrichment | Hooks built by: ML Bridge → | Queried by: Dashboard Backend →
A stdlib-only HTTP JSON API (http.server.ThreadingHTTPServer,
no web framework) that wraps Ingestion (Layer 2) for interactive use, plus
a pure, filesystem-free gating graph (pipeline_stages.py)
that decides which checkboxes the diagram UI is allowed to show as
checkable right now.
batch.run_batch() (Layer 2 / Ingestion, now optionally passing a chunk_indexer hook) on a background thread when the user clicks Run, and calls a cached Layer 9 query function directly (synchronously) when the user submits a query.| File | Depends on | Used by | Key classes / functions | Input → Output |
|---|---|---|---|---|
| dashboard/server.py | image_parser.py, text_parser.py, eml_parser.py, office_parser.py, tabular_parser.py, avro_parser.py, edi_parser.py, surya_backend.py, batch.py, config.py, logging_utils.py, memory_utils.py, scouting.py, pipeline_stages.py, state.py, optional pipeline/model_hooks.py | run_dashboard.bat (python -m pdf_pipeline.dashboard.server) |
|
HTTP requests → JSON responses; drives run_batch() in a background thread, polled by the frontend; answers queries synchronously against the cached query function; saves/loads/deletes storage snapshots and cached embeddings on request |
| dashboard/pipeline_stages.py | stdlib only (dataclasses, typing) -- deliberately filesystem-free and independently unit-testable | dashboard/server.py |
|
Current checkbox state (user's prior selections) + a requested toggle → new state (cascades: unchecking a prerequisite auto-drops everything that depended on it, across Filetypes/Parsing and Embedding/Vector store/Query alike) or a PipelineGatingError |
| dashboard/state.py | stdlib only (threading, time) | dashboard/server.py | RunState |
Thread-safe shared state: current batch run's status/progress/log tail, read by the poll endpoint and written by _run_worker() |
← Embedding, Vector Store & RAG | Drives: Ingestion → | Served to: Dashboard Frontend →
dashboard/index.html is a single self-contained HTML file --
vanilla JS, no build step, no framework -- rendered by the browser the
Dashboard Backend (Layer 10) opens on startup. It is documented completely
independently from the rest of this reference because it has no
direct knowledge of PDFs, Surya, chunking, or the filesystem at all:
every single thing it does is either render state it already has, or make
an HTTP call to the Backend's JSON API and render whatever comes back.
Swap the backend for anything that speaks the same JSON shape, and this
file works unmodified; swap this file for any other client that speaks
the same JSON shape, and the backend works unmodified. It is called
"Layer 11" consistently throughout this reference (not "Independent" in
one place and "Layer 11" in another) -- the independence is architectural
(a clean JSON seam), not a reason to number it differently.
/api/pipeline/view, /api/pipeline/check, /api/surya/settings, /api/chunking/settings, /api/retrieval/settings, /api/query/status, /api/query, /api/snapshots + /save//load//delete, /api/query/embeddings + /delete, /api/run, /api/status, /api/files -- rendered back into the page. Never touches disk or the pdf_pipeline package directly.| Area | Behavior | Backed by (Backend endpoint / data) |
|---|---|---|
| Pipeline diagram | renderDiagram() draws one card per stage (Filetypes → Parsing → Structure → Chunking → Embedding → Vector store → Query) -- all fully generic and interactive now that FUTURE_STAGES is empty server-side; a disabled, unchecked option shows a DISABLED_OPTION_HINTS tooltip explaining exactly which prerequisite is missing. | GET /api/pipeline/view → pipeline_stages.compute_view() |
| Scouting / ETA summary | renderScoutSummary() shows file/page counts and a run-time estimate once an ingestion folder is set. | Embedded in the same view response → scouting.scout_input_folder() + estimate_time_seconds() |
| Surya model settings panel | Enable/license-acknowledge checkboxes, weights/device/mode/DPI/task selectors -- one choice for the whole run, applies outside the diagram. | GET/POST /api/surya/settings → syncs PipelineSelection.surya_ready |
| Chunking settings panel | Keyword count, cluster size, entity mode/labels, concepts.txt path -- plus live "ready"/"not ready" badges per optional model (KeyBERT/topology/GLiNER/concepts), each with a title tooltip reason when not ready. | GET/POST /api/chunking/settings → model_hooks.model_diagnostics() via the Backend |
| Retrieval settings panel | Device, top_k, vector-store-path, and weights-root-override fields, plus a route picker for the embedding/reranker choice and live ready/not-ready diagnostic badges for each. | GET/POST /api/retrieval/settings → model_hooks.rag_diagnostics() via the Backend |
| Vector snapshots controls | A picker listing every saved snapshot (name, timestamp, chunk count, whether weights are bundled) plus Load/Delete buttons, and a "Save current vector store as snapshot" button with an "include model weights" checkbox. Loading a snapshot re-fetches Retrieval settings so vector_store_path/weights_root reflect the loaded snapshot immediately. | GET /api/snapshots, POST /api/snapshots/save//load//delete |
| Query panel | renderQueryFlow() draws the User query → Query processing → Embedding → Vector search → Hybrid search → Reranker flow indicator; a text input + button submits a query and renderQueryResults() lists the returned chunks (text, score, source file, page numbers); an "Evidence breakdown" checkbox surfaces the consensus/minority/contradiction/conclusion view when checked; refreshQueryStatus() disables the panel with an explanatory message when the Query stage isn't enabled in the diagram yet. A "Save embedding" checkbox caches the resolved query vector server-side; a "reuse a saved question" picker loads a cached question + its vector back into the box (cleared automatically if the text is then edited, so a stale vector is never silently reused) and shows an active-embedding badge while one is selected. The status line also surfaces the audit-log path the query was recorded to. | GET /api/query/status, POST /api/query → a cached query function built by model_hooks.build_query_fn(); GET /api/query/embeddings, POST /api/query/embeddings/delete |
| File table + log | pollStatus() polls every few seconds while a run is active, updating per-file status/error and tailing the run log. | GET /api/status, GET /api/files → dashboard/state.py's RunState |