# Workshop Document: PDF redaction to templates

Issue: apiintl/apiconnect#28. A side project that lives in connect for now; every file it adds
is under a `workshop-doc` folder or uses the `workshopDoc` prefix, so it can move to its own repo.

A user uploads a filled-in PDF, marks the private parts in the browser, and saves the result as
a **template**: a PDF with that data taken out of the file (not just covered), plus a manifest
describing the fields. A later Workshop Document workflow reads the templates from
`cache/workshop-doc/templates/`.

## Pages and endpoints

| URL | What |
|---|---|
| `/<system>/workshop-doc/templates` | List of saved templates (also `/workshop-doc`) |
| `/<system>/workshop-doc/redact` | Upload a PDF and mark redactions |
| `/<system>/workshop-doc/template/<id>` | Read-only view of one template with its fields outlined |
| `do/workshopDocUpload` | Store an upload in a working folder, run `ocr.py`, return pages and word boxes |
| `do/workshopDocWorkGet?work_id=` | Stream the working PDF (uploader only) |
| `do/workshopDocWorkDiscard` | Delete a working folder (uploader only) |
| `do/workshopDocSave` | Run `redact.py`, write the template and manifest, delete the working folder |
| `do/workshopDocTemplatesList` | All manifests |
| `do/workshopDocTemplateGet?id=[&part=pdf]` | One manifest, or the template PDF |

Every page and endpoint checks the session. Set `WORKSHOP_DOC_PERM` in `.env` (for example
`Connect.WorkshopDoc`) to require a permission as well; by default any signed-in user of the
system has access.

## Files

```
code/workshop-doc/config.php           settings, overridable from .env
code/workshop-doc/functions.inc.php    helpers for the pages and endpoints
pages/workshop-doc/                    templates-list.php, template-view.php, redact.php
backend/workshopDoc*.php               endpoints (a prefix: /do/ uses basename(), so no subfolder)
web/ui/workshop-doc/                   pdf-pages.js, redact.js, found-values.js, template-view.js, workshop-doc.css
scripts/workshop-doc/                  ocr.py, redact.py, wdlib.py, test_redact.py, cleanup-work.php
cache/workshop-doc/work/<work_id>/     source.pdf, work.json (while an upload is being edited)
cache/workshop-doc/templates/<id>/     template.pdf, manifest.json
```

The route entries are one block in `code/route.inc.php`, and PDF.js is the `pdfjs-dist`
dependency in `web/package.json`.

## Server setup (Ubuntu)

```sh
sudo apt install python3-venv python3-pip tesseract-ocr tesseract-ocr-eng poppler-utils

cd /var/www/connect
python3 -m venv scripts/workshop-doc/.venv
scripts/workshop-doc/.venv/bin/pip install -r scripts/workshop-doc/requirements.txt
(cd web && npm install)                      # pulls in pdfjs-dist

# Check it: needs Tesseract for the scanned pages and pdftotext for an independent check.
scripts/workshop-doc/.venv/bin/python scripts/workshop-doc/test_redact.py
```

