Metadata-Version: 2.5
Name: unpdf-tool
Version: 1.1.0
Summary: Read PDFs into a SQLite database using profiles drawn in a local browser editor.
Project-URL: Repository, https://github.com/mohammedbaqadir/unpdf
Project-URL: Issues, https://github.com/mohammedbaqadir/unpdf/issues
Author: Mohammed
License: Copyright (c) 2026 Mohammed. All rights reserved.
        
        unpdf is proprietary software. You may not copy, modify, merge, publish,
        distribute, sublicense, or sell copies of this software, in whole or in part,
        without the copyright holder's prior written permission.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHOR OR COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Keywords: extraction,pdf,profiles,sqlite
Classifier: Environment :: Console
Classifier: License :: Other/Proprietary License
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Requires-Python: >=3.12
Requires-Dist: pdfplumber
Requires-Dist: pillow
Requires-Dist: pypdfium2
Provides-Extra: suggest
Requires-Dist: openai; extra == 'suggest'
Description-Content-Type: text/markdown

# unpdf

One tool, ten verb commands: `identify` says which profile a PDF matches,
`extract` reads PDFs into SQLite using those profiles, `check` re-validates a
database, `edit` draws profiles in your browser, plus `import`/`export`/`list`/
`path`/`migrate`/`help`.

Extraction runs on your machine and never calls a model. The only network call
in the tool is the optional **Suggest boxes** button in the editor, which sends
one page image to DeepSeek. There is no OCR anywhere: a PDF without a text layer
is refused.

A profile is a JSON file that describes one kind of PDF: its page count, page
size, the label anchors that prove it's the right form, and the box for each
field. You pick one by name, by family, or let the identifier pick it. The
extractor never takes a path to a profile.

- Your PDFs stay on your machine. The editor never writes a PDF or a page image
  to disk; the only file it writes is `profile.json`.
- The editor imports the engine; the engine never imports the editor.

## Install

```powershell
uv tool install unpdf-tool
```

You need Python 3.12 or newer. Nothing else: no Tesseract, no browser build step,
no npm, no CDN. The built editor UI ships with the package.

For development, clone and install editable:

```powershell
git clone https://github.com/mohammedbaqadir/unpdf
cd unpdf
uv tool install --editable .
```

## Quick start

Make a profile from one or more sample PDFs of the same form:

```powershell
unpdf edit invoice C:\samples\invoice.pdf
```

The editor opens in your browser. Draw an **anchor** around a label every
invoice has, draw a **field** around a value, and name it. Then click **Publish**.
Use a sample you won't run on.

Then use it:

```powershell
unpdf identify C:\docs
unpdf extract --type invoice C:\docs
unpdf check --type invoice C:\docs
```

`run` reads every `*.pdf` in the folder, extracts the fields the profile
describes, and writes the database. `check` re-runs the field rules on a
database you already have without opening the PDFs.

To handle a family of profiles at once, use `--family` instead of `--type`:

```powershell
unpdf extract --family invoice C:\docs
unpdf check --family invoice C:\docs
```

## What you get

```text
<name>.db     A --type run writes <name>.db; a --family run writes <family>.db
documents.db  A run with no --type or --family
.unpdf/       The profile snapshot, extraction evidence, and quarantine records
```

Both are created next to the database, which defaults to the PDF folder. Use
`--db` and `--work` to move them. Your PDFs are never moved or changed.

### What `.unpdf/` holds

Every run writes `.unpdf/` next to the database: a profile snapshot (`profiles/<name>.json`,
the definition you approved — no personal data), the words from every accepted document
(`documents/<stem>--<hash>_words.json`), the extracted values
(`documents/<stem>--<hash>_fields.json`), and quarantine records
(`quarantine/<stem>--<hash>.json`). **The files are plaintext: they contain the full text of your
documents and every extracted value (IDs, names, numbers). Nothing is encrypted and nothing is
pruned automatically.**

`.unpdf/` is an audit trail. The tool never reads it. Delete it at any time:

