docwow 0.1.0__py3-none-any.whl
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.
- docwow/__init__.py +108 -0
- docwow/html_parser/__init__.py +4 -0
- docwow/html_parser/_utils.py +28 -0
- docwow/html_parser/html_parser.py +148 -0
- docwow/html_parser/paragraph_parser.py +127 -0
- docwow/html_parser/table_parser.py +45 -0
- docwow/models/__init__.py +25 -0
- docwow/models/document.py +37 -0
- docwow/models/image.py +15 -0
- docwow/models/lists.py +35 -0
- docwow/models/paragraph.py +37 -0
- docwow/models/styles.py +47 -0
- docwow/models/table.py +35 -0
- docwow/parser/__init__.py +3 -0
- docwow/parser/body_parser.py +328 -0
- docwow/parser/docx_parser.py +179 -0
- docwow/parser/image_parser.py +99 -0
- docwow/parser/numbering_parser.py +106 -0
- docwow/parser/style_parser.py +236 -0
- docwow/renderer/__init__.py +3 -0
- docwow/renderer/css_generator.py +174 -0
- docwow/renderer/html_renderer.py +95 -0
- docwow/renderer/image_renderer.py +44 -0
- docwow/renderer/list_renderer.py +112 -0
- docwow/renderer/paragraph_renderer.py +205 -0
- docwow/renderer/table_renderer.py +76 -0
- docwow/utils/__init__.py +50 -0
- docwow/utils/color.py +132 -0
- docwow/utils/units.py +119 -0
- docwow/utils/xml_utils.py +129 -0
- docwow/writer/__init__.py +4 -0
- docwow/writer/_xml.py +89 -0
- docwow/writer/document_writer.py +343 -0
- docwow/writer/docx_writer.py +166 -0
- docwow/writer/numbering_writer.py +83 -0
- docwow/writer/parts_writer.py +117 -0
- docwow/writer/styles_writer.py +155 -0
- docwow-0.1.0.dist-info/METADATA +88 -0
- docwow-0.1.0.dist-info/RECORD +42 -0
- docwow-0.1.0.dist-info/WHEEL +5 -0
- docwow-0.1.0.dist-info/licenses/LICENSE +21 -0
- docwow-0.1.0.dist-info/top_level.txt +1 -0
docwow/__init__.py
ADDED
|
@@ -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,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
|
docwow/models/image.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@dataclass(frozen=True)
|
|
7
|
+
class InlineImage:
|
|
8
|
+
"""An inline image embedded in a paragraph run."""
|
|
9
|
+
|
|
10
|
+
relationship_id: str # rId key from the DOCX relationships file
|
|
11
|
+
content_type: str # MIME type e.g. "image/png", "image/jpeg"
|
|
12
|
+
data: bytes # raw image bytes
|
|
13
|
+
width_pt: float # rendered width in points (converted from EMU at parse time)
|
|
14
|
+
height_pt: float # rendered height in points (converted from EMU at parse time)
|
|
15
|
+
alt_text: str = "" # accessibility description
|
docwow/models/lists.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
from docwow.models.styles import RunFormatting
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass(frozen=True)
|
|
9
|
+
class ListLevel:
|
|
10
|
+
"""Formatting definition for one level of a numbered/bulleted list (0-based)."""
|
|
11
|
+
|
|
12
|
+
level: int # 0–8 (Word supports up to 9 levels)
|
|
13
|
+
num_fmt: str # "bullet" | "decimal" | "lowerLetter" | "upperLetter"
|
|
14
|
+
# | "lowerRoman" | "upperRoman" | "none"
|
|
15
|
+
start_value: int = 1
|
|
16
|
+
text_template: str = "%1." # e.g. "%1." → "1.", "%1.%2." → "1.1."
|
|
17
|
+
indent_pt: float = 0.0 # left indent for the list item text
|
|
18
|
+
hanging_pt: float = 0.0 # hanging indent (bullet/number protrudes left)
|
|
19
|
+
run_fmt: RunFormatting | None = None # formatting applied to the list label
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class NumberingDefinition:
|
|
24
|
+
"""Maps an abstract numbering definition to its per-level configurations."""
|
|
25
|
+
|
|
26
|
+
abstract_num_id: str
|
|
27
|
+
levels: tuple[ListLevel, ...]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True)
|
|
31
|
+
class ListInfo:
|
|
32
|
+
"""Attached to a Paragraph when it is a list item."""
|
|
33
|
+
|
|
34
|
+
num_id: str # references a NumberingDefinition via its concrete num ID
|
|
35
|
+
level: int # 0-based level in the list hierarchy
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from typing import TypeAlias
|
|
5
|
+
|
|
6
|
+
from docwow.models.image import InlineImage
|
|
7
|
+
from docwow.models.lists import ListInfo
|
|
8
|
+
from docwow.models.styles import ParagraphFormatting, RunFormatting
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True)
|
|
12
|
+
class TextRun:
|
|
13
|
+
"""A contiguous run of text sharing the same character formatting."""
|
|
14
|
+
|
|
15
|
+
text: str
|
|
16
|
+
formatting: RunFormatting = field(default_factory=RunFormatting)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class ImageRun:
|
|
21
|
+
"""An inline image treated as a run within a paragraph."""
|
|
22
|
+
|
|
23
|
+
image: InlineImage
|
|
24
|
+
formatting: RunFormatting = field(default_factory=RunFormatting)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
# A paragraph's content is a sequence of runs — either text or an inline image.
|
|
28
|
+
Run: TypeAlias = TextRun | ImageRun
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True)
|
|
32
|
+
class Paragraph:
|
|
33
|
+
"""A Word paragraph: an ordered sequence of runs with paragraph-level formatting."""
|
|
34
|
+
|
|
35
|
+
runs: tuple[Run, ...]
|
|
36
|
+
formatting: ParagraphFormatting = field(default_factory=ParagraphFormatting)
|
|
37
|
+
list_info: ListInfo | None = None # set when this paragraph is a list item
|
docwow/models/styles.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@dataclass(frozen=True)
|
|
7
|
+
class RunFormatting:
|
|
8
|
+
"""Character-level formatting for a run of text."""
|
|
9
|
+
|
|
10
|
+
bold: bool = False
|
|
11
|
+
italic: bool = False
|
|
12
|
+
underline: bool = False
|
|
13
|
+
strike: bool = False
|
|
14
|
+
font_name: str | None = None
|
|
15
|
+
font_size_pt: float | None = None # points; converted from half-points at parse time
|
|
16
|
+
color: str | None = None # hex RGB e.g. "FF0000"; None = auto
|
|
17
|
+
highlight: str | None = None # Word highlight color name e.g. "yellow"
|
|
18
|
+
vertical_align: str | None = None # "superscript" | "subscript" | None
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True)
|
|
22
|
+
class ParagraphFormatting:
|
|
23
|
+
"""Paragraph-level formatting."""
|
|
24
|
+
|
|
25
|
+
style_id: str | None = None
|
|
26
|
+
alignment: str | None = None # "left" | "center" | "right" | "justify" | None
|
|
27
|
+
indent_left_pt: float = 0.0
|
|
28
|
+
indent_right_pt: float = 0.0
|
|
29
|
+
indent_first_line_pt: float = 0.0 # negative = hanging indent
|
|
30
|
+
space_before_pt: float = 0.0
|
|
31
|
+
space_after_pt: float = 0.0
|
|
32
|
+
line_spacing_pt: float | None = None # None = single/auto
|
|
33
|
+
keep_together: bool = False
|
|
34
|
+
keep_with_next: bool = False
|
|
35
|
+
page_break_before: bool = False
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass(frozen=True)
|
|
39
|
+
class Style:
|
|
40
|
+
"""A named Word style definition (paragraph, character, table, or numbering)."""
|
|
41
|
+
|
|
42
|
+
style_id: str
|
|
43
|
+
name: str
|
|
44
|
+
style_type: str # "paragraph" | "character" | "table" | "numbering"
|
|
45
|
+
based_on: str | None = None # style_id of parent style
|
|
46
|
+
paragraph_fmt: ParagraphFormatting | None = None
|
|
47
|
+
run_fmt: RunFormatting | None = None
|