epub-translator 0.0.6__py3-none-any.whl → 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.
- epub_translator/__init__.py +3 -1
- epub_translator/data/fill.jinja +66 -0
- epub_translator/data/mmltex/README.md +67 -0
- epub_translator/data/mmltex/cmarkup.xsl +1106 -0
- epub_translator/data/mmltex/entities.xsl +459 -0
- epub_translator/data/mmltex/glayout.xsl +222 -0
- epub_translator/data/mmltex/mmltex.xsl +36 -0
- epub_translator/data/mmltex/scripts.xsl +375 -0
- epub_translator/data/mmltex/tables.xsl +130 -0
- epub_translator/data/mmltex/tokens.xsl +328 -0
- epub_translator/data/translate.jinja +15 -12
- epub_translator/epub/__init__.py +4 -2
- epub_translator/epub/common.py +43 -0
- epub_translator/epub/math.py +193 -0
- epub_translator/epub/placeholder.py +53 -0
- epub_translator/epub/spines.py +42 -0
- epub_translator/epub/toc.py +505 -0
- epub_translator/epub/zip.py +67 -0
- epub_translator/iter_sync.py +24 -0
- epub_translator/language.py +23 -0
- epub_translator/llm/__init__.py +2 -1
- epub_translator/llm/core.py +175 -0
- epub_translator/llm/error.py +38 -35
- epub_translator/llm/executor.py +159 -136
- epub_translator/llm/increasable.py +28 -28
- epub_translator/llm/types.py +17 -0
- epub_translator/serial/__init__.py +2 -0
- epub_translator/serial/chunk.py +52 -0
- epub_translator/serial/segment.py +17 -0
- epub_translator/serial/splitter.py +50 -0
- epub_translator/template.py +35 -33
- epub_translator/translator.py +205 -168
- epub_translator/utils.py +7 -0
- epub_translator/xml/__init__.py +4 -3
- epub_translator/xml/deduplication.py +38 -0
- epub_translator/xml/firendly/__init__.py +2 -0
- epub_translator/xml/firendly/decoder.py +75 -0
- epub_translator/xml/firendly/encoder.py +84 -0
- epub_translator/xml/firendly/parser.py +177 -0
- epub_translator/xml/firendly/tag.py +118 -0
- epub_translator/xml/firendly/transform.py +36 -0
- epub_translator/xml/xml.py +52 -0
- epub_translator/xml/xml_like.py +176 -0
- epub_translator/xml_translator/__init__.py +3 -0
- epub_translator/xml_translator/const.py +2 -0
- epub_translator/xml_translator/fill.py +128 -0
- epub_translator/xml_translator/format.py +282 -0
- epub_translator/xml_translator/fragmented.py +125 -0
- epub_translator/xml_translator/group.py +183 -0
- epub_translator/xml_translator/progressive_locking.py +256 -0
- epub_translator/xml_translator/submitter.py +102 -0
- epub_translator/xml_translator/text_segment.py +263 -0
- epub_translator/xml_translator/translator.py +178 -0
- epub_translator/xml_translator/utils.py +29 -0
- epub_translator-0.1.0.dist-info/METADATA +283 -0
- epub_translator-0.1.0.dist-info/RECORD +58 -0
- epub_translator/data/format.jinja +0 -33
- epub_translator/epub/content_parser.py +0 -162
- epub_translator/epub/html/__init__.py +0 -1
- epub_translator/epub/html/dom_operator.py +0 -62
- epub_translator/epub/html/empty_tags.py +0 -23
- epub_translator/epub/html/file.py +0 -80
- epub_translator/epub/html/texts_searcher.py +0 -46
- epub_translator/llm/node.py +0 -201
- epub_translator/translation/__init__.py +0 -2
- epub_translator/translation/chunk.py +0 -118
- epub_translator/translation/splitter.py +0 -78
- epub_translator/translation/store.py +0 -36
- epub_translator/translation/translation.py +0 -231
- epub_translator/translation/types.py +0 -45
- epub_translator/translation/utils.py +0 -11
- epub_translator/xml/decoder.py +0 -71
- epub_translator/xml/encoder.py +0 -95
- epub_translator/xml/parser.py +0 -172
- epub_translator/xml/tag.py +0 -93
- epub_translator/xml/transform.py +0 -34
- epub_translator/xml/utils.py +0 -12
- epub_translator/zip_context.py +0 -74
- epub_translator-0.0.6.dist-info/METADATA +0 -170
- epub_translator-0.0.6.dist-info/RECORD +0 -36
- {epub_translator-0.0.6.dist-info → epub_translator-0.1.0.dist-info}/LICENSE +0 -0
- {epub_translator-0.0.6.dist-info → epub_translator-0.1.0.dist-info}/WHEEL +0 -0
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
from collections.abc import Generator, Iterable
|
|
2
|
+
from xml.etree.ElementTree import Element
|
|
3
|
+
|
|
4
|
+
from ..xml import clone_element
|
|
5
|
+
from .parser import parse_tags
|
|
6
|
+
from .tag import Tag, TagKind
|
|
7
|
+
from .transform import tag_to_element
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
# why implement XML decoding?
|
|
11
|
+
# https://github.com/oomol-lab/pdf-craft/issues/149
|
|
12
|
+
def decode_friendly(chars: Iterable[str], tags: Iterable[str] | str = ()) -> Generator[Element, None, None]:
|
|
13
|
+
if isinstance(tags, str):
|
|
14
|
+
tags = set((tags,))
|
|
15
|
+
else:
|
|
16
|
+
tags = set(tags)
|
|
17
|
+
|
|
18
|
+
for element in _collect_elements(chars):
|
|
19
|
+
if element.tag in tags or len(tags) == 0:
|
|
20
|
+
yield clone_element(element)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _collect_elements(chars: Iterable[str]) -> Generator[Element, None, None]:
|
|
24
|
+
opening_stack: list[Element] = []
|
|
25
|
+
last_closed_element: Element | None = None
|
|
26
|
+
|
|
27
|
+
for cell in parse_tags(chars):
|
|
28
|
+
if isinstance(cell, Tag):
|
|
29
|
+
tag: Tag = cell
|
|
30
|
+
element = tag_to_element(tag)
|
|
31
|
+
if tag.kind == TagKind.CLOSING:
|
|
32
|
+
popped = _pop_element(tag.name, opening_stack)
|
|
33
|
+
if popped is not None:
|
|
34
|
+
yield popped
|
|
35
|
+
last_closed_element = popped
|
|
36
|
+
elif last_closed_element is not None:
|
|
37
|
+
_append_to_tail(last_closed_element, tag.proto)
|
|
38
|
+
else:
|
|
39
|
+
if opening_stack:
|
|
40
|
+
opening_stack[-1].append(element)
|
|
41
|
+
if tag.kind == TagKind.SELF_CLOSING:
|
|
42
|
+
yield element
|
|
43
|
+
last_closed_element = element
|
|
44
|
+
elif tag.kind == TagKind.OPENING:
|
|
45
|
+
opening_stack.append(element)
|
|
46
|
+
last_closed_element = None
|
|
47
|
+
|
|
48
|
+
elif last_closed_element is not None:
|
|
49
|
+
_append_to_tail(last_closed_element, cell)
|
|
50
|
+
|
|
51
|
+
elif opening_stack:
|
|
52
|
+
opening_stack[-1].text = cell
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _append_to_tail(element: Element, text: str) -> None:
|
|
56
|
+
if element.tail:
|
|
57
|
+
element.tail += text
|
|
58
|
+
else:
|
|
59
|
+
element.tail = text
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _pop_element(tag_name: str, opening_stack: list[Element]) -> Element | None:
|
|
63
|
+
index = -1
|
|
64
|
+
for i in range(len(opening_stack) - 1, -1, -1):
|
|
65
|
+
opening_element = opening_stack[i]
|
|
66
|
+
if tag_name == opening_element.tag:
|
|
67
|
+
index = i
|
|
68
|
+
break
|
|
69
|
+
if index == -1:
|
|
70
|
+
return None
|
|
71
|
+
|
|
72
|
+
popped: Element | None = None
|
|
73
|
+
for _ in range(len(opening_stack) - index):
|
|
74
|
+
popped = opening_stack.pop()
|
|
75
|
+
return popped
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
from collections.abc import Callable
|
|
2
|
+
from html import escape as escape_html
|
|
3
|
+
from io import StringIO
|
|
4
|
+
from xml.etree.ElementTree import Element
|
|
5
|
+
|
|
6
|
+
from .parser import parse_tags
|
|
7
|
+
from .tag import Tag, TagKind
|
|
8
|
+
from .transform import element_to_tag
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
# why implement XML encoding?
|
|
12
|
+
# https://github.com/oomol-lab/pdf-craft/issues/149
|
|
13
|
+
def encode_friendly(element: Element, indent: int = 2) -> str:
|
|
14
|
+
buffer = StringIO()
|
|
15
|
+
_encode_element(
|
|
16
|
+
buffer=buffer,
|
|
17
|
+
element=element,
|
|
18
|
+
indent=indent,
|
|
19
|
+
depth=0,
|
|
20
|
+
escape=_escape_text,
|
|
21
|
+
)
|
|
22
|
+
return buffer.getvalue()
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _escape_text(text: str) -> str:
|
|
26
|
+
buffer = StringIO()
|
|
27
|
+
for cell in parse_tags(text):
|
|
28
|
+
if isinstance(cell, Tag):
|
|
29
|
+
cell = escape_html(str(cell))
|
|
30
|
+
buffer.write(cell)
|
|
31
|
+
return buffer.getvalue()
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
_TINY_TEXT_LEN = 35
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _encode_element(
|
|
38
|
+
buffer: StringIO,
|
|
39
|
+
element: Element,
|
|
40
|
+
indent: int,
|
|
41
|
+
depth: int,
|
|
42
|
+
escape: Callable[[str], str],
|
|
43
|
+
) -> None:
|
|
44
|
+
_write_indent(buffer, indent, depth)
|
|
45
|
+
if len(element) == 0 and not element.text:
|
|
46
|
+
tag = element_to_tag(element, TagKind.SELF_CLOSING)
|
|
47
|
+
buffer.write(str(tag))
|
|
48
|
+
else:
|
|
49
|
+
text = (element.text or "").strip()
|
|
50
|
+
opening_tag = element_to_tag(element, TagKind.OPENING)
|
|
51
|
+
closing_tag = element_to_tag(element, TagKind.CLOSING)
|
|
52
|
+
buffer.write(str(opening_tag))
|
|
53
|
+
is_one_line = len(text) <= _TINY_TEXT_LEN and len(element) == 0 and "\n" not in text
|
|
54
|
+
if text:
|
|
55
|
+
if not is_one_line:
|
|
56
|
+
buffer.write("\n")
|
|
57
|
+
_write_indent(buffer, indent, depth + 1)
|
|
58
|
+
buffer.write(escape(text))
|
|
59
|
+
|
|
60
|
+
for child in element:
|
|
61
|
+
buffer.write("\n")
|
|
62
|
+
_encode_element(
|
|
63
|
+
buffer=buffer,
|
|
64
|
+
element=child,
|
|
65
|
+
indent=indent,
|
|
66
|
+
depth=depth + 1,
|
|
67
|
+
escape=escape,
|
|
68
|
+
)
|
|
69
|
+
child_tail = (child.tail or "").strip()
|
|
70
|
+
if child_tail:
|
|
71
|
+
buffer.write("\n")
|
|
72
|
+
_write_indent(buffer, indent, depth + 1)
|
|
73
|
+
buffer.write(escape(child_tail))
|
|
74
|
+
|
|
75
|
+
if not is_one_line:
|
|
76
|
+
buffer.write("\n")
|
|
77
|
+
_write_indent(buffer, indent, depth)
|
|
78
|
+
|
|
79
|
+
buffer.write(str(closing_tag))
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _write_indent(buffer: StringIO, indent: int, depth: int) -> None:
|
|
83
|
+
for _ in range(indent * depth):
|
|
84
|
+
buffer.write(" ")
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
from collections.abc import Generator, Iterable
|
|
2
|
+
from enum import Enum, auto
|
|
3
|
+
from io import StringIO
|
|
4
|
+
|
|
5
|
+
from .tag import Tag, TagKind, is_valid_name_char, is_valid_value_char
|
|
6
|
+
|
|
7
|
+
_SPACES = (" ", "\n")
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class _Phase(Enum):
|
|
11
|
+
OUTSIDE = auto()
|
|
12
|
+
LEFT_BRACKET = auto()
|
|
13
|
+
LEFT_SLASH = auto()
|
|
14
|
+
TAG_NAME = auto()
|
|
15
|
+
TAG_GAP = auto()
|
|
16
|
+
ATTRIBUTE_NAME = auto()
|
|
17
|
+
ATTRIBUTE_NAME_EQUAL = auto()
|
|
18
|
+
ATTRIBUTE_VALUE = auto()
|
|
19
|
+
MUST_CLOSING_SIGN = auto()
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class _ParsedResult(Enum):
|
|
23
|
+
Continue = auto()
|
|
24
|
+
Success = auto()
|
|
25
|
+
Failed = auto()
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def parse_tags(chars: Iterable[str]) -> Generator[str | Tag, None, None]:
|
|
29
|
+
yield from _XMLTagsParser().do(chars)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class _XMLTagsParser:
|
|
33
|
+
def __init__(self):
|
|
34
|
+
self._outside_buffer: StringIO = StringIO()
|
|
35
|
+
self._tag_buffer: StringIO = StringIO()
|
|
36
|
+
self._tag: Tag | None = None
|
|
37
|
+
self._phase: _Phase = _Phase.OUTSIDE
|
|
38
|
+
|
|
39
|
+
def do(self, chars: Iterable[str]) -> Generator[str | Tag, None, None]:
|
|
40
|
+
for char in chars:
|
|
41
|
+
parsed_result = self._parse_char(char)
|
|
42
|
+
yield from self._generate_by_result(parsed_result)
|
|
43
|
+
|
|
44
|
+
self._outside_buffer.write(self._tag_buffer.getvalue())
|
|
45
|
+
outside_text = self._outside_buffer.getvalue()
|
|
46
|
+
if outside_text != "":
|
|
47
|
+
yield outside_text
|
|
48
|
+
|
|
49
|
+
def _parse_char(self, char: str) -> _ParsedResult:
|
|
50
|
+
parsed_result: _ParsedResult = _ParsedResult.Continue
|
|
51
|
+
|
|
52
|
+
if self._phase == _Phase.OUTSIDE:
|
|
53
|
+
if char != "<":
|
|
54
|
+
self._outside_buffer.write(char)
|
|
55
|
+
else:
|
|
56
|
+
self._phase = _Phase.LEFT_BRACKET
|
|
57
|
+
self._tag_buffer.write(char)
|
|
58
|
+
self._tag = Tag(
|
|
59
|
+
kind=TagKind.OPENING,
|
|
60
|
+
name="",
|
|
61
|
+
proto="",
|
|
62
|
+
attributes=[],
|
|
63
|
+
)
|
|
64
|
+
else:
|
|
65
|
+
assert self._tag is not None
|
|
66
|
+
self._tag_buffer.write(char)
|
|
67
|
+
|
|
68
|
+
if self._phase == _Phase.LEFT_BRACKET:
|
|
69
|
+
if char == "/":
|
|
70
|
+
self._tag.kind = TagKind.CLOSING
|
|
71
|
+
self._phase = _Phase.LEFT_SLASH
|
|
72
|
+
elif is_valid_name_char(char):
|
|
73
|
+
self._tag.name += char
|
|
74
|
+
self._phase = _Phase.TAG_NAME
|
|
75
|
+
else:
|
|
76
|
+
parsed_result = _ParsedResult.Failed
|
|
77
|
+
|
|
78
|
+
elif self._phase == _Phase.LEFT_SLASH:
|
|
79
|
+
if is_valid_name_char(char):
|
|
80
|
+
self._tag.name += char
|
|
81
|
+
self._phase = _Phase.TAG_NAME
|
|
82
|
+
else:
|
|
83
|
+
parsed_result = _ParsedResult.Failed
|
|
84
|
+
|
|
85
|
+
elif self._phase == _Phase.TAG_NAME:
|
|
86
|
+
if char in _SPACES:
|
|
87
|
+
self._phase = _Phase.TAG_GAP
|
|
88
|
+
elif is_valid_name_char(char):
|
|
89
|
+
self._tag.name += char
|
|
90
|
+
elif char == ">":
|
|
91
|
+
parsed_result = _ParsedResult.Success
|
|
92
|
+
elif char == "/" and self._tag.kind == TagKind.OPENING:
|
|
93
|
+
self._tag.kind = TagKind.SELF_CLOSING
|
|
94
|
+
self._phase = _Phase.MUST_CLOSING_SIGN
|
|
95
|
+
else:
|
|
96
|
+
parsed_result = _ParsedResult.Failed
|
|
97
|
+
|
|
98
|
+
elif self._phase == _Phase.TAG_GAP:
|
|
99
|
+
if char in _SPACES:
|
|
100
|
+
pass
|
|
101
|
+
elif is_valid_name_char(char):
|
|
102
|
+
self._tag.attributes.append((char, ""))
|
|
103
|
+
self._phase = _Phase.ATTRIBUTE_NAME
|
|
104
|
+
elif char == ">":
|
|
105
|
+
parsed_result = _ParsedResult.Success
|
|
106
|
+
elif char == "/" and self._tag.kind == TagKind.OPENING:
|
|
107
|
+
self._tag.kind = TagKind.SELF_CLOSING
|
|
108
|
+
self._phase = _Phase.MUST_CLOSING_SIGN
|
|
109
|
+
else:
|
|
110
|
+
parsed_result = _ParsedResult.Failed
|
|
111
|
+
|
|
112
|
+
elif self._phase == _Phase.ATTRIBUTE_NAME:
|
|
113
|
+
if is_valid_name_char(char):
|
|
114
|
+
attr_name, attr_value = self._tag.attributes[-1]
|
|
115
|
+
attr_name = attr_name + char
|
|
116
|
+
self._tag.attributes[-1] = (attr_name, attr_value)
|
|
117
|
+
elif char == "=":
|
|
118
|
+
self._phase = _Phase.ATTRIBUTE_NAME_EQUAL
|
|
119
|
+
else:
|
|
120
|
+
parsed_result = _ParsedResult.Failed
|
|
121
|
+
|
|
122
|
+
elif self._phase == _Phase.ATTRIBUTE_NAME_EQUAL:
|
|
123
|
+
if char == '"':
|
|
124
|
+
self._phase = _Phase.ATTRIBUTE_VALUE
|
|
125
|
+
else:
|
|
126
|
+
parsed_result = _ParsedResult.Failed
|
|
127
|
+
|
|
128
|
+
elif self._phase == _Phase.ATTRIBUTE_VALUE:
|
|
129
|
+
if is_valid_value_char(char):
|
|
130
|
+
attr_name, attr_value = self._tag.attributes[-1]
|
|
131
|
+
attr_value = attr_value + char
|
|
132
|
+
self._tag.attributes[-1] = (attr_name, attr_value)
|
|
133
|
+
elif char == '"':
|
|
134
|
+
self._phase = _Phase.TAG_GAP
|
|
135
|
+
else:
|
|
136
|
+
parsed_result = _ParsedResult.Failed
|
|
137
|
+
|
|
138
|
+
elif self._phase == _Phase.MUST_CLOSING_SIGN:
|
|
139
|
+
if char == ">":
|
|
140
|
+
parsed_result = _ParsedResult.Success
|
|
141
|
+
else:
|
|
142
|
+
parsed_result = _ParsedResult.Failed
|
|
143
|
+
|
|
144
|
+
return parsed_result
|
|
145
|
+
|
|
146
|
+
def _generate_by_result(self, parsed_result: _ParsedResult) -> Generator[str | Tag, None, None]:
|
|
147
|
+
if parsed_result == _ParsedResult.Success:
|
|
148
|
+
assert self._tag is not None
|
|
149
|
+
if self._is_tag_valid(self._tag):
|
|
150
|
+
outside_text = self._outside_buffer.getvalue()
|
|
151
|
+
self._clear_buffer(self._outside_buffer)
|
|
152
|
+
self._clear_buffer(self._tag_buffer)
|
|
153
|
+
if outside_text != "":
|
|
154
|
+
yield outside_text
|
|
155
|
+
yield self._tag
|
|
156
|
+
else:
|
|
157
|
+
self._tag.proto = self._tag_buffer.getvalue()
|
|
158
|
+
self._outside_buffer.write(self._tag.proto)
|
|
159
|
+
self._clear_buffer(self._tag_buffer)
|
|
160
|
+
self._tag = None
|
|
161
|
+
self._phase = _Phase.OUTSIDE
|
|
162
|
+
|
|
163
|
+
elif parsed_result == _ParsedResult.Failed:
|
|
164
|
+
self._outside_buffer.write(self._tag_buffer.getvalue())
|
|
165
|
+
self._clear_buffer(self._tag_buffer)
|
|
166
|
+
self._phase = _Phase.OUTSIDE
|
|
167
|
+
|
|
168
|
+
def _is_tag_valid(self, tag: Tag) -> bool:
|
|
169
|
+
if tag.kind == TagKind.CLOSING and len(tag.attributes) > 0:
|
|
170
|
+
return False
|
|
171
|
+
if tag.find_invalid_name() is not None:
|
|
172
|
+
return False
|
|
173
|
+
return True
|
|
174
|
+
|
|
175
|
+
def _clear_buffer(self, buffer: StringIO):
|
|
176
|
+
buffer.truncate(0)
|
|
177
|
+
buffer.seek(0)
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
from collections.abc import Generator
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
from enum import Enum, auto
|
|
4
|
+
from io import StringIO
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class TagKind(Enum):
|
|
8
|
+
OPENING = auto()
|
|
9
|
+
CLOSING = auto()
|
|
10
|
+
SELF_CLOSING = auto()
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass
|
|
14
|
+
class Tag:
|
|
15
|
+
kind: TagKind
|
|
16
|
+
name: str
|
|
17
|
+
proto: str
|
|
18
|
+
attributes: list[tuple[str, str]]
|
|
19
|
+
|
|
20
|
+
def __str__(self):
|
|
21
|
+
buffer = StringIO()
|
|
22
|
+
buffer.write("<")
|
|
23
|
+
if self.kind == TagKind.CLOSING:
|
|
24
|
+
buffer.write("/")
|
|
25
|
+
buffer.write(self.name)
|
|
26
|
+
if len(self.attributes) > 0:
|
|
27
|
+
buffer.write(" ")
|
|
28
|
+
for i, (attr_name, attr_value) in enumerate(self.attributes):
|
|
29
|
+
buffer.write(attr_name)
|
|
30
|
+
buffer.write("=")
|
|
31
|
+
buffer.write('"')
|
|
32
|
+
buffer.write(attr_value)
|
|
33
|
+
buffer.write('"')
|
|
34
|
+
if i < len(self.attributes) - 1:
|
|
35
|
+
buffer.write(" ")
|
|
36
|
+
if self.kind == TagKind.SELF_CLOSING:
|
|
37
|
+
buffer.write("/>")
|
|
38
|
+
else:
|
|
39
|
+
buffer.write(">")
|
|
40
|
+
return buffer.getvalue()
|
|
41
|
+
|
|
42
|
+
def find_invalid_name(self) -> str | None:
|
|
43
|
+
for name in self._iter_tag_names():
|
|
44
|
+
if not all(is_valid_value_char(c) for c in name):
|
|
45
|
+
return name
|
|
46
|
+
# https://www.w3schools.com/xml/xml_elements.asp
|
|
47
|
+
# The following logic enforces a subset of XML naming rules:
|
|
48
|
+
# - Names must not be empty.
|
|
49
|
+
# - Names must start with a letter (a-z, A-Z) or an underscore (_).
|
|
50
|
+
if name == "":
|
|
51
|
+
return name
|
|
52
|
+
char = name[0]
|
|
53
|
+
if char == "_":
|
|
54
|
+
continue
|
|
55
|
+
if "a" <= char <= "z" or "A" <= char <= "Z":
|
|
56
|
+
continue
|
|
57
|
+
return name
|
|
58
|
+
|
|
59
|
+
return None
|
|
60
|
+
|
|
61
|
+
def find_invalid_attr_value(self) -> tuple[str, str] | None:
|
|
62
|
+
for attr_name, attr_value in self.attributes:
|
|
63
|
+
if not all(is_valid_value_char(c) for c in attr_value):
|
|
64
|
+
return attr_name, attr_value
|
|
65
|
+
return None
|
|
66
|
+
|
|
67
|
+
def _iter_tag_names(self) -> Generator[str, None, None]:
|
|
68
|
+
yield self.name
|
|
69
|
+
for attr_name, _ in self.attributes:
|
|
70
|
+
yield attr_name
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
# XML Attribute Values: https://www.w3.org/TR/xml/#NT-AttValue
|
|
74
|
+
# URI Syntax: https://www.rfc-editor.org/rfc/rfc3986
|
|
75
|
+
# HTML Attributes: https://html.spec.whatwg.org/multipage/syntax.html#attributes-2
|
|
76
|
+
_VALID_VALUE_CHARS = frozenset(
|
|
77
|
+
(
|
|
78
|
+
",",
|
|
79
|
+
".",
|
|
80
|
+
"/",
|
|
81
|
+
"#",
|
|
82
|
+
"?",
|
|
83
|
+
"&",
|
|
84
|
+
"=",
|
|
85
|
+
":",
|
|
86
|
+
"%",
|
|
87
|
+
";",
|
|
88
|
+
" ",
|
|
89
|
+
)
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
# XML Names: https://www.w3.org/TR/xml/#NT-Name
|
|
94
|
+
# XML Namespaces: https://www.w3.org/TR/xml-names/#ns-qualnames
|
|
95
|
+
# HTML Custom Data Attributes: https://html.spec.whatwg.org/multipage/dom.html#custom-data-attribute
|
|
96
|
+
_VALID_NAME_CHARS = frozenset(("-", "_", ":", "."))
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def is_valid_value_char(char: str) -> bool:
|
|
100
|
+
if is_valid_name_char(char):
|
|
101
|
+
return True
|
|
102
|
+
if char in _VALID_VALUE_CHARS:
|
|
103
|
+
return True
|
|
104
|
+
return False
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def is_valid_name_char(char: str) -> bool:
|
|
108
|
+
if char in _VALID_NAME_CHARS:
|
|
109
|
+
return True
|
|
110
|
+
|
|
111
|
+
# https://www.w3.org/TR/xml/#NT-Name
|
|
112
|
+
if "a" <= char <= "z":
|
|
113
|
+
return True
|
|
114
|
+
if "A" <= char <= "Z":
|
|
115
|
+
return True
|
|
116
|
+
if "0" <= char <= "9":
|
|
117
|
+
return True
|
|
118
|
+
return False
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
from xml.etree.ElementTree import Element
|
|
2
|
+
|
|
3
|
+
from .tag import Tag, TagKind
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def tag_to_element(tag: Tag) -> Element:
|
|
7
|
+
element = Element(tag.name)
|
|
8
|
+
for attr_name, attr_value in tag.attributes:
|
|
9
|
+
element.set(attr_name, attr_value)
|
|
10
|
+
return element
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def element_to_tag(element: Element, kind: TagKind, proto: str = "") -> Tag:
|
|
14
|
+
tag = Tag(
|
|
15
|
+
kind=kind,
|
|
16
|
+
name=element.tag,
|
|
17
|
+
proto=proto,
|
|
18
|
+
attributes=[],
|
|
19
|
+
)
|
|
20
|
+
if kind != TagKind.CLOSING:
|
|
21
|
+
for attr_name in sorted(list(element.keys())):
|
|
22
|
+
attr_value = element.get(attr_name, "")
|
|
23
|
+
tag.attributes.append((attr_name, attr_value))
|
|
24
|
+
|
|
25
|
+
# To make LLM easier to understand, the naming here is restricted in a more strict way.
|
|
26
|
+
# https://github.com/oomol-lab/pdf-craft/issues/149
|
|
27
|
+
invalid_name = tag.find_invalid_name()
|
|
28
|
+
if invalid_name is not None:
|
|
29
|
+
raise ValueError(f"find invalid tag name or attribute name: {invalid_name}")
|
|
30
|
+
|
|
31
|
+
invalid_attr_pair = tag.find_invalid_attr_value()
|
|
32
|
+
if invalid_attr_pair is not None:
|
|
33
|
+
attr_name, attr_value = invalid_attr_pair
|
|
34
|
+
raise ValueError(f'find invalid attribute value: {attr_name}="{attr_value}"')
|
|
35
|
+
|
|
36
|
+
return tag
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
from collections.abc import Generator
|
|
2
|
+
from xml.etree.ElementTree import Element
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def find_first(element: Element, tag: str) -> Element | None:
|
|
6
|
+
if element.tag == tag:
|
|
7
|
+
return element
|
|
8
|
+
for child in element:
|
|
9
|
+
result = find_first(child, tag)
|
|
10
|
+
if result is not None:
|
|
11
|
+
return result
|
|
12
|
+
return None
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def iter_with_stack(element: Element) -> Generator[tuple[list[Element], Element], None, None]:
|
|
16
|
+
"""先序遍历:yield parent_path, element"""
|
|
17
|
+
stack: list[list[Element]] = [[element]]
|
|
18
|
+
while stack:
|
|
19
|
+
current_path = stack.pop()
|
|
20
|
+
current = current_path[-1]
|
|
21
|
+
yield current_path[:-1], current
|
|
22
|
+
|
|
23
|
+
if len(current) == 0:
|
|
24
|
+
continue
|
|
25
|
+
|
|
26
|
+
for child in reversed(list(current)):
|
|
27
|
+
child_path = list(current_path)
|
|
28
|
+
child_path.append(child)
|
|
29
|
+
stack.append(child_path)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def clone_element(element: Element) -> Element:
|
|
33
|
+
new_element = Element(element.tag, element.attrib)
|
|
34
|
+
new_element.text = element.text
|
|
35
|
+
for child in element:
|
|
36
|
+
new_child = clone_element(child)
|
|
37
|
+
new_child.tail = child.tail
|
|
38
|
+
new_element.append(new_child)
|
|
39
|
+
return new_element
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def plain_text(element: Element) -> str:
|
|
43
|
+
return "".join(_iter_text_in(element))
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _iter_text_in(element: Element) -> Generator[str, None, None]:
|
|
47
|
+
if element.text:
|
|
48
|
+
yield element.text
|
|
49
|
+
for child in element:
|
|
50
|
+
yield from _iter_text_in(child)
|
|
51
|
+
if child.tail:
|
|
52
|
+
yield child.tail
|