Local Knowledge RAG Technical architecture reference · General guide · Marketing overview

Getting Started

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.

  1. Requirements

    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.

    Subsystemrequirements fileWhat it unlocks
    requirements.txtempty 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.txtinstalled 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.txtsentence-transformers, keybert, gliner, chonky, torch, scikit-learnKeyword/entity extraction, topology clustering, semantic chunk splitting, and the embedding/reranking models Layer 9 needs
    vectorstore/requirements.txtlancedb, pyarrowThe embedded vector store Layer 9 indexes chunks into and queries against
    requirements-dev.txtpytestRunning 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.

  2. Install the core package

    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 ..
  3. Run something

    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.

  4. Verify the install

    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.

  5. Optional: Surya OCR (license-gated, read before enabling)

    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.

This tab replaces 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.

The technical pipeline

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.

Layer 1
Foundations
config.py, models.py, context.py, logging_utils.py, memory_utils.py, text_sanitize.py -- the shared data model and configuration every other layer imports.
Layer 2
Ingestion
batch.py, batch_cli.py, cli.py, scouting.py -- discovers files on disk, builds one ConversionConfig per file, drives Parsing.
Layer 3
Parsing
pdf_parser.py, image_parser.py, surya_backend.py, struct_tree_extraction.py, text_parser.py, eml_parser.py, office_parser.py, tabular_parser.py, avro_parser.py, edi_parser.py, processors/* -- turns file bytes into the shared IObject content tree, or a native output + Markdown preview for graph-shaped formats.
Layer 4
Structure
structure/tree.py, build.py, graph.py, export.py -- builds the DocumentNode hierarchy + citation/concept graph.
Layer 5
Chunking & Enrichment
chunking/* + chunking/enrich/* -- builds retrieval Chunks and enriches them with cheap, model-free metadata (plus optional model hooks).
Layer 6
Concepts
concepts/__init__.py -- resolves a user-supplied concept list against chunks + the citation graph.
Layer 7
Output Writers
outputs/*, pdfio/*, rasterize/* -- the only layer that writes files into the user's output directory.
Layer 8
Optional ML Bridge
pipeline/model_hooks.py + pipeline/models/* -- the one sanctioned file allowed to import both pdf_pipeline and the optional ML/RAG subsystems.
Layer 9
Embedding, Vector Store & RAG
pipeline/vectorstore/*, pipeline/rag/*, pipeline/storage/*, pipeline/verify/* -- indexes chunks, answers queries via hybrid search + reranking, optionally breaks the answer down into evidence, and persists snapshots/cache/audit log.
Layer 10
Dashboard Backend
dashboard/server.py, pipeline_stages.py, state.py -- an HTTP JSON API wrapping Ingestion + a live gating graph for the UI.
Layer 11
Dashboard Frontend
dashboard/index.html -- a standalone single-page app that only ever speaks JSON to the Backend. Documented on its own.

The whole pipeline, one block per layer

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.

Top-level pipeline, one box per layer
Input
Input folder -- PDFs, images, text, office, tabular, structured-data files
→
Layer 2
Ingestion -- discover files, build config
→
Layer 3
Parsing -- bytes to the shared pages shape
→
Layer 4
Structure -- DocumentNode tree + Graph
→
Layer 5
Chunking & Enrichment -- enriched Chunks
→
Layer 6
Concepts -- concept inventory
→
Layer 7
Output Writers -- files on disk
→
Output
Output folder -- json / md / html / txt / pdf / images
↓ also, independently of Layer 7's output files:
From Layer 5
The same enriched Chunks
→
Layer 9
Embedding, Vector Store & RAG -- index + query
→
Output
LanceDB table -- top-k reranked chunks
Layer 8 (Optional ML Bridge) plugs in sideways, not part of the main chain above -- it hands plain Callable hooks into Layer 3 (keyword / entity / topology / concepts extraction), Layer 5 (keyword / entity / topology), Layer 6 (concepts_resolver), and Layer 9 (chunk_indexer, query_fn), only when the matching model's weights are present on disk. Layer 10 (Dashboard Backend) drives Layer 2's batch runs and answers live queries against Layer 9. Layer 11 (Dashboard Frontend) never talks to any of the above directly -- only to Layer 10, over HTTP JSON.
Standalone/zero-dependency boundary. Everything in Layers 1-7 (the 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.

Layer 1Foundations

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.

In
CLI arguments / dashboard selections (raw strings, booleans, paths).
Out
A validated 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.

What you can choose

This layer has no checkboxes of its own -- it's where every other layer's options land. Two things are worth knowing before you touch any other tab:

Config validation
Input
CLI args / dashboard selections
→
Build
ConversionConfig(...) -- config.py
→
Decision
9 _validate_* checks -- __post_init__
any check fails
Fails fast
raise ValueError -- before any file is touched
all pass
Result
validated config object
→
Substrate
IObject / BoundingBox class hierarchy -- models.py

Files

FileDepends onUsed byKey classes / functionsInput → Output
config.py stdlib only (re, dataclasses, typing) pipeline.py, batch.py, image_parser.py, every outputs/* and processors/* module, dashboard/*
  • ConversionConfig -- every format flag, Surya/chunking/annotation-overlay settings, 9 _validate_* validators run from __post_init__; also generate_native_output (default True -- gates the office/tabular/avro/edi parsers' own native txt/md/json/chunks.jsonl output, independent of json/markdown/html/text)
  • FilterConfig / SanitizationRule -- PII-redaction rules
  • parse_page_ranges() -- page-range grammar ("1,3-5")
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
  • BoundingBox, IObject (base -- OCR provenance fields: ocr_text/ocr_confidence/ocr_source/ocr_low_confidence/ocr_blocks)
  • TextChunk/LineChunk/LineArtChunk/ImageChunk/TextLine/TextBlock/TextColumn
  • SemanticParagraph/Heading/Caption/Footnote/HeaderOrFooter/Formula/Picture, EnrichedImageChunk
  • ListItem/PDFList, TableBorderCell/Row/Border
  • ExtractionResult, ProcessingResult (timing)
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

← Start Here  |  Next layer: Ingestion →

Layer 2Ingestion & Batch Orchestration

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).

In
An input folder path, format flags (json/markdown/html/.../annotated images), optional Surya/chunking settings, and optional model hooks built by the ML Bridge (Layer 8).
Out
One call into pipeline.convert_file() per discovered file, plus a BatchRunSummary (per-file status/error/chunk-count) and a run log file. → feeds Layer 3 (Parsing).

What you can choose

Entry point & discovery
Decision
Entry point? -- user's choice of how to invoke this run
single file
cli.py
single-file conversion
→
Layer 3
pipeline.convert_file()
folder, unattended
batch_cli.py
python -m pdf_pipeline.batch_cli
folder, interactive
dashboard/server.py
Run button, Layer 10
↓ both folder paths converge on:
Discover
discover_input_files() -- batch.py
→
Decision
Extension matches a known parser's set?
yes
Run
run_batch() -- batch.py
→
Layer 3
pipeline.convert_file()
no
Skipped
reported, not converted -- FileRunResult(status=skipped)

Files

FileDepends onUsed byKey classes / functionsInput → 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 —

← Foundations  |  Next layer: Parsing →

Layer 3Parsing -- PDF, Image, Text, Office & Data

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.

In
A PDF, image, plain-text, .eml, office (docx/pptx), tabular (csv/tsv/xlsx), or structured-data (json/xml/yaml/xbrl/avro/edi) file path + ConversionConfig (from Ingestion, Layer 2).
Out
For page-shaped formats: 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.

What you can choose

Route selection by extension and user checkbox
Input
Input file
→
Decision
File extension?
.pdf
config.use_struct_tree?
user checkbox
yes, already tagged
struct_tree_extraction.py
extract_from_struct_tree()
no, default
pdf_parser.py + processors/*
parse_pdf() + 9-step heuristics
image file
enable_surya + license ack?
user checkbox
yes
image_parser.py
parse_image_file_full()
no, default
image_parser.py
_fallback_page() -- opaque picture, no OCR
txt / md / log / ini / cfg
text_parser.py
parse_text_like_file()
.eml
eml_parser.py
parse_eml_file()
docx / pptx
office_parser.py
parse_office_file()
csv / tsv / xlsx
tabular_parser.py
parse_tabular_grid_file()
↓ all six routes above converge on the shared shape:
Shared shape
pages: nested page/IObject lists
a separate, non-converging seventh route (json / xml / yaml / xbrl / avro / edi):
Decision
Other structured data?
→
Structured-data half
tabular_parser.py, plus avro_parser.py / edi_parser.py
→
Diverges here
native output + Markdown preview -- skips Layers 4/5/9

Native PDF: heuristic pipeline vs. struct-tree

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.

Two shapes, two treatments

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.

Files

FileDepends onUsed byKey classes / functionsInput → 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()
  • parse_image_file_full() / parse_image_file()
  • build_pages_from_images_with_results() / build_pages_from_images()
  • render_page_overlay() -- bbox+confidence overlay for image-mode input
  • _build_page_from_ocr_blocks()/_build_page_from_layout_only()/_fallback_page()
  • ocr_extracted_images() (Tier 3: OCR already-extracted images), _bbox_from_surya()
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)
  • TEXT_LIKE_EXTENSIONS (.txt/.md/.log/.ini/.cfg), is_text_like_file()
  • read_text_permissive() (errors="replace" -- never raises on bad encoding)
  • _parse_markdown() (heading/bullet/numbered-list regexes), _parse_log(), _parse_ini_like() (via configparser, falls back to plain paragraphs on parse failure or an empty result)
  • parse_text_like_file(path) -> (pages, page_sizes)
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_EXTENSIONS (.eml), is_eml_file()
  • _HTMLTextExtractor/_html_to_text() -- strips an HTML body down to plain text when no text/plain part exists
  • _extract_body() (prefers text/plain, falls back to text/html), _attachment_names()
  • parse_eml_file(path) via email.message_from_bytes(raw, policy=email.policy.default)
.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)
  • OFFICE_EXTENSIONS (.docx/.pptx), is_office_file()
  • _slide_size_points(), _cell_contents(), _table_from_block(), _picture_from_block() (resolves a real written_path from docparse's own media export -- only for extensions worth linking as an image)
  • build_pages_from_office_document(doc, native_out_dir) -- groups docparse Blocks by page/slide, dispatches Block.type to SemanticHeading/SemanticParagraph/PDFList/TableBorder/SemanticPicture
  • parse_office_file(path, native_output_dir) -> (pages, page_sizes, native_manifest)
.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)
  • TABULAR_EXTENSIONS (.csv/.tsv/.tab/.xlsx/.xlsm/.xls/.parquet/.pq), STRUCTURED_DATA_EXTENSIONS (.json/.ndjson/.jsonl/.xml/.xbrl/.yaml/.yml), LEGACY_STUBBED_TABULAR_EXTENSIONS (.xls/.parquet/.pq -- detect-and-report only, raises tableparse.sniff.UnsupportedFormat with a conversion hint rather than guessing)
  • _table_border_from_grid(), _build_pages_from_tables(), parse_tabular_grid_file(path, native_output_dir) -> (pages, page_sizes) -- the grid-shaped half
  • build_dataset_from_object(root, source, fmt) -> Dataset -- shared with avro_parser.py/edi_parser.py
  • write_native_and_preview(ds, output_dir, stem, fmt) -> dict -- shared native-output + Markdown-preview writer, also reused by avro_parser.py/edi_parser.py
  • _build_preview(ds, fmt) -> str, parse_structured_data_file(path, output_dir) -> dict -- the graph-shaped half (json/xml/yaml/xbrl)
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_EXTENSIONS (.avro) -- hand-rolled Avro Object Container File reader, no external avro/fastavro package
  • AvroReader (_read_record()/_read_enum()/_read_fixed()/_read_array()/_read_map()/_read_union()), zigzag-varint + IEEE754 primitives
  • _collect_named_types() pre-pass (resolves record/enum/fixed references declared elsewhere in the schema before any data decoding), null + deflate codec support (AvroUnsupportedCodec otherwise)
  • read_avro_container(path) -> (schema, records), _jsonify() (bytes/fixed fields → hex strings for JSON safety), parse_avro_file(path, output_dir) -> dict
.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)
  • EDI_EXTENSIONS (.edi/.x12 + curated transaction-set extensions -- .837/.835/.834/.850/.855/.810/.856/.820/.997/...)
  • detect_edi_dialect() -- X12 vs EDIFACT; EDIFACT is cleanly rejected via EDIFACTNotSupported, never mis-parsed as X12
  • _parse_isa() (fixed-width, exact 106-character ISA segment), _group_envelope() (ISA/IEA > GS/GE > ST/SE hierarchy, tolerant of a missing GS via a synthetic ungrouped group)
  • parse_x12_text(text) -> {"interchanges": [...]} (supports multiple concatenated interchanges), parse_edi_file(path, output_dir) -> dict
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 →

Layer 4Structure

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.

In
pages: List[List[IObject]] + document_info (from Parsing, Layer 3).
Out
A 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.

What you can choose

Build-once, shared-by-two-consumers
Input
pages: nested page/IObject lists -- from Layer 3
→
Decision
generate_structure or generate_chunks requested? -- user checkbox
no
Skipped
entirely -- no tree, no graph built
yes
Build
build_document_tree() -- structure/build.py
→
DocumentNode tree
shared by both consumers below
↓ the tree above feeds two independent consumers:
Graph
build_graph() -- structure/graph.py
→
Output
Graph object
Export
to_tree_json() / to_graph_json() -- structure/export.py, reads both the tree and the graph

Files

FileDepends onUsed byKey classes / functionsInput → 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

← Parsing  |  Next layer: Chunking & Enrichment →

Layer 5Chunking & Enrichment

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.

In
A DocumentNode tree (from Structure, Layer 4) + optional keyword_extractor/entity_extractor/topology_fn hooks (from the ML Bridge, Layer 8).
Out
A 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.

What you can choose

View A/E + optional enrichment hooks
Input
DocumentNode tree -- from Layer 4
→
View A
build_view_a_chunks() -- chunking/view_a.py, always runs
Decision
config.chunk_view_e? -- user checkbox
yes
View E
build_view_e_chunks() -- chunking/view_e.py
no
Skipped
View A's chunks only
↓ both views feed the same list, then:
Chunks
a list of Chunks
→
Orchestrator
enrich_chunks() -- chunking/enrich/__init__.py
always runs
5 cheap enrichers
structural / bibliographic / boilerplate / editorial / math
keyword_extractor hook present? -- Layer 8, weights downloaded?
enrich_lexical()
BM25 tokens always; keyphrases only if the hook is present
entity_extractor hook present? -- Layer 8, weights downloaded?
enrich_entities()
entities only if the hook is present
topology_fn hook present? -- Layer 8, weights downloaded?
enrich_topology()
clusters only if the hook is present
↓
Output
a list of Chunks, fully enriched

Files

FileDepends onUsed byKey classes / functionsInput → Output
chunking/models.pystdlib (hashlib, dataclasses)every file in this layerChunk dataclass, compute_chunk_id(), GRANULARITY_*/VIEW_* constantsDefines the Chunk shape (text, provenance, enrichment dict)
chunking/provenance.pystructure/tree.pyview_a.py, view_e.pyown_heading_node(), full_heading_trail(), provenance_from()DocumentNode(s) → page numbers, node ids, bounding boxes for a chunk
chunking/tables.pymodels.pyview_a.pytable_to_markdown()TableBorder → Markdown table text for table chunks
chunking/text_utils.pystdlib (re)view_a.py, view_e.pyword_count(), split_sentences()Raw text → word count / sentence list
chunking/view_a.pystructure/tree.py, chunking/models.py, provenance.py, tables.py, text_utils.pypipeline._generate_chunks()build_view_a_chunks() (+ word-budget packing / optional semantic-splitter hook)DocumentNode tree → hierarchical section/paragraph Chunks
chunking/view_e.pystructure/tree.py, chunking/models.py, provenance.py, text_utils.pypipeline._generate_chunks() when chunk_view_e=True (user checkbox)build_view_e_chunks()DocumentNode tree → sentence-window micro-Chunks
chunking/export.pychunking/models.pypipeline._generate_chunks()to_chunks_dict()/to_chunks_json()List[Chunk] → chunks.json text
chunking/enrich/__init__.pyevery enrich/* submodule belowpipeline._generate_chunks()enrich_chunks() -- the orchestratorList[Chunk] (+ optional hooks) → same list, mutated with .enrichment fields
chunking/enrich/structural.pychunking/models.pyenrich/__init__.pyenrich_provenance(), enrich_structural() (sibling-group hashing)Chunk → provenance + structural-position metadata
chunking/enrich/bibliographic.pychunking/models.pyenrich/__init__.pyenrich_bibliographic(), _classify_heading()Chunk → bibliography-section classification
chunking/enrich/boilerplate.pychunking/models.py, structure/tree.pyenrich/__init__.pyenrich_boilerplate(), _boilerplate_type()Chunk → boilerplate-type flag (running header/footer/TOC/...)
chunking/enrich/editorial.pychunking/models.pyenrich/__init__.pyenrich_editorial(), _detect_environment()Chunk → textbook-environment tag (Theorem/Example/Exercise/...)
chunking/enrich/math_aware.pychunking/models.py, structure/tree.pyenrich/__init__.pyenrich_math()Chunk → formula-density/notation metadata
chunking/enrich/lexical.pychunking/models.pyenrich/__init__.pybm25_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.pychunking/models.pyenrich/__init__.pyenrich_topology() (+ optional HDBSCAN topology_fn hook)All chunk texts → cluster label + nearest-neighbor ids + medoid flag per chunk
chunking/enrich/entities.pychunking/models.py, structure/tree.pyenrich/__init__.pyenrich_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 →

Layer 6Concepts

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.

In
concepts.txt path + List[Chunk] (Layer 5) + Graph (Layer 4) + a concepts_resolver hook (embedding similarity, from the ML Bridge, Layer 8).
Out
Per-concept JSON/Markdown result files under 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).

What you can choose

Concept resolution
Input
a list of Chunks -- from Layer 5, + Graph -- from Layer 4
→
Decision
concepts_path set AND concepts_resolver hook present? -- user file + Layer 8 weights
no
Skipped
layer skipped entirely
yes
Read
read_concepts_file()
→
Resolve
resolve_concepts() -- similarity + k-hop + mentions()
→
Write
write_concept_results()
→
Output
concepts/<doc>/*.json + *.md -- one file per concept

Files

FileDepends onUsed byKey classes / functionsInput → Output
concepts/__init__.py chunking/models.py (Chunk), structure/graph.py (Graph, GraphNode, nodes_by_id), structure/tree.py (NODE_SECTION) pipeline._generate_chunks()
  • read_concepts_file(), slugify()
  • resolve_concepts() -- merges 3 sources: embedding-similarity matches, k-hop graph expansion, direct mentions(concept) edges
  • write_concept_results(), run_concept_inventory() (entry point)
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 →

Layer 7Output Writers

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.

In
pages (Layer 3), DocumentNode/Graph (Layer 4), List[Chunk] (Layer 5) -- whichever the requested formats need.
Out
Every file in 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.

What you can choose

Format dispatch
Input
pages / DocumentNode / Graph / a list of Chunks
→
Decision
Which config.generate_* flags are set? -- user checkboxes
generate_json
json_writer.py
generate_json()
generate_markdown
markdown_writer.py
generate_markdown()
generate_html
html_writer.py
generate_html()
generate_text
text_writer.py
generate_text()
generate_pdf, PDF only
annotated_pdf.py
generate_annotated_pdf()
generate_tagged_pdf, PDF only
tagged_pdf.py
generate_tagged_pdf()
always, if images were found
images.py
write_extracted_images()
↓ every route above writes into the same place:
Output
files in output_dir

Files

FileDepends onUsed byKey classes / functionsInput → Output
outputs/json_writer.pymodels.pypipeline.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.pyconfig.py, models.pypipeline.py (generate_markdown, user checkbox)generate_markdown(), _render_node(), _render_table(), _render_list()pages → <doc>.md
outputs/html_writer.pyconfig.py, models.pypipeline.py (generate_html, user checkbox)generate_html(), _render_node(), _render_table(), _render_list()pages → <doc>.html
outputs/text_writer.pyconfig.py, models.pypipeline.py (generate_text, user checkbox)generate_text(), _render_node()pages → <doc>.txt
outputs/annotated_pdf.pymodels.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.pymodels.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.pycontext.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.pyrasterize/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.pystdlib onlyreader_shim.py, writer.py, content_stream.py callersName, Ref, Dictionary, Array, StreamObjectDefines the PDF COS object primitives
pdfio/content_stream.pystdlib onlyannotated_pdf.py, tagged_pdf.pyrect_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.pyopen_document(), get_page_refs(), walk_struct_tree(), get_raw_dict(), extract_mcid_text_map(), PageRef, _McidTextDevicePDF path → page refs / raw COS dicts / MCID-to-text maps, read via the vendored pdfminer parser
pdfio/writer.pypdfio/cos.py, _vendor/pdfminer_six/*annotated_pdf.py, tagged_pdf.pyPdfWriter, serialize_value(), _contiguous_runs(), format_number()New/updated COS objects → an incrementally-updated PDF file (original content untouched)
rasterize/pdfium_backend.pymodels.py (BoundingBox), rasterize/png_encoder.py, optional pypdfium2outputs/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.pystdlib only (struct, zlib)pdfium_backend.py, outputs/annotate.pyencode_png(), _chunk()Raw pixel buffer → valid PNG bytes (single IDAT, no filtering/palette -- correctness over size)

← Concepts  |  Terminal layer -- writes to disk.

Layer 8Optional ML Bridge

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.

In
Nothing from the pipeline itself -- invoked externally by Ingestion (Layer 2: batch_cli.py) or Dashboard Backend (Layer 10), which call model_hooks.build_*() once per run.
Out
Plain 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.

What you can choose

Nothing here is a runtime checkbox -- readiness is entirely determined by what's on disk and what's installed, checked fresh on every diagnostics call:

Hook readiness gate
Called by
batch_cli.py or dashboard/server.py -- build_*() once per run
→
Check
model_diagnostics() / rag_diagnostics() -- model_hooks.py
→
Decision
weights present on disk AND package importable?
yes
Returns
a Callable hook
→
Used
threaded into Layers 3 / 5 / 6 / 9 as a keyword argument
no
Returns
None + a reason string
→
Degrades gracefully
that layer's model-backed fields stay at their default

Files

FileDepends onUsed byKey classes / functionsInput → 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
  • model_diagnostics() / rag_diagnostics() (weights-present + package-importable per model, built from a shared _diagnose() helper)
  • build_keyword_extractor(), build_entity_extractor(), build_topology_fn(), build_concepts_resolver()
  • build_embedder(), build_reranker()
  • build_chunk_indexer(model_name, device, store_path) -- loads an embedder + opens a VectorStore once per batch run, returns a closure that embeds+upsert_chunks()s one document's chunks
  • build_query_fn(store_path, model_name, device, use_reranker, top_k) -- loads embedder/store/optional reranker once, returns a closure calling rag.query.answer_query()
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
  • load_sentence_transformer(), load_keybert()/load_keybert_as_keyword_extractor(), load_gliner()/load_gliner_as_entity_extractor(), load_chunker()/load_chunker_as_semantic_splitter(), WeightsNotFoundError
  • embedding_model_names() / embedding_dimension(model_name) -- pure-python, no import of sentence-transformers, so pipeline/vectorstore/store.py can size a LanceDB schema without needing torch
  • class Embedder / load_embedder(model_name, device) -- wraps 5 selectable routes (MiniLM/BGE-base default plus 3 alternates, see Layer 9); embed_documents() (no prefix) vs. embed_query() (applies each model's own asymmetric query-instruction prefix where applicable)
  • class Reranker / load_reranker(device) -- wraps 4 selectable cross-encoder routes; score(query, candidates) rescores a shortlist in one batched forward pass
  • class NLIVerifier / load_nli_verifier(device) -- wraps cross-encoder/nli-deberta-v3-base for the evidence-breakdown contradiction check (Layer 9)
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 →

Layer 9Embedding, 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).

In
Indexing path: 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.
Out
Indexing path: rows written into (or deleted-then-rewritten for) one 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().

What you can choose (across all four sub-pipelines below)

Sub-pipeline 1: Indexing

Chunks → LanceDB table
Input
a list of Chunks -- from Layer 5, per document
→
Decision
Embedding stage checked? -- user checkbox
no
Skipped
chunks written to disk only, Layer 7 -- never indexed
yes
Which embedding route?
user radio: default / B / C1 / D
default
Embedder
MiniLM or BGE-base -- models/loaders.py
Route B
Embedder
mxbai-embed-large-v1
Route C1
Embedder
Qwen3-Embedding-0.6B
Route D
Embedder
gte-large-en-v1.5
↓ any route above converges on:
Build
build_chunk_indexer() -- model_hooks.py
→
Upsert
upsert_chunks() -- vectorstore/store.py, delete-by-doc_id then add
→
Output
LanceDB chunks table

Sub-pipeline 2: Query

User query → ranked chunks
Input
User query -- free-text string
→
Decision
Saved query embedding selected? -- user picker
yes, reuse vector
Skip embedding
cached vector passed straight through
no, embed now
Embed
Embedder.embed_query() -- models/loaders.py
↓ both paths converge on:
Process
process_query() -- rag/query.py
dense
Vector search
vector_search() -- vectorstore/store.py, cosine, top vector_k
keyword
BM25
BM25Index -- rag/bm25.py
↓ both rankings combine via:
Fuse
reciprocal_rank_fusion() -- rag/fusion.py
→
Decision
Reranker enabled? -- user checkbox + route
yes
Rerank
Reranker.score() -- 1 of 4 routes
no
Skip
fused ranking used as-is
↓
Result
Top-k chunks, ranked
if OPT_QUERY_EVIDENCE_BREAKDOWN
Evidence
verify.evaluate_evidence() -- see Sub-pipeline 3 below
always, no opt-out
Log
append_qa_entry() -- storage/query_logs.py

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.

Sub-pipeline 3: Evidence Breakdown

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.

Claims → consensus / minority / contradictions / conclusion
Input
Top-k chunks -- from Sub-pipeline 2 above
→
Split
claims_from_results() -- verify/claims.py, stdlib regex sentence split
→
Claims
candidate claim sentences
Embed
with the SAME embedder already loaded for the query
→
Cluster
cluster_chunk_embeddings() -- models/topology.py, reused as-is
→
Decision
Cluster has 2+ distinct sources?
yes
Consensus
claims corroborated by 2+ sources
nli_verifier hook present?
Layer 8, weights downloaded
yes
Classify
NLIVerifier.classify() -- cross-encoder/nli-deberta-v3-base
→
Contradictions
cluster-representative pairs
no
Skipped
no contradiction check this run
no
Minority
1 source, or HDBSCAN noise
↓ consensus + minority + contradictions (if any) all feed:
Rank
composite ranking: distinct sources, minus 1 if contradicted, tiebreak by avg score
→
Output
most strongly supported conclusion

Sub-pipeline 4: Storage (snapshots, query-embedding cache & audit log)

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.

Snapshots, embedding cache & audit log
Vector-store snapshots
Input
Finished vector store + weights, optional
→
Save snapshot?
user button, opt-in
yes
Save
save_snapshot() -- storage/snapshots.py
→
Output
storage/vector_snapshots/<timestamp>/manifest.json
no
Skipped
nothing saved
Load a snapshot?
user picker
→
Override
weights_root override -- skips the creation pipeline entirely
Query-embedding cache
Input
A query's embedding vector
→
Save embedding?
user checkbox, opt-in
yes
Save
storage/query_embeddings/<timestamp>.json
→
Reuse
query_vector passthrough -- skips the embedder call
no
Skipped
nothing cached
Audit log
Every query
unconditionally -- no opt-out
→
Output
storage/query_logs/qa_<YYYYMMDD>.log

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).

Files

FileDepends onUsed byKey classes / functionsInput → 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)
  • class VectorStore -- one LanceDB db directory + one shared chunks table, dimension fixed at construction (varies by the user's chosen embedding route)
  • upsert_chunks(chunks, vectors, doc_id, source_file) -- delete-by-doc_id then add, so re-indexing a document never leaves stale duplicate rows
  • vector_search(query_vector, k) -- cosine nearest-neighbor via table.search().metric("cosine").limit(k)
  • bm25_corpus() -- every row's metadata except the vector column, the full corpus a query-time BM25 index scores over
  • delete_document(), count(), is_available()
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)
Verification status. This layer's pure-Python logic (BM25 scoring, reciprocal rank fusion, the full query-orchestration flow in 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.
A separate, researched-but-not-implemented design doc (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 →

Layer 10Dashboard 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.

In
HTTP GET/POST requests from the Dashboard Frontend (Layer 11): folder path, checkbox toggles, Surya/chunking/retrieval settings, Run button, a live query string.
Out
JSON responses (diagram state, scouting/ETA summary, live run status/log tail/file table, retrieval diagnostics, query results). Triggers 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.

What you can choose

Request routing & gating
Input
HTTP request -- from Layer 11
→
Decision
Which route?
view
GET /api/pipeline/view
pipeline_stages.compute_view()
check
POST /api/pipeline/check
pipeline_stages.apply_check()
is_option_allowed()?
derived from the user's prior checkbox state
allowed
200
new view state
not allowed
409/400
PipelineGatingError
run
POST /api/run
_run_worker(), background thread
status
GET /api/status
state.py RunState
query
POST /api/query
cached build_query_fn() closure
snapshots
POST /api/snapshots/*
storage wrappers

Files

FileDepends onUsed byKey classes / functionsInput → 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)
  • Handler (BaseHTTPRequestHandler subclass -- the whole REST API), configure(), _view_with_scout(), _surya_diagnostics()/_chunking_diagnostics(), _sync_model_ready() (syncs the RAG model keys), _run_worker() (background thread, builds+passes a chunk_indexer hook when embedding is selected), _record_benchmark_sample(), main()
  • _rag_diagnostics(), _resolved_vector_store_path(output_dir), module-level _RETRIEVAL_SETTINGS dict (holds weights_root -- points a query at a snapshot's own copied weights instead of the shared folder) + _QUERY_FN_CACHE (cache key includes weights_root) -- one cached query closure per settings signature, so a query function isn't rebuilt -- reloading the embedder/store/reranker -- on every single query
  • RAG routes: GET/POST /api/retrieval/settings (device/top_k/vector_store_path/weights_root + live model-ready diagnostics), GET /api/query/status (whether the Query stage is currently enabled per the diagram gating), POST /api/query (runs a cached build_query_fn() closure -- accepts an optional embedding_name to reuse a cached vector and save_embedding to cache the one just computed, always calls model_hooks.append_qa_log() before responding, 400 if query empty or Query stage not enabled, 500 on build/execution failure)
  • Storage routes: GET /api/snapshots / POST /api/snapshots/save, /load, /delete (vector-store+weights snapshots); GET /api/query/embeddings / POST /api/query/embeddings/delete (cached query-embedding metadata listing + deletion) -- all thin wrappers around the nine model_hooks.py storage functions
  • _make_filetype_filter() -- the file-listing predicate behind the dashboard's file table; checks each want_* boolean (office/tabular/structured-data/legacy-tabular/avro/edi) against the matching extension sets, checking tabular_parser.LEGACY_STUBBED_TABULAR_EXTENSIONS before the general tabular_parser.TABULAR_EXTENSIONS check since the former is a subset mapped to its own checkbox
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
  • PipelineSelection, is_option_allowed(), normalize(), apply_check(), compute_view(), selection_to_config_kwargs(), set_surya_ready()/set_model_ready()/set_concepts_path(), chunking_feature_flags(), selected_filetypes()
  • FUTURE_STAGES is the empty set -- Embedding/Vector store/Query are real, checkable stages, not reserved placeholders
  • RAG option constants: OPT_EMBED_BUILD, per-route embedding-model options (mutually exclusive), OPT_VECTOR_STORE_LANCEDB, OPT_QUERY_ENABLE, OPT_QUERY_RERANK, OPT_QUERY_EVIDENCE_BREAKDOWN
  • Filetypes/Parsing option constants: one pair (OPT_FILETYPE_* / OPT_PARSE_*) per format family -- txt/md/log/ini/cfg/eml/office/tabular/structured/legacy-tabular/avro/edi; REAL_FILETYPES set constant covers all 12 filetype options
  • CROSS_STAGE_OPTION_REQUIRES -- a generic option → (earlier stage, earlier option) dependency map, modeling Embedding → Vector store → Query as a gating chain the way PARSING_OPTION_REQUIRES_FILETYPE models same-stage dependencies
  • PARSING_OPTION_REQUIRES_FILETYPE -- Dict[str, Tuple[str, ...]] (ANY-of semantics) so e.g. OPT_PARSE_PLAINTEXT can depend on any one of five different Filetypes options being checked, not just one
  • rag_feature_flags(selection) -- resolves the selected embedding model/device/top_k/rerank flag into the kwargs _run_worker() needs to build a chunk_indexer hook
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 →

Layer 11Dashboard 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.

In
User interaction only: typing a folder path, ticking checkboxes, editing Surya/Chunking/Retrieval settings, clicking Run, typing and submitting a query.
Out
HTTP calls to the Dashboard Backend (Layer 10) -- /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.

What you can choose

Every option in this whole document is, in the end, a checkbox, radio button, or text field somewhere on this page -- that's the point of it existing. Nothing here introduces a new pipeline behavior; it only exposes the Backend's own gating graph (Layer 10) interactively, with tooltips explaining why a greyed-out option is greyed out.

User interaction → Backend round-trip
Decision
User interaction -- click / type / submit
toggles a checkbox
renderDiagram()
ticks a checkbox
→
POST /api/pipeline/check
Layer 10
→
GET /api/pipeline/view
Layer 10
→
Redraw
+ DISABLED_OPTION_HINTS tooltip if blocked
clicks Run
Run button
→
pollStatus()
every few seconds
submits a query
Query panel
→
POST /api/query
→
renderQueryResults()

What it renders

AreaBehaviorBacked by (Backend endpoint / data)
Pipeline diagramrenderDiagram() 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 summaryrenderScoutSummary() 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 panelEnable/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 panelKeyword 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 panelDevice, 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 controlsA 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 panelrenderQueryFlow() 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 + logpollStatus() 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
Because this file only speaks JSON to one backend, "documenting it independently" is not just an organizational choice -- it reflects a real architectural seam. Nothing on this page needs to change if Parsing, Structure, Chunking, or any other pipeline-side layer is refactored, as long as the Backend's response shapes stay the same.

← Dashboard Backend  |  ↑ Back to Start Here