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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,8 @@ After setup completes, click Enhance again. When the selected Enhancer checkout

For web PDFs, the viewer sends the already-loaded document to the host in acknowledged chunks. Enhancement does not make another HTTP download, so it can use PDFs that the browser loaded from sites that reject standalone requests. Local PDFs are read directly from disk. Both enhancement modes use `--force-ocr --ai-review` to re-read every page and review recognized text against page images with the local AI models, including when the PDF already contains text. This rasterizes pages in the enhanced copy and takes longer than preserving existing text. The source remains unchanged. The tagger builds heading structure and section bookmarks from the reviewed text. Cached results from the previous pipeline are regenerated on the next enhancement.

Before running OCR, the native helper checks the local Ollama service used for text review. It tries to start an installed Ollama when the connection is refused. If Ollama is missing, the viewer shows where to install it before retrying. When text review loses its connection, it retries the current request. If the job stops, **Enhance PDF** on the same document reuses saved OCR and page reviews with checkpoint-enabled Enhancer checkouts.

Enhanced local copies are saved beside their source PDF. If the native helper cannot read the local path during preparation, the viewer retries using the loaded PDF bytes. If the enhanced copy is available in a different folder, **Save enhanced copy** opens the browser's Save As dialog so you can choose the original folder. The viewer opens the copy from the location you select. Copies staged for Save As and enhanced web copies are stored under `~/Library/Application Support/PDF Magic/Enhanced` on macOS or `~/.local/share/pdf-magic/enhanced` on Linux.

Enhancement requests are deduplicated by the PDF's SHA-256 content hash, including requests from separate tabs and different URLs or filenames. Duplicate requests share the running job's progress and result. Completed results are reused only while their output hash still matches; submitting an unchanged enhanced PDF also reuses that result. Changed or missing outputs are regenerated, and failed or interrupted jobs can be retried. Job records are stored in `.jobs` under the enhanced web-copy directory. Jobs already started by an older native host continue independently.
Expand Down
100 changes: 93 additions & 7 deletions native/pdfmagic-enhancer-host.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@

import base64
from collections import deque
from contextlib import closing
import fcntl
import hashlib
from http.client import HTTPConnection, HTTPException
import json
import os
from pathlib import Path
Expand All @@ -27,6 +29,63 @@
DEFAULT_REVIEW_MODEL = "sec-ocr-review:latest"

HOST_CONFIG = Path.home() / ".config" / "pdf-magic" / "enhancer-host.json"
OLLAMA_HOST = "127.0.0.1:11434"
OLLAMA_STARTUP_TIMEOUT = 20


def ollama_ready() -> bool:
try:
with closing(HTTPConnection(OLLAMA_HOST, timeout=1)) as connection:
connection.request("GET", "/api/version")
response = connection.getresponse()
if response.status == 200:
version = json.loads(response.read(4096))
if isinstance(version, dict) and version.get("version"):
return True
except ConnectionRefusedError:
return False
except (OSError, HTTPException, ValueError):
pass
raise RuntimeError(f"Ollama did not respond at {OLLAMA_HOST}. Check that the local Ollama service is running, then retry Enhance PDF.")


