epub-translator 0.0.7__py3-none-any.whl → 0.1.1__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 +4 -2
- 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 +233 -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 +208 -178
- 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 +231 -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 +179 -0
- epub_translator/xml_translator/utils.py +29 -0
- epub_translator-0.1.1.dist-info/METADATA +283 -0
- epub_translator-0.1.1.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 -68
- 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.7.dist-info/METADATA +0 -170
- epub_translator-0.0.7.dist-info/RECORD +0 -36
- {epub_translator-0.0.7.dist-info → epub_translator-0.1.1.dist-info}/LICENSE +0 -0
- {epub_translator-0.0.7.dist-info → epub_translator-0.1.1.dist-info}/WHEEL +0 -0
epub_translator/translator.py
CHANGED
|
@@ -1,184 +1,214 @@
|
|
|
1
|
-
from
|
|
1
|
+
from collections.abc import Callable
|
|
2
2
|
from pathlib import Path
|
|
3
|
-
from
|
|
4
|
-
from tempfile import mkdtemp
|
|
5
|
-
from shutil import rmtree
|
|
3
|
+
from xml.etree.ElementTree import Element
|
|
6
4
|
|
|
5
|
+
from .epub import Placeholder, Zip, is_placeholder_tag, read_toc, search_spine_paths, write_toc
|
|
6
|
+
from .epub.common import find_opf_path
|
|
7
7
|
from .llm import LLM
|
|
8
|
-
from .
|
|
9
|
-
from .
|
|
10
|
-
from .translation import translate as _translate, Incision, Fragment, Language, ProgressReporter
|
|
8
|
+
from .xml import XMLLikeNode, deduplicate_ids_in_element, find_first, plain_text
|
|
9
|
+
from .xml_translator import XMLGroupContext, XMLTranslator, submit_text_segments
|
|
11
10
|
|
|
12
11
|
|
|
13
|
-
class TranslatedWriteMode(Enum):
|
|
14
|
-
APPEND = auto()
|
|
15
|
-
REPLACE = auto()
|
|
16
|
-
|
|
17
12
|
def translate(
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
13
|
+
llm: LLM,
|
|
14
|
+
source_path: Path,
|
|
15
|
+
target_path: Path,
|
|
16
|
+
target_language: str,
|
|
17
|
+
user_prompt: str | None = None,
|
|
18
|
+
max_retries: int = 5,
|
|
19
|
+
max_group_tokens: int = 1200,
|
|
20
|
+
on_progress: Callable[[float], None] | None = None,
|
|
21
|
+
) -> None:
|
|
22
|
+
translator = XMLTranslator(
|
|
23
|
+
llm=llm,
|
|
24
|
+
target_language=target_language,
|
|
25
|
+
user_prompt=user_prompt,
|
|
26
|
+
ignore_translated_error=False,
|
|
27
|
+
max_retries=max_retries,
|
|
28
|
+
max_fill_displaying_errors=10,
|
|
29
|
+
group_context=XMLGroupContext(
|
|
30
|
+
encoding=llm.encoding,
|
|
31
|
+
max_group_tokens=max_group_tokens,
|
|
32
|
+
),
|
|
33
|
+
)
|
|
34
|
+
with Zip(source_path, target_path) as zip:
|
|
35
|
+
# Progress distribution: TOC 3%, metadata 2%, chapters 95%
|
|
36
|
+
TOC_PROGRESS = 0.03
|
|
37
|
+
METADATA_PROGRESS = 0.02
|
|
38
|
+
CHAPTERS_PROGRESS = 0.95
|
|
39
|
+
|
|
40
|
+
# Count total chapters for progress calculation (lightweight, no content loading)
|
|
41
|
+
total_chapters = _count_chapters(zip)
|
|
42
|
+
chapter_progress_step = CHAPTERS_PROGRESS / total_chapters if total_chapters > 0 else 0
|
|
43
|
+
|
|
44
|
+
current_progress = 0.0
|
|
45
|
+
|
|
46
|
+
# Translate TOC
|
|
47
|
+
_translate_toc(translator, zip)
|
|
48
|
+
current_progress += TOC_PROGRESS
|
|
49
|
+
if on_progress:
|
|
50
|
+
on_progress(current_progress)
|
|
51
|
+
|
|
52
|
+
# Translate metadata
|
|
53
|
+
_translate_metadata(translator, zip)
|
|
54
|
+
current_progress += METADATA_PROGRESS
|
|
55
|
+
if on_progress:
|
|
56
|
+
on_progress(current_progress)
|
|
57
|
+
|
|
58
|
+
# Translate chapters
|
|
59
|
+
processed_chapters = 0
|
|
60
|
+
for element, text_segments, (chapter_path, xml, placeholder) in translator.translate_to_text_segments(
|
|
61
|
+
items=_search_chapter_items(zip),
|
|
62
|
+
):
|
|
63
|
+
submit_text_segments(
|
|
64
|
+
element=element,
|
|
65
|
+
text_segments=(
|
|
66
|
+
segment
|
|
67
|
+
for segment in text_segments
|
|
68
|
+
if not any(is_placeholder_tag(e.tag) for e in segment.parent_stack)
|
|
69
|
+
),
|
|
70
|
+
)
|
|
71
|
+
placeholder.recover()
|
|
72
|
+
deduplicate_ids_in_element(xml.element)
|
|
73
|
+
with zip.replace(chapter_path) as target_file:
|
|
74
|
+
xml.save(target_file)
|
|
75
|
+
|
|
76
|
+
# Update progress after each chapter
|
|
77
|
+
processed_chapters += 1
|
|
78
|
+
current_progress = TOC_PROGRESS + METADATA_PROGRESS + (processed_chapters * chapter_progress_step)
|
|
79
|
+
if on_progress:
|
|
80
|
+
on_progress(current_progress)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _translate_toc(translator: XMLTranslator, zip: Zip):
|
|
84
|
+
"""Translate TOC (Table of Contents) titles."""
|
|
85
|
+
toc_list = read_toc(zip)
|
|
86
|
+
if not toc_list:
|
|
87
|
+
return
|
|
88
|
+
|
|
89
|
+
# Collect all titles recursively
|
|
90
|
+
titles_to_translate: list[str] = []
|
|
91
|
+
|
|
92
|
+
def collect_titles(items):
|
|
93
|
+
for item in items:
|
|
94
|
+
titles_to_translate.append(item.title)
|
|
95
|
+
if item.children:
|
|
96
|
+
collect_titles(item.children)
|
|
97
|
+
|
|
98
|
+
collect_titles(toc_list)
|
|
99
|
+
|
|
100
|
+
# Create XML elements for translation
|
|
101
|
+
elements_to_translate = Element("toc")
|
|
102
|
+
elements_to_translate.extend(_create_text_element(title) for title in titles_to_translate)
|
|
103
|
+
|
|
104
|
+
# Translate all titles at once
|
|
105
|
+
translated_element = translator.translate_to_element(elements_to_translate)
|
|
106
|
+
|
|
107
|
+
# Extract translated texts
|
|
108
|
+
from builtins import zip as builtin_zip
|
|
109
|
+
|
|
110
|
+
translated_titles = [
|
|
111
|
+
plain_text(elem) if elem is not None else original
|
|
112
|
+
for elem, original in builtin_zip(translated_element, titles_to_translate)
|
|
113
|
+
]
|
|
114
|
+
|
|
115
|
+
# Fill back translated titles
|
|
116
|
+
title_index = 0
|
|
117
|
+
|
|
118
|
+
def fill_titles(items):
|
|
119
|
+
nonlocal title_index
|
|
120
|
+
for item in items:
|
|
121
|
+
item.title = translated_titles[title_index]
|
|
122
|
+
title_index += 1
|
|
123
|
+
if item.children:
|
|
124
|
+
fill_titles(item.children)
|
|
125
|
+
|
|
126
|
+
fill_titles(toc_list)
|
|
127
|
+
|
|
128
|
+
# Write back the translated TOC
|
|
129
|
+
write_toc(zip, toc_list)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _translate_metadata(translator: XMLTranslator, zip: Zip):
|
|
133
|
+
"""Translate metadata fields in OPF file."""
|
|
134
|
+
opf_path = find_opf_path(zip)
|
|
135
|
+
|
|
136
|
+
with zip.read(opf_path) as f:
|
|
137
|
+
xml = XMLLikeNode(f)
|
|
138
|
+
|
|
139
|
+
# Find metadata element
|
|
140
|
+
metadata_elem = None
|
|
141
|
+
for child in xml.element:
|
|
142
|
+
if child.tag.endswith("metadata"):
|
|
143
|
+
metadata_elem = child
|
|
144
|
+
break
|
|
145
|
+
|
|
146
|
+
if metadata_elem is None:
|
|
147
|
+
return
|
|
148
|
+
|
|
149
|
+
# Collect metadata fields to translate
|
|
150
|
+
# Skip fields that should not be translated
|
|
151
|
+
skip_fields = {
|
|
152
|
+
"language",
|
|
153
|
+
"identifier",
|
|
154
|
+
"date",
|
|
155
|
+
"meta",
|
|
156
|
+
"contributor", # Usually technical information
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
fields_to_translate: list[tuple[Element, str]] = []
|
|
160
|
+
|
|
161
|
+
for elem in metadata_elem:
|
|
162
|
+
# Get tag name without namespace
|
|
163
|
+
tag_name = elem.tag.split("}")[-1] if "}" in elem.tag else elem.tag
|
|
164
|
+
|
|
165
|
+
# Check if element has text content and should be translated
|
|
166
|
+
if elem.text and elem.text.strip() and tag_name not in skip_fields:
|
|
167
|
+
fields_to_translate.append((elem, elem.text.strip()))
|
|
168
|
+
|
|
169
|
+
if not fields_to_translate:
|
|
170
|
+
return
|
|
171
|
+
|
|
172
|
+
# Create XML elements for translation
|
|
173
|
+
elements_to_translate = Element("metadata")
|
|
174
|
+
elements_to_translate.extend(_create_text_element(text) for _, text in fields_to_translate)
|
|
175
|
+
|
|
176
|
+
# Translate all metadata at once
|
|
177
|
+
translated_element = translator.translate_to_element(elements_to_translate)
|
|
178
|
+
|
|
179
|
+
# Fill back translated texts
|
|
180
|
+
from builtins import zip as builtin_zip
|
|
181
|
+
|
|
182
|
+
for (elem, _), translated_elem in builtin_zip(fields_to_translate, translated_element, strict=True):
|
|
183
|
+
if translated_elem is not None:
|
|
184
|
+
translated_text = plain_text(translated_elem)
|
|
185
|
+
if translated_text:
|
|
186
|
+
elem.text = translated_text
|
|
187
|
+
|
|
188
|
+
# Write back the modified OPF file
|
|
189
|
+
with zip.replace(opf_path) as f:
|
|
190
|
+
xml.save(f)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _count_chapters(zip: Zip) -> int:
|
|
194
|
+
"""Count total chapters without loading content (lightweight)."""
|
|
195
|
+
return sum(1 for _ in search_spine_paths(zip))
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _search_chapter_items(zip: Zip):
|
|
199
|
+
for chapter_path in search_spine_paths(zip):
|
|
200
|
+
with zip.read(chapter_path) as chapter_file:
|
|
201
|
+
xml = XMLLikeNode(
|
|
202
|
+
file=chapter_file,
|
|
203
|
+
is_html_like=chapter_path.suffix.lower() in (".html", ".htm"),
|
|
204
|
+
)
|
|
205
|
+
body_element = find_first(xml.element, "body")
|
|
206
|
+
if body_element is not None:
|
|
207
|
+
placeholder = Placeholder(body_element)
|
|
208
|
+
yield body_element, (chapter_path, xml, placeholder)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _create_text_element(text: str) -> Element:
|
|
212
|
+
elem = Element("text")
|
|
213
|
+
elem.text = text
|
|
214
|
+
return elem
|
epub_translator/utils.py
ADDED
epub_translator/xml/__init__.py
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
-
from .
|
|
2
|
-
from .
|
|
3
|
-
from .
|
|
1
|
+
from .deduplication import *
|
|
2
|
+
from .firendly import *
|
|
3
|
+
from .xml import *
|
|
4
|
+
from .xml_like import *
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
from xml.etree.ElementTree import Element
|
|
2
|
+
|
|
3
|
+
from .xml import iter_with_stack
|
|
4
|
+
|
|
5
|
+
_ID_KEY = "id"
|
|
6
|
+
_SUFFIX = "__translated"
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def deduplicate_ids_in_element(element: Element) -> Element:
|
|
10
|
+
seen_ids: set[str] = set()
|
|
11
|
+
original_id_count: dict[str, int] = {}
|
|
12
|
+
|
|
13
|
+
for _, sub_element in iter_with_stack(element):
|
|
14
|
+
if _ID_KEY not in sub_element.attrib:
|
|
15
|
+
continue
|
|
16
|
+
original_id = sub_element.attrib[_ID_KEY]
|
|
17
|
+
|
|
18
|
+
if original_id not in seen_ids:
|
|
19
|
+
seen_ids.add(original_id)
|
|
20
|
+
original_id_count[original_id] = 1
|
|
21
|
+
else:
|
|
22
|
+
original_id_count[original_id] = original_id_count.get(original_id, 1) + 1
|
|
23
|
+
occurrence = original_id_count[original_id]
|
|
24
|
+
|
|
25
|
+
if occurrence == 2:
|
|
26
|
+
new_id = f"{original_id}{_SUFFIX}"
|
|
27
|
+
else:
|
|
28
|
+
new_id = f"{original_id}{_SUFFIX}_{occurrence - 1}"
|
|
29
|
+
|
|
30
|
+
counter = occurrence - 1
|
|
31
|
+
while new_id in seen_ids:
|
|
32
|
+
counter += 1
|
|
33
|
+
new_id = f"{original_id}{_SUFFIX}_{counter}"
|
|
34
|
+
|
|
35
|
+
sub_element.attrib["id"] = new_id
|
|
36
|
+
seen_ids.add(new_id)
|
|
37
|
+
|
|
38
|
+
return element
|
|
@@ -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(" ")
|