DocRes-Appearance / pdf_cli.py
Seth Thompson
add strength parameter
fe07779
Raw History Blame Contribute Delete
12.4 kB
import argparse
import os
import sys
import tempfile
import threading
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
import numpy as np
from cli import DEFAULT_SPACE_ID, normalize_space_result_path, predict_space_api
POINTS_PER_INCH = 72.0
DEFAULT_DPI = 200
DEFAULT_MAX_INCHES = 12.0
def require_pypdf():
try:
from pypdf import PdfReader
except ImportError as exc:
raise RuntimeError(
"The PDF CLI requires pypdf. Install project dependencies with "
"`uv sync`, or install pypdf directly."
) from exc
return PdfReader
def require_pdf2image():
try:
from pdf2image import convert_from_path
except ImportError as exc:
raise RuntimeError(
"The PDF CLI requires pdf2image. Install project dependencies with "
"`uv sync`, or install pdf2image directly."
) from exc
return convert_from_path
def require_pillow_image():
try:
from PIL import Image
except ImportError as exc:
raise RuntimeError(
"The PDF CLI requires Pillow. Install project dependencies with "
"`uv sync`, or install Pillow directly."
) from exc
return Image
def read_pdf_info(pdf_path, max_inches=DEFAULT_MAX_INCHES, default_dpi=DEFAULT_DPI):
PdfReader = require_pypdf()
reader = PdfReader(str(pdf_path))
max_width_in = 0.0
max_height_in = 0.0
for page in reader.pages:
width_in = float(page.mediabox.width) / POINTS_PER_INCH
height_in = float(page.mediabox.height) / POINTS_PER_INCH
max_width_in = max(max_width_in, width_in)
max_height_in = max(max_height_in, height_in)
max_dim_in = max(max_width_in, max_height_in)
dpi = default_dpi
if max_dim_in > max_inches:
scale = max_inches / max_dim_in
dpi = max(1, int(default_dpi * scale))
print(
"Warning: PDF page size exceeds "
f"{max_inches:g} inches: "
f"{max_width_in:.2f}in x {max_height_in:.2f}in; "
f"reducing DPI to {dpi}.",
file=sys.stderr,
)
return len(reader.pages), dpi
def extract_pdf_pages(pdf_path, total_pages, dpi):
convert_from_path = require_pdf2image()
try:
pages = convert_from_path(
str(pdf_path),
use_cropbox=True,
dpi=dpi,
)
except Exception as exc:
if exc.__class__.__name__ == "PDFInfoNotInstalledError":
raise RuntimeError(
"pdf2image could not find Poppler. Install Poppler so "
"`pdftoppm` is available on PATH."
) from exc
raise
if len(pages) != total_pages:
raise RuntimeError(f"Expected {total_pages} rendered pages, got {len(pages)}")
rgb_pages = []
try:
for page in pages:
rgb_pages.append(page.convert("RGB") if page.mode != "RGB" else page.copy())
finally:
close_images(pages)
return rgb_pages
def output_path_for_pdf(pdf_path, out_folder):
return Path(out_folder) / f"{Path(pdf_path).stem}_appearance.pdf"
def pil_to_bgr_array(image):
import numpy as np
rgb = np.asarray(image.convert("RGB"))
return np.ascontiguousarray(rgb[:, :, ::-1])
def bgr_array_to_pil(image):
import numpy as np
Image = require_pillow_image()
rgb = np.ascontiguousarray(image[:, :, ::-1])
return Image.fromarray(rgb)
def space_result_to_pil(result):
Image = require_pillow_image()
result_path = Path(normalize_space_result_path(result))
if not result_path.exists():
raise FileNotFoundError(f"Could not read Space API result: {result_path}")
with Image.open(result_path) as image:
return image.convert("RGB") if image.mode != "RGB" else image.copy()
def run_concurrent_pages(pages, concurrency, process_page):
indexed_pages = list(enumerate(pages, start=1))
if not indexed_pages:
return []
if concurrency == 1:
results = []
total = len(indexed_pages)
for page_number, image in indexed_pages:
result = process_page(page_number, image)
print(f"Optimized page {page_number}/{total}")
results.append(result)
return results
results = [None] * len(indexed_pages)
with ThreadPoolExecutor(max_workers=concurrency) as executor:
futures = {
executor.submit(process_page, page_number, image): page_number
for page_number, image in indexed_pages
}
completed = 0
for future in as_completed(futures):
page_number = futures[future]
try:
result = future.result()
except Exception as exc:
for pending in futures:
pending.cancel()
raise RuntimeError(f"Failed to optimize page {page_number}: {exc}") from exc
completed += 1
print(f"Optimized page {completed}/{len(indexed_pages)}")
results[page_number - 1] = result
return results
def run_local_pages(args, pages):
from inference import (
blend_with_original,
load_model,
restore_appearance_array,
select_device,
)
device = select_device(args.device)
print(f"Using device: {device}")
model = load_model(args.model_path, device, args.precision)
def process_page(_page_number, image):
original = pil_to_bgr_array(image)
_, restored = restore_appearance_array(
model,
original,
device,
args.precision,
args.max_size,
args.prompt_size,
)
restored = blend_with_original(original, restored, args.strength)
return bgr_array_to_pil(restored)
return run_concurrent_pages(pages, args.concurrency, process_page)
def run_space_api_pages(args, pages):
try:
from gradio_client import Client
except ImportError as exc:
raise RuntimeError(
"The Hugging Face Space API mode requires gradio_client. "
"Install it with `pip install gradio_client`."
) from exc
print(f"Using Hugging Face Space API: {args.space_id}")
thread_local = threading.local()
def get_client():
if not hasattr(thread_local, "client"):
thread_local.client = Client(args.space_id, token=args.hf_token)
return thread_local.client
with tempfile.TemporaryDirectory(prefix="docres-pdf-pages-") as temp_dir:
temp_dir = Path(temp_dir)
def process_page(page_number, image):
page_path = temp_dir / f"{page_number:04d}.jpg"
image.save(page_path, "JPEG")
result = predict_space_api(
page_path,
get_client(),
args.max_size,
args.prompt_size,
args.strength,
)
return space_result_to_pil(result)
return run_concurrent_pages(pages, args.concurrency, process_page)
def write_pdf_from_images(images, output_pdf, dpi):
output_pdf = Path(output_pdf)
output_pdf.parent.mkdir(parents=True, exist_ok=True)
images = list(images)
if not images:
raise RuntimeError("No restored pages were generated.")
first_page, rest = images[0], images[1:]
first_page.save(
output_pdf,
"PDF",
save_all=True,
append_images=rest,
resolution=dpi,
)
return output_pdf
def close_images(images):
for image in images:
image.close()
def positive_int(parser, name, value):
if value < 1:
parser.error(f"{name} must be at least 1")
def non_negative_int(parser, name, value):
if value is not None and value < 0:
parser.error(f"{name} must be non-negative")
def get_args():
parser = argparse.ArgumentParser(
description="Optimize a PDF with DocRes appearance restoration."
)
parser.add_argument("pdf", nargs="?", help="Input PDF file.")
parser.add_argument("--pdf_path", type=str, default=None, help="Input PDF file.")
parser.add_argument(
"--out_folder",
type=str,
default="./restored/",
help="Folder for the optimized PDF.",
)
parser.add_argument(
"--model_path",
type=str,
default="./checkpoints/docres.pkl",
help="Path to the DocRes checkpoint.",
)
parser.add_argument(
"--device",
choices=["auto", "cuda", "mps", "cpu"],
default="auto",
help="Inference device. auto uses CUDA, then MPS, then CPU.",
)
parser.add_argument(
"--precision",
choices=["auto", "fp16", "fp32"],
default="auto",
help="Inference precision. auto uses fp16 on CUDA/MPS and fp32 on CPU.",
)
parser.add_argument(
"--max_size",
type=int,
default=1280,
help=(
"Square model input size for oversized images. "
"Set to 0 for full-resolution model inference."
),
)
parser.add_argument(
"--prompt_size",
type=int,
default=1024,
help=(
"Square size for appearance prompt calculation. "
"Set to 0 to use the full input size."
),
)
parser.add_argument(
"--strength",
type=float,
default=1.0,
help="Blend amount for the restored result, where 1 keeps the full restoration and 0 keeps the original.",
)
parser.add_argument(
"--concurrency",
type=int,
default=2,
help="Number of pages to optimize concurrently.",
)
parser.add_argument(
"--max_inches",
"--max-inches",
dest="max_inches",
type=float,
default=DEFAULT_MAX_INCHES,
help="Maximum allowed PDF page width or height in inches before DPI is scaled down.",
)
parser.add_argument(
"--default_dpi",
"--default-dpi",
dest="default_dpi",
type=int,
default=DEFAULT_DPI,
help="Default PDF rendering DPI.",
)
parser.add_argument(
"--space_api",
action="store_true",
help=(
"Run inference through the Hugging Face Space API instead of "
"loading the model locally."
),
)
parser.add_argument(
"--space_id",
type=str,
default=DEFAULT_SPACE_ID,
help="Hugging Face Space ID to use with --space_api.",
)
parser.add_argument(
"--hf_token",
type=str,
default=os.getenv("HF_TOKEN"),
help="Optional Hugging Face token for private Spaces. Defaults to HF_TOKEN.",
)
args = parser.parse_args()
if args.pdf and args.pdf_path:
parser.error(
"Provide the input PDF either positionally or with --pdf_path, not both"
)
args.pdf_path = args.pdf_path or args.pdf
if not args.pdf_path:
parser.error("An input PDF is required")
non_negative_int(parser, "--max_size", args.max_size)
non_negative_int(parser, "--prompt_size", args.prompt_size)
if not 0.0 <= args.strength <= 1.0:
parser.error("--strength must be between 0 and 1")
positive_int(parser, "--concurrency", args.concurrency)
positive_int(parser, "--default_dpi", args.default_dpi)
if args.max_inches <= 0:
parser.error("--max_inches must be positive")
return args
def main():
args = get_args()
pdf_path = Path(args.pdf_path)
if not pdf_path.exists():
raise FileNotFoundError(f"PDF not found: {pdf_path}")
if not pdf_path.is_file():
raise ValueError(f"PDF path is not a file: {pdf_path}")
page_count, dpi = read_pdf_info(pdf_path, args.max_inches, args.default_dpi)
print(f"Extracting {page_count} pages at {dpi} DPI")
pages = extract_pdf_pages(pdf_path, page_count, dpi)
restored_pages = []
try:
if args.space_api:
restored_pages = run_space_api_pages(args, pages)
else:
restored_pages = run_local_pages(args, pages)
output_pdf = write_pdf_from_images(
restored_pages,
output_path_for_pdf(pdf_path, args.out_folder),
dpi,
)
print(f"Saved: {output_pdf}")
finally:
close_images(pages)
close_images(restored_pages)
if __name__ == "__main__":
main()