File size: 847 Bytes
26fe5b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os


def read_file(path: str) -> str:
    if not os.path.isfile(path):
        return f"Error: file not found at {path}"

    ext = os.path.splitext(path)[1].lower()

    if ext in (".txt", ".csv", ".md", ".json", ".xml", ".yaml", ".yml"):
        with open(path, "r", encoding="utf-8", errors="replace") as f:
            return f.read()
    elif ext == ".pdf":
        return _read_pdf(path)
    elif ext in (".png", ".jpg", ".jpeg", ".gif", ".bmp"):
        return f"[Image file: {os.path.basename(path)}]"
    else:
        return f"[Unsupported file type: {ext}]"


def _read_pdf(path: str) -> str:
    try:
        import pdfminer.high_level
        text = pdfminer.high_level.extract_text(path)
        return text if text.strip() else "[PDF: no extractable text]"
    except ImportError:
        return "[PDF reader not available]"