docwow 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. docwow-0.1.0/LICENSE +21 -0
  2. docwow-0.1.0/PKG-INFO +88 -0
  3. docwow-0.1.0/README.md +54 -0
  4. docwow-0.1.0/docwow/__init__.py +108 -0
  5. docwow-0.1.0/docwow/html_parser/__init__.py +4 -0
  6. docwow-0.1.0/docwow/html_parser/_utils.py +28 -0
  7. docwow-0.1.0/docwow/html_parser/html_parser.py +148 -0
  8. docwow-0.1.0/docwow/html_parser/paragraph_parser.py +127 -0
  9. docwow-0.1.0/docwow/html_parser/table_parser.py +45 -0
  10. docwow-0.1.0/docwow/models/__init__.py +25 -0
  11. docwow-0.1.0/docwow/models/document.py +37 -0
  12. docwow-0.1.0/docwow/models/image.py +15 -0
  13. docwow-0.1.0/docwow/models/lists.py +35 -0
  14. docwow-0.1.0/docwow/models/paragraph.py +37 -0
  15. docwow-0.1.0/docwow/models/styles.py +47 -0
  16. docwow-0.1.0/docwow/models/table.py +35 -0
  17. docwow-0.1.0/docwow/parser/__init__.py +3 -0
  18. docwow-0.1.0/docwow/parser/body_parser.py +328 -0
  19. docwow-0.1.0/docwow/parser/docx_parser.py +179 -0
  20. docwow-0.1.0/docwow/parser/image_parser.py +99 -0
  21. docwow-0.1.0/docwow/parser/numbering_parser.py +106 -0
  22. docwow-0.1.0/docwow/parser/style_parser.py +236 -0
  23. docwow-0.1.0/docwow/renderer/__init__.py +3 -0
  24. docwow-0.1.0/docwow/renderer/css_generator.py +174 -0
  25. docwow-0.1.0/docwow/renderer/html_renderer.py +95 -0
  26. docwow-0.1.0/docwow/renderer/image_renderer.py +44 -0
  27. docwow-0.1.0/docwow/renderer/list_renderer.py +112 -0
  28. docwow-0.1.0/docwow/renderer/paragraph_renderer.py +205 -0
  29. docwow-0.1.0/docwow/renderer/table_renderer.py +76 -0
  30. docwow-0.1.0/docwow/utils/__init__.py +50 -0
  31. docwow-0.1.0/docwow/utils/color.py +132 -0
  32. docwow-0.1.0/docwow/utils/units.py +119 -0
  33. docwow-0.1.0/docwow/utils/xml_utils.py +129 -0
  34. docwow-0.1.0/docwow/writer/__init__.py +4 -0
  35. docwow-0.1.0/docwow/writer/_xml.py +89 -0
  36. docwow-0.1.0/docwow/writer/document_writer.py +343 -0
  37. docwow-0.1.0/docwow/writer/docx_writer.py +166 -0
  38. docwow-0.1.0/docwow/writer/numbering_writer.py +83 -0
  39. docwow-0.1.0/docwow/writer/parts_writer.py +117 -0
  40. docwow-0.1.0/docwow/writer/styles_writer.py +155 -0
  41. docwow-0.1.0/docwow.egg-info/PKG-INFO +88 -0
  42. docwow-0.1.0/docwow.egg-info/SOURCES.txt +46 -0
  43. docwow-0.1.0/docwow.egg-info/dependency_links.txt +1 -0
  44. docwow-0.1.0/docwow.egg-info/requires.txt +12 -0
  45. docwow-0.1.0/docwow.egg-info/top_level.txt +1 -0
  46. docwow-0.1.0/pyproject.toml +55 -0
  47. docwow-0.1.0/setup.cfg +4 -0
  48. docwow-0.1.0/tests/test_integration.py +398 -0