```powershell
Remove-Item .unpdf -Recurse
```

If the documents are sensitive, point `--work` at a private volume. Filenames carry the content
hash, so two files with the same stem never overwrite each other.

The database has:

- `docs`: one row per document.
- `extracted_fields`: one row per field *with a value* — raw `value` plus `kind`,
  `value_num` (numbers), and `value_date` (ISO dates). Fields with no value have
  no row here and appear only in `_field_status`.
- `_field_status`: the status of every field on every document.
- `quarantine`: the PDFs that were rejected.
- `_meta`: one row per key, e.g. `tool_version` and each profile's `fingerprint`.
- `review`: a view of every flagged field.
- `profile_<name>`: one view per profile — columns `doc_id`, `file`, `added_at`
  plus one column per field, typed by kind. Rebuilt on every `run` and `check`.

```sql
SELECT file, reference, total, issue_date FROM profile_invoice WHERE total > 1000;
```

The database format version is `PRAGMA user_version` (5). A version-4 database is
migrated automatically; a legacy pre-`user_version` database is seeded from
`_meta['schema_version']` if present, otherwise as version 4 if it has a `docs`
table (a legacy value of `3` is refused); a database created by a newer extractor
is refused.

## Commands

### Identify

`unpdf identify [path]` checks one PDF, or every top-level `*.pdf` in a folder,
against every approved profile on this machine. It writes nothing.

```powershell
unpdf identify C:\docs
```

```text
identify  a.pdf: fasah-import
identify  b.pdf: none (no profile subtype matched)
identify  c.pdf: ambiguous (matched more than one profile: fasah-import, fasah-export)
identify: 1 matched, 1 none, 1 ambiguous, 0 unreadable
```

Exit code 0 means every PDF matched exactly one profile, 4 means at least one did
not, and 3 means a profile couldn't be loaded or a PDF couldn't be read. If both
happen, 3 wins.

It only sees approved profiles already in `Documents\unpdf\profiles`.

### Extract and check

| Command | What it does |
| ------- | ------------ |
| `extract [folder]` | Read every PDF in the folder into the database |
| `check [folder]` | Re-check a database you already have; opens no PDFs |

Options for `run` and `check`:

| Option | What it does |
| ------ | ------------ |
| `folder` | The folder with the PDFs. Defaults to the current folder |
| `--type NAME` | Use one profile |
| `--family NAME` | Send each PDF to the family member that matches it |
| `--db PATH` | The database file. Defaults to `<name>.db` in the PDF folder. An automatic run writes `documents.db` |
| `--work PATH` | Where the evidence goes. `run` only. Defaults to `.unpdf` next to the database |
| `--no-color` | Plain text output |

`--type` and `--family` are alternatives. If you give neither, the identifier
tries every approved profile and only saves a PDF when exactly one fits.

#### Automatic runs

A run with no `--type` or `--family` uses every approved profile on the machine.
For each PDF it checks each profile's contract:

- exactly one fits: the PDF is extracted with that profile.
- none fits: the PDF is quarantined with `no profile subtype matched`.
- more than one fits: the PDF is quarantined as ambiguous, so tighten the boxes
  that identify the form.

Use `unpdf identify C:\docs` to see the same decision before writing anything.

#### Family runs

The extractor reads each PDF once, then tries every family member's contract and
`match` rule to find the right one. Profile selection never uses file names; file
stems are only checked for duplicates, which fails with exit code 1. A family
needs at least two approved members.

### Edit

```powershell
unpdf edit NAME PDF [PDF ...]
```

The editor:

- reads each sample PDF and keeps its words in memory;
- starts a server on `127.0.0.1` on a free port and opens the page;
- lets you draw anchor boxes over labels, and field boxes over values;
- names each field, picks its kind, and marks the ones that must always exist;
- previews every sample with the same extraction code the extractor uses;
- saves your work automatically to `profiles/NAME/draft.json` as you edit;
- rewrites `profiles/NAME/profile.json` only when you click **Publish**.

