Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions .github/workflows/frontend-ui.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,19 @@ on:
paths:
- "web/**"
- "package.json"
- "tests/*.test.js"
- "tests/web/**"
- "Launch PDF Magic.command"
- "serve.py"
- "tests/server.py"
- ".github/workflows/frontend-ui.yml"
pull_request:
paths:
- "web/**"
- "package.json"
- "tests/*.test.js"
- "tests/web/**"
- "Launch PDF Magic.command"
- "serve.py"
- "tests/server.py"
- ".github/workflows/frontend-ui.yml"

jobs:
Expand All @@ -30,4 +32,4 @@ jobs:
- name: Run frontend unit tests and validate the Mac launcher
run: npm test
- name: Test local file upload server
run: python3 -m unittest discover -s tests -p 'test_local_server.py' -v
run: python3 tests/server.py -v
19 changes: 8 additions & 11 deletions .github/workflows/pdf-regressions.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,11 @@ on:
branches: [snails]
pull_request:
paths:
- "pdf_metadata.py"
- "tag-ocr-pdf.py"
- "ocr-scanned-pdf.sh"
- "compress-and-tag-ocr-pdf.sh"
- "setup-python-env.sh"
- "tests/test_ocr_shell_startup.py"
- "tests/test_pdf_metadata.py"
- "tests/test_tag_existing_text.py"
- "ocr/**"
- "compression/**"
- "setup/**"
- "tests/ocr/**"
- "pytest.ini"
- ".github/workflows/pdf-regressions.yml"

jobs:
Expand All @@ -24,8 +21,8 @@ jobs:
with:
python-version: "3.12"
- name: Install regression dependencies
run: python -m pip install pikepdf pdfminer.six
run: python -m pip install pikepdf pdfminer.six pytest
- name: Run OCR shell startup regression
run: bash -n ocr-scanned-pdf.sh && bash -n compress-and-tag-ocr-pdf.sh && bash -n setup-python-env.sh && python -m unittest discover -s tests -p 'test_ocr_shell_startup.py' -v
run: bash -n ocr/scan.sh && bash -n compression/tagged.sh && bash -n setup/python.sh && python -m pytest -v tests/ocr/shell-startup.py
- name: Run metadata and tagged PDF tests
run: python -m unittest discover -s tests -p 'test_pdf_metadata.py' -v && python -m unittest discover -s tests -p 'test_tag_existing_text.py' -v
run: python -m pytest -v tests/ocr/metadata.py tests/ocr/existing-text.py tests/ocr/dates.py tests/ocr/punctuation.py tests/ocr/order.py
22 changes: 11 additions & 11 deletions OCR.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,18 @@ compressed derivatives of scanned PDFs without replacing the source.
Install the Enhancer's isolated Python dependencies once:

```sh
./setup-python-env.sh
./setup/python.sh
```

This creates `.venv/` beside the Enhancer scripts with `pikepdf` and Pillow.
This creates `.venv/` at the repository root with `pikepdf` and Pillow.
The OCR and compression scripts prefer `.venv/bin/python` for tagging, local AI
review, and metadata helpers. Existing standalone installations without this
environment can still use Python with the required packages, including the
interpreter bundled with OCRmyPDF. An incomplete project venv produces an error
instead of silently using an unrelated global interpreter.

The browser viewer's native-host installer also initializes this environment
when an Enhancer checkout supplies `setup-python-env.sh`. OCRmyPDF and qpdf
when an Enhancer checkout supplies `setup/python.sh`. OCRmyPDF and qpdf
remain separate system executables, typically installed using Homebrew.

## Create searchable OCR
Expand All @@ -28,14 +28,14 @@ Run the OCR, paragraph grouping, table-block classification, and heading
tagging without replacing the source:

```sh
./ocr-scanned-pdf.sh SOURCE.pdf NEW-OCR.pdf
./ocr/scan.sh SOURCE.pdf NEW-OCR.pdf
```

To rebuild every page's text, including pages with existing OCR or digital text,
and apply the local AI review in one run:

```sh
./ocr-scanned-pdf.sh SOURCE.pdf NEW-AI-OCR.pdf --force-ocr --ai-review
./ocr/scan.sh SOURCE.pdf NEW-AI-OCR.pdf --force-ocr --ai-review
```

To use different locally installed Ollama models for the two stages, add
Expand All @@ -54,7 +54,7 @@ not reused from the viewer's enhancement cache.
Optionally add or override descriptive metadata while enhancing:

