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.
Files changed (82) hide show
  1. epub_translator/__init__.py +4 -2
  2. epub_translator/data/fill.jinja +66 -0
  3. epub_translator/data/mmltex/README.md +67 -0
  4. epub_translator/data/mmltex/cmarkup.xsl +1106 -0
  5. epub_translator/data/mmltex/entities.xsl +459 -0
  6. epub_translator/data/mmltex/glayout.xsl +222 -0
  7. epub_translator/data/mmltex/mmltex.xsl +36 -0
  8. epub_translator/data/mmltex/scripts.xsl +375 -0
  9. epub_translator/data/mmltex/tables.xsl +130 -0
  10. epub_translator/data/mmltex/tokens.xsl +328 -0
  11. epub_translator/data/translate.jinja +15 -12
  12. epub_translator/epub/__init__.py +4 -2
  13. epub_translator/epub/common.py +43 -0
  14. epub_translator/epub/math.py +193 -0
  15. epub_translator/epub/placeholder.py +53 -0
  16. epub_translator/epub/spines.py +42 -0
  17. epub_translator/epub/toc.py +505 -0
  18. epub_translator/epub/zip.py +67 -0
  19. epub_translator/iter_sync.py +24 -0
  20. epub_translator/language.py +23 -0
  21. epub_translator/llm/__init__.py +2 -1
  22. epub_translator/llm/core.py +233 -0
  23. epub_translator/llm/error.py +38 -35
  24. epub_translator/llm/executor.py +159 -136
  25. epub_translator/llm/increasable.py +28 -28
  26. epub_translator/llm/types.py +17 -0
  27. epub_translator/serial/__init__.py +2 -0
  28. epub_translator/serial/chunk.py +52 -0
  29. epub_translator/serial/segment.py +17 -0
  30. epub_translator/serial/splitter.py +50 -0
  31. epub_translator/template.py +35 -33
  32. epub_translator/translator.py +208 -178
  33. epub_translator/utils.py +7 -0
  34. epub_translator/xml/__init__.py +4 -3
  35. epub_translator/xml/deduplication.py +38 -0
  36. epub_translator/xml/firendly/__init__.py +2 -0
  37. epub_translator/xml/firendly/decoder.py +75 -0
  38. epub_translator/xml/firendly/encoder.py +84 -0
  39. epub_translator/xml/firendly/parser.py +177 -0
  40. epub_translator/xml/firendly/tag.py +118 -0
  41. epub_translator/xml/firendly/transform.py +36 -0
  42. epub_translator/xml/xml.py +52 -0
  43. epub_translator/xml/xml_like.py +231 -0
  44. epub_translator/xml_translator/__init__.py +3 -0
  45. epub_translator/xml_translator/const.py +2 -0
  46. epub_translator/xml_translator/fill.py +128 -0
  47. epub_translator/xml_translator/format.py +282 -0
  48. epub_translator/xml_translator/fragmented.py +125 -0
  49. epub_translator/xml_translator/group.py +183 -0
  50. epub_translator/xml_translator/progressive_locking.py +256 -0
  51. epub_translator/xml_translator/submitter.py +102 -0
  52. epub_translator/xml_translator/text_segment.py +263 -0
  53. epub_translator/xml_translator/translator.py +179 -0
  54. epub_translator/xml_translator/utils.py +29 -0
  55. epub_translator-0.1.1.dist-info/METADATA +283 -0
  56. epub_translator-0.1.1.dist-info/RECORD +58 -0
  57. epub_translator/data/format.jinja +0 -33
  58. epub_translator/epub/content_parser.py +0 -162
  59. epub_translator/epub/html/__init__.py +0 -1
  60. epub_translator/epub/html/dom_operator.py +0 -68
  61. epub_translator/epub/html/empty_tags.py +0 -23
  62. epub_translator/epub/html/file.py +0 -80
  63. epub_translator/epub/html/texts_searcher.py +0 -46
  64. epub_translator/llm/node.py +0 -201
  65. epub_translator/translation/__init__.py +0 -2
  66. epub_translator/translation/chunk.py +0 -118
  67. epub_translator/translation/splitter.py +0 -78
  68. epub_translator/translation/store.py +0 -36
  69. epub_translator/translation/translation.py +0 -231
  70. epub_translator/translation/types.py +0 -45
  71. epub_translator/translation/utils.py +0 -11
  72. epub_translator/xml/decoder.py +0 -71
  73. epub_translator/xml/encoder.py +0 -95
  74. epub_translator/xml/parser.py +0 -172
  75. epub_translator/xml/tag.py +0 -93
  76. epub_translator/xml/transform.py +0 -34
  77. epub_translator/xml/utils.py +0 -12
  78. epub_translator/zip_context.py +0 -74
  79. epub_translator-0.0.7.dist-info/METADATA +0 -170
  80. epub_translator-0.0.7.dist-info/RECORD +0 -36
  81. {epub_translator-0.0.7.dist-info → epub_translator-0.1.1.dist-info}/LICENSE +0 -0
  82. {epub_translator-0.0.7.dist-info → epub_translator-0.1.1.dist-info}/WHEEL +0 -0