def start_ollama() -> bool:
if sys.platform == "darwin":
result = subprocess.run(
["/usr/bin/open", "-g", "-a", "Ollama"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=5,
)
if result.returncode == 0:
return True

executable = shutil.which("ollama")
if executable is None:
return False
subprocess.Popen(
[executable, "serve"], env={**os.environ, "OLLAMA_HOST": OLLAMA_HOST},
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
start_new_session=True,
)
return True


def ensure_ollama(report) -> None:
if ollama_ready():
return
report({"type": "progress", "stage": "ollama"})
try:
started = start_ollama()
except (OSError, subprocess.TimeoutExpired) as error:
raise RuntimeError("Could not start Ollama. Open Ollama or run `ollama serve`, then retry Enhance PDF.") from error
if not started:
raise RuntimeError("Install Ollama from https://ollama.com/download, start it, then retry Enhance PDF.")

deadline = time.monotonic() + OLLAMA_STARTUP_TIMEOUT
while time.monotonic() < deadline:
if ollama_ready():
return
time.sleep(0.25)
raise RuntimeError(f"Ollama did not become ready at {OLLAMA_HOST}. Open Ollama or run `ollama serve`, then retry Enhance PDF.")


def document_hash(path: Path) -> str:
Expand Down Expand Up @@ -86,13 +145,15 @@ def serialized_enhancement(create, report, directory: Path) -> Path:
fcntl.flock(slot, fcntl.LOCK_UN)


def shared_enhancement(input_path: Path, create, progress: bool, directory: Path, cache_key: str = "") -> Path:
def shared_enhancement(
input_path: Path, create, progress: bool, directory: Path, cache_key: str = "", *, input_hash: str | None = None, after_save=None,
) -> Path:
"""Serialize owners by input bytes and let duplicate hosts follow their job."""
directory.mkdir(parents=True, exist_ok=True, mode=0o700)
def identity_for(digest: str) -> str:
return hashlib.sha256(f"{digest}:{cache_key}".encode()).hexdigest() if cache_key else digest

input_hash = document_hash(input_path)
input_hash = input_hash or document_hash(input_path)
identity = identity_for(input_hash)
state_path = directory / f"{identity}.json"
waited = False
Expand Down Expand Up @@ -122,6 +183,8 @@ def notify(event):
state = read_job(state_path)
cached = completed_output(state)
if cached is not None:
if after_save is not None:
after_save()
return cached
if waited and state.get("status") == "failed":
raise RuntimeError(str(state.get("error") or "Shared PDF enhancement failed"))
Expand All @@ -138,6 +201,8 @@ def report(event):
output_hash = document_hash(output)
state = {"status": "complete", "pipelineVersion": PIPELINE_VERSION, "output": str(output), "outputHash": output_hash}
write_job(state_path, state)
if after_save is not None:
after_save()
# An enhanced PDF is also an alias for the completed result.
# Never overwrite another job that is already running for it.
if output_hash != input_hash:
Expand Down Expand Up @@ -441,19 +506,26 @@ def progress_from_log(line: str) -> dict[str, object] | None:
return None


def run_enhancer(command: list[str], progress: bool, report_progress=None) -> None:
def run_enhancer(command: list[str], progress: bool, report_progress=None, *, checkpoint: Path | None = None) -> None:
if not progress and report_progress is None:
result = subprocess.run(command, stdout=sys.stderr, stderr=subprocess.PIPE, text=True)
if result.returncode:
raise RuntimeError(result.stderr.strip()[-2000:] or f"PDF enhancement failed (exit {result.returncode})")
return
logs = deque(maxlen=80)
environment = {**os.environ, "PYTHONUNBUFFERED": "1"}
if checkpoint is not None:
environment["PDF_MAGIC_REVIEW_CHECKPOINT"] = str(checkpoint)
with subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True, bufsize=1, env=environment) as process:
for line in process.stdout:
logs.append(line)
print(line, file=sys.stderr, end="")
if line.startswith("PDF_MAGIC_OLLAMA_RETRY "):
try:
ensure_ollama(lambda _: None)
except RuntimeError as error:
print(error, file=sys.stderr)
event = progress_from_log(line)
if event:
if report_progress is not None:
Expand All @@ -462,7 +534,10 @@ def run_enhancer(command: list[str], progress: bool, report_progress=None) -> No
send_message(event)
code = process.wait()
if code:
raise RuntimeError("".join(logs).strip()[-2000:] or f"PDF enhancement failed (exit {code})")
details = "".join(logs).strip()
if re.search(r"^RuntimeError: Ollama request failed .*Connection refused", details, re.MULTILINE):
raise RuntimeError("Ollama stopped responding during text review. Retry Enhance PDF to start it again.")
raise RuntimeError(details[-2000:] or f"PDF enhancement failed (exit {code})")


