CoolFace
Apppublic

VTdevelops/bond-text-extraction

sourceHugging Faceupdated 5mo agoView on Hugging Face
0likes
pdf_loader.py45 linesDownload Raw Back to text_extraction
1from __future__ import annotations2 3from pathlib import Path4 5from pypdf import PdfReader6 7 8class PdfExtractionError(RuntimeError):9    """Raised when PDF text extraction fails."""10 11 12def extract_text_from_pdf(pdf_path: Path) -> str:13    """Read textual content from *pdf_path*.14 15    The function uses pypdf, which means the PDF must contain extractable text16    (it will not OCR scanned images)."""17 18    if not pdf_path.exists():19        raise PdfExtractionError(f"PDF does not exist: {pdf_path}")20    if not pdf_path.is_file():21        raise PdfExtractionError(f"Expected a file but found: {pdf_path}")22 23    try:24        reader = PdfReader(str(pdf_path))25    except Exception as exc:  # pragma: no cover - defensive path26        raise PdfExtractionError(f"Failed to open PDF {pdf_path}: {exc}") from exc27 28    pages: list[str] = []29    for index, page in enumerate(reader.pages):30        try:31            text = page.extract_text() or ""32        except Exception as exc:  # pragma: no cover - defensive path33            raise PdfExtractionError(34                f"Failed to extract text from page {index} in {pdf_path}: {exc}"35            ) from exc36        pages.append(text.strip())37 38    return "\n\n".join(filter(None, pages))39 40 41def extract_text_from_pdfs(paths: list[Path]) -> list[str]:42    """Extract text for each PDF path and return the list of page content."""43 44    return [extract_text_from_pdf(path) for path in paths]45