Spaces:
Sleeping
Sleeping
Download ocr/pdf_utils.py from afueth/malayalam-ocr: direct link, hf CLI and curl.
- Browser
- Download file 696 Bytes
-
https://huggingface.co/spaces/afueth/malayalam-ocr/resolve/main/ocr/pdf_utils.py
- Command line
-
hf download hf://spaces/afueth/malayalam-ocr/ocr/pdf_utils.py
-
curl -L -o pdf_utils.py https://huggingface.co/spaces/afueth/malayalam-ocr/resolve/main/ocr/pdf_utils.py
696 Bytes
| from __future__ import annotations | |
| import io | |
| import fitz # PyMuPDF | |
| from PIL import Image | |
| def pdf_has_native_text(page: fitz.Page, min_chars: int = 50) -> bool: | |
| txt = (page.get_text("text") or "").strip() | |
| return len(txt) >= min_chars | |
| def extract_native_text(page: fitz.Page) -> str: | |
| return (page.get_text("text") or "").strip() | |
| def render_page_to_pil(page: fitz.Page, zoom: float = 2.0) -> Image.Image: | |
| """ | |
| Render PDF page to image for OCR. zoom ~2.0 is a good balance. | |
| Higher zoom -> better OCR but slower. | |
| """ | |
| mat = fitz.Matrix(zoom, zoom) | |
| pix = page.get_pixmap(matrix=mat, alpha=False) | |
| img = Image.open(io.BytesIO(pix.tobytes("png"))) | |
| return img | |