test_document_parser_vlm.py
11.6 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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
import os
from pathlib import Path
from types import SimpleNamespace
import tempfile
import unittest
from unittest.mock import patch
from src.tools import document_parser
class DocumentParserVlmTest(unittest.TestCase):
def test_is_presentation_file_matches_ppt_and_pptx_only(self):
self.assertTrue(document_parser.is_presentation_file("slides.ppt"))
self.assertTrue(document_parser.is_presentation_file("slides.PPTX"))
self.assertFalse(document_parser.is_presentation_file("notes.pdf"))
self.assertFalse(document_parser.is_presentation_file("doc.docx"))
def test_pdf_uses_existing_rag_pdf_loader(self):
with tempfile.TemporaryDirectory() as tmp:
pdf_path = Path(tmp) / "sample.pdf"
pdf_path.write_bytes(b"not a real pdf")
called = {}
def fake_load_pdf(path):
called["path"] = path
return [
SimpleNamespace(text="第一页正文", block_type="paragraph", page_number=1, source_offset=0),
SimpleNamespace(text="| 列 | 值 |\n| --- | --- |\n| A | 1 |", block_type="table", page_number=1, source_offset=1),
SimpleNamespace(text="第二页正文", block_type="paragraph", page_number=2, source_offset=0),
]
with patch.object(document_parser, "_load_pdf_blocks", fake_load_pdf, create=True):
text = document_parser.extract_text_from_file(str(pdf_path))
self.assertEqual(called["path"], str(pdf_path))
self.assertIn("## Page 1", text)
self.assertIn("第一页正文", text)
self.assertIn("| 列 | 值 |", text)
self.assertIn("## Page 2", text)
self.assertIn("第二页正文", text)
def test_pdf_records_last_vlm_token_stats(self):
with tempfile.TemporaryDirectory() as tmp:
pdf_path = Path(tmp) / "sample.pdf"
pdf_path.write_bytes(b"not a real pdf")
def fake_load_pdf(path):
return [
SimpleNamespace(
text="第一页正文",
block_type="paragraph",
page_number=1,
source_offset=0,
metadata={
"parse_engine": "vlm",
"vlm_page_count": 2,
"vlm_input_tokens": 100,
"vlm_output_tokens": 20,
"vlm_image_tokens": 80,
"vlm_total_tokens": 120,
"vlm_duration_ms": 3210,
},
)
]
with patch.object(document_parser, "_load_pdf_blocks", fake_load_pdf, create=True):
document_parser.extract_text_from_file(str(pdf_path))
self.assertEqual(
document_parser.get_last_extract_stats(str(pdf_path)),
{
"parse_engine": "vlm",
"vlm_page_count": 2,
"vlm_input_tokens": 100,
"vlm_output_tokens": 20,
"vlm_image_tokens": 80,
"vlm_total_tokens": 120,
"vlm_duration_ms": 3210,
},
)
def test_pptx_converts_to_pdf_then_reuses_pdf_parser(self):
with tempfile.TemporaryDirectory() as tmp:
pptx_path = Path(tmp) / "slides.pptx"
pptx_path.write_bytes(b"fake pptx")
calls = {}
def fake_run(cmd, capture_output, text, timeout, check):
calls["cmd"] = cmd
outdir = Path(cmd[cmd.index("--outdir") + 1])
(outdir / "slides.pdf").write_bytes(b"fake pdf")
class Result:
stdout = "convert ok"
stderr = ""
return Result()
def fake_extract_pdf(path):
calls["pdf_path"] = Path(path)
return "PPT 转换后的 VLM 内容"
with (
patch("shutil.which", lambda name: "/usr/bin/soffice" if name == "soffice" else None),
patch("subprocess.run", fake_run),
patch.object(document_parser, "_extract_text_pdf", fake_extract_pdf),
):
text = document_parser.extract_text_from_file(str(pptx_path))
self.assertEqual(text, "PPT 转换后的 VLM 内容")
self.assertEqual(calls["cmd"][0], "/usr/bin/soffice")
self.assertIn("--headless", calls["cmd"])
self.assertIn("--convert-to", calls["cmd"])
self.assertTrue(
any(part.startswith("-env:UserInstallation=") for part in calls["cmd"]),
calls["cmd"],
)
self.assertEqual(calls["pdf_path"].name, "slides.pdf")
def test_ppt_requires_libreoffice(self):
with tempfile.TemporaryDirectory() as tmp:
ppt_path = Path(tmp) / "legacy.ppt"
ppt_path.write_bytes(b"fake ppt")
with (
patch("shutil.which", lambda name: None),
patch.object(document_parser.Path, "exists", lambda path: False),
):
with self.assertRaises(RuntimeError) as ctx:
document_parser.extract_text_from_file(str(ppt_path))
self.assertIn("LibreOffice", str(ctx.exception))
self.assertIn("soffice", str(ctx.exception))
def test_ppt_finds_windows_default_libreoffice_install(self):
with (
patch("shutil.which", lambda name: None),
patch.object(
document_parser.Path,
"exists",
lambda path: str(path) == r"C:\Program Files\LibreOffice\program\soffice.exe",
),
):
self.assertEqual(
document_parser._resolve_soffice_path(),
r"C:\Program Files\LibreOffice\program\soffice.exe",
)
def test_office_preview_pdf_uses_original_name_and_file_id_cache_name(self):
with tempfile.TemporaryDirectory() as tmp:
pptx_path = Path(tmp) / "七大轻改产品知识.pptx"
pptx_path.write_bytes(b"fake pptx")
preview_dir = Path(tmp) / "preview"
file_id = "a8771d59-ede5-40e9-b21c-72596674e21a"
calls = {}
def fake_run(cmd, capture_output, text, timeout, check):
calls["cmd"] = cmd
outdir = Path(cmd[cmd.index("--outdir") + 1])
(outdir / "七大轻改产品知识.pdf").write_bytes(b"fake pdf")
class Result:
stdout = "convert ok"
stderr = ""
return Result()
with (
patch("shutil.which", lambda name: "/usr/bin/soffice" if name == "soffice" else None),
patch("subprocess.run", fake_run),
):
pdf_path = document_parser.get_or_create_office_preview_pdf(
str(pptx_path),
file_id,
str(preview_dir),
)
expected_pdf = preview_dir / f"七大轻改产品知识_{file_id}.pdf"
self.assertEqual(Path(pdf_path), expected_pdf)
self.assertTrue(expected_pdf.exists())
self.assertEqual(calls["cmd"][0], "/usr/bin/soffice")
self.assertIn("--convert-to", calls["cmd"])
def test_office_preview_pdf_reuses_fresh_cache_without_conversion(self):
with tempfile.TemporaryDirectory() as tmp:
pptx_path = Path(tmp) / "slides.pptx"
pptx_path.write_bytes(b"fake pptx")
preview_dir = Path(tmp) / "preview"
preview_dir.mkdir()
file_id = "file-123"
cached_pdf = preview_dir / f"slides_{file_id}.pdf"
cached_pdf.write_bytes(b"cached pdf")
source_mtime = pptx_path.stat().st_mtime
os.utime(cached_pdf, (source_mtime + 10, source_mtime + 10))
with patch("subprocess.run") as run_mock:
pdf_path = document_parser.get_or_create_office_preview_pdf(
str(pptx_path),
file_id,
str(preview_dir),
)
self.assertEqual(Path(pdf_path), cached_pdf)
run_mock.assert_not_called()
def test_pptx_ingest_reuses_fresh_preview_pdf_without_conversion(self):
with tempfile.TemporaryDirectory() as tmp:
pptx_path = Path(tmp) / "slides.pptx"
pptx_path.write_bytes(b"fake pptx")
preview_dir = Path(tmp) / "preview"
preview_dir.mkdir()
file_id = "file-123"
cached_pdf = preview_dir / f"slides_{file_id}.pdf"
cached_pdf.write_bytes(b"cached pdf")
source_mtime = pptx_path.stat().st_mtime
os.utime(cached_pdf, (source_mtime + 10, source_mtime + 10))
def fake_extract_pdf(path):
self.assertEqual(Path(path), cached_pdf)
return "cached preview pdf content"
with (
patch("subprocess.run") as run_mock,
patch.object(document_parser, "_extract_text_pdf", fake_extract_pdf),
):
text = document_parser.extract_text_from_file(
str(pptx_path),
preview_file_id=file_id,
preview_dir=str(preview_dir),
)
self.assertEqual(text, "cached preview pdf content")
run_mock.assert_not_called()
def test_delete_office_preview_pdf_removes_cached_pdf(self):
with tempfile.TemporaryDirectory() as tmp:
pptx_path = Path(tmp) / "slides.pptx"
pptx_path.write_bytes(b"fake pptx")
preview_dir = Path(tmp) / "preview"
preview_dir.mkdir()
file_id = "file-123"
cached_pdf = preview_dir / f"slides_{file_id}.pdf"
cached_pdf.write_bytes(b"cached pdf")
deleted = document_parser.delete_office_preview_pdf(
str(pptx_path),
file_id,
str(preview_dir),
)
self.assertEqual(deleted, str(cached_pdf))
self.assertFalse(cached_pdf.exists())
def test_office_preview_pdf_overwrites_stale_cache(self):
with tempfile.TemporaryDirectory() as tmp:
pptx_path = Path(tmp) / "slides.pptx"
pptx_path.write_bytes(b"fake pptx")
preview_dir = Path(tmp) / "preview"
preview_dir.mkdir()
file_id = "file-123"
cached_pdf = preview_dir / f"slides_{file_id}.pdf"
cached_pdf.write_bytes(b"old pdf")
source_mtime = pptx_path.stat().st_mtime
os.utime(cached_pdf, (source_mtime - 10, source_mtime - 10))
def fake_run(cmd, capture_output, text, timeout, check):
outdir = Path(cmd[cmd.index("--outdir") + 1])
(outdir / "slides.pdf").write_bytes(b"new pdf")
class Result:
stdout = "convert ok"
stderr = ""
return Result()
with (
patch("shutil.which", lambda name: "/usr/bin/soffice" if name == "soffice" else None),
patch("subprocess.run", fake_run),
):
pdf_path = document_parser.get_or_create_office_preview_pdf(
str(pptx_path),
file_id,
str(preview_dir),
)
self.assertEqual(Path(pdf_path), cached_pdf)
self.assertEqual(cached_pdf.read_bytes(), b"new pdf")
if __name__ == "__main__":
unittest.main()