EbookFlux 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,8 @@
1
+ .DS_Store
2
+
3
+ .venv/
4
+ __pycache__/
5
+ *.py[cod]
6
+
7
+ .ruff_cache/
8
+ dist/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Dnomd343
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,15 @@
1
+ Metadata-Version: 2.5
2
+ Name: EbookFlux
3
+ Version: 0.1.0
4
+ Summary: Simple paragraph-based ebook models and exporters
5
+ Author-email: Dnomd343 <dnomd343@gmail.com>
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.12
9
+ Description-Content-Type: text/markdown
10
+
11
+ # EbookFlux
12
+
13
+ A Python library for organizing plain-text books and exporting them as EPUB and TXT, with no runtime dependencies.
14
+
15
+ MIT ©2026 [@dnomd343](https://github.com/dnomd343)
@@ -0,0 +1,5 @@
1
+ # EbookFlux
2
+
3
+ A Python library for organizing plain-text books and exporting them as EPUB and TXT, with no runtime dependencies.
4
+
5
+ MIT ©2026 [@dnomd343](https://github.com/dnomd343)
@@ -0,0 +1,36 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27.0"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "EbookFlux"
7
+ version = "0.1.0"
8
+ requires-python = ">=3.12"
9
+ description = "Simple paragraph-based ebook models and exporters"
10
+
11
+ readme = "README.md"
12
+ license = "MIT"
13
+ license-files = ["LICENSE"]
14
+ authors = [{ name = "Dnomd343", email = "dnomd343@gmail.com" }]
15
+
16
+ dependencies = []
17
+
18
+ [dependency-groups]
19
+ dev = [
20
+ "pyright>=1.1.414",
21
+ "ruff>=0.17.5",
22
+ ]
23
+
24
+ [tool.hatch.build.targets]
25
+ wheel.packages = ["src/ebookflux"]
26
+ sdist.include = ["src/ebookflux", "pyproject.toml", "uv.lock"]
27
+
28
+ [tool.ruff]
29
+ line-length = 120
30
+ lint.select = ["E4", "E7", "E9", "F", "I", "UP"]
31
+ format.quote-style = "single"
32
+
33
+ [tool.pyright]
34
+ include = ["src"]
35
+ pythonVersion = "3.12"
36
+ typeCheckingMode = "standard"
@@ -0,0 +1,7 @@
1
+ """Public EbookFlux API."""
2
+
3
+ from .epub import HeadingStyle, render_epub, write_epub
4
+ from .models import Book, Chapter
5
+ from .txt import render_txt, write_txt
6
+
7
+ __all__ = ['Book', 'Chapter', 'HeadingStyle', 'render_epub', 'render_txt', 'write_epub', 'write_txt']
@@ -0,0 +1,44 @@
1
+ """Read JPEG and PNG dimensions without decoding image pixels."""
2
+
3
+ from typing import BinaryIO
4
+
5
+
6
+ def image_info(source: BinaryIO) -> tuple[str, str, int, int]:
7
+ header = source.read(8)
8
+ if header == b'\x89PNG\r\n\x1a\n':
9
+ chunk = source.read(16)
10
+ if len(chunk) == 16 and chunk[:8] == b'\x00\x00\x00\rIHDR':
11
+ width = int.from_bytes(chunk[8:12], 'big')
12
+ height = int.from_bytes(chunk[12:16], 'big')
13
+ if width > 0 and height > 0:
14
+ return 'cover.png', 'image/png', width, height
15
+ raise ValueError('Invalid PNG cover dimensions')
16
+
17
+ if not header.startswith(b'\xff\xd8\xff'):
18
+ raise ValueError('Cover must be a JPEG or PNG image')
19
+ source.seek(2)
20
+ while source.read(1) == b'\xff':
21
+ marker = source.read(1)
22
+ while marker == b'\xff':
23
+ marker = source.read(1)
24
+ if not marker or marker in (b'\xda', b'\xd9'):
25
+ break
26
+ if marker == b'\x01' or b'\xd0' <= marker <= b'\xd8':
27
+ continue
28
+ length = source.read(2)
29
+ if len(length) != 2:
30
+ break
31
+ size = int.from_bytes(length, 'big')
32
+ if size < 2:
33
+ break
34
+ if b'\xc0' <= marker <= b'\xcf' and marker not in (b'\xc4', b'\xc8', b'\xcc'):
35
+ frame = source.read(5)
36
+ if size < 8 or len(frame) != 5:
37
+ break
38
+ height = int.from_bytes(frame[1:3], 'big')
39
+ width = int.from_bytes(frame[3:5], 'big')
40
+ if width > 0 and height > 0:
41
+ return 'cover.jpg', 'image/jpeg', width, height
42
+ break
43
+ source.seek(size - 2, 1)
44
+ raise ValueError('Invalid JPEG cover dimensions')
@@ -0,0 +1,25 @@
1
+ """Localized display labels shared by exporters."""
2
+
3
+ from dataclasses import dataclass
4
+
5
+ _TRANSLATIONS = {
6
+ 'en-us': ('Cover', 'Title page', 'Body text', 'Author: ', 'Producer: ', 'Publisher: ', ', '),
7
+ 'zh-cn': ('封面', '扉页', '正文', '作者:', '制作:', '发行:', '、'),
8
+ }
9
+
10
+
11
+ @dataclass(frozen=True, slots=True)
12
+ class Labels:
13
+ """Display labels selected by language, defaulting to en-US."""
14
+
15
+ cover: str
16
+ title_page: str
17
+ text: str
18
+ author: str
19
+ producer: str
20
+ publisher: str
21
+ name_separator: str
22
+
23
+ @classmethod
24
+ def for_language(cls, language: str = 'en-US') -> 'Labels':
25
+ return cls(*_TRANSLATIONS.get(language.lower(), _TRANSLATIONS['en-us']))
@@ -0,0 +1,442 @@
1
+ """EPUB 2 serialization using the standard library."""
2
+
3
+ import re
4
+ from enum import StrEnum
5
+ from importlib.metadata import version
6
+ from io import BytesIO
7
+ from pathlib import Path
8
+ from shutil import copyfileobj
9
+ from tempfile import NamedTemporaryFile
10
+ from xml.etree import ElementTree as ET
11
+ from zipfile import ZIP_DEFLATED, ZIP_STORED, ZipFile, ZipInfo
12
+
13
+ from ._images import image_info
14
+ from ._labels import Labels
15
+ from .models import Book
16
+
17
+
18
+ class HeadingStyle(StrEnum):
19
+ """Chapter heading presentation."""
20
+
21
+ DEFAULT = 'default'
22
+ CENTER = 'center'
23
+ FADE_LINE = 'fade-line'
24
+ DIAMOND_LINE = 'diamond-line'
25
+
26
+
27
+ XHTML = 'http://www.w3.org/1999/xhtml'
28
+ OPF = 'http://www.idpf.org/2007/opf'
29
+ DC = 'http://purl.org/dc/elements/1.1/'
30
+ NCX = 'http://www.daisy.org/z3986/2005/ncx/'
31
+ CONTAINER = 'urn:oasis:names:tc:opendocument:xmlns:container'
32
+ XML = 'http://www.w3.org/XML/1998/namespace'
33
+
34
+ ET.register_namespace('dc', DC)
35
+ ET.register_namespace('opf', OPF)
36
+
37
+
38
+ def _validate_text(value: str, field: str, *, allow_blank: bool = False) -> None:
39
+ if not allow_blank and not value.strip():
40
+ raise ValueError(f'{field} must not be blank')
41
+ if any(
42
+ not (c in '\t\n\r' or '\u0020' <= c <= '\ud7ff' or '\ue000' <= c <= '\ufffd' or ord(c) >= 0x10000)
43
+ for c in value
44
+ ):
45
+ raise ValueError(f'{field} contains characters invalid in XML')
46
+
47
+
48
+ def _validate(book: Book, heading_style: HeadingStyle) -> None:
49
+ """Check required content, title arity, and XML characters."""
50
+ for field, value in (('name', book.name), ('unique_id', book.unique_id), ('language', book.language)):
51
+ _validate_text(value, field)
52
+ if book.publisher is not None:
53
+ _validate_text(book.publisher, 'publisher')
54
+ for field, values in (
55
+ ('authors', book.authors),
56
+ ('producers', book.producers),
57
+ ('links', book.links),
58
+ ('blurb', book.blurb),
59
+ ):
60
+ for index, value in enumerate(values):
61
+ _validate_text(value, f'{field}[{index}]')
62
+ if not book.chapters:
63
+ raise ValueError('A book needs at least one chapter')
64
+ title_length = 1 if heading_style in (HeadingStyle.DEFAULT, HeadingStyle.CENTER) else 2
65
+ for index, chapter in enumerate(book.chapters):
66
+ field = f'chapters[{index}]'
67
+ if not isinstance(chapter.title, tuple) or len(chapter.title) != title_length:
68
+ raise ValueError(f'{field}.title must be a tuple of {title_length} strings for {heading_style.value}')
69
+ for line, value in enumerate(chapter.title):
70
+ _validate_text(value, f'{field}.title[{line}]', allow_blank=title_length == 2)
71
+ if not chapter.paragraphs:
72
+ raise ValueError(f'{field} needs at least one paragraph')
73
+ for paragraph_index, paragraph in enumerate(chapter.paragraphs):
74
+ _validate_text(paragraph, f'{field}.paragraphs[{paragraph_index}]')
75
+
76
+
77
+ def _element(
78
+ parent: ET.Element,
79
+ tag: str,
80
+ text: str | None = None,
81
+ **attributes: str,
82
+ ) -> ET.Element:
83
+ element = ET.SubElement(parent, tag, attributes)
84
+ element.text = text
85
+ return element
86
+
87
+
88
+ def _xml(root: ET.Element) -> bytes:
89
+ # Preserve mixed content: indentation around br would alter paragraph text.
90
+ def format_tree(element: ET.Element, level: int = 0) -> None:
91
+ if not len(element) or element.tag in {'p', 'h1', 'h2', 'title', 'text'}:
92
+ return
93
+ element.text = '\n' + ' ' * (level + 1)
94
+ for child in element:
95
+ format_tree(child, level + 1)
96
+ child.tail = '\n' + ' ' * (level + 1)
97
+ element[-1].tail = '\n' + ' ' * level
98
+
99
+ format_tree(root)
100
+ data = ET.tostring(root, encoding='utf-8', xml_declaration=True)
101
+ # HTML parsers require explicit closing tags for empty spans.
102
+ return re.sub(rb'<span(\s[^<>]*?)? />', rb'<span\1></span>', data)
103
+
104
+
105
+ def _page(
106
+ title: tuple[str, ...],
107
+ heading: str,
108
+ paragraphs: list[str],
109
+ language: str,
110
+ *,
111
+ heading_style: HeadingStyle,
112
+ ) -> bytes:
113
+ root = ET.Element('html', {'xmlns': XHTML, f'{{{XML}}}lang': language})
114
+ head = _element(root, 'head')
115
+ _element(head, 'meta', **{'http-equiv': 'Content-Type', 'content': 'text/html; charset=utf-8'})
116
+ _element(head, 'title', ' '.join(title))
117
+ _element(head, 'link', rel='stylesheet', type='text/css', href='style.css')
118
+ body = _element(root, 'body')
119
+ element = _element(body, heading)
120
+ if heading == 'h2' and heading_style in (HeadingStyle.FADE_LINE, HeadingStyle.DIAMOND_LINE):
121
+ element.set('class', 'chapter-heading')
122
+ _element(element, 'span', title[0], **{'class': 'chapter-number'}).tail = ' '
123
+ rule = _element(element, 'span', **{'class': 'chapter-rule'})
124
+ if heading_style == HeadingStyle.DIAMOND_LINE:
125
+ _element(rule, 'span', **{'class': 'chapter-diamond'})
126
+ _element(element, 'span', title[1], **{'class': 'chapter-title'})
127
+ else:
128
+ element.text = title[0]
129
+ for text in paragraphs:
130
+ lines = text.replace('\r\n', '\n').replace('\r', '\n').split('\n')
131
+ paragraph = _element(body, 'p', lines[0])
132
+ for line in lines[1:]:
133
+ _element(paragraph, 'br').tail = line
134
+ return _xml(root)
135
+
136
+
137
+ def _cover_page(title: str, language: str, name: str, width: int, height: int) -> bytes:
138
+ cover = ET.Element('html', {'xmlns': XHTML, f'{{{XML}}}lang': language})
139
+ cover_head = _element(cover, 'head')
140
+ _element(cover_head, 'meta', **{'http-equiv': 'Content-Type', 'content': 'text/html; charset=utf-8'})
141
+ _element(cover_head, 'title', title)
142
+ _element(
143
+ cover_head,
144
+ 'style',
145
+ """
146
+ @page { margin: 0; padding: 0; }
147
+ html, body { margin: 0; padding: 0; height: 100%; }
148
+ svg { display: block; }
149
+ """,
150
+ type='text/css',
151
+ )
152
+ svg = _element(
153
+ _element(cover, 'body'),
154
+ 'svg',
155
+ xmlns='http://www.w3.org/2000/svg',
156
+ **{'xmlns:xlink': 'http://www.w3.org/1999/xlink'},
157
+ version='1.1',
158
+ width='100%',
159
+ height='100%',
160
+ viewBox=f'0 0 {width} {height}',
161
+ )
162
+ _element(
163
+ svg,
164
+ 'image',
165
+ width=str(width),
166
+ height=str(height),
167
+ **{'xlink:href': name},
168
+ )
169
+ return _xml(cover)
170
+
171
+
172
+ def _write_entry(archive: ZipFile, name: str, data: str | bytes, *, compress_type: int = ZIP_DEFLATED) -> None:
173
+ # ZipInfo defaults to a fixed timestamp, keeping identical builds reproducible.
174
+ entry = ZipInfo(name)
175
+ entry.compress_type = compress_type
176
+ archive.writestr(entry, data)
177
+
178
+
179
+ def _write_cover_image(archive: ZipFile, path: Path) -> tuple[str, str, int, int]:
180
+ with path.open('rb') as source:
181
+ name, media_type, width, height = image_info(source)
182
+ source.seek(0)
183
+ with archive.open(name, 'w') as destination:
184
+ copyfileobj(source, destination)
185
+ return name, media_type, width, height
186
+
187
+
188
+ def _heading_css(heading_style: HeadingStyle) -> str:
189
+ if heading_style == HeadingStyle.DEFAULT:
190
+ return """h2 {
191
+ text-align: left;
192
+ }
193
+ """
194
+ if heading_style == HeadingStyle.CENTER:
195
+ return ''
196
+ css = """h2 .chapter-number, h2 .chapter-title {
197
+ display: block;
198
+ }
199
+ h2.chapter-heading {
200
+ font-size: 1.25em;
201
+ font-weight: normal;
202
+ line-height: 1.2;
203
+ margin: 1.2em 0 1.5em;
204
+ page-break-inside: avoid;
205
+ }
206
+ .chapter-number {
207
+ font-size: 0.82em;
208
+ font-weight: normal;
209
+ letter-spacing: 0.12em;
210
+ padding-left: 0.12em;
211
+ opacity: 0.65;
212
+ }
213
+ .chapter-rule {
214
+ display: block;
215
+ width: 6.5em;
216
+ max-width: 60%;
217
+ height: 1px;
218
+ margin: 0.5em auto 0.55em;
219
+ opacity: 0.5;
220
+ }
221
+ .chapter-title {
222
+ font-size: 1.2em;
223
+ font-weight: bold;
224
+ line-height: 1.25;
225
+ letter-spacing: 0.05em;
226
+ padding-left: 0.05em;
227
+ }
228
+ """
229
+ if heading_style == HeadingStyle.FADE_LINE:
230
+ return (
231
+ css
232
+ + """.chapter-rule {
233
+ background: currentColor;
234
+ background: linear-gradient(to right, transparent, currentColor 50%, transparent);
235
+ }
236
+ """
237
+ )
238
+ return (
239
+ css
240
+ + """.chapter-rule {
241
+ position: relative;
242
+ height: 0.4em;
243
+ }
244
+ .chapter-rule:before, .chapter-rule:after {
245
+ content: "";
246
+ position: absolute;
247
+ top: 50%;
248
+ width: 40%;
249
+ border-top: 1px solid;
250
+ }
251
+ .chapter-rule:before {
252
+ left: 0;
253
+ }
254
+ .chapter-rule:after {
255
+ right: 0;
256
+ }
257
+ .chapter-diamond {
258
+ position: absolute;
259
+ top: 50%;
260
+ left: 50%;
261
+ width: 0.30em;
262
+ height: 0.30em;
263
+ margin: -0.15em 0 0 -0.15em;
264
+ border: 1px solid;
265
+ box-sizing: border-box;
266
+ transform: rotate(45deg);
267
+ }
268
+ """
269
+ )
270
+
271
+
272
+ def _write_archive(
273
+ book: Book,
274
+ archive: ZipFile,
275
+ *,
276
+ indent: bool,
277
+ cover_page: bool,
278
+ heading_style: HeadingStyle,
279
+ ) -> None:
280
+ heading_style = HeadingStyle(heading_style)
281
+ _validate(book, heading_style)
282
+ labels = Labels.for_language(book.language)
283
+ package = ET.Element(
284
+ 'package',
285
+ {
286
+ 'xmlns': OPF,
287
+ 'version': '2.0',
288
+ 'unique-identifier': 'book-id',
289
+ },
290
+ )
291
+ metadata = _element(package, 'metadata')
292
+ _element(metadata, f'{{{DC}}}identifier', book.unique_id, id='book-id')
293
+ _element(metadata, f'{{{DC}}}title', book.name)
294
+ _element(metadata, f'{{{DC}}}language', book.language)
295
+ for author in book.authors:
296
+ _element(metadata, f'{{{DC}}}creator', author, **{f'{{{OPF}}}role': 'aut'})
297
+ for producer in book.producers:
298
+ _element(metadata, f'{{{DC}}}contributor', producer, **{f'{{{OPF}}}role': 'bkp'})
299
+ if book.publisher is not None:
300
+ _element(metadata, f'{{{DC}}}publisher', book.publisher)
301
+ for link in book.links:
302
+ _element(metadata, f'{{{DC}}}relation', link)
303
+ if book.blurb:
304
+ _element(metadata, f'{{{DC}}}description', '\n'.join(book.blurb))
305
+ manifest = _element(package, 'manifest')
306
+ _element(manifest, 'item', id='ncx', href='toc.ncx', **{'media-type': 'application/x-dtbncx+xml'})
307
+ spine = _element(package, 'spine', toc='ncx')
308
+ guide = _element(package, 'guide')
309
+
310
+ _write_entry(archive, 'mimetype', 'application/epub+zip', compress_type=ZIP_STORED)
311
+ container = ET.Element('container', {'xmlns': CONTAINER, 'version': '1.0'})
312
+ _element(
313
+ _element(container, 'rootfiles'),
314
+ 'rootfile',
315
+ **{'full-path': 'content.opf', 'media-type': 'application/oebps-package+xml'},
316
+ )
317
+ _write_entry(archive, 'META-INF/container.xml', _xml(container))
318
+
319
+ text_indent = '2em' if indent else '0'
320
+ _write_entry(
321
+ archive,
322
+ 'style.css',
323
+ f"""\
324
+ @page {{
325
+ margin-top: 5pt;
326
+ margin-bottom: 5pt;
327
+ }}
328
+ body {{
329
+ font-size: 1em;
330
+ margin: 0 5pt;
331
+ padding: 0;
332
+ }}
333
+ h1, h2 {{
334
+ font-weight: bold;
335
+ line-height: 1.2;
336
+ text-align: center;
337
+ text-indent: 0;
338
+ page-break-after: avoid;
339
+ }}
340
+ h1 {{
341
+ font-size: 2em;
342
+ margin: 1em 0;
343
+ }}
344
+ h2 {{
345
+ font-size: 1.5em;
346
+ margin: 0.8em 0;
347
+ }}
348
+ p {{
349
+ line-height: 1.5;
350
+ text-indent: {text_indent};
351
+ margin: 0 0 0.5em;
352
+ padding: 0;
353
+ }}
354
+ """
355
+ + _heading_css(heading_style),
356
+ )
357
+ _element(manifest, 'item', id='style', href='style.css', **{'media-type': 'text/css'})
358
+
359
+ if book.cover is not None:
360
+ name, media_type, width, height = _write_cover_image(archive, book.cover)
361
+ _element(manifest, 'item', id='cover', href=name, **{'media-type': media_type})
362
+ _element(metadata, 'meta', name='cover', content='cover')
363
+ if cover_page:
364
+ _write_entry(archive, 'cover.xhtml', _cover_page(labels.cover, book.language, name, width, height))
365
+ _element(manifest, 'item', id='cover-page', href='cover.xhtml', **{'media-type': 'application/xhtml+xml'})
366
+ _element(spine, 'itemref', idref='cover-page', linear='no')
367
+ _element(guide, 'reference', type='cover', title=labels.cover, href='cover.xhtml')
368
+
369
+ ncx = ET.Element('ncx', {'xmlns': NCX, 'version': '2005-1', f'{{{XML}}}lang': book.language})
370
+ head = _element(ncx, 'head')
371
+ for name, content in (
372
+ ('dtb:uid', book.unique_id),
373
+ ('dtb:generator', f'EbookFlux {version("ebookflux")}'),
374
+ ('dtb:depth', '1'),
375
+ ('dtb:totalPageCount', '0'),
376
+ ('dtb:maxPageNumber', '0'),
377
+ ):
378
+ _element(head, 'meta', name=name, content=content)
379
+ _element(_element(ncx, 'docTitle'), 'text', book.name)
380
+ navigation = _element(ncx, 'navMap')
381
+
382
+ width = len(str(len(book.chapters)))
383
+ pages: list[tuple[str, tuple[str, ...], list[str], str]] = [('title-page', (book.name,), book.blurb, 'h1')]
384
+ pages.extend(
385
+ (f'chapter-{index:0{width}d}', chapter.title, chapter.paragraphs, 'h2')
386
+ for index, chapter in enumerate(book.chapters, 1)
387
+ )
388
+ for order, (page_id, title, paragraphs, heading) in enumerate(pages, 1):
389
+ name = 'titlepage.xhtml' if page_id == 'title-page' else f'{page_id}.xhtml'
390
+ _write_entry(archive, name, _page(title, heading, paragraphs, book.language, heading_style=heading_style))
391
+ _element(manifest, 'item', id=page_id, href=name, **{'media-type': 'application/xhtml+xml'})
392
+ _element(spine, 'itemref', idref=page_id)
393
+ if page_id == 'title-page':
394
+ _element(guide, 'reference', type='title-page', title=labels.title_page, href=name)
395
+ else:
396
+ if order == 2:
397
+ _element(guide, 'reference', type='text', title=labels.text, href=name)
398
+ point = _element(navigation, 'navPoint', id=page_id, playOrder=str(order - 1))
399
+ _element(_element(point, 'navLabel'), 'text', ' '.join(title))
400
+ _element(point, 'content', src=name)
401
+
402
+ _write_entry(archive, 'toc.ncx', _xml(ncx))
403
+ _write_entry(archive, 'content.opf', _xml(package))
404
+
405
+
406
+ def render_epub(
407
+ book: Book,
408
+ *,
409
+ indent: bool = False,
410
+ cover_page: bool = True,
411
+ heading_style: HeadingStyle = HeadingStyle.DEFAULT,
412
+ ) -> bytes:
413
+ """Return EPUB 2 bytes; indent=True sets a 2em first-line paragraph indent."""
414
+ output = BytesIO()
415
+ with ZipFile(output, 'w', compression=ZIP_DEFLATED) as archive:
416
+ _write_archive(book, archive, indent=indent, cover_page=cover_page, heading_style=heading_style)
417
+ return output.getvalue()
418
+
419
+
420
+ def write_epub(
421
+ book: Book,
422
+ path: str | Path,
423
+ *,
424
+ indent: bool = False,
425
+ cover_page: bool = True,
426
+ heading_style: HeadingStyle = HeadingStyle.DEFAULT,
427
+ ) -> Path:
428
+ """Write an EPUB atomically and return its path; the parent directory must exist."""
429
+ destination = Path(path)
430
+ temporary: Path | None = None
431
+ try:
432
+ with NamedTemporaryFile(
433
+ dir=destination.parent, prefix=f'.{destination.name}.', suffix='.tmp', delete=False
434
+ ) as file:
435
+ temporary = Path(file.name)
436
+ with ZipFile(file, 'w', compression=ZIP_DEFLATED) as archive:
437
+ _write_archive(book, archive, indent=indent, cover_page=cover_page, heading_style=heading_style)
438
+ temporary.replace(destination)
439
+ finally:
440
+ if temporary is not None:
441
+ temporary.unlink(missing_ok=True)
442
+ return destination
@@ -0,0 +1,29 @@
1
+ """Format-independent book models."""
2
+
3
+ from dataclasses import dataclass, field
4
+ from pathlib import Path
5
+
6
+
7
+ @dataclass(slots=True, kw_only=True)
8
+ class Chapter:
9
+ """Plain-text paragraphs with an ordered tuple of title lines."""
10
+
11
+ title: tuple[str, ...]
12
+ paragraphs: list[str]
13
+
14
+
15
+ @dataclass(slots=True, kw_only=True)
16
+ class Book:
17
+ """Book metadata and ordered chapters."""
18
+
19
+ name: str
20
+ unique_id: str
21
+ language: str
22
+ chapters: list[Chapter]
23
+
24
+ authors: list[str] = field(default_factory=list)
25
+ producers: list[str] = field(default_factory=list)
26
+ publisher: str | None = None
27
+ links: list[str] = field(default_factory=list)
28
+ blurb: list[str] = field(default_factory=list)
29
+ cover: Path | None = None
File without changes
@@ -0,0 +1,77 @@
1
+ """UTF-8 plain-text export."""
2
+
3
+ from collections.abc import Iterator
4
+ from pathlib import Path
5
+ from tempfile import NamedTemporaryFile
6
+
7
+ from ._labels import Labels
8
+ from .models import Book
9
+
10
+
11
+ def _chunks(book: Book, *, indent: bool, compact: bool, with_producers: bool, with_publisher: bool) -> Iterator[bytes]:
12
+ prefix = '\u3000\u3000' if indent else ''
13
+ paragraph_separator = '\n' if compact else '\n\n'
14
+ chapter_separator = '\n\n' if compact else '\n\n\n'
15
+ labels = Labels.for_language(book.language)
16
+
17
+ def encode(text: str) -> bytes:
18
+ return text.replace('\r\n', '\n').replace('\r', '\n').encode('utf-8')
19
+
20
+ header = [book.name]
21
+ if book.authors:
22
+ header.append(labels.author + labels.name_separator.join(book.authors))
23
+ if with_producers and book.producers:
24
+ header.append(labels.producer + labels.name_separator.join(book.producers))
25
+ if with_publisher and book.publisher is not None:
26
+ header.append(labels.publisher + book.publisher)
27
+ yield encode('\n'.join(header))
28
+ for index, paragraph in enumerate(book.blurb):
29
+ yield encode(('\n\n' if index == 0 else paragraph_separator) + prefix + paragraph)
30
+ for chapter in book.chapters:
31
+ yield encode(chapter_separator + ' '.join(chapter.title))
32
+ for index, paragraph in enumerate(chapter.paragraphs):
33
+ yield encode(('\n\n' if index == 0 else paragraph_separator) + prefix + paragraph)
34
+ yield b'\n'
35
+
36
+
37
+ def render_txt(
38
+ book: Book,
39
+ *,
40
+ indent: bool = False,
41
+ compact: bool = False,
42
+ with_producers: bool = True,
43
+ with_publisher: bool = True,
44
+ ) -> bytes:
45
+ """Return UTF-8 bytes; indent=True prefixes paragraphs with two full-width spaces."""
46
+ return b''.join(
47
+ _chunks(book, indent=indent, compact=compact, with_producers=with_producers, with_publisher=with_publisher)
48
+ )
49
+
50
+
51
+ def write_txt(
52
+ book: Book,
53
+ path: str | Path,
54
+ *,
55
+ indent: bool = False,
56
+ compact: bool = False,
57
+ with_producers: bool = True,
58
+ with_publisher: bool = True,
59
+ ) -> Path:
60
+ """Write TXT atomically and return its path; the parent directory must exist."""
61
+ destination = Path(path)
62
+ temporary: Path | None = None
63
+ try:
64
+ with NamedTemporaryFile(
65
+ dir=destination.parent, prefix=f'.{destination.name}.', suffix='.tmp', delete=False
66
+ ) as file:
67
+ temporary = Path(file.name)
68
+ file.writelines(
69
+ _chunks(
70
+ book, indent=indent, compact=compact, with_producers=with_producers, with_publisher=with_publisher
71
+ )
72
+ )
73
+ temporary.replace(destination)
74
+ finally:
75
+ if temporary is not None:
76
+ temporary.unlink(missing_ok=True)
77
+ return destination
@@ -0,0 +1,78 @@
1
+ version = 1
2
+ revision = 5
3
+ requires-python = ">=3.12"
4
+
5
+ [[package]]
6
+ name = "ebookflux"
7
+ version = "0.1.0"
8
+ source = { editable = "." }
9
+
10
+ [package.dev-dependencies]
11
+ dev = [
12
+ { name = "pyright" },
13
+ { name = "ruff" },
14
+ ]
15
+
16
+ [package.metadata]
17
+
18
+ [package.metadata.requires-dev]
19
+ dev = [
20
+ { name = "pyright", specifier = ">=1.1.414" },
21
+ { name = "ruff", specifier = ">=0.17.5" },
22
+ ]
23
+
24
+ [[package]]
25
+ name = "nodeenv"
26
+ version = "1.12.0"
27
+ source = { registry = "https://pypi.org/simple" }
28
+ sdist = { url = "https://files.pythonhosted.org/packages/e6/99/d27cfc9518f49e4cbc25c683ec7cf8704a9d31311341c291c0e78ddf791b/nodeenv-1.12.0.tar.gz", hash = "sha256:4ea7f88339310afebc3253f2c7a91b94bacf97d73a36a5c108962abdfaca501e", size = 131292, upload-time = "2026-10-31T19:03:18.847Z" }
29
+ wheels = [
30
+ { url = "https://files.pythonhosted.org/packages/2d/6a/8a9ac7d5e2f7cf53c459bfef90ebc17a2f8cd54b665af96799d4c534840e/nodeenv-1.12.0-py3-none-any.whl", hash = "sha256:80644d65c10cc2be12e3e4b54b3367ff288c7ad24ae75c2dcc65454fc7449d4d", size = 39442, upload-time = "2026-10-31T19:03:17.427Z" },
31
+ ]
32
+
33
+ [[package]]
34
+ name = "pyright"
35
+ version = "1.1.414"
36
+ source = { registry = "https://pypi.org/simple" }
37
+ dependencies = [
38
+ { name = "nodeenv" },
39
+ { name = "typing-extensions" },
40
+ ]
41
+ sdist = { url = "https://files.pythonhosted.org/packages/e1/1b/244c7b710031ada80f27e579ec20d28a2285dfc318fed0339866b1047f12/pyright-1.1.414.tar.gz", hash = "sha256:523c0a97c60da6333234955c277730c9cf4f5bd6d5399e7b7d2b0fc5d3599524", size = 4154638, upload-time = "2026-09-10T12:26:53.181Z" }
42
+ wheels = [
43
+ { url = "https://files.pythonhosted.org/packages/d7/ba/18b6e682ead424ad24bcc134339ae5d1b931cd9ae260540592a058a91279/pyright-1.1.414-py3-none-any.whl", hash = "sha256:2a6b4b3298c9eec174c5ed83bd338de6eee82df2992f3e1930e6199d381be36f", size = 6225049, upload-time = "2026-09-10T12:26:51.427Z" },
44
+ ]
45
+
46
+ [[package]]
47
+ name = "ruff"
48
+ version = "0.17.5"
49
+ source = { registry = "https://pypi.org/simple" }
50
+ sdist = { url = "https://files.pythonhosted.org/packages/86/cc/7b71512eb8b49926efb887cc66c74dd993642943c29eba51a877f6b85692/ruff-0.17.5.tar.gz", hash = "sha256:625e57d80cd43352d12ea81690f3eac46cddc8c0f35026d137fb0f157f94592e", size = 5368382, upload-time = "2026-11-12T17:54:55.04Z" }
51
+ wheels = [
52
+ { url = "https://files.pythonhosted.org/packages/d4/f2/61df414cb4338617290a9023ad09486e207fb9a6d09357a7be34f2e369a4/ruff-0.17.5-py3-none-linux_armv6l.whl", hash = "sha256:d511dd302982e46a285528942fa6557d57730edc4bdb9def95e86a2603d77396", size = 10231309, upload-time = "2026-11-12T17:54:09.314Z" },
53
+ { url = "https://files.pythonhosted.org/packages/d1/72/8ed970f3361f7c8d3f8e1b3b1af27cf086bc4b3a6b62ec20e21a1aaaaff5/ruff-0.17.5-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:b72fbc232e328bdbb9cdddf4f1aedcd61bd1aa64d75fc012114b4add0bd7f26b", size = 10250018, upload-time = "2026-11-12T17:54:11.983Z" },
54
+ { url = "https://files.pythonhosted.org/packages/dc/4b/8b10f6c9d0a18413301ae8dd2af9d180a81bb738b1b731d944a37404c523/ruff-0.17.5-py3-none-macosx_11_0_arm64.whl", hash = "sha256:6f0db748508f04a04e3fbebcc636a5c8b3bd76274f8ed28f497c44d75c2ea2d7", size = 9504737, upload-time = "2026-11-12T17:54:14.567Z" },
55
+ { url = "https://files.pythonhosted.org/packages/b7/ea/1b3afa3943239dede7a0755ea139bdb51879f0f3f96f92894081d5c7d2e5/ruff-0.17.5-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6f6a7b138edf9cc402ca736a59d9525e6d766e5395760b72e7e146e6251ac963", size = 10168006, upload-time = "2026-11-12T17:54:17.195Z" },
56
+ { url = "https://files.pythonhosted.org/packages/31/08/ee641daa45f83792f91274b65796cb011f1065f588911bfa3909ad9e31e7/ruff-0.17.5-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:e52622ecf3a0df9d03e796fe3eed4aa085adda65520db7e0619cbd2192a97342", size = 10043751, upload-time = "2026-11-12T17:54:19.815Z" },
57
+ { url = "https://files.pythonhosted.org/packages/f8/cf/1c59fdb42d0b5671ad5b160636fab4005ee28db72cb06aef6e3f3c04f377/ruff-0.17.5-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:54c0f67d1be11b55d12c184a819fc229f5eee3ef45c16c4fcad41258e83b4882", size = 10690562, upload-time = "2026-11-12T17:54:22.789Z" },
58
+ { url = "https://files.pythonhosted.org/packages/49/c5/578074716173fb0c1591e9648a9f85c469888d9530cb35b89b757dc1208b/ruff-0.17.5-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:dd0dfe7c6fe5a447fce467c58e69893be1d9a7e4378f5b9906432da33d94a97f", size = 11338465, upload-time = "2026-11-12T17:54:25.523Z" },
59
+ { url = "https://files.pythonhosted.org/packages/aa/b9/d6428bcf5ed88f4dc1d6e3417ee350236ed36e7a35f9477b727c00e437bf/ruff-0.17.5-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:ec4ecf40fb4d6e1265b009dbe551727920926fc0f769070c452d6d84b422a74d", size = 10895501, upload-time = "2026-11-12T17:54:28.441Z" },
60
+ { url = "https://files.pythonhosted.org/packages/f2/8a/1e29c0c3785ae7e5cd0d54ee8717a08867ef71545796340be4c653c57e24/ruff-0.17.5-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:40ca8afaac309b41a5b2e09e4e7beb1f824826b93c25697c4d74f573324fba4e", size = 10613231, upload-time = "2026-11-12T17:54:30.862Z" },
61
+ { url = "https://files.pythonhosted.org/packages/32/b6/88944350c14bb90651014d678ad554e233ae2a79c14ad52101845f93d15b/ruff-0.17.5-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:8e85601bd6d9b6c3e3b95c0e0dccdbac1d23c6bcef006d187fbcddaf8225a5df", size = 10562789, upload-time = "2026-11-12T17:54:33.869Z" },
62
+ { url = "https://files.pythonhosted.org/packages/6f/fd/2792e955b0bf54295cdcdddc4bb3f380c0790d7e60e789f528a9e6e48a31/ruff-0.17.5-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:f93d2b7d449ed9545304f6923699ca20d13c675b69f258481709a08ae61076db", size = 10069824, upload-time = "2026-11-12T17:54:36.663Z" },
63
+ { url = "https://files.pythonhosted.org/packages/07/9c/d7cad341b4c19237948a6dd1fcea1c9c39c9d08b70f22f0e157d1236ebd6/ruff-0.17.5-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:0e5c125c5b31dc8efc948d41357496a4c4a312977565ccba740030efdff83580", size = 10038961, upload-time = "2026-11-12T17:54:39.452Z" },
64
+ { url = "https://files.pythonhosted.org/packages/cc/a1/9cd0d4c371ddc70267d3bd557e718e2bdfb94c25e49d25605edfabb764bd/ruff-0.17.5-py3-none-musllinux_1_2_i686.whl", hash = "sha256:50dfc3c6b3ebd0a932f11dfd579bd42234b0b7137e68940eb6abdbfdb9d69697", size = 10385012, upload-time = "2026-11-12T17:54:41.808Z" },
65
+ { url = "https://files.pythonhosted.org/packages/8f/a9/35f078ce98d4df318328ea5270382b5b65e680f7953b3db54f8e009c420c/ruff-0.17.5-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:86bd1f3b83c25f9b8055c6e796f0685b39d3127ce947322098c3108cf82fd586", size = 10793672, upload-time = "2026-11-12T17:54:44.342Z" },
66
+ { url = "https://files.pythonhosted.org/packages/2c/a5/2e136dede2a88aaaf54498bbbdc81bc810f788ef6ef01efb97037d73cd1d/ruff-0.17.5-py3-none-win32.whl", hash = "sha256:e1546609b2ad73f1d6c5c076881b788672b7b3cc3283981182cbdbb6524ed88a", size = 9929908, upload-time = "2026-11-12T17:54:47.067Z" },
67
+ { url = "https://files.pythonhosted.org/packages/ec/8c/e4db9ae1e0ee233c04df007ab6d0d42f799ae9abd95d352b6092ee7bc4bf/ruff-0.17.5-py3-none-win_amd64.whl", hash = "sha256:aa415d57c244299279901d776607fee3df7831c2a7435433fbfacde8632c6550", size = 10275454, upload-time = "2026-11-12T17:54:49.401Z" },
68
+ { url = "https://files.pythonhosted.org/packages/e6/65/a1648bc1550e7683bf7bf1e2ce2485c9f8535cbca6cca9ec7b73cc12fb8e/ruff-0.17.5-py3-none-win_arm64.whl", hash = "sha256:64a6fd668a336df959c522991de33e9e3c8be463afc0c9ac8f029f9d19ef756e", size = 9849020, upload-time = "2026-11-12T17:54:52.055Z" },
69
+ ]
70
+
71
+ [[package]]
72
+ name = "typing-extensions"
73
+ version = "4.16.0"
74
+ source = { registry = "https://pypi.org/simple" }
75
+ sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3306cebfbda2c520f545d36b5be2c7255cc528bb45d6/typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5", size = 113555, upload-time = "2026-07-02T08:40:05.92Z" }
76
+ wheels = [
77
+ { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" },
78
+ ]