Download services/pdf_utils.py from ZeloTech/zelotech: direct link, hf CLI and curl.
- Browser
- Download file 974 Bytes
-
https://huggingface.co/spaces/ZeloTech/zelotech/resolve/main/services/pdf_utils.py
- Command line
-
hf download hf://spaces/ZeloTech/zelotech/services/pdf_utils.py
-
curl -L -o pdf_utils.py https://huggingface.co/spaces/ZeloTech/zelotech/resolve/main/services/pdf_utils.py
974 Bytes
| import io | |
| import fitz # PyMuPDF | |
| from PIL import Image | |
| from services.ocr import ocr_image | |
| def extract_pdf_text( | |
| path: str, | |
| dpi: int = 300, | |
| min_chars_per_page: int = 20, | |
| lang: str = "por", | |
| ) -> str: | |
| """Extrai texto de um PDF, pagina a pagina. | |
| Se a pagina ja tem camada de texto, usa-a direto (rapido e exato). | |
| Se for uma pagina escaneada (texto ausente ou irrisorio), rasteriza | |
| a pagina e roda OCR. Assim PDFs mistos tambem funcionam. | |
| """ | |
| parts: list[str] = [] | |
| with fitz.open(path) as doc: | |
| for page in doc: | |
| text = page.get_text("text").strip() | |
| if len(text) >= min_chars_per_page: | |
| parts.append(text) | |
| else: | |
| pix = page.get_pixmap(dpi=dpi) | |
| img = Image.open(io.BytesIO(pix.tobytes("png"))) | |
| parts.append(ocr_image(img, lang=lang).strip()) | |
| return "\n".join(p for p in parts if p).strip() | |