diff --git a/.github/workflows/frontend-ui.yml b/.github/workflows/frontend-ui.yml index d69a2f5..26ffc84 100644 --- a/.github/workflows/frontend-ui.yml +++ b/.github/workflows/frontend-ui.yml @@ -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: @@ -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 diff --git a/.github/workflows/pdf-regressions.yml b/.github/workflows/pdf-regressions.yml index 548bcf0..c3d5661 100644 --- a/.github/workflows/pdf-regressions.yml +++ b/.github/workflows/pdf-regressions.yml @@ -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: @@ -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 diff --git a/OCR.md b/OCR.md index 99163a6..d1aaae8 100644 --- a/OCR.md +++ b/OCR.md @@ -8,10 +8,10 @@ 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 @@ -19,7 +19,7 @@ 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 @@ -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 @@ -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" \ @@ -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 @@ -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 @@ -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 @@ -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 @@ -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 diff --git a/README.md b/README.md index 7a7e2d9..aac91cd 100644 --- a/README.md +++ b/README.md @@ -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. @@ -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 @@ -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 @@ -124,13 +136,13 @@ 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. @@ -138,7 +150,7 @@ Set an identifying SEC User-Agent locally and provide the file number: ```sh export SEC_USER_AGENT='Your Name your@email.com' -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. diff --git a/compress-pdf-images.py b/compression/images.py similarity index 100% rename from compress-pdf-images.py rename to compression/images.py diff --git a/compress-and-tag-ocr-pdf.sh b/compression/tagged.sh old mode 100644 new mode 100755 similarity index 88% rename from compress-and-tag-ocr-pdf.sh rename to compression/tagged.sh index 3bf679d..fdef3fa --- a/compress-and-tag-ocr-pdf.sh +++ b/compression/tagged.sh @@ -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 @@ -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 @@ -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") @@ -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 @@ -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" @@ -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") diff --git a/download-sec-comments.py b/download/sec-comments.py similarity index 100% rename from download-sec-comments.py rename to download/sec-comments.py diff --git a/export-archive-book.py b/export/archive.py similarity index 100% rename from export-archive-book.py rename to export/archive.py diff --git a/export-google-book.py b/export/google.py similarity index 100% rename from export-google-book.py rename to export/google.py diff --git a/ocr_dates.py b/ocr/dates.py similarity index 100% rename from ocr_dates.py rename to ocr/dates.py diff --git a/pdf_metadata.py b/ocr/metadata.py similarity index 100% rename from pdf_metadata.py rename to ocr/metadata.py diff --git a/reading_order.py b/ocr/order.py similarity index 100% rename from reading_order.py rename to ocr/order.py diff --git a/ocr_punctuation.py b/ocr/punctuation.py similarity index 100% rename from ocr_punctuation.py rename to ocr/punctuation.py diff --git a/ollama-review-ocr.py b/ocr/review.py old mode 100644 new mode 100755 similarity index 99% rename from ollama-review-ocr.py rename to ocr/review.py index 7897ebc..af58aae --- a/ollama-review-ocr.py +++ b/ocr/review.py @@ -10,6 +10,7 @@ import os import re import subprocess +import sys import tempfile import time import urllib.error @@ -17,7 +18,9 @@ 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" diff --git a/ocr-scanned-pdf.sh b/ocr/scan.sh old mode 100644 new mode 100755 similarity index 94% rename from ocr-scanned-pdf.sh rename to ocr/scan.sh index 8d31c59..79705ed --- a/ocr-scanned-pdf.sh +++ b/ocr/scan.sh @@ -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 @@ -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 @@ -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") @@ -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 @@ -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' diff --git a/tag-ocr-pdf.py b/ocr/tag.py similarity index 99% rename from tag-ocr-pdf.py rename to ocr/tag.py index 05ce62c..58b697e 100644 --- a/tag-ocr-pdf.py +++ b/ocr/tag.py @@ -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, ) @@ -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"): diff --git a/package.json b/package.json index 25e7f22..dfdfe75 100644 --- a/package.json +++ b/package.json @@ -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'" } diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000..276b448 --- /dev/null +++ b/pytest.ini @@ -0,0 +1,4 @@ +[pytest] +testpaths = tests +python_files = *.py +addopts = --import-mode=importlib diff --git a/setup-ollama-ocr.sh b/setup/ollama.sh similarity index 90% rename from setup-ollama-ocr.sh rename to setup/ollama.sh index 449f2f0..d390f1d 100755 --- a/setup-ollama-ocr.sh +++ b/setup/ollama.sh @@ -14,7 +14,7 @@ fi ollama pull deepseek-ocr:latest ollama pull qwen3-vl:32b-instruct-q4_K_M script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) -ollama create sec-ocr-review -f "$script_dir/ollama/Modelfile.sec-ocr-review" +ollama create sec-ocr-review -f "$script_dir/../ollama/Modelfile.sec-ocr-review" printf '%s\n' 'Installed the local OCR review models:' ollama list | grep -E '^(deepseek-ocr|qwen3-vl:32b-instruct-q4_K_M|sec-ocr-review)' || true diff --git a/setup-python-env.sh b/setup/python.sh similarity index 81% rename from setup-python-env.sh rename to setup/python.sh index b0867f0..c43bf8d 100755 --- a/setup-python-env.sh +++ b/setup/python.sh @@ -2,15 +2,15 @@ set -euo pipefail # Install only Enhancer's Python dependencies; Homebrew manages the OCR binaries. -script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) -venv_python="$script_dir/.venv/bin/python" +repo_dir=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +venv_python="$repo_dir/.venv/bin/python" if [[ ! -x "$venv_python" ]]; then bootstrap_python="${PDF_MAGIC_BOOTSTRAP_PYTHON:-python3}" if ! command -v "$bootstrap_python" >/dev/null 2>&1; then printf 'Python 3 is required to create the Enhancer virtual environment.\n' >&2 exit 1 fi - "$bootstrap_python" -m venv "$script_dir/.venv" + "$bootstrap_python" -m venv "$repo_dir/.venv" fi if ! "$venv_python" -c 'import pikepdf, PIL' >/dev/null 2>&1; then "$venv_python" -m pip install --disable-pip-version-check pikepdf Pillow diff --git a/tests/test_export_archive_book.py b/tests/export/archive.py similarity index 98% rename from tests/test_export_archive_book.py rename to tests/export/archive.py index 4391149..f7b8573 100644 --- a/tests/test_export_archive_book.py +++ b/tests/export/archive.py @@ -10,7 +10,7 @@ from playwright.sync_api import sync_playwright spec = importlib.util.spec_from_file_location( - "archive_exporter", Path(__file__).resolve().parents[1] / "export-archive-book.py") + "archive_exporter", Path(__file__).resolve().parents[2] / "export/archive.py") exporter = importlib.util.module_from_spec(spec) spec.loader.exec_module(exporter) diff --git a/tests/test_export_google_book.py b/tests/export/google.py similarity index 97% rename from tests/test_export_google_book.py rename to tests/export/google.py index 6c83321..bd2276d 100644 --- a/tests/test_export_google_book.py +++ b/tests/export/google.py @@ -1,4 +1,4 @@ -"""Browser regressions; run with .venv/bin/python -m unittest discover -s tests.""" +"""Browser regressions; run with .venv/bin/python -m pytest.""" import importlib.util from pathlib import Path from tempfile import TemporaryDirectory @@ -8,7 +8,7 @@ from playwright.sync_api import sync_playwright spec = importlib.util.spec_from_file_location( - "exporter", Path(__file__).resolve().parents[1] / "export-google-book.py" + "exporter", Path(__file__).resolve().parents[2] / "export/google.py" ) exporter = importlib.util.module_from_spec(spec) spec.loader.exec_module(exporter) diff --git a/tests/test_ocr_dates.py b/tests/ocr/dates.py similarity index 97% rename from tests/test_ocr_dates.py rename to tests/ocr/dates.py index 3a5a0f1..e09aab5 100644 --- a/tests/test_ocr_dates.py +++ b/tests/ocr/dates.py @@ -6,8 +6,8 @@ import tempfile import unittest -sys.path.insert(0, str(Path(__file__).resolve().parents[1])) -from ocr_dates import normalize_ocr_dates +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from ocr.dates import normalize_ocr_dates class OcrDateTests(unittest.TestCase): @@ -53,7 +53,7 @@ def test_leap_year_and_idempotency(self): def test_tagger_corrects_pdf_actualtext_and_audits_without_rewriting_source(self): import pikepdf spec = importlib.util.spec_from_file_location( - "ocr_date_tagger", Path(__file__).resolve().parents[1] / "tag-ocr-pdf.py") + "ocr_date_tagger", Path(__file__).resolve().parents[2] / "ocr/tag.py") tagger = importlib.util.module_from_spec(spec) sys.modules[spec.name] = tagger spec.loader.exec_module(tagger) diff --git a/tests/test_tag_existing_text.py b/tests/ocr/existing-text.py similarity index 99% rename from tests/test_tag_existing_text.py rename to tests/ocr/existing-text.py index 2cf35f3..561df82 100644 --- a/tests/test_tag_existing_text.py +++ b/tests/ocr/existing-text.py @@ -8,10 +8,10 @@ import pikepdf -sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) spec = importlib.util.spec_from_file_location( - "tag_ocr_pdf", Path(__file__).resolve().parents[1] / "tag-ocr-pdf.py" + "tag_ocr_pdf", Path(__file__).resolve().parents[2] / "ocr/tag.py" ) tagger = importlib.util.module_from_spec(spec) sys.modules[spec.name] = tagger diff --git a/tests/test_pdf_metadata.py b/tests/ocr/metadata.py similarity index 99% rename from tests/test_pdf_metadata.py rename to tests/ocr/metadata.py index bc4f1a8..14dd2de 100644 --- a/tests/test_pdf_metadata.py +++ b/tests/ocr/metadata.py @@ -7,10 +7,10 @@ import pikepdf -sys.path.insert(0, str(Path(__file__).resolve().parents[1])) -import pdf_metadata as metadata +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from ocr import metadata -spec = importlib.util.spec_from_file_location("metadata_tagger", Path(__file__).resolve().parents[1] / "tag-ocr-pdf.py") +spec = importlib.util.spec_from_file_location("metadata_tagger", Path(__file__).resolve().parents[2] / "ocr/tag.py") tagger = importlib.util.module_from_spec(spec) sys.modules[spec.name] = tagger spec.loader.exec_module(tagger) diff --git a/tests/test_reading_order.py b/tests/ocr/order.py similarity index 98% rename from tests/test_reading_order.py rename to tests/ocr/order.py index 331005c..882a8e7 100644 --- a/tests/test_reading_order.py +++ b/tests/ocr/order.py @@ -6,8 +6,8 @@ from types import SimpleNamespace import unittest -sys.path.insert(0, str(Path(__file__).resolve().parents[1])) -from reading_order import ( +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from ocr.order import ( reconstruct_reading_order, group_native_runs, reorder_safe_text_units, crosses_column_gutter, ) diff --git a/tests/test_ocr_punctuation.py b/tests/ocr/punctuation.py similarity index 92% rename from tests/test_ocr_punctuation.py rename to tests/ocr/punctuation.py index 934dfff..fb12e27 100644 --- a/tests/test_ocr_punctuation.py +++ b/tests/ocr/punctuation.py @@ -10,12 +10,12 @@ from unittest.mock import patch from types import SimpleNamespace -sys.path.insert(0, str(Path(__file__).resolve().parents[1])) -from ocr_punctuation import tilde_candidates, tilde_change_warning +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from ocr.punctuation import tilde_candidates, tilde_change_warning def load_script(name, filename): - spec = importlib.util.spec_from_file_location(name, Path(__file__).resolve().parents[1] / filename) + spec = importlib.util.spec_from_file_location(name, Path(__file__).resolve().parents[2] / filename) module = importlib.util.module_from_spec(spec) sys.modules[name] = module spec.loader.exec_module(module) @@ -35,7 +35,7 @@ def decision(text=STA_TEXT): class PunctuationTests(unittest.TestCase): def test_ollama_retries_dropped_connections_and_server_restart(self): - reviewer = load_script("punctuation_reviewer", "ollama-review-ocr.py") + reviewer = load_script("punctuation_reviewer", "ocr/review.py") responses = [RemoteDisconnected(), URLError(ConnectionRefusedError()), BytesIO(b'{"message":{"content":"reviewed"}}')] with patch.object(reviewer.urllib.request, "urlopen", side_effect=responses) as send, \ @@ -45,7 +45,7 @@ def test_ollama_retries_dropped_connections_and_server_restart(self): self.assertEqual([call.args[0] for call in wait.call_args_list], [2, 5]) def test_ollama_reports_an_http_model_error_without_retrying(self): - reviewer = load_script("punctuation_reviewer", "ollama-review-ocr.py") + reviewer = load_script("punctuation_reviewer", "ocr/review.py") error = HTTPError("http://localhost/chat", 404, "Not Found", {}, None) with patch.object(reviewer.urllib.request, "urlopen", side_effect=error) as send: with self.assertRaisesRegex(reviewer.OllamaRequestError, "HTTP 404 for model"): @@ -53,7 +53,7 @@ def test_ollama_reports_an_http_model_error_without_retrying(self): send.assert_called_once() def test_resume_discards_only_an_interrupted_checkpoint_record(self): - reviewer = load_script("punctuation_reviewer", "ollama-review-ocr.py") + reviewer = load_script("punctuation_reviewer", "ocr/review.py") with tempfile.TemporaryDirectory() as folder: checkpoint = Path(folder) / "review.jsonl" saved = b'{"page":1}\n{"page":3}\n' @@ -92,7 +92,7 @@ def test_legitimate_tildes_and_correct_hyphens_survive(self): self.assertIsNone(tilde_change_warning(source, source, {})) def test_review_prompt_includes_candidates_and_evidence_contract(self): - reviewer = load_script("punctuation_reviewer", "ollama-review-ocr.py") + reviewer = load_script("punctuation_reviewer", "ocr/review.py") block = {"id": "p0001-b0001", "type": "body", "text": STA_TEXT, "protected_tokens": [], "position": {}} with patch.object(reviewer, "ollama_chat", return_value=json.dumps({"decisions": [decision()]})) as chat: @@ -102,7 +102,7 @@ def test_review_prompt_includes_candidates_and_evidence_contract(self): self.assertIn("tilde_corrections", chat.call_args.args[4]["properties"]["decisions"]["items"]["required"]) def test_bad_page_review_keeps_valid_batches_and_preserves_unreviewed_ocr(self): - reviewer = load_script("punctuation_reviewer", "ollama-review-ocr.py") + reviewer = load_script("punctuation_reviewer", "ocr/review.py") args = SimpleNamespace(endpoint="unused", review_model="test", extract_model="test", skip_extractor=True) blocks = [ {"id": f"p0001-b{index:04d}", "type": "body", "text": STA_TEXT, @@ -119,7 +119,7 @@ def test_bad_page_review_keeps_valid_batches_and_preserves_unreviewed_ocr(self): def test_tagger_writes_corrected_actualtext_without_changing_drawing(self): import pikepdf - tagger = load_script("punctuation_tagger", "tag-ocr-pdf.py") + tagger = load_script("punctuation_tagger", "ocr/tag.py") with tempfile.TemporaryDirectory() as folder: source, output, report = (Path(folder) / name for name in ("source.pdf", "output.pdf", "report.json")) text = "DTC is a self~regulatory organization." diff --git a/tests/test_reading_order_pdf.py b/tests/ocr/reading-order-pdf.py similarity index 97% rename from tests/test_reading_order_pdf.py rename to tests/ocr/reading-order-pdf.py index 608c5c2..adb1905 100644 --- a/tests/test_reading_order_pdf.py +++ b/tests/ocr/reading-order-pdf.py @@ -1,7 +1,7 @@ """Full-document regression for --retag; run on macOS with the book available. PDF_MAGIC_BOOK=/Users/GitHub/JFWooten4/JFWooten4/static/book.pdf \ - python3 -m pytest -q tests/test_reading_order_pdf.py + python3 -m pytest -q tests/ocr/reading-order-pdf.py This creates only temporary output files. It never replaces the original book. Preview drag selection is deliberately a separate manual acceptance test. @@ -20,7 +20,7 @@ fitz = pytest.importorskip('fitz') BOOK = os.environ.get('PDF_MAGIC_BOOK', '') -TAGGER = Path(__file__).resolve().parents[1] / 'tag-ocr-pdf.py' +TAGGER = Path(__file__).resolve().parents[2] / 'ocr/tag.py' def _layout(page): diff --git a/tests/test_ocr_shell_startup.py b/tests/ocr/shell-startup.py similarity index 92% rename from tests/test_ocr_shell_startup.py rename to tests/ocr/shell-startup.py index 9265485..5766466 100644 --- a/tests/test_ocr_shell_startup.py +++ b/tests/ocr/shell-startup.py @@ -9,14 +9,15 @@ import unittest -SCRIPT = Path(__file__).resolve().parents[1] / "ocr-scanned-pdf.sh" +SCRIPT = Path(__file__).resolve().parents[2] / "ocr" / "scan.sh" class OcrShellStartupTests(unittest.TestCase): def test_interrupted_review_reuses_ocr_and_saved_pages(self): with tempfile.TemporaryDirectory() as folder: directory = Path(folder) - script = directory / SCRIPT.name + script = directory / "ocr" / SCRIPT.name + script.parent.mkdir() script.write_bytes(SCRIPT.read_bytes()) source = directory / "source.pdf" source.write_bytes(b"%PDF-1.7\noriginal") @@ -36,13 +37,13 @@ def test_interrupted_review_reuses_ocr_and_saved_pages(self): shim = commands / name shim.write_text(code) shim.chmod(0o755) - (directory / "tag-ocr-pdf.py").write_text( + (script.parent / "tag.py").write_text( "import pathlib, shutil, sys\n" "shutil.copyfile(sys.argv[1], sys.argv[2])\n" "report = pathlib.Path(sys.argv[sys.argv.index('--report') + 1])\n" "report.write_text('{\"blocks\":[{\"type\":\"body\",\"text\":\"content\"}]}')\n" ) - (directory / "ollama-review-ocr.py").write_text( + (script.parent / "review.py").write_text( "from pathlib import Path\n" "import sys\n" "assert sys.argv[4:] == ['--resume', '--extract-model', 'custom-ocr:latest', '--review-model', 'custom-review:latest']\n" @@ -107,9 +108,10 @@ def test_python3_on_path_with_pikepdf_can_start_ocr(self): def test_project_venv_wins_over_python_on_path(self): with tempfile.TemporaryDirectory() as folder: directory = Path(folder) - script = directory / "ocr-scanned-pdf.sh" + script = directory / "ocr" / "scan.sh" + script.parent.mkdir() script.write_bytes(SCRIPT.read_bytes()) - (directory / "tag-ocr-pdf.py").write_text("# placeholder\n") + (script.parent / "tag.py").write_text("# placeholder\n") venv = directory / ".venv" / "bin" venv.mkdir(parents=True) venv_python = venv / "python" @@ -147,9 +149,10 @@ def test_project_venv_wins_over_python_on_path(self): def test_incomplete_project_venv_fails_without_falling_back_to_system_python(self): with tempfile.TemporaryDirectory() as folder: directory = Path(folder) - script = directory / "ocr-scanned-pdf.sh" + script = directory / "ocr" / "scan.sh" + script.parent.mkdir() script.write_bytes(SCRIPT.read_bytes()) - (directory / "tag-ocr-pdf.py").write_text("# placeholder\n") + (script.parent / "tag.py").write_text("# placeholder\n") venv = directory / ".venv" / "bin" venv.mkdir(parents=True) executable = venv / "python" @@ -169,7 +172,7 @@ def test_incomplete_project_venv_fails_without_falling_back_to_system_python(sel env=env, capture_output=True, text=True, ) self.assertNotEqual(result.returncode, 0) - self.assertIn("setup-python-env.sh", result.stderr) + self.assertIn("setup/python.sh", result.stderr) if __name__ == "__main__": unittest.main() diff --git a/tests/test_local_server.py b/tests/server.py similarity index 98% rename from tests/test_local_server.py rename to tests/server.py index 52e6b8d..28eb216 100644 --- a/tests/test_local_server.py +++ b/tests/server.py @@ -8,6 +8,10 @@ from http.server import ThreadingHTTPServer from pathlib import Path +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + from serve import ToolbenchHandler, safe_filename diff --git a/tests/frontend-command-builders.test.js b/tests/web/command-builders.test.js similarity index 68% rename from tests/frontend-command-builders.test.js rename to tests/web/command-builders.test.js index c8e5f22..8a985a9 100644 --- a/tests/frontend-command-builders.test.js +++ b/tests/web/command-builders.test.js @@ -1,16 +1,16 @@ import test from "node:test"; import assert from "node:assert/strict"; -import { aiReview } from "../web/js/tools/ai-review.js"; -import { compression } from "../web/js/tools/compression.js"; -import { googleExport } from "../web/js/tools/google-export.js"; -import { archiveExport } from "../web/js/tools/archive-export.js"; -import { ocr } from "../web/js/tools/ocr.js"; +import { aiReview } from "../../web/js/tools/ai-review.js"; +import { compression } from "../../web/js/tools/compression.js"; +import { googleExport } from "../../web/js/tools/google-export.js"; +import { archiveExport } from "../../web/js/tools/archive-export.js"; +import { ocr } from "../../web/js/tools/ocr.js"; test("Google export builds isolated output arguments", () => { assert.equal( googleExport.build({ bookId: "abc_123", outputPdf: "My Book.pdf", workers: "2" }), - "python3 export-google-book.py abc_123 --output-pdf 'My Book.pdf' --workers 2", + "python3 export/google.py abc_123 --output-pdf 'My Book.pdf' --workers 2", ); }); @@ -22,7 +22,7 @@ test("Internet Archive accepts the linked two-page URL and scan range", () => { assert.equal(archiveExport.build({ book: "https://archive.org/details/transformationof00seli/mode/2up", start: "2", end: "10", outputPdf: "Wall Street.pdf", - }), "python3 export-archive-book.py transformationof00seli --output-pdf 'Wall Street.pdf' --start 2 --end 10"); + }), "python3 export/archive.py transformationof00seli --output-pdf 'Wall Street.pdf' --start 2 --end 10"); }); test("Internet Archive rejects unsafe sources and reversed ranges", () => { @@ -35,14 +35,14 @@ test("Internet Archive rejects unsafe sources and reversed ranges", () => { test("OCR preserves paths with spaces", () => { assert.equal( ocr.build({ input: "Source Scan.pdf", output: "OCR Copy.pdf" }), - "./ocr-scanned-pdf.sh 'Source Scan.pdf' 'OCR Copy.pdf'", + "./ocr/scan.sh 'Source Scan.pdf' 'OCR Copy.pdf'", ); }); test("OCR forwards optional descriptive metadata and tags", () => { assert.equal( ocr.build({ input: "scan.pdf", title: "Nine to Noon", description: "An investing guide", keywords: "stocks, ETFs" }), - "./ocr-scanned-pdf.sh scan.pdf --title 'Nine to Noon' --description 'An investing guide' --keywords 'stocks, ETFs'", + "./ocr/scan.sh scan.pdf --title 'Nine to Noon' --description 'An investing guide' --keywords 'stocks, ETFs'", ); }); @@ -56,21 +56,21 @@ test("AI review exposes resumable page selection", () => { resume: true, skipExtractor: false, }), - "python3 ollama-review-ocr.py ocr.pdf ocr.tagging.json review.jsonl --pages 1-10,14 --resume", + "python3 ocr/review.py ocr.pdf ocr.tagging.json review.jsonl --pages 1-10,14 --resume", ); }); test("Compression modes remain independent", () => { assert.equal( compression.build({ mode: "compression-only", input: "in.pdf", output: "out.pdf", report: "report.json" }), - "python3 compress-pdf-images.py in.pdf out.pdf --report report.json", + "python3 compression/images.py in.pdf out.pdf --report report.json", ); assert.equal( compression.build({ mode: "tagged", input: "in.pdf", output: "out.pdf", review: "review.jsonl" }), - "./compress-and-tag-ocr-pdf.sh in.pdf out.pdf review.jsonl", + "./compression/tagged.sh in.pdf out.pdf review.jsonl", ); assert.equal( compression.build({ mode: "tagged", input: "in.pdf", output: "out.pdf", description: "Summary", keywords: "finance, books" }), - "./compress-and-tag-ocr-pdf.sh in.pdf out.pdf --description Summary --tags 'finance, books'", + "./compression/tagged.sh in.pdf out.pdf --description Summary --tags 'finance, books'", ); }); diff --git a/tests/file-inputs.test.js b/tests/web/file-inputs.test.js similarity index 71% rename from tests/file-inputs.test.js rename to tests/web/file-inputs.test.js index 34355da..5abfebc 100644 --- a/tests/file-inputs.test.js +++ b/tests/web/file-inputs.test.js @@ -1,8 +1,8 @@ import test from "node:test"; import assert from "node:assert/strict"; -import { ocr } from "../web/js/tools/ocr.js"; -import { aiReview } from "../web/js/tools/ai-review.js"; -import { compression } from "../web/js/tools/compression.js"; +import { ocr } from "../../web/js/tools/ocr.js"; +import { aiReview } from "../../web/js/tools/ai-review.js"; +import { compression } from "../../web/js/tools/compression.js"; test("source file fields are genuine file-picker targets", () => { for (const [tool, name, accept] of [ @@ -23,14 +23,14 @@ test("source file fields are genuine file-picker targets", () => { test("command builders accept staged paths with spaces and keep output editable", () => { assert.equal( ocr.build({ input: "/tmp/PDF Magic/scan.pdf", output: "enhanced.pdf" }), - "./ocr-scanned-pdf.sh '/tmp/PDF Magic/scan.pdf' enhanced.pdf", + "./ocr/scan.sh '/tmp/PDF Magic/scan.pdf' enhanced.pdf", ); assert.equal( aiReview.build({ pdf: "/tmp/book.pdf", report: "/tmp/blocks.json", output: "review.jsonl" }), - "python3 ollama-review-ocr.py /tmp/book.pdf /tmp/blocks.json review.jsonl", + "python3 ocr/review.py /tmp/book.pdf /tmp/blocks.json review.jsonl", ); assert.equal( compression.build({ input: "/tmp/book.pdf", output: "compressed.pdf", review: "/tmp/notes.jsonl", mode: "tagged" }), - "./compress-and-tag-ocr-pdf.sh /tmp/book.pdf compressed.pdf /tmp/notes.jsonl", + "./compression/tagged.sh /tmp/book.pdf compressed.pdf /tmp/notes.jsonl", ); }); diff --git a/tests/launcher.test.js b/tests/web/launcher.test.js similarity index 80% rename from tests/launcher.test.js rename to tests/web/launcher.test.js index 3c7d3cc..07b829d 100644 --- a/tests/launcher.test.js +++ b/tests/web/launcher.test.js @@ -4,6 +4,6 @@ import { fileURLToPath } from "node:url"; test("macOS launcher has valid shell syntax", () => { execFileSync("bash", ["-n", "Launch PDF Magic.command"], { - cwd: fileURLToPath(new URL("../", import.meta.url)), + cwd: fileURLToPath(new URL("../../", import.meta.url)), }); }); diff --git a/tests/theme.test.js b/tests/web/theme.test.js similarity index 89% rename from tests/theme.test.js rename to tests/web/theme.test.js index 56f5f43..8dd191a 100644 --- a/tests/theme.test.js +++ b/tests/web/theme.test.js @@ -1,7 +1,7 @@ import test from "node:test"; import assert from "node:assert/strict"; -import { oppositeTheme, resolveTheme } from "../web/js/theme.js"; +import { oppositeTheme, resolveTheme } from "../../web/js/theme.js"; test("theme follows system preference until explicitly overridden", () => { assert.equal(resolveTheme(null, true), "dark"); diff --git a/web/js/tools/ai-review.js b/web/js/tools/ai-review.js index ccbdd1e..f9c9fee 100644 --- a/web/js/tools/ai-review.js +++ b/web/js/tools/ai-review.js @@ -19,7 +19,7 @@ export const aiReview = { build(values) { const parts = [ "python3", - "ollama-review-ocr.py", + "ocr/review.py", shellQuote(requireValue(values, "pdf", "OCR PDF")), shellQuote(requireValue(values, "report", "Tagging report")), shellQuote(requireValue(values, "output", "Review output")), diff --git a/web/js/tools/archive-export.js b/web/js/tools/archive-export.js index 0fa3393..e6257aa 100644 --- a/web/js/tools/archive-export.js +++ b/web/js/tools/archive-export.js @@ -39,7 +39,7 @@ export const archiveExport = { const start = positiveInteger(values.start, "First scan"); const end = positiveInteger(values.end, "Last scan"); if (end != null && end < (start ?? 1)) throw new Error("Last scan must be at least the first scan."); - const parts = ["python3", "export-archive-book.py", shellQuote(id)]; + const parts = ["python3", "export/archive.py", shellQuote(id)]; optionalFlag(parts, "--output-dir", values.outputDir); optionalFlag(parts, "--output-pdf", values.outputPdf); if (start != null) parts.push("--start", String(start)); diff --git a/web/js/tools/compression.js b/web/js/tools/compression.js index cdd3e4d..a1c70ef 100644 --- a/web/js/tools/compression.js +++ b/web/js/tools/compression.js @@ -30,11 +30,11 @@ export const compression = { const input = shellQuote(requireValue(values, "input", "Input PDF")); const output = shellQuote(requireValue(values, "output", "Output PDF")); if (values.mode === "compression-only") { - const parts = ["python3", "compress-pdf-images.py", input, output]; + const parts = ["python3", "compression/images.py", input, output]; optionalFlag(parts, "--report", values.report); return command(parts); } - const parts = ["./compress-and-tag-ocr-pdf.sh", input, output, shellQuote(values.review)]; + const parts = ["./compression/tagged.sh", input, output, shellQuote(values.review)]; optionalFlag(parts, "--description", values.description); optionalFlag(parts, "--tags", values.keywords); return command(parts); diff --git a/web/js/tools/google-export.js b/web/js/tools/google-export.js index 1b41d7e..c434a44 100644 --- a/web/js/tools/google-export.js +++ b/web/js/tools/google-export.js @@ -21,7 +21,7 @@ export const googleExport = { if (!/^[A-Za-z0-9_-]+$/.test(bookId)) { throw new Error("Book ID may contain only letters, numbers, underscores, or hyphens."); } - const parts = ["python3", "export-google-book.py", shellQuote(bookId)]; + const parts = ["python3", "export/google.py", shellQuote(bookId)]; optionalFlag(parts, "--output-dir", values.outputDir); optionalFlag(parts, "--output-pdf", values.outputPdf); for (const [name, flag, label] of [ diff --git a/web/js/tools/ocr.js b/web/js/tools/ocr.js index 6f3f164..400d30d 100644 --- a/web/js/tools/ocr.js +++ b/web/js/tools/ocr.js @@ -21,7 +21,7 @@ export const ocr = { ], build(values) { const input = requireValue(values, "input", "Source PDF"); - const parts = ["./ocr-scanned-pdf.sh", shellQuote(input), shellQuote(values.output)]; + const parts = ["./ocr/scan.sh", shellQuote(input), shellQuote(values.output)]; for (const field of ["title", "author", "description", "keywords", "publisher", "rights", "language", "identifier"]) { optionalFlag(parts, `--${field}`, values[field]); }