@@ -1,184 +1,214 @@
1
- from os import PathLike
1
+ from collections.abc import Callable
2
2
  from pathlib import Path
3
- from enum import auto, Enum
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 .epub import HTMLFile
9
- from .zip_context import ZipContext
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
- llm: LLM,
19
- source_path: PathLike,
20
- translated_path: PathLike,
21
- target_language: Language,
22
- write_mode: TranslatedWriteMode = TranslatedWriteMode.APPEND,
23
- user_prompt: str | None = None,
24
- working_path: PathLike | None = None,
25
- max_chunk_tokens_count: int = 3000,
26
- max_threads_count: int = 1,
27
- report_progress: ProgressReporter | None = None,
28
- ) -> None:
29
-
30
- source_path = Path(source_path)
31
- translated_path = Path(translated_path)
32
- working_path = Path(working_path) if working_path else None
33
- report_progress = report_progress or (lambda _: None)
34
-
35
- _Translator(
36
- llm=llm,
37
- target_language=target_language,
38
- write_mode=write_mode,
39
- user_prompt=user_prompt,
40
- max_chunk_tokens_count=max_chunk_tokens_count,
41
- max_threads_count=max_threads_count,
42
- report_progress=report_progress,
43
- ).do(
44
- source_path=source_path,
45
- translated_path=translated_path,
46
- working_path=working_path,
47
- )
48
-
49
- class _Translator:
50
- def __init__(
51
- self,
52
- llm: LLM,
53
- target_language: Language,
54
- write_mode: TranslatedWriteMode,
55
- user_prompt: str | None,
56
- max_chunk_tokens_count: int,
57
- max_threads_count: int,
58
- report_progress: ProgressReporter,
59
- ) -> None:
60
-
61
- self._llm: LLM = llm
62
- self._target_language: Language = target_language
63
- self._write_mode: TranslatedWriteMode = write_mode
64
- self._user_prompt: str | None = user_prompt
65
- self._max_chunk_tokens_count: int = max_chunk_tokens_count
66
- self._max_threads_count: int = max_threads_count
67
- self._report_progress: ProgressReporter = report_progress
68
-
69
- def do(self, source_path: Path, translated_path: Path, working_path: Path | None) -> None:
70
- is_temp_workspace = not bool(working_path)
71
- working_path = working_path or Path(mkdtemp())
72
- try:
73
- temp_dir = _clean_path(working_path / "temp")
74
- temp_dir.mkdir(parents=True, exist_ok=True)
75
- cache_path = working_path / "cache"
76
-
77
- context = ZipContext(
78
- epub_path=Path(source_path),
79
- temp_dir=temp_dir,
80
- )
81
- context.replace_ncx(lambda texts: self._translate_ncx(
82
- texts=texts,
83
- cache_path=cache_path,
84
- report_progress=lambda p: self._report_progress(p * 0.1)),
85
- )
86
- self._translate_spine(
87
- context=context,
88
- cache_path=cache_path,
89
- report_progress=lambda p: self._report_progress(0.1 + p * 0.8),
90
- )
91
- context.archive(translated_path)
92
- self._report_progress(1.0)
93
-
94
- finally:
95
- if is_temp_workspace:
96
- rmtree(working_path, ignore_errors=True)
97
-
98
- def _translate_ncx(self, texts: list[str], cache_path: Path, report_progress: ProgressReporter) -> list[str]:
99
- return list(_translate(
100
- llm=self._llm,
101
- cache_path=cache_path,
102
- max_chunk_tokens_count=self._max_chunk_tokens_count,
103
- max_threads_count=1,
104
- target_language=self._target_language,
105
- user_prompt=self._user_prompt,
106
- report_progress=report_progress,
107
- gen_fragments_iter=lambda: (
108
- Fragment(
109
- text=text,
110
- start_incision=Incision.IMPOSSIBLE,
111
- end_incision=Incision.IMPOSSIBLE,
112
- )
113
- for text in texts
114
- ),
115
- ))
116
-
117
- def _translate_spine(self, context: ZipContext, cache_path: Path, report_progress: ProgressReporter):
118
- spine_paths_iter = iter(list(context.search_spine_paths()))
119
- spine: tuple[Path, HTMLFile] | None = None
120
- translated_texts: list[str] = []
121
- translated_count: int = 0
122
- append = (self._write_mode == TranslatedWriteMode.APPEND)
123
-
124
- for translated_text in _translate(
125
- llm=self._llm,
126
- gen_fragments_iter=lambda: _gen_fragments(context),
127
- cache_path=cache_path,
128
- max_chunk_tokens_count=self._max_chunk_tokens_count,
129
- max_threads_count=self._max_threads_count,
130
- target_language=self._target_language,
131
- user_prompt=self._user_prompt,
132
- report_progress=report_progress,
133
- ):
134
- did_touch_end = False
135
-
136
- if spine and translated_count >= len(translated_texts):
137
- spine_path, spine_file = spine
138
- spine_file.write_texts(translated_texts, append)
139
- context.write_spine_file(spine_path, spine_file)
140
- spine = None
141
-
142
- while not spine:
143
- spine_path = next(spine_paths_iter, None)
144
- if spine_path is None:
145
- spine = None
146
- did_touch_end = True
147
- break
148
- spine_file = context.read_spine_file(spine_path)
149
- if spine_file.texts_length == 0:
150
- continue
151
- spine = (spine_path, spine_file)
152
- translated_texts = [""] * spine_file.texts_length
153
- translated_count = 0
154
- break
155
-
156
- translated_texts[translated_count] = translated_text
157
- translated_count += 1
158
-
159
- if did_touch_end:
160
- break
161
-
162
- if spine:
163
- spine_path, spine_file = spine
164
- if translated_count > 0:
165
- spine_file.write_texts(translated_texts, append)
166
- context.write_spine_file(spine_path, spine_file)
167
-
168
- def _gen_fragments(context: ZipContext):
169
- for spine_path in context.search_spine_paths():
170
- spine_file = context.read_spine_file(spine_path)
171
- for text in spine_file.read_texts():
172
- yield Fragment(
173
- text=text,
174
- start_incision=Incision.IMPOSSIBLE,
175
- end_incision=Incision.IMPOSSIBLE,
176
- )
177
-
178
- def _clean_path(path: Path) -> Path:
179
- if path.exists():
180
- if path.is_file():
181
- path.unlink()
182
- elif path.is_dir():
183
- rmtree(path, ignore_errors=True)
184
- return path
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
@@ -0,0 +1,7 @@
1
+ import re
2
+
3
+ _WHITESPACE_PATTERN = re.compile(r"\s+")
4
+
5
+
6
+ def normalize_whitespace(text: str) -> str:
7
+ return _WHITESPACE_PATTERN.sub(" ", text)
@@ -1,3 +1,4 @@
1
- from .encoder import encode, encode_friendly
2
- from .decoder import decode_friendly
3
- from .utils import clone
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,2 @@
1
+ from .decoder import decode_friendly
2
+ from .encoder import encode_friendly
@@ -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(" ")