Spaces:
Sleeping
Sleeping
Download src/pdf_processing/extractor.py from yashpixl09/IP-Safe: direct link, hf CLI and curl.
- Browser
- Download file 4.58 kB
-
https://huggingface.co/spaces/yashpixl09/IP-Safe/resolve/main/src/pdf_processing/extractor.py
- Command line
-
hf download hf://spaces/yashpixl09/IP-Safe/src/pdf_processing/extractor.py
-
curl -L -o extractor.py https://huggingface.co/spaces/yashpixl09/IP-Safe/resolve/main/src/pdf_processing/extractor.py
4.58 kB
| """PDF image extraction module using PyMuPDF.""" | |
| import fitz # PyMuPDF | |
| from PIL import Image | |
| import io | |
| import os | |
| from typing import List, Dict | |
| from loguru import logger | |
| class PDFImageExtractor: | |
| """Extract images from PDF files at high resolution.""" | |
| def __init__(self, output_dir: str = "output/extracted"): | |
| """ | |
| Initialize the PDF image extractor. | |
| Args: | |
| output_dir: Directory to save extracted images | |
| """ | |
| self.output_dir = output_dir | |
| os.makedirs(output_dir, exist_ok=True) | |
| def extract_images_from_pdf(self, pdf_path: str) -> List[Dict]: | |
| """ | |
| Extract all images from a PDF file. | |
| Args: | |
| pdf_path: Path to the PDF file | |
| Returns: | |
| List of dictionaries containing image metadata: | |
| [ | |
| { | |
| 'image_id': 'page_01_img_001', | |
| 'page_number': 1, | |
| 'image_index': 1, | |
| 'path': 'output/extracted/page_01_img_001.png', | |
| 'width': 2048, | |
| 'height': 2048 | |
| }, | |
| ... | |
| ] | |
| """ | |
| if not os.path.exists(pdf_path): | |
| raise FileNotFoundError(f"PDF file not found: {pdf_path}") | |
| logger.info(f"Opening PDF: {pdf_path}") | |
| doc = fitz.open(pdf_path) | |
| images = [] | |
| total_pages = len(doc) | |
| logger.info(f"PDF has {total_pages} pages") | |
| for page_num, page in enumerate(doc, start=1): | |
| logger.debug(f"Processing page {page_num}/{total_pages}") | |
| # Get all images on this page | |
| image_list = page.get_images(full=True) | |
| logger.debug(f"Found {len(image_list)} images on page {page_num}") | |
| for img_index, img_info in enumerate(image_list, start=1): | |
| try: | |
| # Extract image | |
| xref = img_info[0] | |
| base_image = doc.extract_image(xref) | |
| # Convert to PIL Image | |
| image_bytes = base_image["image"] | |
| image = Image.open(io.BytesIO(image_bytes)) | |
| # Generate unique image ID | |
| image_id = f"page_{page_num:02d}_img_{img_index:03d}" | |
| # Save as PNG (lossless) | |
| output_path = os.path.join(self.output_dir, f"{image_id}.png") | |
| image.save(output_path, "PNG") | |
| logger.info(f"Extracted {image_id}: {image.width}x{image.height}") | |
| images.append( | |
| { | |
| "image_id": image_id, | |
| "page_number": page_num, | |
| "image_index": img_index, | |
| "path": output_path, | |
| "width": image.width, | |
| "height": image.height, | |
| "format": base_image.get("ext", "unknown"), | |
| } | |
| ) | |
| except Exception as e: | |
| logger.error( | |
| f"Failed to extract image {img_index} from page {page_num}: {e}" | |
| ) | |
| continue | |
| doc.close() | |
| logger.info(f"Successfully extracted {len(images)} images from PDF") | |
| return images | |
| def validate_images(self, images: List[Dict], min_size: int = 100) -> List[Dict]: | |
| """ | |
| Validate extracted images (minimum size, corruption check). | |
| Args: | |
| images: List of image metadata dicts | |
| min_size: Minimum width/height in pixels | |
| Returns: | |
| List of valid image metadata dicts | |
| """ | |
| valid_images = [] | |
| for img_meta in images: | |
| try: | |
| # Check size | |
| if img_meta["width"] < min_size or img_meta["height"] < min_size: | |
| logger.warning( | |
| f"Image {img_meta['image_id']} too small " | |
| f"({img_meta['width']}x{img_meta['height']}), skipping" | |
| ) | |
| continue | |
| # Verify image file can be opened | |
| with Image.open(img_meta["path"]) as img: | |
| img.verify() | |
| valid_images.append(img_meta) | |
| except Exception as e: | |
| logger.error(f"Invalid image {img_meta['image_id']}: {e}") | |
| continue | |
| logger.info(f"Validated {len(valid_images)}/{len(images)} images") | |
| return valid_images | |