-
Notifications
You must be signed in to change notification settings - Fork 13.6k
fix(docx): preserve namespaces when repairing stylesheets #2467
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+231
−9
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
db95c44
fix: avoid splitting UTF-8 characters during charset detection
afourney 16389ca
fix(docx): preserve namespaces when repairing stylesheets
afourney 44ead2e
Merge branch 'main' into utf8_splitting
afourney 1ac833f
Fixed d:strike as well
afourney File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,152 @@ | ||
| """DOCX stylesheet repair must preserve namespace-qualified attributes.""" | ||
|
|
||
| import io | ||
| from pathlib import Path | ||
| import re | ||
| import zipfile | ||
|
|
||
| from lxml import etree | ||
| import pytest | ||
|
|
||
| from markitdown import MarkItDown, StreamInfo | ||
| from markitdown.converter_utils.docx.pre_process import _pre_process_styles | ||
|
|
||
|
|
||
| WORD_NAMESPACE = "http://schemas.openxmlformats.org/wordprocessingml/2006/main" | ||
| W = f"{{{WORD_NAMESPACE}}}" | ||
| TEST_DOCX = Path(__file__).parent / "test_files" / "test.docx" | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("double_strike", [False, True]) | ||
| @pytest.mark.parametrize("missing_type", [False, True]) | ||
| def test_docx_styles_with_redundant_default_namespace( | ||
| missing_type: bool, double_strike: bool | ||
| ) -> None: | ||
| markitdown = MarkItDown() | ||
| expected = markitdown.convert(TEST_DOCX).markdown | ||
| fixture = io.BytesIO() | ||
| declaration = f'xmlns:w="{WORD_NAMESPACE}"'.encode("utf-8") | ||
|
|
||
| with zipfile.ZipFile(TEST_DOCX) as source, zipfile.ZipFile(fixture, "w") as target: | ||
| for item in source.infolist(): | ||
| content = source.read(item) | ||
| if item.filename == "word/styles.xml": | ||
| if double_strike: | ||
| assert content.count(b"</w:styles>") == 1 | ||
| content = content.replace( | ||
| b"</w:styles>", | ||
| b'<w:style w:type="character" w:styleId="DoubleStrike">' | ||
| b'<w:name w:val="Double Strike"/>' | ||
| b'<w:rPr><w:dstrike w:val="1"/></w:rPr>' | ||
| b"</w:style></w:styles>", | ||
| 1, | ||
| ) | ||
| assert content.count(declaration) == 1 | ||
| content = content.replace( | ||
| declaration, | ||
| declaration + f' xmlns="{WORD_NAMESPACE}"'.encode("utf-8"), | ||
| 1, | ||
| ) | ||
| if missing_type: | ||
| content, count = re.subn( | ||
| rb'<w:style\s+w:type="[^"]+"(\s+w:styleId="1")', | ||
| rb"<w:style\1", | ||
| content, | ||
| ) | ||
| assert count == 1 | ||
| styles = etree.fromstring(content).findall(W + "style") | ||
| assert styles | ||
| assert all(W + "styleId" in style.attrib for style in styles) | ||
| target.writestr(item, content) | ||
|
|
||
| fixture.seek(0) | ||
| actual = markitdown.convert_stream( | ||
| fixture, stream_info=StreamInfo(extension=".docx") | ||
| ).markdown | ||
|
|
||
| assert "# Abstract" in actual | ||
| assert actual == expected | ||
|
|
||
|
|
||
| @pytest.fixture(params=["w", "word"]) | ||
| def styles_xml(request: pytest.FixtureRequest) -> bytes: | ||
| prefix = request.param | ||
| return f"""<?xml version="1.0" encoding="UTF-8" standalone="yes"?> | ||
| <{prefix}:styles xmlns:{prefix}="{WORD_NAMESPACE}" xmlns="{WORD_NAMESPACE}" | ||
| xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" | ||
| xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" | ||
| mc:Ignorable="w14"> | ||
| <{prefix}:style {prefix}:type="paragraph" {prefix}:styleId="Normal"> | ||
| <{prefix}:name {prefix}:val="Normal"/> | ||
| </{prefix}:style> | ||
| </{prefix}:styles>""".encode( | ||
| "utf-8" | ||
| ) | ||
|
|
||
|
|
||
| def test_valid_styles_are_returned_unchanged(styles_xml: bytes) -> None: | ||
| assert _pre_process_styles(styles_xml) == styles_xml | ||
|
|
||
|
|
||
| def test_missing_type_repair_preserves_namespaces(styles_xml: bytes) -> None: | ||
| malformed, count = re.subn(rb'\s+(?:w|word):type="paragraph"', b"", styles_xml) | ||
| assert count == 1 | ||
| original = etree.fromstring(styles_xml) | ||
|
|
||
| repaired = etree.fromstring(_pre_process_styles(malformed)) | ||
|
|
||
| assert repaired.nsmap == original.nsmap | ||
| assert repaired.attrib == original.attrib | ||
| style = repaired.find(W + "style") | ||
| assert style is not None | ||
| assert style.attrib == {W + "type": "paragraph", W + "styleId": "Normal"} | ||
| name = style.find(W + "name") | ||
| assert name is not None | ||
| assert name.attrib == {W + "val": "Normal"} | ||
|
|
||
|
|
||
| def test_styles_without_ids_are_removed(styles_xml: bytes) -> None: | ||
| malformed, count = re.subn(rb'\s+(?:w|word):styleId="Normal"', b"", styles_xml) | ||
| assert count == 1 | ||
|
|
||
| repaired = etree.fromstring(_pre_process_styles(malformed)) | ||
|
|
||
| assert repaired.findall(W + "style") == [] | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("value", [None, "0", "1"]) | ||
| @pytest.mark.parametrize("missing_type", [False, True]) | ||
| def test_style_strike_repair_preserves_namespaces( | ||
| styles_xml: bytes, value: str | None, missing_type: bool | ||
| ) -> None: | ||
| original = etree.fromstring(styles_xml) | ||
| style = original.find(W + "style") | ||
| assert style is not None | ||
| if missing_type: | ||
| del style.attrib[W + "type"] | ||
| properties = etree.SubElement(style, W + "rPr") | ||
| strike = etree.SubElement(properties, W + "dstrike") | ||
| if value is not None: | ||
| strike.set(W + "val", value) | ||
| etree.SubElement(properties, W + "b") | ||
|
|
||
| repaired = etree.fromstring(_pre_process_styles(etree.tostring(original))) | ||
|
|
||
| assert repaired.nsmap == original.nsmap | ||
| assert repaired.attrib == original.attrib | ||
| style = repaired.find(W + "style") | ||
| assert style is not None | ||
| assert style.attrib == {W + "type": "paragraph", W + "styleId": "Normal"} | ||
| assert repaired.find(".//" + W + "dstrike") is None | ||
| strike = style.find(f"{W}rPr/{W}strike") | ||
| assert strike is not None | ||
| assert strike.attrib == ({} if value is None else {W + "val": value}) | ||
| assert style.find(f"{W}rPr/{W}b") is not None | ||
|
|
||
|
|
||
| def test_other_namespace_dstrike_is_unchanged(styles_xml: bytes) -> None: | ||
| original = etree.fromstring(styles_xml) | ||
| etree.SubElement(original, "{urn:extension}dstrike") | ||
| content = etree.tostring(original) | ||
|
|
||
| assert _pre_process_styles(content) == content |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.