office_loader.py 4.47 KB
from __future__ import annotations

import re

from src.rag.loaders.base import DocumentBlock, register_loader
from src.rag.loaders.common import enrich_blocks
from src.rag.utils import normalize_text


class DocxLoader:
    extensions = {".docx"}

    def load(self, path: str) -> list[DocumentBlock]:
        import docx
        from docx.table import Table
        from docx.text.paragraph import Paragraph

        doc = docx.Document(path)
        blocks: list[DocumentBlock] = []
        headings: list[str] = []
        offset = 0

        def iter_body_items():
            for child in doc.element.body.iterchildren():
                if child.tag.endswith("}p"):
                    yield Paragraph(child, doc)
                elif child.tag.endswith("}tbl"):
                    yield Table(child, doc)

        for item in iter_body_items():
            if isinstance(item, Table):
                rows = _docx_table_rows(item)
                if rows:
                    blocks.append(
                        DocumentBlock(
                            text="\n".join(rows),
                            block_type="table",
                            title_path=" / ".join(headings),
                            source_offset=offset,
                            metadata={
                                "parse_method": "docx_table",
                                "content_role": "table",
                                "content_kind": "table",
                                "table_id": f"docx_table_{offset}",
                            },
                        )
                    )
                    offset += 1
                continue

            text = item.text.strip()
            if not text:
                continue
            style = (item.style.name or "").lower()
            if "heading" in style or "title" in style or "biaoti" in style:
                level_match = re.search(r"(\d+)", style)
                level = int(level_match.group(1)) if level_match else 1
                headings[:] = headings[: level - 1]
                headings.append(text)
                continue
            blocks.append(
                DocumentBlock(
                    text=text,
                    title_path=" / ".join(headings),
                    source_offset=offset,
                    metadata={
                        "parse_method": "docx_paragraph",
                        "content_role": "body",
                        "content_kind": "text",
                    },
                )
            )
            offset += 1

        return enrich_blocks(blocks, parse_method="docx")


def _docx_table_rows(table) -> list[str]:
    rows = []
    for row in table.rows:
        cells = [cell.text.strip().replace("\n", " ") for cell in row.cells]
        if any(cells):
            rows.append("| " + " | ".join(cells) + " |")
    if not rows:
        return []
    width = max(rows[0].count("|") - 1, 1)
    rows.insert(1, "| " + " | ".join(["---"] * width) + " |")
    return rows


class PptxLoader:
    extensions = {".pptx"}

    def load(self, path: str) -> list[DocumentBlock]:
        import pptx

        prs = pptx.Presentation(path)
        blocks: list[DocumentBlock] = []
        for slide_index, slide in enumerate(prs.slides, start=1):
            texts = []
            for shape in slide.shapes:
                if hasattr(shape, "text") and shape.text.strip():
                    texts.append(shape.text.strip())
            if texts:
                title = texts[0].splitlines()[0][:120]
                blocks.append(
                    DocumentBlock(
                        text=normalize_text("\n\n".join(texts)),
                        title_path=title,
                        slide_number=slide_index,
                        source_offset=slide_index,
                        metadata={
                            "parse_method": "pptx_slide",
                            "content_role": "body",
                            "content_kind": "slide_text",
                            "section_path": [title],
                            "section_title": title,
                        },
                    )
                )
        return enrich_blocks(blocks, parse_method="pptx")


class LegacyPptLoader:
    extensions = {".ppt"}

    def load(self, path: str) -> list[DocumentBlock]:
        raise RuntimeError("Direct .ppt parsing is not supported. Please convert it to .pptx before uploading.")


register_loader(DocxLoader())
register_loader(PptxLoader())
register_loader(LegacyPptLoader())