From 2e4875893ccaded789b30568cd779036c679fecf Mon Sep 17 00:00:00 2001 From: Sadia-Tasnim-Meem Date: Sun, 29 Nov 2026 22:42:12 +0600 Subject: [PATCH] implement docx parser with test --- gknowledge/core/ingestion.py | 2 +- gknowledge/core/parsers.py | 73 +++++++++++++++++++++++++ tests/test_core.py | 101 ++++++++++++++++++++++++++++++++++- 3 files changed, 174 insertions(+), 2 deletions(-) diff --git a/gknowledge/core/ingestion.py b/gknowledge/core/ingestion.py index 3ea3df4..433fa81 100644 --- a/gknowledge/core/ingestion.py +++ b/gknowledge/core/ingestion.py @@ -32,7 +32,7 @@ IMPORTABLE_SUFFIXES = ( parsers.TEXT_EXTS | parsers.HTML_EXTS | parsers.CODE_EXTS - | parsers.EPUB_EXTS | {".pdf"} + | parsers.EPUB_EXTS | parsers.DOCX_EXTS | {".pdf"} ) diff --git a/gknowledge/core/parsers.py b/gknowledge/core/parsers.py index 055ec7c..3806b1e 100644 --- a/gknowledge/core/parsers.py +++ b/gknowledge/core/parsers.py @@ -10,14 +10,21 @@ import html import mimetypes import re +import xml.etree.ElementTree as ET import zipfile from pathlib import Path TEXT_EXTS = {".md", ".markdown", ".txt", ".text", ".rst", ".org", ".csv", ".log"} HTML_EXTS = {".html", ".htm"} EPUB_EXTS = {".epub"} +DOCX_EXTS = {".docx"} CODE_EXTS = {".py", ".js", ".ts", ".json", ".yaml", ".yml", ".toml", ".ini"} +_W = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}" +_DOCX_HEADINGS = {"Title": 1, "Subtitle": 1, + "Heading1": 1, "Heading2": 2, "Heading3": 3, + "Heading4": 4, "Heading5": 5, "Heading6": 6} + _TAG_RE = re.compile(r"<[^>]+>") _WS_RE = re.compile(r"[ \t]+") _NL_RE = re.compile(r"\n{3,}") @@ -71,6 +78,70 @@ def _extract_epub(path: Path) -> str: return "\n\n".join(parts) +def _docx_paragraph_text(p: ET.Element) -> str: + """One ``w:p``: heading style becomes a Markdown prefix, runs are joined.""" + level = 0 + style = p.find(f"{_W}pPr/{_W}pStyle") + if style is not None: + level = _DOCX_HEADINGS.get(style.get(f"{_W}val", ""), 0) + chunks = [] + for node in p.iter(): + if node.tag == f"{_W}t": + chunks.append(node.text or "") + elif node.tag == f"{_W}tab": + chunks.append(" ") + elif node.tag == f"{_W}br": + chunks.append("\n") + # Only w:t is collected, so field instructions (w:instrText) stay out. + text = "".join(chunks).strip() + if not text: + return "" + return ("#" * level + " " + text) if level else text + + +def _walk_docx(node: ET.Element, out: list[str]) -> None: + """Walk a document body: paragraphs, then tables, then wrapper elements.""" + for child in node: + if child.tag == f"{_W}p": + text = _docx_paragraph_text(child) + if text: + out.append(text) + elif child.tag == f"{_W}tbl": + rows = [] + for tr in child.findall(f"{_W}tr"): + cells = [] + for tc in tr.findall(f"{_W}tc"): + cell: list[str] = [] + _walk_docx(tc, cell) + cells.append(" ".join(cell)) + if any(cells): + rows.append(" | ".join(cells)) + if rows: + out.append("\n".join(rows)) + else: + # w:sdt and friends wrap paragraphs of their own. + _walk_docx(child, out) + + +def _extract_docx(path: Path) -> str: + # A .docx is a zip of XML parts; stdlib is enough for the common case. + try: + with zipfile.ZipFile(path) as zf: + raw = zf.read("word/document.xml") + except Exception: + # Corrupt, not a zip at all (an encrypted .docx is an OLE file), or + # not a Word package: same graceful "" as the PDF path. + return "" + try: + root = ET.fromstring(raw) + except ET.ParseError: + return "" + body = root.find(f"{_W}body") + parts: list[str] = [] + _walk_docx(body if body is not None else root, parts) + return "\n\n".join(parts) + + def normalize(text: str) -> str: text = text.replace("\r\n", "\n").replace("\r", "\n") text = _WS_RE.sub(" ", text) @@ -90,6 +161,8 @@ def parse(path: str | Path) -> str: return normalize(_extract_pdf(p)) if ext in EPUB_EXTS: return normalize(_extract_epub(p)) + if ext in DOCX_EXTS: + return normalize(_extract_docx(p)) # Fall back to a best-effort text read for unknown extensions. try: return normalize(_read_text(p)) diff --git a/tests/test_core.py b/tests/test_core.py index 8bf1478..febf0da 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -8,6 +8,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) +from gknowledge.core import parsers from gknowledge.core.ingestion import IngestionManager from gknowledge.core.knowledge import KnowledgeWriter from gknowledge.core.lint import ChangeDetector, stale_sources @@ -75,6 +76,39 @@ def _write_minimal_epub(path: Path, chapter: str) -> None: zf.writestr("OEBPS/chapter1.xhtml", chapter) +def _write_minimal_docx(path: Path, body: str) -> None: + """Build the smallest docx Word would open: no binary fixture.""" + content_types = ( + '' + '' + '' + '' + '' + '' + ) + rels = ( + '' + '' + '' + '' + ) + document = ( + '' + '' + f'{body}' + ) + with zipfile.ZipFile(path, "w") as zf: + zf.writestr("[Content_Types].xml", content_types) + zf.writestr("_rels/.rels", rels) + zf.writestr("word/document.xml", document) + + def test_project_layout(tmp_path): proj = make_project(tmp_path) assert Project.is_project(proj.root) @@ -280,6 +314,68 @@ def test_import_and_ingest_epub(tmp_path): proj.close() +def test_import_and_ingest_docx(tmp_path): + proj = make_project(tmp_path) + docx = tmp_path / "smoke.docx" + _write_minimal_docx( + docx, + '' + "DOCX Smoke Test" + "DOCX smoke test content for the gknowledge test suite. " + "The offline extractor only needs a sentence or two of real text to " + "summarize." + "" + "Cell A" + "Cell B" + "", + ) + + parsed = parsers.parse(docx) + # Word heading styles become Markdown headings, table cells join on a row. + assert parsed.startswith("# DOCX Smoke Test") + assert "DOCX smoke test content" in parsed + assert "Cell A | Cell B" in parsed + + mgr = IngestionManager(proj, build_provider(proj.settings.as_dict())) + source = mgr.import_file(docx) + assert source is not None + # The title came out of the document, not the file stem. + assert source.title == "DOCX Smoke Test" + + done = mgr.process_pending() + assert done == 1 + + source = proj.store.get_source(source.id) + assert source.status == SourceStatus.INGESTED + + pages = proj.store.list_pages() + source_page = next(p for p in pages if p.kind == PageKind.SOURCE) + md = (proj.knowledge_dir / source_page.rel_path).read_text("utf-8") + assert "DOCX smoke test content" in md + proj.close() + + +def test_parse_docx_returns_empty_on_corrupt_file(tmp_path): + """A broken or non-zip file yields "" instead of raising, like the PDF path.""" + bad = tmp_path / "broken.docx" + bad.write_bytes(b"this is not a zip archive") + assert parsers.parse(bad) == "" + + +def test_import_folder_accepts_docx(tmp_path): + proj = make_project(tmp_path) + folder = tmp_path / "drop" + folder.mkdir() + _write_minimal_docx( + folder / "note.docx", + "Folder import content.", + ) + mgr = IngestionManager(proj, build_provider(proj.settings.as_dict())) + outcome = mgr.import_folder(folder) + assert [s.title for s in outcome.imported] == ["Folder import content."] + proj.close() + + def test_lint_flags_and_refreshes_sources_whose_original_changed(tmp_path): proj = make_project(tmp_path) src_file = tmp_path / "solar.md" @@ -344,7 +440,10 @@ def test_store_converts_a_wal_database(tmp_path): ("e", test_reingest_clears_stale_pages_and_rebuilds_source), ("f", test_remove_source_detaches_shared_pages_and_deletes_orphans), ("g", test_lint_flags_and_refreshes_sources_whose_original_changed), - ("h", test_store_converts_a_wal_database)): + ("h", test_store_converts_a_wal_database), + ("i", test_import_and_ingest_docx), + ("j", test_parse_docx_returns_empty_on_corrupt_file), + ("k", test_import_folder_accepts_docx)): d = tmp / name d.mkdir(parents=True, exist_ok=True) fn(d)