File size: 1,869 Bytes
26b8deb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
"""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}")