docwow-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Pritesh Thaker
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
docwow-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,88 @@
1
+ Metadata-Version: 2.4
2
+ Name: docwow
3
+ Version: 0.1.0
4
+ Summary: Pure Python Word (DOCX) ↔ HTML conversion with guaranteed round-trip fidelity
5
+ Author-email: Pritesh Thaker <pritesh.thaker@zentechsolution.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://docwow.dev
8
+ Project-URL: Repository, https://github.com/py-prit/docwow
9
+ Project-URL: Documentation, https://docwow.dev
10
+ Project-URL: Bug Tracker, https://github.com/py-prit/docwow/issues
11
+ Keywords: docx,word,html,conversion,round-trip,document
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Office/Business :: Office Suites
19
+ Classifier: Topic :: Text Processing :: Markup :: HTML
20
+ Requires-Python: >=3.10
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: lxml>=5.0
24
+ Requires-Dist: Pillow>=10.0
25
+ Provides-Extra: dev
26
+ Requires-Dist: pytest>=8.0; extra == "dev"
27
+ Requires-Dist: pytest-cov>=5.0; extra == "dev"
28
+ Requires-Dist: python-docx>=1.1; extra == "dev"
29
+ Provides-Extra: docs
30
+ Requires-Dist: mkdocs>=1.6; extra == "docs"
31
+ Requires-Dist: mkdocs-material>=9.0; extra == "docs"
32
+ Requires-Dist: mkdocstrings[python]>=0.25; extra == "docs"
33
+ Dynamic: license-file
34
+
35
+ # docwow
36
+
37
+ **Pure Python Word (DOCX) ↔ HTML conversion with guaranteed round-trip fidelity.**
38
+
39
+ docwow converts Word documents to a self-contained HTML representation and back again — without losing a single paragraph indent, table merge, list level, or inline image.
40
+
41
+ ## Why docwow?
42
+
43
+ Existing libraries solve half the problem:
44
+
45
+ | Library | DOCX → HTML | HTML → DOCX | Round-trip |
46
+ |---|---|---|---|
47
+ | mammoth | good | — | — |
48
+ | python-docx | — | basic | — |
49
+ | **docwow** | **yes** | **yes** | **guaranteed** |
50
+
51
+ The key insight: docwow embeds every piece of Word metadata into `data-dw-*` HTML attributes alongside the visual CSS. The browser renders the CSS; when you convert back to DOCX, docwow reads the data attributes and reconstructs the original Word XML exactly.
52
+
53
+ ## Install
54
+
55
+ ```bash
56
+ pip install docwow
57
+ ```
58
+
59
+ ## Quick Start
60
+
61
+ ```python
62
+ import docwow
63
+
64
+ # DOCX → HTML
65
+ html = docwow.to_html("document.docx")
66
+
67
+ # HTML → DOCX (round-trip)
68
+ docwow.to_docx(html, "output.docx")
69
+
70
+ # Or use the Document object
71
+ doc = docwow.open("document.docx")
72
+ html = doc.to_html()
73
+ doc.to_docx("output.docx")
74
+ ```
75
+
76
+ ## Documentation
77
+
78
+ Full documentation at [docwow.dev](https://docwow.dev).
79
+
80
+ ## Requirements
81
+
82
+ - Python 3.10+
83
+ - lxml
84
+ - Pillow
85
+
86
+ ## License
87
+
88
+ MIT
docwow-0.1.0/README.md ADDED
@@ -0,0 +1,54 @@
1
+ # docwow
2
+
3
+ **Pure Python Word (DOCX) ↔ HTML conversion with guaranteed round-trip fidelity.**
4
+
5
+ docwow converts Word documents to a self-contained HTML representation and back again — without losing a single paragraph indent, table merge, list level, or inline image.
6
+
7
+ ## Why docwow?
8
+
9
+ Existing libraries solve half the problem:
10
+
11
+ | Library | DOCX → HTML | HTML → DOCX | Round-trip |
12
+ |---|---|---|---|
13
+ | mammoth | good | — | — |
14
+ | python-docx | — | basic | — |
15
+ | **docwow** | **yes** | **yes** | **guaranteed** |
16
+
17
+ The key insight: docwow embeds every piece of Word metadata into `data-dw-*` HTML attributes alongside the visual CSS. The browser renders the CSS; when you convert back to DOCX, docwow reads the data attributes and reconstructs the original Word XML exactly.
18
+
19
+ ## Install
20
+
21
+ ```bash
22
+ pip install docwow
23
+ ```
24
+
25
+ ## Quick Start
26
+
27
+ ```python
28
+ import docwow
29
+
30
+ # DOCX → HTML
31
+ html = docwow.to_html("document.docx")
32
+
33
+ # HTML → DOCX (round-trip)
34
+ docwow.to_docx(html, "output.docx")
35
+
36
+ # Or use the Document object
37
+ doc = docwow.open("document.docx")
38
+ html = doc.to_html()
39
+ doc.to_docx("output.docx")
40
+ ```
41
+
42
+ ## Documentation
43
+
44
+ Full documentation at [docwow.dev](https://docwow.dev).
45
+
46
+ ## Requirements
47
+
48
+ - Python 3.10+
49
+ - lxml
50
+ - Pillow
51
+
52
+ ## License
53
+
54
+ MIT
@@ -0,0 +1,108 @@
1
+ """
2
+ docwow — pixel-perfect Word ↔ HTML conversion.
3
+
4
+ Public API
5
+ ----------
6
+ Parse::
7
+
8
+ doc = docwow.open("report.docx") # DOCX → Document
9
+ doc = docwow.open(html_string) # docwow HTML → Document
10
+
11
+ Convert::
12
+
13
+ html = docwow.to_html("report.docx") # DOCX → HTML string
14
+ data = docwow.to_docx(html_string) # HTML → DOCX bytes
15
+ data = docwow.to_docx(html_string, target="out.docx")
16
+
17
+ Low-level::
18
+
19
+ doc = docwow.parse_docx(source) # bytes | str | Path → Document
20
+ doc = docwow.parse_html(source) # str | bytes → Document
21
+ html = docwow.render_document(doc) # Document → HTML string
22
+ data = docwow.write_docx(doc, target=None) # Document → DOCX bytes
23
+ """
24
+ from __future__ import annotations
25
+
26
+ from pathlib import Path
27
+
28
+ from docwow.html_parser.html_parser import parse_html
29
+ from docwow.parser.docx_parser import parse_docx
30
+ from docwow.renderer.html_renderer import render_document
31
+ from docwow.writer.docx_writer import write_docx
32
+
33
+ __all__ = [
34
+ "open",
35
+ "to_html",
36
+ "to_docx",
37
+ "parse_docx",
38
+ "parse_html",
39
+ "render_document",
40
+ "write_docx",
41
+ ]
42
+
43
+ __version__ = "0.1.0"
44
+
45
+
46
+ # ---------------------------------------------------------------------------
47
+ # Convenience API
48
+ # ---------------------------------------------------------------------------
49
+
50
+ def open(source: str | Path | bytes) -> "Document":
51
+ """Parse a DOCX file *or* a docwow HTML string into a Document model.
52
+
53
+ Args:
54
+ source: A file path (``str`` or :class:`~pathlib.Path`) or raw bytes
55
+ pointing to a ``.docx`` file, **or** an HTML string produced
56
+ by :func:`render_document`.
57
+
58
+ Returns:
59
+ A :class:`~docwow.models.document.Document` instance.
60
+ """
61
+ if isinstance(source, (str, Path)):
62
+ path = Path(source)
63
+ try:
64
+ is_docx = path.exists() and path.suffix.lower() in (".docx", ".doc")
65
+ except (OSError, ValueError):
66
+ is_docx = False
67
+ if is_docx:
68
+ return parse_docx(source)
69
+ # Treat as HTML string
70
+ return parse_html(str(source))
71
+ # bytes — try DOCX first (ZIP magic bytes), fall back to HTML
72
+ if isinstance(source, bytes):
73
+ if source[:2] == b"PK":
74
+ return parse_docx(source)
75
+ return parse_html(source)
76
+ raise TypeError(f"Expected str, Path, or bytes; got {type(source).__name__}")
77
+
78
+
79
+ def to_html(source: str | Path | bytes) -> str:
80
+ """Convert a DOCX file to a self-contained HTML string.
81
+
82
+ Args:
83
+ source: Path to a ``.docx`` file, or raw DOCX bytes.
84
+
85
+ Returns:
86
+ UTF-8 HTML string produced by :func:`render_document`.
87
+ """
88
+ doc = parse_docx(source)
89
+ return render_document(doc)
90
+
91
+
92
+ def to_docx(
93
+ html: str | bytes,
94
+ target: str | Path | None = None,
95
+ ) -> bytes:
96
+ """Convert a docwow HTML string back to a DOCX file.
97
+
98
+ Args:
99
+ html: HTML string or bytes produced by :func:`render_document` /
100
+ :func:`to_html`.
101
+ target: Optional output path. When provided the bytes are also
102
+ written to disk.
103
+
104
+ Returns:
105
+ Raw DOCX bytes (a valid ZIP archive).
106
+ """
107
+ doc = parse_html(html)
108
+ return write_docx(doc, target=target)
@@ -0,0 +1,4 @@
1
+ """HTML → Document model parser for docwow."""
2
+ from .html_parser import parse_html
3
+
4
+ __all__ = ["parse_html"]
@@ -0,0 +1,28 @@
1
+ """Shared low-level helpers for the HTML parser."""
2
+ from __future__ import annotations
3
+
4
+
5
+ def has_class(el, cls: str) -> bool:
6
+ """Return True if *el* carries the given CSS class."""
7
+ return cls in el.get("class", "").split()
8
+
9
+
10
+ def pt_val(s: str | None, default: float | None = None) -> float | None:
11
+ """Parse a CSS pt string to float.
12
+
13
+ Examples::
14
+
15
+ pt_val("36pt") -> 36.0
16
+ pt_val("36.5pt") -> 36.5
17
+ pt_val(None) -> None (or *default*)
18
+ pt_val(None, 0.0) -> 0.0
19
+ """
20
+ if s is None:
21
+ return default
22
+ s = s.strip()
23
+ if s.endswith("pt"):
24
+ try:
25
+ return float(s[:-2])
26
+ except ValueError:
27
+ return default
28
+ return default
@@ -0,0 +1,148 @@
1
+ """
2
+ Parse docwow-generated HTML back into a Document model.
3
+
4
+ The HTML produced by render_document() encodes all Word metadata in
5
+ data-dw-* attributes, so the round-trip is lossless for structure and
6
+ formatting. Styles are reconstructed as minimal Style objects (style_id
7
+ and name only); full style declarations are preserved per-paragraph via
8
+ the data attributes on each <p> element.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import lxml.html
13
+
14
+ from docwow.html_parser._utils import has_class, pt_val
15
+ from docwow.html_parser.paragraph_parser import parse_paragraph
16
+ from docwow.html_parser.table_parser import parse_table
17
+ from docwow.models.document import Document
18
+ from docwow.models.lists import ListLevel, NumberingDefinition
19
+ from docwow.models.paragraph import Paragraph
20
+ from docwow.models.styles import Style
21
+ from docwow.models.table import Table
22
+
23
+
24
+ def parse_html(source: str | bytes) -> Document:
25
+ """Parse a docwow HTML string back into a Document model.
26
+
27
+ Args:
28
+ source: HTML produced by ``render_document()``, as a string or
29
+ UTF-8 bytes.
30
+
31
+ Returns:
32
+ A :class:`~docwow.models.document.Document` whose body, geometry,
33
+ styles, and numbering reflect the content of the HTML.
34
+
35
+ Raises:
36
+ ValueError: If the HTML does not contain a ``dw-document`` element.
37
+ """
38
+ if isinstance(source, str):
39
+ source = source.encode("utf-8")
40
+ root = lxml.html.document_fromstring(source)
41
+
42
+ divs = root.xpath('.//div[contains(@class,"dw-document")]')
43
+ if not divs:
44
+ raise ValueError("HTML does not contain a dw-document element")
45
+ doc_div = divs[0]
46
+
47
+ # Page geometry — fall back to A4 / 1-inch margins if attributes absent
48
+ g = doc_div.get
49
+ page_width_pt = pt_val(g("data-dw-page-width"), 595.28)
50
+ page_height_pt = pt_val(g("data-dw-page-height"), 841.89)
51
+ margin_top_pt = pt_val(g("data-dw-margin-top"), 72.0)
52
+ margin_bottom_pt = pt_val(g("data-dw-margin-bottom"), 72.0)
53
+ margin_left_pt = pt_val(g("data-dw-margin-left"), 72.0)
54
+ margin_right_pt = pt_val(g("data-dw-margin-right"), 72.0)
55
+
56
+ body, numbering, style_ids = _parse_body(doc_div)
57
+
58
+ # Minimal Style objects: carry the style_id so the writer can reference them
59
+ styles = tuple(
60
+ Style(style_id=sid, name=sid, style_type="paragraph")
61
+ for sid in sorted(style_ids)
62
+ )
63
+
64
+ return Document(
65
+ body=body,
66
+ styles=styles,
67
+ numbering=numbering,
68
+ page_width_pt=page_width_pt,
69
+ page_height_pt=page_height_pt,
70
+ margin_top_pt=margin_top_pt,
71
+ margin_bottom_pt=margin_bottom_pt,
72
+ margin_left_pt=margin_left_pt,
73
+ margin_right_pt=margin_right_pt,
74
+ )
75
+
76
+
77
+ # ---------------------------------------------------------------------------
78
+ # Body traversal
79
+ # ---------------------------------------------------------------------------
80
+
81
+ def _parse_body(
82
+ doc_div,
83
+ ) -> tuple[tuple[Paragraph | Table, ...], tuple[NumberingDefinition, ...], set[str]]:
84
+ """Walk direct children of the dw-document div and build the body tuple."""
85
+ body: list[Paragraph | Table] = []
86
+ style_ids: set[str] = set()
87
+ # num_id → {level → num_fmt}
88
+ numbering_levels: dict[str, dict[int, str]] = {}
89
+
90
+ for child in doc_div:
91
+ tag = child.tag
92
+ if tag == "p" and has_class(child, "dw-p"):
93
+ para = parse_paragraph(child)
94
+ body.append(para)
95
+ _collect_style(para, style_ids)
96
+
97
+ elif tag == "table" and has_class(child, "dw-table"):
98
+ body.append(parse_table(child))
99
+
100
+ elif tag in ("ul", "ol") and has_class(child, "dw-list"):
101
+ _collect_list(child, body, style_ids, numbering_levels)
102
+
103
+ return tuple(body), _build_numbering(numbering_levels), style_ids
104
+
105
+
106
+ def _collect_list(
107
+ list_el,
108
+ body: list,
109
+ style_ids: set[str],
110
+ numbering_levels: dict[str, dict[int, str]],
111
+ ) -> None:
112
+ """Extract paragraphs from a dw-list element, handling nesting."""
113
+ num_id = list_el.get("data-dw-num-id", "")
114
+ num_fmt = "bullet" if list_el.tag == "ul" else "decimal"
115
+
116
+ for li in list_el:
117
+ if li.tag != "li":
118
+ continue
119
+ level = int(li.get("data-dw-level", "0"))
120
+ numbering_levels.setdefault(num_id, {})[level] = num_fmt
121
+
122
+ for child in li:
123
+ if child.tag == "p" and has_class(child, "dw-p"):
124
+ para = parse_paragraph(child)
125
+ body.append(para)
126
+ _collect_style(para, style_ids)
127
+ elif child.tag in ("ul", "ol") and has_class(child, "dw-list"):
128
+ _collect_list(child, body, style_ids, numbering_levels)
129
+
130
+
131
+ def _collect_style(para: Paragraph, style_ids: set[str]) -> None:
132
+ if para.formatting.style_id:
133
+ style_ids.add(para.formatting.style_id)
134
+
135
+
136
+ def _build_numbering(
137
+ numbering_levels: dict[str, dict[int, str]],
138
+ ) -> tuple[NumberingDefinition, ...]:
139
+ return tuple(
140
+ NumberingDefinition(
141
+ abstract_num_id=num_id,
142
+ levels=tuple(
143
+ ListLevel(level=lvl, num_fmt=fmt)
144
+ for lvl, fmt in sorted(levels.items())
145
+ ),
146
+ )
147
+ for num_id, levels in sorted(numbering_levels.items())
148
+ )
@@ -0,0 +1,127 @@
1
+ """Parse <p class="dw-p"> elements into Paragraph model objects."""
2
+ from __future__ import annotations
3
+
4
+ import base64
5
+
6
+ from docwow.html_parser._utils import has_class, pt_val
7
+ from docwow.models.image import InlineImage
8
+ from docwow.models.lists import ListInfo
9
+ from docwow.models.paragraph import ImageRun, Paragraph, Run, TextRun
10
+ from docwow.models.styles import ParagraphFormatting, RunFormatting
11
+
12
+
13
+ def parse_paragraph(p_el) -> Paragraph:
14
+ """Parse a <p class="dw-p"> lxml element into a Paragraph."""
15
+ return Paragraph(
16
+ runs=tuple(_parse_runs(p_el)),
17
+ formatting=_parse_para_formatting(p_el),
18
+ list_info=_parse_list_info(p_el),
19
+ )
20
+
21
+
22
+ # ---------------------------------------------------------------------------
23
+ # Paragraph-level
24
+ # ---------------------------------------------------------------------------
25
+
26
+ def _parse_para_formatting(p_el) -> ParagraphFormatting:
27
+ g = p_el.get
28
+ return ParagraphFormatting(
29
+ style_id=g("data-dw-style"),
30
+ alignment=g("data-dw-alignment"),
31
+ indent_left_pt=pt_val(g("data-dw-indent-left"), 0.0),
32
+ indent_right_pt=pt_val(g("data-dw-indent-right"), 0.0),
33
+ indent_first_line_pt=pt_val(g("data-dw-indent-first-line"), 0.0),
34
+ space_before_pt=pt_val(g("data-dw-space-before"), 0.0),
35
+ space_after_pt=pt_val(g("data-dw-space-after"), 0.0),
36
+ line_spacing_pt=pt_val(g("data-dw-line-spacing")),
37
+ keep_together=g("data-dw-keep-together") == "true",
38
+ keep_with_next=g("data-dw-keep-with-next") == "true",
39
+ page_break_before=g("data-dw-page-break-before") == "true",
40
+ )
41
+
42
+
43
+ def _parse_list_info(p_el) -> ListInfo | None:
44
+ num_id = p_el.get("data-dw-num-id")
45
+ if num_id is None:
46
+ return None
47
+ return ListInfo(num_id=num_id, level=int(p_el.get("data-dw-level", "0")))
48
+
49
+
50
+ # ---------------------------------------------------------------------------
51
+ # Run-level
52
+ # ---------------------------------------------------------------------------
53
+
54
+ def _parse_runs(p_el) -> list[Run]:
55
+ runs: list[Run] = []
56
+ for child in p_el:
57
+ if child.tag == "span" and has_class(child, "dw-r"):
58
+ runs.append(_parse_text_run(child))
59
+ elif child.tag == "img" and has_class(child, "dw-img"):
60
+ runs.append(_parse_image_run(child))
61
+ return runs
62
+
63
+
64
+ def _parse_text_run(span_el) -> TextRun:
65
+ return TextRun(
66
+ text=_extract_text(span_el),
67
+ formatting=_parse_run_formatting(span_el),
68
+ )
69
+
70
+
71
+ def _extract_text(span_el) -> str:
72
+ """Reconstruct text content, turning <br> elements back into newlines."""
73
+ parts: list[str] = []
74
+ if span_el.text:
75
+ parts.append(span_el.text)
76
+ for child in span_el:
77
+ if child.tag == "br":
78
+ parts.append("\n")
79
+ if child.tail:
80
+ parts.append(child.tail)
81
+ return "".join(parts)
82
+
83
+
84
+ def _parse_run_formatting(span_el) -> RunFormatting:
85
+ g = span_el.get
86
+ return RunFormatting(
87
+ bold=g("data-dw-bold") == "true",
88
+ italic=g("data-dw-italic") == "true",
89
+ underline=g("data-dw-underline") == "true",
90
+ strike=g("data-dw-strike") == "true",
91
+ font_name=g("data-dw-font-name"),
92
+ font_size_pt=pt_val(g("data-dw-font-size")),
93
+ color=g("data-dw-color"),
94
+ highlight=g("data-dw-highlight"),
95
+ vertical_align=g("data-dw-vertical-align"),
96
+ )
97
+
98
+
99
+ def _parse_image_run(img_el) -> ImageRun:
100
+ width_pt = pt_val(img_el.get("data-dw-width"), 0.0)
101
+ height_pt = pt_val(img_el.get("data-dw-height"), 0.0)
102
+ content_type, data = _parse_data_uri(img_el.get("src", ""))
103
+ return ImageRun(
104
+ image=InlineImage(
105
+ relationship_id=img_el.get("data-dw-rid", ""),
106
+ content_type=content_type,
107
+ data=data,
108
+ width_pt=width_pt,
109
+ height_pt=height_pt,
110
+ alt_text=img_el.get("alt", ""),
111
+ )
112
+ )
113
+
114
+
115
+ def _parse_data_uri(src: str) -> tuple[str, bytes]:
116
+ """Decode a base64 data URI into (content_type, raw_bytes)."""
117
+ if not src.startswith("data:"):
118
+ return ("", b"")
119
+ rest = src[5:] # "{content_type};base64,{b64}"
120
+ if "," not in rest:
121
+ return ("", b"")
122
+ meta, b64_data = rest.split(",", 1)
123
+ content_type = meta.split(";")[0]
124
+ try:
125
+ return content_type, base64.b64decode(b64_data)
126
+ except Exception:
127
+ return content_type, b""
@@ -0,0 +1,45 @@
1
+ """Parse <table class="dw-table"> elements into Table model objects."""
2
+ from __future__ import annotations
3
+
4
+ from docwow.html_parser._utils import has_class, pt_val
5
+ from docwow.html_parser.paragraph_parser import parse_paragraph
6
+ from docwow.models.table import Table, TableCell, TableRow
7
+
8
+
9
+ def parse_table(table_el) -> Table:
10
+ """Parse a <table class="dw-table"> lxml element into a Table."""
11
+ col_widths_str = table_el.get("data-dw-col-widths", "")
12
+ col_widths_pt = tuple(
13
+ pt_val(w.strip()) or 0.0
14
+ for w in col_widths_str.split(",")
15
+ if w.strip()
16
+ )
17
+ return Table(
18
+ rows=tuple(_parse_row(tr) for tr in table_el if tr.tag == "tr"),
19
+ style_id=table_el.get("data-dw-style"),
20
+ width_pt=pt_val(table_el.get("data-dw-width")),
21
+ col_widths_pt=col_widths_pt,
22
+ )
23
+
24
+
25
+ def _parse_row(tr_el) -> TableRow:
26
+ return TableRow(
27
+ cells=tuple(_parse_cell(td) for td in tr_el if td.tag == "td"),
28
+ height_pt=pt_val(tr_el.get("data-dw-height")),
29
+ )
30
+
31
+
32
+ def _parse_cell(td_el) -> TableCell:
33
+ paragraphs = tuple(
34
+ parse_paragraph(child)
35
+ for child in td_el
36
+ if child.tag == "p" and has_class(child, "dw-p")
37
+ )
38
+ return TableCell(
39
+ paragraphs=paragraphs,
40
+ col_span=int(td_el.get("colspan", "1")),
41
+ row_span=int(td_el.get("rowspan", "1")),
42
+ width_pt=pt_val(td_el.get("data-dw-width")),
43
+ v_merge_start=td_el.get("data-dw-v-merge-start") == "true",
44
+ v_merge_continue=td_el.get("data-dw-v-merge-continue") == "true",
45
+ )
@@ -0,0 +1,25 @@
1
+ from docwow.models.document import Document, BodyElement
2
+ from docwow.models.image import InlineImage
3
+ from docwow.models.lists import ListInfo, ListLevel, NumberingDefinition
4
+ from docwow.models.paragraph import ImageRun, Paragraph, Run, TextRun
5
+ from docwow.models.styles import ParagraphFormatting, RunFormatting, Style
6
+ from docwow.models.table import Table, TableCell, TableRow
7
+
8
+ __all__ = [
9
+ "BodyElement",
10
+ "Document",
11
+ "ImageRun",
12
+ "InlineImage",
13
+ "ListInfo",
14
+ "ListLevel",
15
+ "NumberingDefinition",
16
+ "Paragraph",
17
+ "ParagraphFormatting",
18
+ "Run",
19
+ "RunFormatting",
20
+ "Style",
21
+ "Table",
22
+ "TableCell",
23
+ "TableRow",
24
+ "TextRun",
25
+ ]
@@ -0,0 +1,37 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import TypeAlias
5
+
6
+ from docwow.models.lists import NumberingDefinition
7
+ from docwow.models.paragraph import Paragraph
8
+ from docwow.models.styles import Style
9
+ from docwow.models.table import Table
10
+
11
+ # Top-level body elements (v0.1: paragraphs and tables only)
12
+ BodyElement: TypeAlias = Paragraph | Table
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class Document:
17
+ """
18
+ Root of the internal document model.
19
+
20
+ All lengths are in points (pt). EMU→pt conversion happens in the parser;
21
+ pt→CSS conversion happens in the renderer.
22
+
23
+ Default page size: A4 (595.28 × 841.89 pt).
24
+ Default margins: 1 inch (72 pt) on all sides.
25
+ """
26
+
27
+ body: tuple[BodyElement, ...]
28
+ styles: tuple[Style, ...]
29
+ numbering: tuple[NumberingDefinition, ...]
30
+
31
+ # Page geometry (pt)
32
+ page_width_pt: float = 595.28 # A4 width
33
+ page_height_pt: float = 841.89 # A4 height
34
+ margin_top_pt: float = 72.0 # 1 inch
35
+ margin_bottom_pt: float = 72.0
36
+ margin_left_pt: float = 72.0
37
+ margin_right_pt: float = 72.0