test_document_parser_vlm.py 11.6 KB
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()