Metadata-Version: 2.4
Name: qaechi-parser
Version: 2.2.0
Summary: Evidence-first document extraction engine: every value comes with its quote and page.
Author: Taeyong Kang
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/qaechi/qaechi-parser
Project-URL: Documentation, https://qaechi.github.io/qaechi-parser/
Project-URL: Issues, https://github.com/qaechi/qaechi-parser/issues
Project-URL: Changelog, https://github.com/qaechi/qaechi-parser/blob/main/CHANGELOG.md
Keywords: rag,document-parsing,extraction,llm,provenance,fastapi,langgraph
Classifier: Development Status :: 5 - Production/Stable
Classifier: Framework :: FastAPI
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Text Processing
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
Requires-Dist: pydantic<3,>=2.6
Provides-Extra: server
Requires-Dist: fastapi<1,>=0.110; extra == "server"
Requires-Dist: uvicorn[standard]<1,>=0.29; extra == "server"
Provides-Extra: parse
Requires-Dist: httpx<1,>=0.27; extra == "parse"
Requires-Dist: openpyxl<4,>=3.1; extra == "parse"
Requires-Dist: pymupdf<3,>=1.24; extra == "parse"
Requires-Dist: pymupdf4llm>=0.0.17; extra == "parse"
Requires-Dist: python-pptx<2,>=1.0; extra == "parse"
Provides-Extra: llm
Requires-Dist: langchain-openai<2,>=1.0; extra == "llm"
Requires-Dist: langchain-text-splitters<2,>=1.0; extra == "llm"
Requires-Dist: langgraph<2,>=1.0; extra == "llm"
Provides-Extra: otel
Requires-Dist: opentelemetry-api<2,>=1.45.2; extra == "otel"
Requires-Dist: opentelemetry-sdk<2,>=1.45.2; extra == "otel"
Requires-Dist: opentelemetry-exporter-otlp-proto-http<2,>=1.45.2; extra == "otel"
Provides-Extra: kafka
Requires-Dist: confluent-kafka<3,>=2.16.2; extra == "kafka"
Provides-Extra: postgres
Requires-Dist: psycopg[binary,pool]<4,>=3.3.9; extra == "postgres"
Provides-Extra: all
Requires-Dist: qaechi-parser[kafka,llm,otel,parse,postgres,server]; extra == "all"
Provides-Extra: dev
Requires-Dist: qaechi-parser[kafka,otel,postgres,server]; extra == "dev"
Requires-Dist: pytest<10,>=8; extra == "dev"
Requires-Dist: httpx<1,>=0.27; extra == "dev"
Requires-Dist: openpyxl<4,>=3.1; extra == "dev"
Requires-Dist: python-dotenv<2,>=1; extra == "dev"
Requires-Dist: ruff==0.16.*; extra == "dev"
Dynamic: license-file

<div align="center">

<img src="https://raw.githubusercontent.com/qaechi/qaechi-parser/main/docs/assets/brand/qaechi-social-preview-2560x1280.png" alt="qaechi: evidence-first document extraction. Each value comes back with its quote and page." width="100%">

# qaechi-parser

**Evidence-first document extraction for RAG and business systems.**<br>
Every value comes back with the exact quote and page it was read from.