The suggestion button is optional. It sends one page image to DeepSeek and comes
back with boxes you can move or delete. Nothing is sent unless you click it, and
it needs `DEEPSEEK_API_KEY` plus `uv sync --extra suggest`. One click, one page,
nothing written to disk.

The editor refuses a scanned PDF: with no text layer there is nothing to read.
The samples must all have the same page count. The server listens only on this
machine while the editor is open; **Close** stops it.

#### Drafts and publishing

- **draft.json** is your working copy. It is saved automatically, it is
  gitignored, and the extractor never reads it.
- **profile.json** is the approved file the extractor reads. It changes only
  when you click **Publish**, and it must load before you can.
- A required field must have a value in every sample before you can publish.
- A profile has no version. Edit it and publish again: the new content replaces
  the old profile in place. Publishing identical content writes nothing.
  If the PDF form itself changes, make a **different profile** with a different
  name — a changed form is a different form, not a new version.
- The editor keeps a `draft.conflict-*.json` copy instead of overwriting a discarded draft.

### Help

Help works offline. `unpdf help` shows the overview, `unpdf help identify` or
`unpdf help extract` explains one command, `unpdf help all` prints every
page, and there's one page per profile. `unpdf COMMAND --help` works the same as
`unpdf help COMMAND`. The topics are `profiles`, `extraction`, `review`,
`contract`, `quarantine`, and `exit-codes`.

## Profiles

A profile lives at `Documents\unpdf\profiles\NAME\profile.json` (POSIX:
`~/Documents/unpdf/profiles/NAME/profile.json`). That is the one fixed folder the tool
reads and writes — there is no path flag. A name starts with a letter
and uses only lowercase letters, digits, and hyphens. The repository ships no profiles:
make your own with `unpdf edit`, or copy yours into that folder. Only approved
profiles work. Naming an unapproved one with `--type` exits with
code 4; an automatic run skips it.

Field names must be lowercase snake_case (`^[a-z][a-z0-9_]*$`) and can't be
`doc_id`, `file`, `format`, or `added_at` — they become view columns. `family`
must match `^[a-z][a-z0-9-]*$`; `match.field` must name a declared field and
`match.contains_any` needs at least one value. The extractor accepts
`schema_version` 1 to 4; versions 1–4 share the same shape, so older files load
without rewriting. Unknown keys are ignored when *loading* a supported
profile (schema_version 1-4) and rejected when a profile is *approved*.

### Fallback boxes

A field can have an optional `fallback_box` next to its `box`. The extractor
reads it only when the first box finds no value. That covers forms that leave a
labelled row blank and print the value one row lower. The stored `bbox` is always
the box that produced the value, so the evidence points at the words that were
actually read.

### Modes

A field's `mode` decides how much of its box becomes the value:

- `line` keeps the longest line.
- `multi` joins every line.

If a value wraps onto a second line, use `multi` and a box tall enough for both
lines. With `line`, the second line is dropped without any warning.

## Results

Every field ends up with one of three statuses:

```text
accepted   present, and passed its check
review     present but failed a check, or a required field is empty
missing    absent: optional, or genuinely blank
```

`value_num` holds the numeric reading of `number`/`integer` fields and
`value_date` the ISO date of `date` fields; both are NULL for text/digits and for
values that failed their check. The raw value is always kept in `value`.

If a PDF fails the contract check, it's quarantined with a reason, and the rest
of the batch keeps going.

Each run ends with a summary:

```text
run: 3 added, 1 skipped, 0 failed
database: 4 document(s) | 57 accepted, 2 review, 5 missing (optional)

review queue:
  invoice.pdf | number | not a number
```

`skipped` counts PDFs that are already in the database, and the same content
showing up twice in one batch. `missing` fields are optional. A blank required
field goes to review.

## Exit codes

Extractor and identify commands:

