document_parser.py 725 B

123456789101112131415161718192021
  1. from pathlib import Path
  2. from docx import Document
  3. from pypdf import PdfReader
  4. class DocumentParser:
  5. @staticmethod
  6. def parse_file(file_path: str) -> str:
  7. path = Path(file_path)
  8. suffix = path.suffix.lower()
  9. if suffix == ".txt":
  10. return path.read_text(encoding="utf-8", errors="ignore")
  11. if suffix == ".docx":
  12. doc = Document(file_path)
  13. return "\n".join([p.text for p in doc.paragraphs if p.text.strip()])
  14. if suffix == ".pdf":
  15. reader = PdfReader(file_path)
  16. pages = [page.extract_text() or "" for page in reader.pages]
  17. return "\n".join(pages)
  18. return path.read_text(encoding="utf-8", errors="ignore")