Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion gknowledge/core/ingestion.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"}
)


Expand Down
73 changes: 73 additions & 0 deletions gknowledge/core/parsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,}")
Expand Down Expand Up @@ -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)
Expand All @@ -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))
Expand Down
101 changes: 100 additions & 1 deletion tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 = (
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
'<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">'
'<Default Extension="rels" '
'ContentType="application/vnd.openxmlformats-package.relationships+xml"/>'
'<Default Extension="xml" ContentType="application/xml"/>'
'<Override PartName="/word/document.xml" ContentType="application/'
'vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>'
'</Types>'
)
rels = (
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
'<Relationships '
'xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
'<Relationship Id="rId1" '
'Type="http://schemas.openxmlformats.org/officeDocument/2006/'
'relationships/officeDocument" Target="word/document.xml"/>'
'</Relationships>'
)
document = (
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
'<w:document '
'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">'
f'<w:body>{body}</w:body></w:document>'
)
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)
Expand Down Expand Up @@ -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,
'<w:p><w:pPr><w:pStyle w:val="Title"/></w:pPr>'
"<w:r><w:t>DOCX Smoke Test</w:t></w:r></w:p>"
"<w:p><w:r><w:t>DOCX smoke test content for the gknowledge test suite. "
"The offline extractor only needs a sentence or two of real text to "
"summarize.</w:t></w:r></w:p>"
"<w:tbl><w:tr>"
"<w:tc><w:p><w:r><w:t>Cell A</w:t></w:r></w:p></w:tc>"
"<w:tc><w:p><w:r><w:t>Cell B</w:t></w:r></w:p></w:tc>"
"</w:tr></w:tbl>",
)

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",
"<w:p><w:r><w:t>Folder import content.</w:t></w:r></w:p>",
)
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"
Expand Down Expand Up @@ -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)
Expand Down
Loading