office.py
4.5 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
from __future__ import annotations
import re
from src.rag.ingestion.loaders.base import DocumentBlock, register_loader
from src.rag.ingestion.loaders.common import enrich_blocks
from src.rag.core.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())