|
| 1 | +from pathlib import Path |
| 2 | +from PyPDF2 import PdfReader |
| 3 | +import docx |
| 4 | + |
| 5 | + |
| 6 | +SUPPORTED_EXTENSIONS = {'.txt', '.md', '.pdf', '.docx', '.csv'} |
| 7 | + |
| 8 | + |
| 9 | +def extract_text(file_path: str) -> str: |
| 10 | + path = Path(file_path) |
| 11 | + ext = path.suffix.lower() |
| 12 | + |
| 13 | + if ext not in SUPPORTED_EXTENSIONS: |
| 14 | + raise ValueError(f"Unsupported format: {ext}") |
| 15 | + |
| 16 | + extractors = { |
| 17 | + '.txt': extract_txt, |
| 18 | + '.md': extract_markdown, |
| 19 | + '.pdf': extract_pdf, |
| 20 | + '.docx': extract_docx, |
| 21 | + '.csv': extract_csv, |
| 22 | + } |
| 23 | + |
| 24 | + return extractors[ext](file_path) |
| 25 | + |
| 26 | + |
| 27 | +def extract_txt(file_path: str) -> str: |
| 28 | + with open(file_path, 'r', encoding='utf-8', errors='ignore') as f: |
| 29 | + return f.read() |
| 30 | + |
| 31 | + |
| 32 | +def extract_markdown(file_path: str) -> str: |
| 33 | + with open(file_path, 'r', encoding='utf-8', errors='ignore') as f: |
| 34 | + return f.read() |
| 35 | + |
| 36 | + |
| 37 | +def extract_pdf(file_path: str) -> str: |
| 38 | + reader = PdfReader(file_path) |
| 39 | + text_parts = [] |
| 40 | + for page in reader.pages: |
| 41 | + text = page.extract_text() |
| 42 | + if text: |
| 43 | + text_parts.append(text) |
| 44 | + return "\n\n".join(text_parts) |
| 45 | + |
| 46 | + |
| 47 | +def extract_docx(file_path: str) -> str: |
| 48 | + doc = docx.Document(file_path) |
| 49 | + paragraphs = [p.text for p in doc.paragraphs if p.text.strip()] |
| 50 | + return "\n\n".join(paragraphs) |
| 51 | + |
| 52 | + |
| 53 | +def extract_csv(file_path: str) -> str: |
| 54 | + with open(file_path, 'r', encoding='utf-8', errors='ignore') as f: |
| 55 | + return f.read() |
0 commit comments