def model_name(value: object) -> str:
Expand Down Expand Up @@ -557,19 +632,28 @@ def enhance_pdf(
else:
output_directory = source_directory
options = enhancement_options(enhancement_mode, extract_model, review_model)
jobs = web_output_directory / ".jobs"
input_hash = document_hash(input_path)
cache_key = json.dumps(options[2:]) if len(options) > 2 else ""
checkpoint_hash = hashlib.sha256(f"{input_hash}:{cache_key}".encode()).hexdigest() if cache_key else input_hash
checkpoint = jobs / f"{checkpoint_hash}.review-v{PIPELINE_VERSION}"

def create(report):
ensure_ollama(report)
output_path = unique_output(output_directory, safe_stem(source_url))
run_enhancer(
["/bin/bash", str(enhancer), str(input_path), str(output_path), *options],
progress, report_progress=report,
progress, report_progress=report, checkpoint=checkpoint,
)
report({"type": "progress", "stage": "finalizing"})
output_path = rename_for_ocr_title(output_path)
stamp_source_url(output_path, reference_url)
return output_path

cache_key = json.dumps(options[2:]) if len(options) > 2 else ""
return shared_enhancement(input_path, create, progress, web_output_directory / ".jobs", cache_key)
return shared_enhancement(
input_path, create, progress, jobs, cache_key=cache_key, input_hash=input_hash,
after_save=lambda: shutil.rmtree(checkpoint, ignore_errors=True),
)


def enhance_uploaded_pdf(message: dict[str, object]) -> Path:
Expand Down Expand Up @@ -662,10 +746,12 @@ def main() -> int:
message = read_message()
if message.get("action") == "list-ollama-models":
load_config()
ensure_ollama(lambda _: None)
send_message(ollama_models())
return 0
if message.get("action") == "pull-ollama-model":
load_config()
ensure_ollama(lambda _: None)
pull_ollama_model(message.get("model"))
send_message({"ok": True})
return 0
Expand Down
1 change: 1 addition & 0 deletions src/viewer.html
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,7 @@ <h2 id="enhancer-model-title">Enhance PDF</h2>
<strong>Could not enhance PDF</strong>
<p id="enhance-error-message"></p>
<div class="enhance-error-actions">
<a id="enhance-install-ollama" href="https://ollama.com/download" target="_blank" rel="noopener noreferrer" hidden>Download Ollama</a>
<button id="enhance-copy-error" type="button">Copy error</button>
<button id="enhance-dismiss-error" type="button">Dismiss</button>
</div>
Expand Down
10 changes: 9 additions & 1 deletion src/viewer/enhance-pdf.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ const progressLabel = document.querySelector("#enhance-progress-label");
const progressPercentage = document.querySelector("#enhance-progress-percentage");
const errorNotice = document.querySelector("#enhance-error-notice");
const errorMessage = document.querySelector("#enhance-error-message");
const installOllamaLink = document.querySelector("#enhance-install-ollama");
const copyErrorButton = document.querySelector("#enhance-copy-error");
const dismissErrorButton = document.querySelector("#enhance-dismiss-error");
const saveNotice = document.querySelector("#enhance-save-notice");
Expand Down Expand Up @@ -101,6 +102,7 @@ function updateEnhancementProgress(stage, completed, total) {
preparing: "Preparing enhancement…",
queued: "Waiting for another PDF enhancement…",
upload: "Sending PDF for enhancement…",
ollama: "Starting Ollama for text review…",
ocr: "Checking text and structure…",
review: "Enhancing…",
finalizing: "Building sections and saving PDF…",
Expand Down Expand Up @@ -219,12 +221,14 @@ function showEnhancementFailure(message) {
preparing: "Preparing the document",
queued: "Waiting for the enhancer",
upload: "Sending PDF bytes",
ollama: "Starting Ollama",
ocr: "Running OCR",
review: "Reviewing text",
finalizing: "Saving the enhanced PDF",
};
const stage = stageLabels[lastEnhancementStage] || "Enhancing PDF";
errorMessage.textContent = `${stage}: ${message}`;
installOllamaLink.hidden = !message.startsWith("Install Ollama from ");
errorNotice.hidden = false;
}

Expand Down Expand Up @@ -453,7 +457,11 @@ async function refreshModels() {
fillModelSelect(reviewModel, "");
const message = error?.message || "Unable to detect Ollama models";
modelStatus.textContent = `${message}. Make sure Ollama is running, then refresh.`;
if (isMissingNativeHost(message)) {
if (message.startsWith("Install Ollama from ")) {
modelPopover.hidePopover();
lastEnhancementStage = "ollama";
showEnhancementFailure(message);
} else if (isMissingNativeHost(message)) {
modelPopover.hidePopover();
await offerEnhancerSetup();
}
Expand Down
Loading
Loading