| Code | Meaning |
| ---- | ------- |
| 0 | Clean: nothing failed, nothing quarantined, nothing in review |
| 1 | Nothing to do, or a usage or setup mistake |
| 2 | Review needed: at least one field needs review |
| 3 | A profile or PDF couldn't be read, or a database is too new |
| 4 | A PDF was quarantined, the profile isn't approved, or `identify` found no single match |

If more than one applies, 3 wins over 4, and 4 wins over 2. Documents that passed
are still saved. `identify` never returns 2; it uses 0, 1, 3, and 4.
`unpdf help exit-codes` shows the same table offline.

Profiler commands:

| Code | Meaning |
| ---- | ------- |
| 0 | Success |
| 1 | Usage, missing input, or configuration |
| 2 | An invalid profile name |
| 3 | A sample or profile couldn't be read |

Parse errors exit 1 for every command.

### Messages

| Message | Code | What to do first |
| ------- | ---- | ---------------- |
| `Unknown profile 'x'.` | 1 | Check the name; approved profiles in `Documents\unpdf\profiles` are used |
| `No PDFs in ...` | 1 | Point the command at the folder that holds the PDFs |
| `Folder not found: ...` | 1 | Fix the path. Nothing was read |
| `No database at ...` | 1 | `check` needs a database from an earlier `run` |
| `file is not a database` | 1 | Replace or remove that database file, or point `--db` at the right one |
| `No approved profiles found...` | 1 | Add a profile to `profiles/` |
| `Family 'x' has N approved profile(s)...` | 1 | Approve the missing members |
| `Duplicate PDF file names in ...` | 1 | Rename the files. Nothing was read |
| `Profile 'x' is not approved.` | 4 | Approve it, or pick a different profile |
| `Profile is empty or unreadable: ...` | 3 | Fix or remove that profile's `profile.json` |
| `This database was created by a newer extractor…` | 3 | Update the extractor |
| `Profile schema version … needs a newer extractor` | 3 | Update the extractor |
| `Profile field '<name>' …` (bad name or reserved) | 3 | Fix the field name and re-approve |
| `quarantine <file>: expected N page(s), found M` | 4 | The folder and the profile disagree about the form |
| `quarantine <file>: no profile subtype matched` | 4 | No profile describes this document |
| `quarantine <file>: matched more than one profile` | 4 | Tighten the boxes that identify the form |
| `identify <file>: none (...)` | 4 | No profile describes this document |
| `identify <file>: ambiguous (...)` | 4 | More than one profile fits |
| `no text layer` | 3 | The editor needs a text layer; there is no OCR |
| `quarantine <file>: no text layer` | 4 | Extraction found no words to read; the file is set aside |

## Setup

`uv sync` installs the engine. The suggestion button also needs the optional
package and a key:

    uv sync --extra suggest
    $env:DEEPSEEK_API_KEY = "..."

No `.env` file is loaded. Nothing is sent to a model unless you click **Suggest**.

### Environment variables

| Name | Used by | What it does |
| ---- | ------- | ------------ |
| `DEEPSEEK_API_KEY` | Profiler | API key for the suggestion button |
| `UNPDF_DEEPSEEK_MODEL` | Profiler | Model id. Default `deepseek-flash` |
| `UNPDF_DEEPSEEK_MAX_TOKENS` | Profiler | Reply size limit. Default `8192` |
| `NO_COLOR` | Both | Plain text output, same as `--no-color` |

There's no registry, no token, and no cache to configure: a profile is a file you
keep.

### Common problems

| Symptom | What to do first |
| ------- | ---------------- |
| `no text layer` | The PDF is scanned. There is no OCR; use a PDF with real text |
| A sample doesn't match in the editor | The anchor box or its tokens are wrong; redraw them |
| A field is cut in half | Make the box taller and use `mode: multi` |

## Tests

End users never need Bun (the built UI ships in the wheel). Contributors do, for the UI suite:

```powershell
uv run python -m unittest discover -s tests -v
uvx ruff@0.17.2 check --select E9,F src tests tools
cd ui
bun run test
bun run check
```

```powershell
cd ui
bun run test
bun run check
```
