DocuPurse / src /extraction.py
Zayeemk's picture
Initial commit: DocuParse AI complete implementation
26b8deb
Raw History Blame Contribute Delete
1.87 kB
"""Document text extraction coordinator.
Responsible for:
- Determining extraction method based on file type
- Coordinating PDF parsing and OCR
- Returning raw text and method metadata
Does NOT perform financial validation or LLM calls.
"""
from __future__ import annotations
import logging
from pathlib import Path
from typing import Tuple
from .utils import get_file_extension, validate_file
logger = logging.getLogger(__name__)
def extract_text_from_file(file_path: str) -> Tuple[str, str, int]:
"""
Extract text from any supported file type.
Returns:
(text, extraction_method, page_count)
where extraction_method is one of:
'native_pdf_text' | 'ocr' | 'plain_text'
"""
validate_file(file_path)
ext = get_file_extension(file_path)
if ext == ".pdf":
from .pdf_parser import extract_text_from_pdf
text, method, pages = extract_text_from_pdf(file_path)
if not text.strip():
raise ValueError(
"No text could be extracted from this PDF. "
"The file may be empty, corrupted, or a scanned image requiring better OCR."
)
return text, method, pages
elif ext in (".png", ".jpg", ".jpeg"):
from .ocr import ocr_image_file
text = ocr_image_file(file_path)
if not text.strip():
raise ValueError(
"OCR produced no text from this image. "
"The image may be blank, too blurry, or not contain readable text."
)
return text, "ocr", 1
elif ext == ".txt":
content = Path(file_path).read_text(encoding="utf-8", errors="replace")
if not content.strip():
raise ValueError("The text file is empty.")
return content.strip(), "plain_text", 1
else:
raise ValueError(f"Unsupported file type: {ext}")