#!/usr/bin/env python3 """Resumable PDFHQ document task example; never automatically authorizes a charge. Examples: PDFHQ_API_KEY=... python pdfhq_task_cli.py --tool compress --file report.pdf PDFHQ_API_KEY=... python pdfhq_task_cli.py --resume TASK_UUID --approve-quote The first command uploads files and displays the HQTools quote, then stops. A task can be resumed after operator approval without creating another job. Requires the PDFHQ Python task SDK, available in sdk/generated/python/pdfhq.py. """ from __future__ import annotations import argparse from decimal import Decimal, InvalidOperation import json import os import sys from pathlib import Path from typing import Callable, Any TOOLS = ( "compress", "merge", "split", "rotate", "pdf_to_image", "optimize", "remove_metadata", "redact", "sign", "organize", "annotate", "fill_form", "flatten", ) TERMINAL = frozenset({"succeeded", "failed", "cancelled", "expired", "deleted"}) def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description=__doc__) start = parser.add_mutually_exclusive_group(required=True) start.add_argument("--tool", choices=TOOLS) start.add_argument("--resume", metavar="TASK_UUID", help="Existing task. Never start a new billable job during recovery.") parser.add_argument("--file", action="append", type=Path, default=[], help="Input PDF (repeat for merge)") parser.add_argument("--options", default="{}", help="JSON object of operation settings") parser.add_argument("--approve-quote", action="store_true", help="Explicitly authorize this task's HQTools quote") parser.add_argument("--poll-timeout", type=float, default=300) parser.add_argument("--api-base", default="https://api.pdfhq.io/v1") parser.add_argument("--show-download-url", action="store_true", help="Print short-lived download URL (sensitive)") return parser def run(args: argparse.Namespace, client: Any, *, emit: Callable[[str], None] = print) -> int: try: options = json.loads(args.options) except ValueError as exc: raise ValueError("--options must contain valid JSON") from exc if not isinstance(options, dict): raise ValueError("--options must be a JSON object") if args.poll_timeout <= 0: raise ValueError("--poll-timeout must be positive") if args.resume: if args.file: raise ValueError("--resume cannot be combined with new uploads; use the existing task") task_id = args.resume current = client.get(task_id) if current["status"] not in {"waiting", "submitting", "processing", "queued", "running", "succeeded"}: emit(f"Existing task {task_id}: {current['status']} (no new submission)") return 1 if current["status"] not in {"waiting"}: emit(f"Existing task {task_id}: {current['status']} (polling only)") finished = client.wait(task_id, timeout=args.poll_timeout) return _report(finished, client, task_id, args.show_download_url, emit) else: if not args.file: raise ValueError("At least one --file is required") if args.tool == "merge" and len(args.file) < 2: raise ValueError("merge requires at least two PDFs") if args.tool != "merge" and len(args.file) != 1: raise ValueError("Only merge accepts multiple PDFs in this example") # Validate local paths before creating a remotely persisted task. for source in args.file: if not source.is_file() or source.suffix.lower() != ".pdf" or source.stat().st_size <= 0: raise ValueError(f"Expected a nonempty PDF file: {source}") current = client.start(args.tool) task_id = current["task_id"] emit(f"TASK_ID={task_id} (save this value to resume safely)") for source in args.file: client.upload(task_id, source) quote = client.quote(task_id) emit("HQTools estimate: " + json.dumps({ key: quote.get(key) for key in ("operation", "estimated_units", "estimated_hq_credits", "estimate_only") }, sort_keys=True)) if quote.get("estimate_only") is not True or quote.get("price_source") != "hqtools": raise ValueError("Quote was not an informational HQTools price; refusing to process") try: credits = Decimal(str(quote["estimated_hq_credits"])) if not credits.is_finite() or credits < 0: raise ValueError("Invalid credit estimate") except (KeyError, TypeError, InvalidOperation) as exc: raise ValueError("Quote is missing a valid HQTools credit estimate") from exc if not args.approve_quote: emit("Not submitted. Obtain customer approval; resume with --resume TASK_ID --approve-quote.") return 0 emit("Approved explicitly: submitting exactly one task (no client-side retries).") client.process(task_id, options) finished = client.wait(task_id, timeout=args.poll_timeout) return _report(finished, client, task_id, args.show_download_url, emit) def _report(result: dict, client: Any, task_id: str, reveal: bool, emit: Callable[[str], None]) -> int: emit(f"Task {task_id}: {result['status']}") if result["status"] != "succeeded": emit(f"Code: {result.get('error_code') or 'unspecified'}") return 1 if reveal: emit("Short-lived URL: " + str(client.download_url(task_id)["url"])) else: emit("Output available; call client.download_url(TASK_ID) to retrieve a short-lived private link.") return 0 def main(argv: list[str] | None = None) -> int: args = build_parser().parse_args(argv) api_key = os.getenv("PDFHQ_API_KEY") if not api_key: print("PDFHQ_API_KEY is required (server-side only)", file=sys.stderr) return 2 # Support both a generated source checkout and a separately unzipped SDK. local_sdk = Path(__file__).resolve().parents[2] / "sdk" / "generated" / "python" if local_sdk.is_dir(): sys.path.insert(0, str(local_sdk)) from pdfhq import PDFHQClient, PDFHQError try: return run(args, PDFHQClient(api_key, base_url=args.api_base)) except (PDFHQError, ValueError, TimeoutError, KeyError, OSError) as exc: print(f"Task not repeated automatically: {exc}", file=sys.stderr) return 2 if __name__ == "__main__": raise SystemExit(main())