diff --git a/docreader/parser/registry.py b/docreader/parser/registry.py index 7016d298..158fd176 100644 --- a/docreader/parser/registry.py +++ b/docreader/parser/registry.py @@ -16,6 +16,7 @@ from docreader.parser.opendataloader_parser import ( opendataloader_available, ) from docreader.parser.pdf_parser import PDFParser +from docreader.parser.xmind_parser import XMindParser logger = logging.getLogger(__name__) @@ -140,6 +141,7 @@ def _build_default_registry() -> ParserEngineRegistry: "html": HTMLParser, "htm": HTMLParser, "mhtml": MHTMLParser, + "xmind": XMindParser, **_image_types, }, description="内置解析引擎", diff --git a/docreader/parser/xmind_parser.py b/docreader/parser/xmind_parser.py new file mode 100644 index 00000000..90ae3c00 --- /dev/null +++ b/docreader/parser/xmind_parser.py @@ -0,0 +1,246 @@ +"""Parse XMind archives into Markdown outlines.""" + +import io +import json +import zipfile +from dataclasses import dataclass, field +from xml.etree import ElementTree +from xml.etree.ElementTree import Element + +from docreader.models.document import Document +from docreader.parser.base_parser import BaseParser + + +MAX_CONTENT_BYTES = 32 * 1024 * 1024 + + +@dataclass +class _Topic: + title: str = "" + note: str = "" + children: list["_Topic"] = field(default_factory=list) + + +@dataclass +class _Sheet: + title: str = "" + root_topic: _Topic | None = None + + +def _clean_text(value: object) -> str: + return value.strip() if isinstance(value, str) else "" + + +def _topic_from_json(value: object) -> _Topic | None: + if not isinstance(value, dict): + return None + + note = "" + notes = value.get("notes") + if isinstance(notes, dict): + plain = notes.get("plain") + if isinstance(plain, dict): + note = _clean_text(plain.get("content")) + + topics: list[_Topic] = [] + children = value.get("children") + if isinstance(children, dict): + attached = children.get("attached") + if isinstance(attached, list): + for child in attached: + topic = _topic_from_json(child) + if topic is not None: + topics.append(topic) + + return _Topic( + title=_clean_text(value.get("title")), + note=note, + children=topics, + ) + + +def _parse_json_sheets(payload: bytes) -> list[_Sheet]: + values = json.loads(payload) + if not isinstance(values, list): + raise ValueError("invalid XMind content.json: expected a sheet list") + + sheets: list[_Sheet] = [] + for value in values: + if not isinstance(value, dict): + continue + sheets.append( + _Sheet( + title=_clean_text(value.get("title")), + root_topic=_topic_from_json(value.get("rootTopic")), + ) + ) + return sheets + + +def _local_name(tag: str) -> str: + return tag.rsplit("}", 1)[-1].split(":", 1)[-1] + + +def _direct_children(element: Element, name: str) -> list[Element]: + return [child for child in element if _local_name(child.tag) == name] + + +def _first_child(element: Element, name: str) -> Element | None: + children = _direct_children(element, name) + return children[0] if children else None + + +def _element_text(element: Element | None) -> str: + if element is None: + return "" + return "".join(element.itertext()).strip() + + +def _topic_from_xml(element: Element) -> _Topic: + notes = _first_child(element, "notes") + plain = _first_child(notes, "plain") if notes is not None else None + + topics: list[_Topic] = [] + for children in _direct_children(element, "children"): + for topic_group in _direct_children(children, "topics"): + topics.extend( + _topic_from_xml(topic) + for topic in _direct_children(topic_group, "topic") + ) + + return _Topic( + title=_element_text(_first_child(element, "title")), + note=_element_text(plain), + children=topics, + ) + + +def _parse_xml_sheets(payload: bytes) -> list[_Sheet]: + try: + root = ElementTree.fromstring(payload) + except ElementTree.ParseError as exc: + raise ValueError("invalid XMind content.xml") from exc + + sheets: list[_Sheet] = [] + for sheet in _direct_children(root, "sheet"): + root_topic = _first_child(sheet, "topic") + sheets.append( + _Sheet( + title=_element_text(_first_child(sheet, "title")), + root_topic=( + _topic_from_xml(root_topic) if root_topic is not None else None + ), + ) + ) + return sheets + + +def _read_content_entry(content: bytes) -> tuple[str, bytes]: + try: + with zipfile.ZipFile(io.BytesIO(content)) as archive: + try: + info = archive.getinfo("content.json") + content_format = "json" + except KeyError: + try: + info = archive.getinfo("content.xml") + except KeyError as exc: + raise ValueError( + "XMind archive is missing content.json or content.xml" + ) from exc + content_format = "xml" + + if info.flag_bits & 0x1: + raise ValueError("encrypted XMind content is not supported") + if info.file_size > MAX_CONTENT_BYTES: + raise ValueError("XMind content entry exceeds the 32 MiB limit") + + with archive.open(info) as entry: + payload = entry.read(MAX_CONTENT_BYTES + 1) + if len(payload) > MAX_CONTENT_BYTES: + raise ValueError("XMind content entry exceeds the 32 MiB limit") + return content_format, payload + except zipfile.BadZipFile as exc: + raise ValueError("invalid XMind archive") from exc + + +def _render_topic(topic: _Topic, depth: int) -> tuple[list[str], int, int]: + lines: list[str] = [] + topic_count = 0 + note_count = 0 + child_depth = depth + + if topic.title: + lines.append(f"{' ' * depth}- {topic.title}") + topic_count = 1 + child_depth += 1 + if topic.note: + for note_line in topic.note.splitlines(): + normalized = note_line.strip() + quote = f"> {normalized}" if normalized else ">" + lines.append(f"{' ' * child_depth}{quote}") + note_count = 1 + + for child in topic.children: + child_lines, child_topics, child_notes = _render_topic(child, child_depth) + lines.extend(child_lines) + topic_count += child_topics + note_count += child_notes + + return lines, topic_count, note_count + + +def _render_sheets(sheets: list[_Sheet]) -> tuple[str, int, int, int]: + rendered_sheets: list[str] = [] + topic_count = 0 + note_count = 0 + + for index, sheet in enumerate(sheets, start=1): + if sheet.root_topic is None: + continue + lines, sheet_topics, sheet_notes = _render_topic(sheet.root_topic, 0) + if not lines: + continue + title = sheet.title or f"Sheet {index}" + rendered_sheets.append(f"# {title}\n\n" + "\n".join(lines)) + topic_count += sheet_topics + note_count += sheet_notes + + return ( + "\n\n---\n\n".join(rendered_sheets), + len(rendered_sheets), + topic_count, + note_count, + ) + + +class XMindParser(BaseParser): + """Extract topic hierarchy and plain-text notes from XMind files.""" + + def parse_into_text(self, content: bytes) -> Document: + content_format, payload = _read_content_entry(content) + + if content_format == "json": + try: + sheets = _parse_json_sheets(payload) + except (json.JSONDecodeError, UnicodeDecodeError) as exc: + raise ValueError("invalid XMind content.json") from exc + else: + sheets = _parse_xml_sheets(payload) + + markdown, sheet_count, topic_count, note_count = _render_sheets( + sheets + ) + if not markdown: + raise ValueError("XMind archive contains no renderable topics") + return Document( + content=markdown, + metadata={ + "source_format": "xmind", + "xmind_content_format": content_format, + "file_size": len(content), + "sheet_count": sheet_count, + "topic_count": topic_count, + "note_count": note_count, + }, + ) diff --git a/docreader/tests/test_parser_routing.py b/docreader/tests/test_parser_routing.py index d074358d..8dccb499 100644 --- a/docreader/tests/test_parser_routing.py +++ b/docreader/tests/test_parser_routing.py @@ -3,6 +3,8 @@ import unittest from docreader.models.document import Document from docreader.parser.base_parser import BaseParser from docreader.parser.parser import Parser, detect_effective_file_type +from docreader.parser.registry import BUILTIN_ENGINE, registry +from docreader.parser.xmind_parser import XMindParser OLE_MAGIC = b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1" @@ -29,6 +31,11 @@ class _RecordingRegistry: class ParserRoutingTest(unittest.TestCase): + def test_builtin_registry_routes_xmind_to_xmind_parser(self): + parser_class = registry.get_parser_class(BUILTIN_ENGINE, "xmind") + + self.assertIs(parser_class, XMindParser) + def test_legacy_doc_payload_renamed_to_docx_uses_doc_parser(self): registry = _RecordingRegistry() parser = Parser() diff --git a/docreader/tests/test_xmind_parser.py b/docreader/tests/test_xmind_parser.py new file mode 100644 index 00000000..1d92e63e --- /dev/null +++ b/docreader/tests/test_xmind_parser.py @@ -0,0 +1,286 @@ +import io +import json +import unittest +import zipfile +from unittest.mock import patch + +from docreader.parser.xmind_parser import XMindParser + + +def _xmind_zip(entries: dict[str, bytes | str]) -> bytes: + buffer = io.BytesIO() + with zipfile.ZipFile(buffer, "w", compression=zipfile.ZIP_DEFLATED) as archive: + for name, value in entries.items(): + payload = value.encode("utf-8") if isinstance(value, str) else value + archive.writestr(name, payload) + return buffer.getvalue() + + +def _modern_xmind_bytes(sheets: list[dict]) -> bytes: + return _xmind_zip({"content.json": json.dumps(sheets, ensure_ascii=False)}) + + +def _classic_xmind_bytes(xml: str) -> bytes: + return _xmind_zip({"content.xml": xml}) + + +def _mark_entry_encrypted(payload: bytes) -> bytes: + marked = bytearray(payload) + local_header = marked.index(b"PK\x03\x04") + central_header = marked.index(b"PK\x01\x02") + for offset in (local_header + 6, central_header + 8): + flags = int.from_bytes(marked[offset : offset + 2], "little") | 0x1 + marked[offset : offset + 2] = flags.to_bytes(2, "little") + return bytes(marked) + + +class XMindParserModernTests(unittest.TestCase): + def test_finds_content_without_enumerating_unrelated_entries(self): + payload = _xmind_zip( + { + "attachments/preview.png": b"preview", + "content.json": json.dumps( + [{"title": "Outline", "rootTopic": {"title": "Root"}}] + ), + } + ) + + with patch.object( + zipfile.ZipFile, + "namelist", + side_effect=AssertionError("archive entries must not be enumerated"), + ): + document = XMindParser().parse_into_text(payload) + + self.assertEqual("# Outline\n\n- Root", document.content) + + def test_parses_topic_hierarchy_and_plain_notes(self): + payload = _modern_xmind_bytes( + [ + { + "title": "Launch Plan", + "rootTopic": { + "title": "Release", + "notes": {"plain": {"content": "Coordinate teams"}}, + "children": { + "attached": [ + { + "title": "Backend", + "children": { + "attached": [{"title": "API freeze"}] + }, + } + ] + }, + }, + } + ] + ) + + document = XMindParser(file_name="launch.xmind").parse_into_text(payload) + + self.assertEqual( + "# Launch Plan\n\n" + "- Release\n" + " > Coordinate teams\n" + " - Backend\n" + " - API freeze", + document.content, + ) + self.assertEqual(document.metadata["source_format"], "xmind") + self.assertEqual(document.metadata["xmind_content_format"], "json") + self.assertEqual(document.metadata["sheet_count"], 1) + self.assertEqual(document.metadata["topic_count"], 3) + self.assertEqual(document.metadata["note_count"], 1) + self.assertEqual(document.metadata["file_size"], len(payload)) + + def test_renders_multiple_sheets_with_fallback_title(self): + payload = _modern_xmind_bytes( + [ + {"title": "One", "rootTopic": {"title": "Alpha"}}, + {"title": " ", "rootTopic": {"title": "Beta"}}, + ] + ) + + document = XMindParser().parse_into_text(payload) + + self.assertEqual( + "# One\n\n- Alpha\n\n---\n\n# Sheet 2\n\n- Beta", + document.content, + ) + self.assertEqual(document.metadata["sheet_count"], 2) + self.assertEqual(document.metadata["topic_count"], 2) + + def test_promotes_children_of_blank_topic(self): + payload = _modern_xmind_bytes( + [ + { + "title": "Outline", + "rootTopic": { + "title": " ", + "children": { + "attached": [ + { + "title": "Visible", + "children": { + "attached": [{"title": "Nested"}] + }, + } + ] + }, + }, + } + ] + ) + + document = XMindParser().parse_into_text(payload) + + self.assertEqual("# Outline\n\n- Visible\n - Nested", document.content) + self.assertEqual(document.metadata["topic_count"], 2) + + def test_renders_multiline_note_as_blockquotes(self): + payload = _modern_xmind_bytes( + [ + { + "title": "Notes", + "rootTopic": { + "title": "Root", + "notes": { + "plain": {"content": " First line \n\n Second line "} + }, + }, + } + ] + ) + + document = XMindParser().parse_into_text(payload) + + self.assertEqual( + "# Notes\n\n- Root\n > First line\n >\n > Second line", + document.content, + ) + + +class XMindParserClassicTests(unittest.TestCase): + def test_parses_namespaced_xml_hierarchy_and_notes(self): + payload = _classic_xmind_bytes( + """ + + + Architecture + + Platform + Owns ingress + + + Gateway + + + + + +""" + ) + + document = XMindParser().parse_into_text(payload) + + self.assertEqual( + "# Architecture\n\n- Platform\n > Owns ingress\n - Gateway", + document.content, + ) + self.assertEqual(document.metadata["xmind_content_format"], "xml") + self.assertEqual(document.metadata["sheet_count"], 1) + self.assertEqual(document.metadata["topic_count"], 2) + self.assertEqual(document.metadata["note_count"], 1) + + def test_prefers_content_json_when_both_entries_exist(self): + xml = """XML +XML topic""" + json_content = json.dumps( + [{"title": "JSON", "rootTopic": {"title": "JSON topic"}}] + ) + payload = _xmind_zip( + {"content.xml": xml, "content.json": json_content} + ) + + document = XMindParser().parse_into_text(payload) + + self.assertEqual("# JSON\n\n- JSON topic", document.content) + self.assertEqual(document.metadata["xmind_content_format"], "json") + + +class XMindParserValidationTests(unittest.TestCase): + def test_rejects_invalid_zip(self): + with self.assertRaises(ValueError) as context: + XMindParser().parse_into_text(b"not a ZIP archive") + + self.assertEqual(str(context.exception), "invalid XMind archive") + + def test_rejects_archive_without_supported_content(self): + payload = _xmind_zip({"manifest.json": "{}"}) + + with self.assertRaises(ValueError) as context: + XMindParser().parse_into_text(payload) + + self.assertEqual( + str(context.exception), + "XMind archive is missing content.json or content.xml", + ) + + def test_rejects_malformed_json(self): + payload = _xmind_zip({"content.json": "{"}) + + with self.assertRaises(ValueError) as context: + XMindParser().parse_into_text(payload) + + self.assertEqual(str(context.exception), "invalid XMind content.json") + + def test_rejects_malformed_xml(self): + payload = _classic_xmind_bytes("") + + with self.assertRaises(ValueError) as context: + XMindParser().parse_into_text(payload) + + self.assertEqual(str(context.exception), "invalid XMind content.xml") + + def test_rejects_archive_without_renderable_topics(self): + payload = _modern_xmind_bytes( + [{"title": "Empty", "rootTopic": {"title": " "}}] + ) + + with self.assertRaises(ValueError) as context: + XMindParser().parse_into_text(payload) + + self.assertEqual( + str(context.exception), + "XMind archive contains no renderable topics", + ) + + def test_rejects_content_entry_over_limit(self): + payload = _xmind_zip({"content.json": "12345"}) + + with patch("docreader.parser.xmind_parser.MAX_CONTENT_BYTES", 4): + with self.assertRaises(ValueError) as context: + XMindParser().parse_into_text(payload) + + self.assertEqual( + str(context.exception), + "XMind content entry exceeds the 32 MiB limit", + ) + + def test_rejects_encrypted_content_entry(self): + payload = _mark_entry_encrypted( + _xmind_zip({"content.json": "[]"}) + ) + + with self.assertRaises(ValueError) as context: + XMindParser().parse_into_text(payload) + + self.assertEqual( + str(context.exception), + "encrypted XMind content is not supported", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/internal/infrastructure/docparser/engine_registry_test.go b/internal/infrastructure/docparser/engine_registry_test.go index f2a9b07b..d4930934 100644 --- a/internal/infrastructure/docparser/engine_registry_test.go +++ b/internal/infrastructure/docparser/engine_registry_test.go @@ -2,7 +2,7 @@ package docparser import "testing" -func TestListAllEnginesBuiltinIncludesHTML(t *testing.T) { +func TestListAllEnginesBuiltinIncludesDocumentFormats(t *testing.T) { engines := ListAllEngines(true, nil, nil) for _, engine := range engines { if engine.Name != "builtin" { @@ -16,7 +16,7 @@ func TestListAllEnginesBuiltinIncludesHTML(t *testing.T) { for _, fileType := range engine.FileTypes { fileTypes[fileType] = true } - for _, want := range []string{"html", "htm"} { + for _, want := range []string{"html", "htm", "xmind"} { if !fileTypes[want] { t.Errorf("builtin engine file types do not include %q: %v", want, engine.FileTypes) } diff --git a/internal/infrastructure/docparser/engines.go b/internal/infrastructure/docparser/engines.go index f45c9e95..ae71ffb7 100644 --- a/internal/infrastructure/docparser/engines.go +++ b/internal/infrastructure/docparser/engines.go @@ -52,7 +52,7 @@ func (e *builtinEngine) Description() string { return "DocReader built-in parser func (e *builtinEngine) FileTypes(_ bool) []string { return []string{ "docx", "doc", "pdf", "md", "markdown", "xlsx", "xls", "epub", - "html", "htm", "mhtml", + "html", "htm", "mhtml", "xmind", "jpg", "jpeg", "png", "gif", "bmp", "tiff", "webp", "mp3", "wav", "m4a", "flac", "ogg", }