`poppler-utils` is only needed by the test. The web server must be able to write
`cache/workshop-doc/` (it's created on first use with mode 0770) and run the venv's Python.

PDF.js is loaded as ES modules (`.mjs`). Apache on Ubuntu serves `.mjs` as JavaScript through
`/etc/mime.types`; if the browser console reports a MIME type error for `pdf.min.mjs`, add
`AddType text/javascript .mjs` to the site config.

Settings (`.env`, all optional):

| Variable | Default |
|---|---|
| `WORKSHOP_DOC_PERM` | empty: any signed-in user |
| `WORKSHOP_DOC_PYTHON` | `scripts/workshop-doc/.venv/bin/python` if present, else `python3` |
| `WORKSHOP_DOC_TESSDATA` | found automatically (`/usr/share/tesseract-ocr/*/tessdata`, Homebrew) |
| `WORKSHOP_DOC_WORK_MAX_AGE_HOURS` | `4` |

### Cron

Uploads that are never saved or discarded leave the original PDF on the server. Delete them:

```
*/30 * * * * cd /var/www/connect && php scripts/workshop-doc/cleanup-work.php > /dev/null
```

`--dry-run` lists what it would delete.

## Found values

On a long document, clicking every value is slow and easy to get wrong, so the redact page lists
what's in it under **Found in the document** (`found-values.js`, all in the browser):

- Each page's words are put into rows by position, and a row is split into segments at wide gaps
  and at leader dots. Text that runs into leader dots is the report's own label and isn't listed.
- A segment with a colon is split into label and value (`RO Number : 788821`); a lone `Label :`
  labels the next segment. An unlabeled segment of more than four words is running text, so its
  words are listed one by one.
- Values are grouped by their text, ignoring case and punctuation. A value seen only on scanned
  pages that is one character off another (two for values of ten or more) is folded into it as
  *similar*, so an OCR misread of a VIN isn't left behind.
- Groups under the same label are one entry. Entries are listed labeled first, then values with
  digits, then other text (collapsed), each by number of pages.

Clicking an entry outlines every place it appears; **Redact** makes one field covering all of
them and anywhere else the same words appear, replaced on text pages and removed on scanned
pages (or removed everywhere in Remove area mode). A field can then mix modes per part, so
`parts[].mode` overrides the field's mode in the page and in the payload sent to save.

## How redaction works

`ocr.py` decides per page whether it's **digital** (it draws visible text) or **flat** (a scan or
image; a scan's invisible OCR layer doesn't count). Flat pages are OCR'd with Tesseract unless
they already carry a text layer. It returns every word's box.

`redact.py` then, for each page:

- **remove** (rectangles; the only mode on flat pages): text, image pixels and fully covered
  vector art under the rectangle are removed, and the area is filled black.
- **replace** (digital pages): the characters under the selected words are removed from the
  content stream and the replacement is drawn on the same baseline, in the closest base-14 font
  (Helvetica, Times or Courier, with bold and italic) at the same size and color, shrunk if it
  doesn't fit. A value that wraps is shared across its lines. Only a thin band through the
  middle of each line is redacted, because MuPDF drops every glyph a redaction rectangle touches
  and full word boxes would clip the lines above and below.

Afterwards it deletes annotations, links, form fields, attachments, bookmarks, JavaScript,
metadata, XMP and hidden text, and saves with garbage collection so no unused objects survive.

Finally it reopens the output and looks for every original value (taken from the source PDF, not
from the browser) in the text layer, in an OCR of the flat pages, and in the raw objects. If one
is still there, for example a name that also appears unredacted on another page, the output is
deleted, the save fails, and the page flags the fields to fix. Words with no letter or digit
(OCR of dotted leaders) are ignored, values with fewer than three letters and digits aren't
checked, and neither is a value that is part of some replacement.

The browser never sends original values to the server, and the server never logs or stores them.
Script errors are reported by type only.

## Manifest

```json
{
  "id": "32 hex characters",
  "source_name": "original-filename.pdf",
  "created_by": 123,
  "created_by_name": "First Last",
  "created_at": "2026-10-14T12:00:00Z",
  "pages": 3,
  "page_sizes": [[612, 792], [612, 792], [792, 612]],
  "fields": [
    { "page": 1, "mode": "replace", "bbox": [x0, y0, x1, y1], "field": "Customer name", "shape": "First Last", "replacement": "Jane Doe" },
    { "page": 2, "mode": "remove",  "bbox": [x0, y0, x1, y1], "field": "SSN", "shape": "###-##-####" }
  ]
}
```

Boxes are in PDF points with the origin at the top-left of the page **as displayed** (crop box,
after any `/Rotate`), y pointing down, which is what PDF.js gives at scale 1. `page_sizes` are
the displayed page sizes in the same units. A replace field's `bbox` is the union of its words,
so for a value that wraps it spans both lines. `shape` may be empty.

## Limitations

- Replacement text uses a base-14 font, not the document's own (embedded fonts are usually
  subsets that lack the new glyphs). Unusual fonts will look a little different.
- Replace mode only handles text set at right angles; skewed text should use a rectangle.
- Content on optional-content layers that are switched off isn't shown in the browser, so it
  can't be marked.
- `source_name` is the uploaded filename, which may itself contain private data.
