zelotech / services /pdf_utils.py
matheusalencar's picture
first commit
1b64148
Raw History Blame Contribute Delete
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()