"""DOCX loader using python-docx."""
from zipfile import BadZipFile
from docx.opc.exceptions import PackageNotFoundError
from langchain_core.documents import Document
from .base import BaseFileLoader
[docs]
class DOCXFileLoader(BaseFileLoader):
"""Extract paragraphs and tables from Microsoft Word documents."""
[docs]
def load(self) -> list[Document]:
"""Extract paragraph text and table rows in document order by section."""
from docx import Document as WordDocument
try:
word_document = WordDocument(self.file_path)
sections = [
paragraph.text.strip()
for paragraph in word_document.paragraphs
if paragraph.text.strip()
]
for table in word_document.tables:
rows = [
" | ".join(cell.text.strip() for cell in row.cells)
for row in table.rows
]
if rows:
sections.append("\n".join(rows))
except (OSError, ValueError, KeyError, BadZipFile, PackageNotFoundError) as exc:
raise RuntimeError(
f"Failed to load DOCX file {self.file_path}: {exc}"
) from exc
content = "\n\n".join(sections)
return [
Document(page_content=content, metadata={"source": str(self.file_path)})
]
[docs]
@staticmethod
def get_install_command() -> str:
"""Return the installation command for this loader."""
return "pip install python-docx"