[![CI](https://github.com/qaechi/qaechi-parser/actions/workflows/ci.yml/badge.svg)](https://github.com/qaechi/qaechi-parser/actions/workflows/ci.yml)
[![Release](https://img.shields.io/github/v/release/qaechi/qaechi-parser?sort=semver)](https://github.com/qaechi/qaechi-parser/releases)
[![Python](https://img.shields.io/badge/python-3.11%20%7C%203.12%20%7C%203.13-blue)](https://github.com/qaechi/qaechi-parser/blob/main/pyproject.toml)
[![License](https://img.shields.io/badge/license-Apache--2.0-green)](https://github.com/qaechi/qaechi-parser/blob/main/LICENSE)
[![Docs](https://img.shields.io/badge/docs-qaechi--foundation.github.io-ffd84d?labelColor=101418)](https://qaechi.github.io/qaechi-parser/)

[Quickstart](#quickstart) | [How it works](#how-it-works) | [Parsing rules](#parsing-rules) | [Benchmarks](#benchmarks) | [Plugins](#write-a-parser-plugin) | [API](#http-api) | [Config](#configuration) | [Contact](#contact) | [Maintainer](#maintainer) | [한국어](https://github.com/qaechi/qaechi-parser/blob/main/README.ko.md)

</div>

---

## Why qaechi-parser

LLM extraction is easy to demo and hard to trust. When a number is wrong, you need to
know **where it came from**. When the model is unsure, you want `null`, not a guess.

qaechi-parser is the extraction layer of the **Qaechi** framework. It reads a document and
**proposes** values with evidence. Your system (an ERP, a review queue, an agent)
decides what to accept.

| qaechi-parser does | qaechi-parser does not |
|---|---|
| Load, chunk, index, extract, grade | Authenticate or authorize users |
| Return each value with `quote` and `page` | Approve, confirm or post anything |
| Report quotes it could not find in the source | Fix values so totals add up |
| Count what it skipped or truncated | Drop rows or sheets silently |

## Features

- **Provenance on every value.** `quote`, `page` and `chunkId` for each field and line item.
- **Verbatim check.** Each LLM quote is matched against the source text; misses are listed in `quoteCheck.notInSource`.
- **Deterministic parsers first.** Fixed layouts go to plugins that read the file directly: zero tokens, confidence 1.0.
- **LLM route for the rest.** You describe the fields you want; qaechi-parser builds the structured-output schema.
- **Groundedness grade.** A second pass labels results `yes` / `no` / `unknown`. No key means `unknown`, never an optimistic `yes`.
- **Runs without anything.** With no keys and no storage it starts in stub mode and returns `null`s, so you can wire your UI first.
- **LangGraph optional.** Same nodes and edges run on LangGraph or on a built-in sequential runner.
- **Safe defaults.** Loopback bind, constant-time token check, API docs off, path traversal blocked, input size limits.

## Quickstart

```bash
pip install "qaechi-parser[parse] @ git+https://github.com/qaechi/qaechi-parser@qaechi-parser-v1.2.7"

# Parse a local file (built-in ledger parser)
qaechi-parser parse examples/ledger.csv --doc-type ledger
```

```jsonc
{
  "route": "parser",
  "parser": "ledger",
  "lines": [
    { "label": "Design work",
      "amount": { "value": 1200000, "confidence": 1.0,
                  "provenance": { "page": 1, "quote": "Design work | 1 | 1,200,000" } } }
    // ...
  ],
  "total": { "value": 1225000, ... },
  "groundedness": "yes"
}
```

Ask an LLM for free-form fields (needs `pip install "qaechi-parser[all]"` and `OPENAI_API_KEY`):

```bash
qaechi-parser parse contract.pdf --doc-type contract \
  --field "party:text:the counterparty name" \
  --field "fee:integer:monthly fee" \
  --field "start:date:contract start date"
```

Or from Python:

```python
import qaechi.parser as qp

result = qp.parse("contract.pdf", "contract",
                          fields=[{"name": "fee", "kind": "integer"}])
print(result.fields["fee"].value, result.fields["fee"].provenance.quote)
```

## How it works

```mermaid
flowchart LR
  F[fetch] -->|parser matches| P[parse]
  F -->|no source / no LLM| S[stub]
  F -->|LLM route| L[load] --> C[chunk] --> I[index] --> R[retrieve] --> E[extract] --> G[grade]
  G -->|"no (once)"| W[rewrite] --> E
  G --> V[save]
  P --> V
  S --> V
```

1. **fetch**: get the file from a local directory or an HTTP object store.
2. **route**: a registered parser that matches `docType` + extension (+ `sourceKind`) wins. Otherwise LLM, or stub.
3. **load / chunk**: PDF, PPTX, XLSX (every sheet), CSV, TXT, MD. Tables are never split.
4. **retrieve** *(opt-in)*: long documents are narrowed to the chunks that hold evidence.
5. **extract**: structured output with a quote per value.
6. **grade**: groundedness as a secondary signal; one widened retry on a clear `no` *(opt-in)*.
7. **save**: the result is stored as a proposal with its quote check.

## Parsing rules

<!-- --8<-- [start:parsing-rules] -->

qaechi-parser decides what to read, how to cut it and what counts as evidence by fixed
rules, not by model judgment. Same file in, same pages and chunks out.

### 1. Route: who reads the document

| Order | Condition | Route | Tokens | Confidence |
|---|---|---|---|---|
| 1 | A registered parser matches `docType` **and** extension (**and** `sourceKind`, if the parser declares any). The most recently registered match wins, so a plugin overrides a built-in. | `parser` | 0 | 1.0 |
| 2 | No parser, a source file exists and an LLM key is set | `llm` | yes | model's |
| 3 | Anything else | `stub` (all `null`, with the reason in `notes`) | 0 | 0 |

A parser that does not recognise the layout raises `LayoutError` rather than guessing.

### 2. Load: what each format turns into

Every loader returns **pages**, and the page number travels to `provenance.page`.

| Format | Page = | Rules |
|---|---|---|
| **PDF** | PDF page | Text layer via pymupdf4llm, tables kept as markdown. A page with no text is kept empty and reported in `notes` as `no text on N page(s)` (likely scanned; put OCR in front). Encrypted files fail unless `QAECHI_PDF_PASSWORD` opens them. |
| **PPTX** | slide | Title first as `# title`. Shapes in **reading order** (top-to-bottom, then left-to-right), **including shapes inside groups**. Tables become `\| a \| b \|` rows. **Charts** become a `series \| category...` table with their values. Speaker notes follow a `[notes]` marker. |
| **XLSX / XLSM** | sheet | **Every sheet**, hidden sheets too (marked `(hidden)`). Cached values, not formulas. Blank rows dropped and trailing empty cells trimmed; empty cells in the middle stay so columns line up. `1200000.0` prints as `1200000`, a midnight datetime as `2026-01-31`; nothing is rounded. Up to 20,000 rows are read per sheet for parsers; the first 300 non-blank rows go to the LLM, and the sheet header says so. |
| **CSV** | whole file | Delimiter sniffed (`, ; tab \|`), UTF-8 with or without BOM. Same row rules as XLSX. |
| **TXT / MD** | whole file | As is. |

### 3. Chunk: how pages are cut

| Rule | Why |
|---|---|
| A sheet page is one chunk, however long. | A table split from its header loses meaning. |
| Other pages are cut into **table blocks** (lines with 2+ `\|`) and **prose blocks**. | A PDF page often holds both. |
| Table blocks are never split. Prose blocks over 1,000 chars are split (100-char overlap). | Retrieval gets small prose chunks without breaking tables. |
| Small neighbouring blocks are packed together up to 1,000 chars. | A table keeps the sentence that introduces it. |
| Each chunk starts with `[doc: <type> \| period: <p> \| p.<n>]`. | The model can cite the page. |
| Chunk text is verbatim. | Quotes are checked against it. |

### 4. Evidence: when a quote counts

Each LLM quote is searched for in the chunk text. Before matching, both sides are normalized
**only** for: Unicode compatibility forms (full-width `１,０００`, NBSP), typographic quotes and
dashes (`“ ”` `–` `−`), markdown the loader added (`|`, `**`, `__`, `<br>`), and runs of
whitespace. Letters, digits and their order must match exactly, so a changed digit, a moved
decimal point or a dropped minus sign is reported in `quoteCheck.notInSource`.

### 5. Grade and save

- Groundedness is `yes` / `no` / `unknown`; without an LLM key it is `unknown`, never `yes`.
  Parser results are `yes` because their values are read, not generated.
- A clear `no` retries once with the full context, and only if `QAECHI_REWRITE` is on.
- Nothing is dropped silently: skipped rows, skipped sheets, truncated sheets, empty pages and
  quotes not found in the source are all counted in the result.

<!-- --8<-- [end:parsing-rules] -->

## Benchmarks

What these rules buy you, measured on a seeded synthetic corpus (20 decks, 20 workbooks,
60 PDF-style pages, 380 quote trials). Each pipeline reads the same files:

- **Naive baseline**: what a quick RAG prototype does (text frames only, active sheet only,
  a fixed 1,000-char window, "is the number in the quote" check).
- **qaechi-parser 1.1**: the previous release's rules.
- **qaechi-parser 1.2**: the rules described above.

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/qaechi/qaechi-parser/main/docs/assets/benchmark-dark.png">
  <img alt="Benchmark chart: qaechi-parser 1.2 recovers 100% of PPTX text (naive 11%, 1.1 70%), reaches 100% of XLSX values (naive 34%), keeps 100% of tables whole (naive 22%), keeps 100% of chunks within budget (1.1 0%), matches 100% of genuine quotes (1.1 75%) and flags 100% of invented quotes (naive 0%), while sending 78% less XLSX text than 1.1." src="https://raw.githubusercontent.com/qaechi/qaechi-parser/main/docs/assets/benchmark.png">
</picture>

| Metric | Naive | v1.1 | **v1.2** |
|---|---:|---:|---:|
| PPTX text recovered (groups, tables, charts, notes) | 11% | 70% | **100%** |
| XLSX values reachable (all sheets, incl. hidden) | 34% | 100% | **100%** |
| XLSX text sent to the LLM (relative to 1.1) | 34%¹ | 100% | **22%** |
| Tables kept whole with their header | 22% | 100% | **100%** |
| Chunks within the 1,000-char budget | 100% | 0%² | **100%** |
| Genuine quotes matched despite formatting | 100% | 75% | **100%** |
| Invented quotes flagged (one digit changed) | 0% | 100% | **100%** |
| Tokens spent on a `ledger` file (parser route) | n/a | 0 | **0** |

¹ Smaller only because it reads one sheet of three. ² 1.1 kept any page with a table as one
chunk, prose included.

The corpus isolates one rule per metric; it is not a claim about any specific real-world
document set. Reproduce or extend it with:

```bash
pip install -e ".[parse,dev]" langchain-text-splitters matplotlib
python benchmarks/run.py   # writes benchmarks/results.json and docs/assets/benchmark*.png
```

## Write a parser plugin

A plugin reads one fixed layout and never calls an LLM.

```python
from qaechi.parser.registry import LayoutError, ParseInput, ParseOutput, register
from qaechi.parser.schemas import FieldValue, Provenance

@register("acme_invoice", doc_types={"invoice"}, extensions=(".xlsx",),
          source_kinds={"acme"}, version="1")
def parse(doc: ParseInput) -> ParseOutput:
    ...
    if header_not_found:
        raise LayoutError("not an ACME invoice")   # stop rather than misread
    return ParseOutput(fields={"invoice_no": FieldValue(
        value="A-001", confidence=1.0,
        provenance=Provenance(document_id=doc.document_id, page=1, quote="Invoice No. A-001"))})
```

Load it with `QAECHI_PLUGINS=my_package.acme`, or ship it as a package with an entry point:

```toml
[project.entry-points."qaechi.parsers"]
acme = "my_package.acme"
```

See [`examples/key_value_parser.py`](https://github.com/qaechi/qaechi-parser/blob/main/examples/key_value_parser.py) for a runnable one.

## HTTP API

```bash
pip install "qaechi-parser[parse,server] @ git+https://github.com/qaechi/qaechi-parser@qaechi-parser-v1.2.7"
cp .env.example .env            # sets QAECHI_INTERNAL_TOKEN and QAECHI_SOURCE_DIR
qaechi-parser serve                # 127.0.0.1:3100
```

| Method | Path | |
|---|---|---|
| `GET` | `/health` | status, engine, optional modules (no token) |
| `POST` | `/jobs` | queue a job, returns `202` right away |
| `GET` | `/jobs/{jobId}` | `queued` / `running` / `succeeded` / `failed` |
| `GET` | `/results?documentId=&limit=&offset=` | list results (`limit` 1 to 200) |
| `GET` | `/results/{id}` | full result with provenance |
| `GET` | `/parsers` | registered parsers |

```bash
curl -X POST http://127.0.0.1:3100/jobs \
  -H "X-Internal-Token: $QAECHI_INTERNAL_TOKEN" -H "Content-Type: application/json" \
  -d '{"documentId":"doc-1","source":"ledger.csv","docType":"ledger"}'
```

JSON is camelCase. Full contract: [`docs/api.md`](https://github.com/qaechi/qaechi-parser/blob/main/docs/api.md).

## Configuration

| Variable | Default | |
|---|---|---|
| `QAECHI_INTERNAL_TOKEN` | *(required for API)* | shared token for `X-Internal-Token` |
| `QAECHI_SOURCE_DIR` | | read sources from this directory |
| `QAECHI_SOURCE_URL` / `QAECHI_SOURCE_TOKEN` | | read sources from `{url}/{source}` with a bearer token |
| `OPENAI_API_KEY` | | enables the LLM route and grading |
| `QAECHI_LLM_MODEL` | `gpt-4o-mini` | |
| `QAECHI_RETRIEVE` / `QAECHI_REWRITE` | off | narrowing and one retry (they change results) |
| `QAECHI_PLUGINS` | | comma-separated modules to import |
| `QAECHI_PDF_PASSWORD` | | for encrypted PDFs |

All variables: [`.env.example`](https://github.com/qaechi/qaechi-parser/blob/main/.env.example).

## Install options

| Extra | Adds |
|---|---|
| *(none)* | the library: CSV/TXT, parser plugins, stub mode |
| `server` | the HTTP service (`qaechi-parser serve`): FastAPI, Uvicorn |
| `parse` | PDF, PPTX, XLSX, HTTP sources |
| `llm` | LLM extraction, grading, LangGraph |
| `otel` | OpenTelemetry metrics and traces ([Observability](https://qaechi.github.io/qaechi-parser/latest/observability/)) |
| `kafka` | queue mode: `qaechi-parser worker` and `POST /jobs` publishing to Kafka ([Queue mode](https://qaechi.github.io/qaechi-parser/latest/queue-mode/)) |
| `postgres` | PostgreSQL job and result store shared by the API and workers |
| `all` | all of the above |

Docker: `docker build -t qaechi-parser . && docker run -p 127.0.0.1:3100:3100 --env-file .env qaechi-parser`

## Roadmap

- [ ] Postgres / pgvector store
- [ ] More model providers
- [ ] OCR front end for scanned PDFs
- [ ] Evaluation harness with golden sets

Ideas and votes are welcome in [Discussions](https://github.com/qaechi/qaechi-parser/discussions).

## Contributing

Issues and PRs are welcome. Read [CONTRIBUTING.md](https://github.com/qaechi/qaechi-parser/blob/main/CONTRIBUTING.md) first; commits follow
[Conventional Commits](https://www.conventionalcommits.org/) so releases are automatic.
Security reports go through [SECURITY.md](https://github.com/qaechi/qaechi-parser/blob/main/SECURITY.md), not public issues.

## Contact

Questions, ideas and use-case reports: [GitHub Discussions](https://github.com/qaechi/qaechi-parser/discussions)
or email [ddaeyongee@gmail.com](mailto:ddaeyongee@gmail.com).
Bugs go to [Issues](https://github.com/qaechi/qaechi-parser/issues); security reports follow [SECURITY.md](https://github.com/qaechi/qaechi-parser/blob/main/SECURITY.md).

## Maintainer

**Taeyong Kang** ([@ddaeyongee](https://github.com/ddaeyongee)), Seoul, South Korea

Application Architect at **LG CNS** (2021 to present) and Founder of **CNTSOFT** (2026 to present),
previously at **POSCO DX**. 11+ years designing enterprise applications, focused on microservice
architecture and real-time, high-volume event streaming.

- **Microservice architecture:** application architect for a platform of about 200 microservices on
  Amazon EKS serving about 50,000 concurrent users; reusable MSA application standards adopted
  across banking, insurance and public-sector programs.
- **Event streaming:** Apache Kafka and Amazon MSK with the transactional outbox pattern and change
  data capture, with no message loss or duplication. Designed and built parallel processing
  (a swimlane dispatcher) in the open-source Eventuate CDC framework together with its original
  author, to meet production TPS targets.
- **Telemetry and observability:** Kafka-based log pipelines (Amazon MSK + ELK), CloudWatch,
  Prometheus and Grafana, VictoriaMetrics and Grafana Alloy.
- **AI document pipelines:** RAG and LLM structured output with LangGraph, the groundwork for this project.

This background shapes Qaechi's next modules: batch processing and event streaming for documents at scale.

## License

[Apache-2.0](https://github.com/qaechi/qaechi-parser/blob/main/LICENSE) © 2026 Taeyong Kang
