Spaces:
Sleeping
Sleeping
File size: 12,433 Bytes
5dc8e48 fe07779 5dc8e48 fe07779 5dc8e48 fe07779 5dc8e48 fe07779 5dc8e48 fe07779 5dc8e48 fe07779 5dc8e48 fe07779 5dc8e48 fe07779 5dc8e48 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 | 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()
|