local.py
8.29 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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
from __future__ import annotations
import statistics
from pathlib import Path
from typing import Any
from openpyxl import load_workbook
from weknora_eval.loaders import compact_text, write_json, write_jsonl
from weknora_eval.schemas import ParsedDocument
def parse_raw_docs(config: dict[str, Any]) -> tuple[list[dict[str, Any]], dict[str, Any]]:
parsing = config["parsing"]
local_config = parsing.get("local", {})
min_chars = int(local_config.get("min_chars", 80))
pdf_backend = local_config.get("pdf_backend", "pypdf")
xlsx_mode = local_config.get("xlsx_mode", "row_text")
docs: list[ParsedDocument] = []
failures: list[dict[str, Any]] = []
for pdf_path in sorted(Path("data/raw_docs/pdf").glob("*.pdf")):
try:
docs.extend(parse_pdf(pdf_path, backend=pdf_backend, min_chars=min_chars))
except Exception as exc: # noqa: BLE001 - parser failures must be persisted.
failures.append(
{
"source_file": pdf_path.name,
"parser": f"local:{pdf_backend}",
"status": "failed",
"error": str(exc),
"fallback_used": None,
}
)
for xlsx_path in sorted(Path("data/raw_docs/xlsx").glob("*.xlsx")):
try:
docs.extend(parse_xlsx(xlsx_path, mode=xlsx_mode, min_chars=min_chars))
except Exception as exc: # noqa: BLE001
failures.append(
{
"source_file": xlsx_path.name,
"parser": "local:openpyxl",
"status": "failed",
"error": str(exc),
"fallback_used": None,
}
)
rows = [doc.to_dict() for doc in docs]
write_jsonl(parsing.get("output_path", "data/parsed_docs/documents.jsonl"), rows)
if failures:
write_jsonl(parsing.get("failed_path", "data/parsed_docs/failed_parse.jsonl"), failures)
summary = build_parse_summary(rows, failures, parser=f"local:{pdf_backend}")
write_json(parsing.get("summary_path", "data/parsed_docs/parse_summary.json"), summary)
return rows, summary
def parse_pdf(path: str | Path, *, backend: str = "pypdf", min_chars: int = 80) -> list[ParsedDocument]:
target = Path(path)
backend = backend.lower()
if backend == "pymupdf":
return _parse_pdf_pymupdf(target, min_chars=min_chars)
if backend == "pdfplumber":
return _parse_pdf_pdfplumber(target, min_chars=min_chars)
if backend == "pypdf":
return _parse_pdf_pypdf(target, min_chars=min_chars)
raise ValueError(f"Unsupported PDF backend: {backend}")
def _parse_pdf_pypdf(path: Path, *, min_chars: int) -> list[ParsedDocument]:
from pypdf import PdfReader
reader = PdfReader(str(path))
docs: list[ParsedDocument] = []
for index, page in enumerate(reader.pages, start=1):
content = compact_text(page.extract_text() or "")
if len(content) < min_chars:
continue
docs.append(_pdf_doc(path, index, content, "local:pypdf"))
return docs
def _parse_pdf_pymupdf(path: Path, *, min_chars: int) -> list[ParsedDocument]:
try:
import fitz
except ImportError as exc:
raise ImportError("pymupdf backend requires `pip install -e '.[pdf]'`") from exc
docs: list[ParsedDocument] = []
with fitz.open(path) as document:
for index, page in enumerate(document, start=1):
content = compact_text(page.get_text("text"))
if len(content) < min_chars:
continue
docs.append(_pdf_doc(path, index, content, "local:pymupdf"))
return docs
def _parse_pdf_pdfplumber(path: Path, *, min_chars: int) -> list[ParsedDocument]:
try:
import pdfplumber
except ImportError as exc:
raise ImportError("pdfplumber backend requires `pip install -e '.[pdf]'`") from exc
docs: list[ParsedDocument] = []
with pdfplumber.open(path) as pdf:
for index, page in enumerate(pdf.pages, start=1):
content = compact_text(page.extract_text() or "")
if len(content) < min_chars:
continue
docs.append(_pdf_doc(path, index, content, "local:pdfplumber"))
return docs
def _pdf_doc(path: Path, page: int, content: str, parser: str) -> ParsedDocument:
return ParsedDocument(
doc_id=f"{path.name}::page-{page}",
source_file=path.name,
file_type="pdf",
page=page,
content=content,
metadata={"parser": parser},
)
def parse_xlsx(path: str | Path, *, mode: str = "row_text", min_chars: int = 80) -> list[ParsedDocument]:
target = Path(path)
mode = mode.lower()
workbook = load_workbook(target, data_only=True, read_only=True)
if mode == "row_text":
return _parse_xlsx_row_text(target, workbook, min_chars=min_chars)
if mode == "markdown_table":
return _parse_xlsx_markdown_table(target, workbook, min_chars=min_chars)
raise ValueError(f"Unsupported XLSX mode: {mode}")
def _parse_xlsx_row_text(path: Path, workbook: Any, *, min_chars: int) -> list[ParsedDocument]:
docs: list[ParsedDocument] = []
for sheet in workbook.worksheets:
rows = list(sheet.iter_rows(values_only=True))
if not rows:
continue
headers = [_cell_to_text(value) or f"col_{index}" for index, value in enumerate(rows[0], start=1)]
for row_index, row in enumerate(rows[1:], start=2):
pairs = []
for header, value in zip(headers, row, strict=False):
cell = _cell_to_text(value)
if cell:
pairs.append(f"{header}: {cell}")
content = "\n".join(pairs).strip()
if len(content) < min_chars:
continue
docs.append(
ParsedDocument(
doc_id=f"{path.name}::{sheet.title}::row-{row_index}",
source_file=path.name,
file_type="xlsx",
sheet=sheet.title,
row_index=row_index,
content=content,
metadata={"parser": "local:openpyxl", "columns": headers},
)
)
return docs
def _parse_xlsx_markdown_table(path: Path, workbook: Any, *, min_chars: int) -> list[ParsedDocument]:
docs: list[ParsedDocument] = []
for sheet in workbook.worksheets:
rows = [
[_cell_to_text(value) for value in row]
for row in sheet.iter_rows(values_only=True)
if any(value is not None for value in row)
]
if not rows:
continue
width = max(len(row) for row in rows)
normalized = [row + [""] * (width - len(row)) for row in rows]
header = normalized[0]
separator = ["---"] * width
body = normalized[1:]
lines = [
"| " + " | ".join(header) + " |",
"| " + " | ".join(separator) + " |",
]
lines.extend("| " + " | ".join(row) + " |" for row in body)
content = "\n".join(lines)
if len(content) < min_chars:
continue
docs.append(
ParsedDocument(
doc_id=f"{path.name}::{sheet.title}",
source_file=path.name,
file_type="xlsx",
sheet=sheet.title,
content=content,
metadata={"parser": "local:openpyxl", "mode": "markdown_table"},
)
)
return docs
def _cell_to_text(value: Any) -> str:
if value is None:
return ""
text = str(value).strip()
return text.replace("\n", " ")
def build_parse_summary(
rows: list[dict[str, Any]],
failures: list[dict[str, Any]],
*,
parser: str,
) -> dict[str, Any]:
source_files = {row.get("source_file") for row in rows if row.get("source_file")}
failed_files = {row.get("source_file") for row in failures if row.get("source_file")}
lengths = [len(row.get("content") or "") for row in rows]
return {
"total_files": len(source_files | failed_files),
"parsed_files": len(source_files),
"failed_files": len(failed_files),
"total_documents": len(rows),
"empty_documents": sum(1 for length in lengths if length == 0),
"avg_chars": round(statistics.mean(lengths), 2) if lengths else 0,
"parser": parser,
}