```sh
./ocr-scanned-pdf.sh SOURCE.pdf NEW-OCR.pdf \
./ocr/scan.sh SOURCE.pdf NEW-OCR.pdf \
--title "Example Title" \
--description "A summary of the document" \
--tags "finance, investing" \
Expand Down Expand Up @@ -84,7 +84,7 @@ bookmarks use the AI-reviewed heading text and levels when AI review is enabled.
To rebuild paragraph copy text in an already tagged PDF, use:

```sh
python3 tag-ocr-pdf.py TAGGED.pdf RETAGGED.pdf --retag
python3 ocr/tag.py TAGGED.pdf RETAGGED.pdf --retag
```

This replaces text structure tags and paragraph `/ActualText`, preserves existing
Expand All @@ -97,7 +97,7 @@ Create a new losslessly optimized derivative, then apply the same structure
tags:

```sh
./compress-and-tag-ocr-pdf.sh EXISTING-OCR.pdf NEW-COMPACT.pdf
./compression/tagged.sh EXISTING-OCR.pdf NEW-COMPACT.pdf
```

The source is never edited. A compression report records byte counts and the
Expand All @@ -114,7 +114,7 @@ image encoding.
Install the two Ollama models selected for a 48 GB Apple Silicon Mac:

```sh
./setup-ollama-ocr.sh
./setup/ollama.sh
```

Setup also creates `sec-ocr-review`, a local custom model that embeds the
Expand All @@ -124,7 +124,7 @@ Review all page images and initial blocks. The output is JSONL so an interrupted
long run can resume without losing completed pages:

```sh
./ollama-review-ocr.py \
./ocr/review.py \
INITIAL-TAGGED.pdf \
INITIAL-TAGGED.tagging.json \
REVIEW-v1.jsonl
Expand All @@ -136,7 +136,7 @@ Resume an interrupted review with `--resume`. Test a page range first with
Apply the review while creating another new compressed version:

```sh
./compress-and-tag-ocr-pdf.sh \
./compression/tagged.sh \
EXISTING-UNTAGGED-OCR.pdf \
NEW-AI-REVIEWED-COMPACT.pdf \
REVIEW-v1.jsonl
Expand Down
28 changes: 20 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,23 @@ Light mode** button in the top-right corner to override it; the preference is
saved in your browser. The interface still only **builds commands**. It does not
run book exports or PDF enhancement jobs itself.

Run the frontend tests with `npm test`.
Run the frontend tests with `npm test`. Run the Python regressions with
`python3 -m pytest` after installing pytest and the relevant tool dependencies.

## Repository layout

Run CLI commands from the repository root. Source files are grouped by feature:

- `export/` — book capture and PDF assembly.
- `ocr/` — text recognition, tagging, metadata, reading order, and AI review.
- `compression/` — lossless image compression and combined tagging.
- `download/` — public comment downloads.
- `setup/` — local Python and Ollama setup.
- `tests/` — regressions grouped by feature and web UI.

## Google Play Books export

`export-google-book.py` captures the visible pages available through a Google
`export/google.py` captures the visible pages available through a Google
Play Books reader session and combines them into a PDF. It uses a persistent
browser profile so the user can sign in and retain reader access.

Expand All @@ -58,7 +70,7 @@ python3 -m playwright install chromium
Export a volume by its Google Books ID:

```sh
python3 export-google-book.py BOOK_ID
python3 export/google.py BOOK_ID
```

By default, captures are written to `BOOK_ID-pages/` and the combined document
Expand All @@ -68,13 +80,13 @@ assembly.

## Internet Archive export

`export-archive-book.py` captures individual scans from Internet Archive's
`export/archive.py` captures individual scans from Internet Archive's
BookReader, including books opened in two-page mode. It accepts an item ID or
the full details URL and uses the same `img2pdf` and Playwright dependencies
listed above.

```sh
python3 export-archive-book.py https://archive.org/details/transformationof00seli/mode/2up
python3 export/archive.py https://archive.org/details/transformationof00seli/mode/2up
```

Playwright opens a visible Chromium browser window. The exporter pauses and
Expand Down Expand Up @@ -124,21 +136,21 @@ Subject, and Keywords map to XMP `dc:title`, `dc:description`, and
identifier are mapped into Dublin Core XMP, and language also sets PDF `/Lang`.
The web toolbench offers editable metadata fields.

Pass `--source-url URL` to `ocr-scanned-pdf.sh` to store the original document
Pass `--source-url URL` to `ocr/scan.sh` to store the original document
URL in the XMP `pdfmagic:href` property. Existing original URLs are retained
when processing an enhanced local copy again.

## SEC concept-release comment references

`download-sec-comments.py` downloads the PDF and raw HTML submissions listed
`download/sec-comments.py` downloads the PDF and raw HTML submissions listed
for an SEC file number. Public-comment PDFs, raw HTML comments, and meeting
memoranda are stored in separate directories.

Set an identifying SEC User-Agent locally and provide the file number:

```sh
export SEC_USER_AGENT='Your Name [email protected]'
python3 download-sec-comments.py S7-27-15
python3 download/sec-comments.py S7-27-15
```

If `SEC_USER_AGENT` is unset, the tool prompts for it in an interactive shell.
Expand Down
File renamed without changes.
13 changes: 7 additions & 6 deletions compress-and-tag-ocr-pdf.sh → compression/tagged.sh
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
set -euo pipefail

if [[ $# -lt 2 ]]; then
printf 'Usage: ./compress-and-tag-ocr-pdf.sh INPUT.pdf OUTPUT.pdf [REVIEW.jsonl] [metadata options]\n' >&2
printf 'Usage: ./compression/tagged.sh INPUT.pdf OUTPUT.pdf [REVIEW.jsonl] [metadata options]\n' >&2
exit 2
fi

Expand Down Expand Up @@ -33,6 +33,7 @@ output_stem=${output%.*}
compression_report="$output_stem.compression.json"
tagging_report="$output_stem.tagging.json"
script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
repo_dir=$(CDPATH= cd -- "$script_dir/.." && pwd)

if [[ ! -f "$input" ]]; then
printf 'Input PDF not found: %s\n' "$input" >&2
Expand All @@ -53,11 +54,11 @@ for command_name in ocrmypdf qpdf; do
fi
done

venv_python="$script_dir/.venv/bin/python"
venv_python="$repo_dir/.venv/bin/python"
if [[ -e "$venv_python" || -L "$venv_python" ]]; then
if [[ ! -x "$venv_python" ]] || ! "$venv_python" -c 'import pikepdf, PIL' >/dev/null 2>&1; then
printf 'PDF Enhancer virtual environment needs repair: %s\n' "$venv_python" >&2
printf 'Run %s/setup-python-env.sh to install its dependencies.\n' "$script_dir" >&2
printf 'Run %s/setup/python.sh to install its dependencies.\n' "$repo_dir" >&2
exit 1
fi
tagger_python=("$venv_python")
Expand All @@ -73,7 +74,7 @@ else
fi
if (( ${#tagger_python[@]} == 0 )) || \
! "${tagger_python[@]}" -c 'import pikepdf, PIL' >/dev/null 2>&1; then
printf 'No Python with pikepdf/Pillow found; run %s/setup-python-env.sh.\n' "$script_dir" >&2
printf 'No Python with pikepdf/Pillow found; run %s/setup/python.sh.\n' "$repo_dir" >&2
exit 1
fi
fi
Expand All @@ -82,7 +83,7 @@ work_dir=$(mktemp -d "${TMPDIR:-/tmp}/compress-tag-pdf.XXXXXX")
trap 'rm -rf -- "$work_dir"' EXIT
compressed="$work_dir/compressed.pdf"

"${tagger_python[@]}" "$script_dir/compress-pdf-images.py" \
"${tagger_python[@]}" "$script_dir/images.py" \
"$input" "$compressed" \
--report "$compression_report" \
--reported-output "$output"
Expand All @@ -101,7 +102,7 @@ if [[ -n "$review" ]]; then
fi
tagger_args+=(--review "$review")
fi
"${tagger_python[@]}" "$script_dir/tag-ocr-pdf.py" "${tagger_args[@]}"
"${tagger_python[@]}" "$repo_dir/ocr/tag.py" "${tagger_args[@]}"

qpdf --check "$output"
input_pages=$(qpdf --show-npages "$input")
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
5 changes: 4 additions & 1 deletion ollama-review-ocr.py → ocr/review.py
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,17 @@
import os
import re
import subprocess
import sys
import tempfile
import time
import urllib.error
import urllib.request
from collections import defaultdict
from pathlib import Path

from ocr_punctuation import tilde_candidates
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from ocr.punctuation import tilde_candidates


DEFAULT_REVIEW_MODEL = "sec-ocr-review:latest"
Expand Down
13 changes: 7 additions & 6 deletions ocr-scanned-pdf.sh → ocr/scan.sh
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ set -euo pipefail

usage() {
cat <<'EOF'
Usage: ./ocr-scanned-pdf.sh INPUT.pdf [OUTPUT.pdf] [--skip-text|--force-ocr] [--ai-review] [--extract-model MODEL] [--review-model MODEL] [metadata options]
Usage: ./ocr/scan.sh INPUT.pdf [OUTPUT.pdf] [--skip-text|--force-ocr] [--ai-review] [--extract-model MODEL] [--review-model MODEL] [metadata options]

Create a searchable, tagged PDF from an English-language scanned PDF. If
OUTPUT.pdf is omitted, the output is written beside the input as
Expand Down Expand Up @@ -112,7 +112,8 @@ if "$ai_review" && [[ -e "$review_report" ]]; then
fi

script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
tagger="$script_dir/tag-ocr-pdf.py"
repo_dir=$(CDPATH= cd -- "$script_dir/.." && pwd)
tagger="$script_dir/tag.py"

if [[ ! -f "$tagger" ]]; then
printf 'PDF tagging script not found: %s\n' "$tagger" >&2
Expand All @@ -129,11 +130,11 @@ done

# Prefer the Enhancer's own isolated Python dependencies when installed.
# Keep the prior interpreter discovery for existing standalone installations.
venv_python="$script_dir/.venv/bin/python"
venv_python="$repo_dir/.venv/bin/python"
if [[ -e "$venv_python" || -L "$venv_python" ]]; then
if [[ ! -x "$venv_python" ]] || ! "$venv_python" -c 'import pikepdf' >/dev/null 2>&1; then
printf 'PDF Enhancer virtual environment needs repair: %s\n' "$venv_python" >&2
printf 'Run %s/setup-python-env.sh to install its dependencies.\n' "$script_dir" >&2
printf 'Run %s/setup/python.sh to install its dependencies.\n' "$repo_dir" >&2
exit 1
fi
tagger_python=("$venv_python")
Expand All @@ -150,7 +151,7 @@ else
fi
if (( ${#tagger_python[@]} == 0 )) || \
! "${tagger_python[@]}" -c 'import pikepdf' >/dev/null 2>&1; then
printf 'No Python with pikepdf found; run %s/setup-python-env.sh.\n' "$script_dir" >&2
printf 'No Python with pikepdf found; run %s/setup/python.sh.\n' "$repo_dir" >&2
exit 1
fi
fi
Expand Down Expand Up @@ -218,7 +219,7 @@ fi

if "$ai_review"; then
printf 'PDF_MAGIC_PROGRESS review %s\n' "$input_pages"
"${tagger_python[@]}" "$script_dir/ollama-review-ocr.py" \
"${tagger_python[@]}" "$script_dir/review.py" \
"$tagged_output" "$initial_report" "$review_report" ${resume_review[@]+"${resume_review[@]}"} ${review_options[@]+"${review_options[@]}"}
reviewed_output="$tagging_dir/reviewed.pdf"
printf 'PDF_MAGIC_PROGRESS finalizing\n'
Expand Down
12 changes: 7 additions & 5 deletions tag-ocr-pdf.py → ocr/tag.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,12 @@
import pikepdf
from pikepdf import Array, Dictionary, Name, Operator, String

from pdf_metadata import apply_metadata, choose_source_url, local_user_name, source_details, visible_creator
from ocr_punctuation import tilde_change_warning
from ocr_dates import normalize_ocr_dates
from reading_order import (
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from ocr.metadata import apply_metadata, choose_source_url, local_user_name, source_details, visible_creator
from ocr.punctuation import tilde_change_warning
from ocr.dates import normalize_ocr_dates
from ocr.order import (
group_native_runs, reconstruct_reading_order,
reorder_safe_text_units, order_changes, crosses_column_gutter,
)
Expand Down Expand Up @@ -100,7 +102,7 @@ def parse_args() -> argparse.Namespace:
parser.add_argument(
"--review",
type=Path,
help="optional Ollama JSON/JSONL decisions produced by ollama-review-ocr.py",
help="optional Ollama JSON/JSONL decisions produced by ocr/review.py",
)
parser.add_argument("--source-url", default="", help="original document URL to retain as pdfmagic:href")
for field in ("title", "author", "description", "keywords", "publisher", "rights", "language", "identifier"):
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"private": true,
"type": "module",
"scripts": {
"test": "node --test tests/*.test.js",
"test": "node --test tests/web/*.test.js",
"serve": "python3 serve.py",
"open": "bash './Launch PDF Magic.command'"
}
Expand Down
4 changes: 4 additions & 0 deletions pytest.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[pytest]
testpaths = tests
python_files = *.py
addopts = --import-mode=importlib
Loading
Loading