ndlocr-lite 1.4.0.dev0__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 (43) hide show
  1. cli.py +15 -0
  2. config/NDLmoji.yaml +4 -0
  3. config/__init__.py +0 -0
  4. config/ndl.yaml +21 -0
  5. deim.py +169 -0
  6. model/__init__.py +0 -0
  7. model_download.py +87 -0
  8. ndl_parser.py +1083 -0
  9. ndlocr_lite-1.4.0.dev0.dist-info/METADATA +182 -0
  10. ndlocr_lite-1.4.0.dev0.dist-info/RECORD +43 -0
  11. ndlocr_lite-1.4.0.dev0.dist-info/WHEEL +5 -0
  12. ndlocr_lite-1.4.0.dev0.dist-info/entry_points.txt +2 -0
  13. ndlocr_lite-1.4.0.dev0.dist-info/licenses/LICENCE +395 -0
  14. ndlocr_lite-1.4.0.dev0.dist-info/licenses/LICENCE_DEPENDENCEIES +1891 -0
  15. ndlocr_lite-1.4.0.dev0.dist-info/top_level.txt +16 -0
  16. ndlocr_lite_gui/__init__.py +12 -0
  17. ndlocr_lite_gui/assets/icon.png +0 -0
  18. ndlocr_lite_gui/gui_config.py +21 -0
  19. ndlocr_lite_gui/main.py +2105 -0
  20. ocr.py +1425 -0
  21. optional_features/__init__.py +52 -0
  22. parseq.py +74 -0
  23. pdf_output_utils.py +71 -0
  24. reading_order/__init__.py +0 -0
  25. reading_order/order/__init__.py +0 -0
  26. reading_order/order/parse_xml.py +143 -0
  27. reading_order/order/reorder.py +211 -0
  28. reading_order/order/smooth_order.py +110 -0
  29. reading_order/order/warichu_block.py +178 -0
  30. reading_order/order/wrap_dataset.py +13 -0
  31. reading_order/utils/__init__.py +0 -0
  32. reading_order/utils/file.py +21 -0
  33. reading_order/utils/logger.py +29 -0
  34. reading_order/utils/time.py +63 -0
  35. reading_order/utils/xml.py +97 -0
  36. reading_order/xy_cut/__init__.py +0 -0
  37. reading_order/xy_cut/block_xy_cut.py +366 -0
  38. reading_order/xy_cut/eval.py +55 -0
  39. tcy_wrapper.py +202 -0
  40. tools/ndlkoten2tei.py +115 -0
  41. uicomponent/localelabel.py +118 -0
  42. uicomponent/textdaisy.py +1093 -0
  43. version.py +3 -0
@@ -0,0 +1,1093 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from datetime import date
5
+ from pathlib import Path
6
+ from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple
7
+ from urllib.parse import quote
8
+ from uuid import uuid4
9
+ import re
10
+ import shutil
11
+ import xml.etree.ElementTree as ET
12
+ from xml.sax.saxutils import escape
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class TextDaisyExportResult:
17
+ """生成したテキストDAISYファイル一式の保存先。"""
18
+
19
+ directory: str
20
+ zip_path: Optional[str]
21
+ page_count: int
22
+
23
+
24
+ class TextDaisyExporter:
25
+ """NDLOCR-Lite の OCR 結果から DAISY 3 textNCX ファイルセットを生成する。
26
+
27
+ 変換方針:
28
+ - NDLOCR-Lite XML の <TEXTBLOCK> 1 件を DTBook の <p> 1 件へ対応させる。
29
+ - <LINE TYPE="タイトル本文"> が出た位置で新しいセクションを開始する。
30
+ - セクションごとに ptk00001.xml / ptk00001.smil、ptk00002.xml / ptk00002.smil ... を出力する。
31
+ - 各セクション内の <sent id="t0000001"> と <par id="phr00001"> は、そのファイルごとに 1 から採番する。
32
+ - 各 OCR 行は <sent> として出力し、対応する SMIL の <par id="phrxxxxx"> と相互参照する。
33
+ - NDLOCR-Lite XML の <BLOCK TYPE="図版"> は DTBook の <imggroup>/<img> と、同期用説明 <p><sent> として出力する。
34
+
35
+ pages は main.py の alljsonobjlist と同じ形式を基本としつつ、XML 構造を使う場合は
36
+ 各 page dict に次のいずれかのキーで NDLOCR-Lite XML 文字列または XML パスを渡す。
37
+ - "xml", "xmlstr", "ocr_xml", "ndl_xml", "page_xml"
38
+ - "xml_path", "ocr_xml_path", "ndl_xml_path"
39
+
40
+ XML が渡されない場合は従来どおり JSON の OCR 行を 1 行 1 段落としてフォールバックする。
41
+ """
42
+
43
+ # 代表ファイル名。実際の本文/SMILはセクションごとに ptk000NN.xml / ptk000NN.smil を生成する。
44
+ DTBOOK_FILE = "ptk00001.xml"
45
+ NCX_FILE = "toc.ncx"
46
+ SMIL_FILE = "ptk00001.smil"
47
+ OPF_FILE = "book.opf"
48
+
49
+ TITLE_LINE_TYPE = "タイトル本文"
50
+ FIGURE_BLOCK_TYPE = "図版"
51
+ FIGURE_PLACEHOLDER_FILE = "images/figure_placeholder.svg"
52
+
53
+ def __init__(
54
+ self,
55
+ *,
56
+ title: str,
57
+ language: str = "ja",
58
+ producer: str = "NDLOCR-Lite",
59
+ identifier: Optional[str] = "urn:uuid:ad57085e-ba0e-4145-a8e7-ffe6d5d13a58",
60
+ generator: str = "PLEXTALK DAISY Producer",
61
+ ) -> None:
62
+ self.title = title.strip() or "NDLOCR-Lite OCR Result"
63
+ self.language = language or "ja"
64
+ self.producer = producer
65
+ self.generator = generator
66
+ self.identifier = identifier or f"urn:uuid:{uuid4()}"
67
+ self.produced_date = date.today().isoformat()
68
+ self.asset_stem = self._safe_identifier_for_asset_name(self.identifier)
69
+ self.CSS_FILE = f"{self.asset_stem}.css"
70
+ self.XSL_FILE = f"{self.asset_stem}.xsl"
71
+
72
+ def export(
73
+ self,
74
+ pages: List[Dict[str, Any]],
75
+ output_dir: str,
76
+ *,
77
+ folder_name: Optional[str] = None,
78
+ make_zip: bool = True,
79
+ ) -> TextDaisyExportResult:
80
+ """DAISY 3 text-only のファイルセットを出力する。"""
81
+ if not pages:
82
+ raise ValueError("Text DAISY export requires at least one OCR result page.")
83
+
84
+ normalized_pages = self._normalize_pages(pages)
85
+ sections = self._build_sections(normalized_pages)
86
+ self._ensure_sections_start_with_heading(sections)
87
+ self._ensure_sections_have_body(sections)
88
+ phrases = self._assign_phrase_ids(sections, normalized_pages)
89
+ safe_folder = self._safe_filename(folder_name or f"{self.title}_textdaisy")
90
+ book_dir = Path(output_dir) / safe_folder
91
+
92
+ if book_dir.exists():
93
+ shutil.rmtree(book_dir)
94
+
95
+ book_dir.mkdir(parents=True, exist_ok=True)
96
+
97
+ for section in sections:
98
+ (book_dir / section["dtbook_file"]).write_text(
99
+ self._build_dtbook(section), encoding="utf-8"
100
+ )
101
+ (book_dir / section["smil_file"]).write_text(
102
+ self._build_smil(section), encoding="utf-8"
103
+ )
104
+
105
+ if self._sections_have_figures(sections):
106
+ figure_path = book_dir / self.FIGURE_PLACEHOLDER_FILE
107
+ figure_path.parent.mkdir(parents=True, exist_ok=True)
108
+ figure_path.write_text(self._build_figure_placeholder_svg(), encoding="utf-8")
109
+
110
+ (book_dir / self.NCX_FILE).write_text(
111
+ self._build_ncx(normalized_pages, sections, phrases), encoding="utf-8"
112
+ )
113
+ (book_dir / self.OPF_FILE).write_text(
114
+ self._build_opf(sections), encoding="utf-8"
115
+ )
116
+ (book_dir / self.CSS_FILE).write_text(
117
+ self._build_css(), encoding="utf-8"
118
+ )
119
+ (book_dir / self.XSL_FILE).write_text(
120
+ self._build_xsl(), encoding="utf-8"
121
+ )
122
+
123
+ zip_path: Optional[str] = None
124
+ if make_zip:
125
+ archive_base = str(book_dir)
126
+ zip_path = shutil.make_archive(archive_base, "zip", root_dir=book_dir)
127
+
128
+ return TextDaisyExportResult(
129
+ directory=str(book_dir),
130
+ zip_path=zip_path,
131
+ page_count=len(normalized_pages),
132
+ )
133
+
134
+ def _normalize_pages(self, pages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
135
+ normalized: List[Dict[str, Any]] = []
136
+
137
+ for fallback_page_index, page in enumerate(pages, start=1):
138
+ xml_source = self._get_xml_source(page)
139
+ if xml_source:
140
+ xml_pages = self._extract_pages_from_ndl_xml(xml_source)
141
+ if xml_pages:
142
+ normalized.extend(xml_pages)
143
+ continue
144
+
145
+ normalized.append(self._normalize_page_from_json(page, fallback_page_index))
146
+
147
+ # XML を複数ページ含む形で受け取った場合にも、全体として 1 始まりのページ番号へ振り直す。
148
+ for page_no, page in enumerate(normalized, start=1):
149
+ page["page_no"] = page_no
150
+ for block in page.get("blocks", []):
151
+ block["page_no"] = page_no
152
+
153
+ return normalized
154
+
155
+ def _normalize_page_from_json(
156
+ self,
157
+ page: Dict[str, Any],
158
+ page_index: int,
159
+ ) -> Dict[str, Any]:
160
+ imginfo = page.get("imginfo", {}) or {}
161
+ label = imginfo.get("img_name") or f"page-{page_index}"
162
+ line_objects = self._extract_json_line_objects(page)
163
+
164
+ if not line_objects:
165
+ line_objects = [{"text": " ", "line_type": "本文"}]
166
+
167
+ blocks = self._blocks_from_json_lines(line_objects)
168
+ for block in blocks:
169
+ block["page_no"] = page_index
170
+
171
+ return {
172
+ "page_no": page_index,
173
+ "label": label,
174
+ "blocks": blocks,
175
+ }
176
+
177
+ def _extract_json_line_objects(self, page: Dict[str, Any]) -> List[Dict[str, Any]]:
178
+ contents = page.get("contents") or []
179
+ if not contents:
180
+ return []
181
+
182
+ line_objects: Iterable[Dict[str, Any]] = contents[0] or []
183
+ sorted_lines = sorted(
184
+ line_objects,
185
+ key=lambda obj: int(obj.get("id", 0))
186
+ if str(obj.get("id", "0")).isdigit()
187
+ else 0,
188
+ )
189
+
190
+ lines: List[Dict[str, Any]] = []
191
+ for obj in sorted_lines:
192
+ text = str(obj.get("text", "")).strip()
193
+ if not text:
194
+ continue
195
+ lines.append(
196
+ {
197
+ "text": text,
198
+ "line_type": self._get_json_line_type(obj),
199
+ "block_key": self._get_json_block_key(obj),
200
+ }
201
+ )
202
+
203
+ return lines
204
+
205
+ def _get_json_line_type(self, obj: Dict[str, Any]) -> str:
206
+ for key in ("line_type", "lineType", "type", "TYPE", "ndl_type", "category"):
207
+ value = obj.get(key)
208
+ if value:
209
+ return str(value)
210
+ return "本文"
211
+
212
+ def _get_json_block_key(self, obj: Dict[str, Any]) -> Optional[str]:
213
+ for key in (
214
+ "textblock_id",
215
+ "textBlockId",
216
+ "block_id",
217
+ "blockId",
218
+ "block_index",
219
+ "blockIndex",
220
+ "TEXTBLOCK_ID",
221
+ ):
222
+ value = obj.get(key)
223
+ if value is not None:
224
+ return str(value)
225
+ return None
226
+
227
+ def _blocks_from_json_lines(
228
+ self,
229
+ line_objects: Sequence[Dict[str, Any]],
230
+ ) -> List[Dict[str, Any]]:
231
+ # block_key が入っている場合は同じ TEXTBLOCK に属する行をまとめる。
232
+ # 入っていない既存 JSON では構造が分からないため、1 行 1 ブロックへフォールバックする。
233
+ blocks: List[Dict[str, Any]] = []
234
+ current_key: Optional[str] = None
235
+ current_lines: List[Dict[str, Any]] = []
236
+
237
+ def flush() -> None:
238
+ nonlocal current_lines
239
+ if current_lines:
240
+ blocks.extend(self._split_lines_to_dtbook_blocks(current_lines))
241
+ current_lines = []
242
+
243
+ for line in line_objects:
244
+ block_key = line.get("block_key")
245
+ if block_key is None:
246
+ flush()
247
+ blocks.extend(self._split_lines_to_dtbook_blocks([line]))
248
+ current_key = None
249
+ continue
250
+
251
+ if current_key is None:
252
+ current_key = block_key
253
+ elif current_key != block_key:
254
+ flush()
255
+ current_key = block_key
256
+
257
+ current_lines.append(line)
258
+
259
+ flush()
260
+ return blocks or [self._make_dtbook_block("p", [{"text": " ", "line_type": "本文"}])]
261
+
262
+ def _get_xml_source(self, page: Dict[str, Any]) -> Optional[str]:
263
+ for key in ("xml", "xmlstr", "ocr_xml", "ndl_xml", "page_xml"):
264
+ value = page.get(key)
265
+ if value:
266
+ return str(value)
267
+
268
+ for key in ("xml_path", "ocr_xml_path", "ndl_xml_path"):
269
+ value = page.get(key)
270
+ if not value:
271
+ continue
272
+ path = Path(str(value))
273
+ if path.exists():
274
+ return path.read_text(encoding="utf-8")
275
+
276
+ return None
277
+
278
+ def _extract_pages_from_ndl_xml(self, xml_source: str) -> List[Dict[str, Any]]:
279
+ try:
280
+ root = ET.fromstring(xml_source)
281
+ except ET.ParseError:
282
+ return []
283
+
284
+ root_tag = self._local_name(root.tag)
285
+ if root_tag == "PAGE":
286
+ page_elements = [root]
287
+ else:
288
+ page_elements = [elem for elem in root.iter() if self._local_name(elem.tag) == "PAGE"]
289
+
290
+ normalized_pages: List[Dict[str, Any]] = []
291
+ for index, page_elem in enumerate(page_elements, start=1):
292
+ label = page_elem.attrib.get("IMAGENAME") or f"page-{index}"
293
+ blocks = self._extract_dtbook_blocks_from_page_xml(page_elem)
294
+ if not blocks:
295
+ blocks = [self._make_dtbook_block("p", [{"text": " ", "line_type": "本文"}])]
296
+ for block in blocks:
297
+ block["page_no"] = index
298
+ normalized_pages.append(
299
+ {
300
+ "page_no": index,
301
+ "label": label,
302
+ "blocks": blocks,
303
+ }
304
+ )
305
+
306
+ return normalized_pages
307
+
308
+ def _extract_dtbook_blocks_from_page_xml(self, page_elem: ET.Element) -> List[Dict[str, Any]]:
309
+ blocks: List[Dict[str, Any]] = []
310
+
311
+ for elem in list(page_elem):
312
+ tag = self._local_name(elem.tag)
313
+
314
+ if tag == "TEXTBLOCK":
315
+ blocks.extend(self._blocks_from_textblock_elem(elem))
316
+ elif tag == "LINE":
317
+ blocks.extend(self._split_lines_to_dtbook_blocks([self._line_from_xml(elem)]))
318
+ elif tag == "BLOCK":
319
+ blocks.extend(self._blocks_from_block_elem(elem))
320
+
321
+ return blocks
322
+
323
+ def _blocks_from_block_elem(self, block_elem: ET.Element) -> List[Dict[str, Any]]:
324
+ blocks: List[Dict[str, Any]] = []
325
+ pending_lines: List[Dict[str, Any]] = []
326
+ block_type = str(block_elem.attrib.get("TYPE", "")).strip()
327
+
328
+ def flush_pending_lines() -> None:
329
+ nonlocal pending_lines
330
+ if pending_lines:
331
+ blocks.extend(self._split_lines_to_dtbook_blocks(pending_lines))
332
+ pending_lines = []
333
+
334
+ if self._is_figure_block_type(block_type):
335
+ # 図版ブロック自体を DTBook の画像要素として残す。
336
+ # SMIL で同期できるよう、後続の説明 p/sent も同じ内部ブロックから生成する。
337
+ blocks.append(self._make_figure_block(block_elem))
338
+
339
+ for elem in list(block_elem):
340
+ tag = self._local_name(elem.tag)
341
+ if tag == "TEXTBLOCK":
342
+ flush_pending_lines()
343
+ blocks.extend(self._blocks_from_textblock_elem(elem))
344
+ elif tag == "LINE":
345
+ pending_lines.append(self._line_from_xml(elem))
346
+ elif tag == "BLOCK":
347
+ flush_pending_lines()
348
+ blocks.extend(self._blocks_from_block_elem(elem))
349
+
350
+ flush_pending_lines()
351
+ return blocks
352
+
353
+ def _blocks_from_textblock_elem(self, textblock_elem: ET.Element) -> List[Dict[str, Any]]:
354
+ lines: List[Dict[str, Any]] = []
355
+ for elem in list(textblock_elem):
356
+ if self._local_name(elem.tag) != "LINE":
357
+ continue
358
+ line = self._line_from_xml(elem)
359
+ if line["text"]:
360
+ lines.append(line)
361
+
362
+ return self._split_lines_to_dtbook_blocks(lines)
363
+
364
+ def _line_from_xml(self, line_elem: ET.Element) -> Dict[str, Any]:
365
+ text = (line_elem.attrib.get("STRING") or line_elem.attrib.get("TEXT") or "").strip()
366
+ if not text:
367
+ text = "".join(
368
+ char.attrib.get("MOJI", "")
369
+ for char in line_elem.iter()
370
+ if self._local_name(char.tag) == "CHAR"
371
+ ).strip()
372
+
373
+ return {
374
+ "text": text,
375
+ "line_type": line_elem.attrib.get("TYPE", "本文"),
376
+ }
377
+
378
+ def _split_lines_to_dtbook_blocks(self, lines: Sequence[Dict[str, Any]]) -> List[Dict[str, Any]]:
379
+ blocks: List[Dict[str, Any]] = []
380
+ current_tag: Optional[str] = None
381
+ current_lines: List[Dict[str, Any]] = []
382
+
383
+ def tag_for_line(line: Dict[str, Any]) -> str:
384
+ return "h1" if self._is_title_line(line) else "p"
385
+
386
+ def flush() -> None:
387
+ nonlocal current_lines, current_tag
388
+ if current_lines and current_tag:
389
+ blocks.append(self._make_dtbook_block(current_tag, current_lines))
390
+ current_tag = None
391
+ current_lines = []
392
+
393
+ for line in lines:
394
+ text = str(line.get("text", "")).strip()
395
+ if not text:
396
+ continue
397
+
398
+ tag = tag_for_line(line)
399
+ if current_tag is None:
400
+ current_tag = tag
401
+ elif current_tag != tag:
402
+ # TEXTBLOCK の途中に「タイトル本文」がある場合も、そこで段落/見出しを切る。
403
+ flush()
404
+ current_tag = tag
405
+
406
+ current_lines.append({"text": text, "line_type": line.get("line_type", "本文")})
407
+
408
+ flush()
409
+ return blocks
410
+
411
+ def _make_dtbook_block(
412
+ self,
413
+ tag: str,
414
+ lines: Sequence[Dict[str, Any]],
415
+ *,
416
+ generated: bool = False,
417
+ ) -> Dict[str, Any]:
418
+ return {
419
+ "tag": tag,
420
+ "is_heading": tag.startswith("h"),
421
+ "generated": generated,
422
+ "lines": [dict(line) for line in lines],
423
+ }
424
+
425
+ def _make_generated_body_block(self) -> Dict[str, Any]:
426
+ # DTBook 2005-3 では level1 が h1 だけで終わると不完全になるため、
427
+ # タイトルだけのセクションに最小限の本文要素を補う。
428
+ return self._make_dtbook_block(
429
+ "p",
430
+ [{"text": " ", "line_type": "本文", "generated": True}],
431
+ generated=True,
432
+ )
433
+
434
+ def _make_generated_heading_block(self, text: Optional[str] = None) -> Dict[str, Any]:
435
+ # DTBook 2005-3 の level1 直下には、先頭要素として見出しを置く。
436
+ # 元XMLにタイトル本文が無いセクションでは、書名を補助見出しとして使う。
437
+ heading_text = (text or self.title or " ").strip() or " "
438
+ return self._make_dtbook_block(
439
+ "h1",
440
+ [{"text": heading_text, "line_type": self.TITLE_LINE_TYPE, "generated": True}],
441
+ generated=True,
442
+ )
443
+
444
+ def _is_figure_block_type(self, block_type: str) -> bool:
445
+ normalized = block_type.strip().lower()
446
+ return block_type.strip() == self.FIGURE_BLOCK_TYPE or normalized in {
447
+ "block_fig",
448
+ "figure",
449
+ "fig",
450
+ "image",
451
+ }
452
+
453
+ def _make_figure_block(self, block_elem: ET.Element) -> Dict[str, Any]:
454
+ figure_label = self._figure_label(block_elem)
455
+ return {
456
+ "tag": "imggroup",
457
+ "is_heading": False,
458
+ "is_figure": True,
459
+ "generated": False,
460
+ "figure": {
461
+ "alt": figure_label,
462
+ "src": self.FIGURE_PLACEHOLDER_FILE,
463
+ "source_type": block_elem.attrib.get("TYPE", self.FIGURE_BLOCK_TYPE),
464
+ "x": block_elem.attrib.get("X", ""),
465
+ "y": block_elem.attrib.get("Y", ""),
466
+ "width": block_elem.attrib.get("WIDTH", ""),
467
+ "height": block_elem.attrib.get("HEIGHT", ""),
468
+ "conf": block_elem.attrib.get("CONF", ""),
469
+ },
470
+ # 画像要素そのものは SMIL の text 参照先にできない再生環境があるため、
471
+ # 同期・読み上げ用に説明文を p/sent として続けて出力する。
472
+ "lines": [
473
+ {
474
+ "text": figure_label,
475
+ "line_type": self.FIGURE_BLOCK_TYPE,
476
+ "generated": True,
477
+ }
478
+ ],
479
+ }
480
+
481
+ def _figure_label(self, block_elem: ET.Element) -> str:
482
+ for key in ("ALT", "alt", "TITLE", "title", "LABEL", "label"):
483
+ value = block_elem.attrib.get(key)
484
+ if value and str(value).strip():
485
+ return str(value).strip()
486
+ return self.FIGURE_BLOCK_TYPE
487
+
488
+ def _is_title_line(self, line: Dict[str, Any]) -> bool:
489
+ line_type = str(line.get("line_type", "")).strip()
490
+ return (
491
+ line_type == self.TITLE_LINE_TYPE
492
+ or line_type == "line_title"
493
+ or "タイトル本文" in line_type
494
+ )
495
+
496
+ def _dtbook_filename(self, section_index: int) -> str:
497
+ return f"ptk{section_index:05d}.xml"
498
+
499
+ def _smil_filename(self, section_index: int) -> str:
500
+ return f"ptk{section_index:05d}.smil"
501
+
502
+ def _build_sections(self, pages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
503
+ """タイトル本文でセクションを切り、各セクションを別ファイル単位にする。"""
504
+ sections: List[Dict[str, Any]] = []
505
+ current: Optional[Dict[str, Any]] = None
506
+
507
+ def new_section() -> Dict[str, Any]:
508
+ section_index = len(sections) + 1
509
+ return {
510
+ "index": section_index,
511
+ "dtbook_file": self._dtbook_filename(section_index),
512
+ "smil_file": self._smil_filename(section_index),
513
+ "blocks": [],
514
+ "page_nos": [],
515
+ "phrases": [],
516
+ "heading_blocks": [],
517
+ "first_phrase": None,
518
+ }
519
+
520
+ def append_current() -> None:
521
+ nonlocal current
522
+ if current is not None and current.get("blocks"):
523
+ sections.append(current)
524
+ current = None
525
+
526
+ for page in pages:
527
+ page_no = int(page.get("page_no", len(sections) + 1))
528
+ for block in page.get("blocks", []):
529
+ copied_block = self._copy_block(block)
530
+ copied_block["page_no"] = page_no
531
+
532
+ if copied_block.get("is_heading"):
533
+ # タイトル本文が出たら、そこで前セクションを閉じて新ファイルを開始する。
534
+ append_current()
535
+ current = new_section()
536
+ elif current is None:
537
+ current = new_section()
538
+
539
+ current["blocks"].append(copied_block)
540
+ if page_no not in current["page_nos"]:
541
+ current["page_nos"].append(page_no)
542
+
543
+ append_current()
544
+
545
+ if not sections:
546
+ section = new_section()
547
+ section["blocks"].append(self._make_generated_body_block())
548
+ section["page_nos"].append(1)
549
+ sections.append(section)
550
+
551
+ # append_current() 後に index がずれることは通常ないが、念のためファイル名を正規化する。
552
+ for index, section in enumerate(sections, start=1):
553
+ section["index"] = index
554
+ section["dtbook_file"] = self._dtbook_filename(index)
555
+ section["smil_file"] = self._smil_filename(index)
556
+
557
+ return sections
558
+
559
+ def _copy_block(self, block: Dict[str, Any]) -> Dict[str, Any]:
560
+ copied = dict(block)
561
+ copied["lines"] = [dict(line) for line in block.get("lines", [])]
562
+ copied.pop("phrases", None)
563
+ copied.pop("id", None)
564
+ return copied
565
+
566
+ def _ensure_sections_start_with_heading(self, sections: List[Dict[str, Any]]) -> None:
567
+ """各セクションの level1 直下が必ず h1 から始まるようにする。
568
+
569
+ TEXT DAISY 3 / DTBook 2005-3 では、level1 の構造を安定させるため、
570
+ セクション冒頭に見出しを置く。元の NDLOCR-Lite XML に
571
+ TYPE="タイトル本文" が無いまま始まるセクションでは、書名を補助見出しとして追加する。
572
+ """
573
+ for section in sections:
574
+ blocks = section.get("blocks", [])
575
+
576
+ if not blocks:
577
+ generated_heading = self._make_generated_heading_block()
578
+ if section.get("page_nos"):
579
+ generated_heading["page_no"] = section["page_nos"][0]
580
+ section["blocks"] = [generated_heading]
581
+ continue
582
+
583
+ first_block = blocks[0]
584
+ if bool(first_block.get("is_heading")):
585
+ continue
586
+
587
+ generated_heading = self._make_generated_heading_block()
588
+ generated_heading["page_no"] = first_block.get(
589
+ "page_no",
590
+ section.get("page_nos", [1])[0] if section.get("page_nos") else 1,
591
+ )
592
+ blocks.insert(0, generated_heading)
593
+ section["blocks"] = blocks
594
+
595
+ def _ensure_sections_have_body(self, sections: List[Dict[str, Any]]) -> None:
596
+ """各セクションの level1 が h1 だけで終わらないようにする。"""
597
+ for section in sections:
598
+ blocks = section.get("blocks", [])
599
+ if not blocks:
600
+ section["blocks"] = [
601
+ self._make_generated_heading_block(),
602
+ self._make_generated_body_block(),
603
+ ]
604
+ continue
605
+
606
+ has_body = any(not bool(block.get("is_heading")) for block in blocks)
607
+ if not has_body:
608
+ generated = self._make_generated_body_block()
609
+ if section.get("page_nos"):
610
+ generated["page_no"] = section["page_nos"][-1]
611
+ else:
612
+ generated["page_no"] = blocks[0].get("page_no", 1)
613
+ section["blocks"].append(generated)
614
+
615
+ def _assign_phrase_ids(
616
+ self,
617
+ sections: List[Dict[str, Any]],
618
+ pages: List[Dict[str, Any]],
619
+ ) -> List[Dict[str, Any]]:
620
+ phrases: List[Dict[str, Any]] = []
621
+
622
+ for page in pages:
623
+ page["first_phrase"] = None
624
+
625
+ page_index: Dict[int, Dict[str, Any]] = {
626
+ int(page.get("page_no", index)): page for index, page in enumerate(pages, start=1)
627
+ }
628
+
629
+ for section in sections:
630
+ phrase_index = 1
631
+ block_index = 1
632
+ section["phrases"] = []
633
+ section["heading_blocks"] = []
634
+ section["first_phrase"] = None
635
+
636
+ for block in section.get("blocks", []):
637
+ block["id"] = f"s{section['index']:05d}_block{block_index:05d}"
638
+ block_index += 1
639
+
640
+ block_phrases: List[Dict[str, Any]] = []
641
+ for line in block.get("lines", []):
642
+ page_no = int(block.get("page_no") or section.get("page_nos", [1])[0])
643
+ phrase = {
644
+ "index": phrase_index,
645
+ "text_id": f"t{phrase_index:07d}",
646
+ "par_id": f"phr{phrase_index:05d}",
647
+ "text": str(line.get("text", "")),
648
+ "line_type": str(line.get("line_type", "")),
649
+ "page_no": page_no,
650
+ "page_label": page_index.get(page_no, {}).get("label", f"page-{page_no}"),
651
+ "block_id": block["id"],
652
+ "block_tag": block["tag"],
653
+ "section_index": section["index"],
654
+ "dtbook_file": section["dtbook_file"],
655
+ "smil_file": section["smil_file"],
656
+ "generated": bool(block.get("generated") or line.get("generated")),
657
+ }
658
+ phrases.append(phrase)
659
+ section["phrases"].append(phrase)
660
+ block_phrases.append(phrase)
661
+
662
+ if section["first_phrase"] is None and not phrase["generated"]:
663
+ section["first_phrase"] = phrase
664
+
665
+ page_obj = page_index.get(page_no)
666
+ if page_obj is not None and page_obj.get("first_phrase") is None and not phrase["generated"]:
667
+ page_obj["first_phrase"] = phrase
668
+
669
+ phrase_index += 1
670
+
671
+ block["phrases"] = block_phrases
672
+ if block.get("is_heading") and block_phrases:
673
+ section["heading_blocks"].append(block)
674
+
675
+ if section["first_phrase"] is None and section.get("phrases"):
676
+ section["first_phrase"] = section["phrases"][0]
677
+
678
+ # 構造補完用の空白だけのページがある場合でも pageList が空参照にならないようにする。
679
+ for page in pages:
680
+ if page.get("first_phrase") is not None:
681
+ continue
682
+ page_no = int(page.get("page_no", 1))
683
+ for phrase in phrases:
684
+ if int(phrase.get("page_no", -1)) == page_no:
685
+ page["first_phrase"] = phrase
686
+ break
687
+
688
+ if not phrases:
689
+ # 通常は _build_sections() と _ensure_sections_have_body() により到達しない。
690
+ section = sections[0]
691
+ phrase = {
692
+ "index": 1,
693
+ "text_id": "t0000001",
694
+ "par_id": "phr00001",
695
+ "text": " ",
696
+ "line_type": "本文",
697
+ "page_no": 1,
698
+ "page_label": "page-1",
699
+ "block_id": "s00001_block00001",
700
+ "block_tag": "p",
701
+ "section_index": 1,
702
+ "dtbook_file": section["dtbook_file"],
703
+ "smil_file": section["smil_file"],
704
+ "generated": True,
705
+ }
706
+ section["phrases"] = [phrase]
707
+ section["first_phrase"] = phrase
708
+ phrases.append(phrase)
709
+
710
+ return phrases
711
+
712
+ def _build_dtbook(self, section: Dict[str, Any]) -> str:
713
+ body: List[str] = []
714
+
715
+ body.append('<?xml version="1.0" encoding="utf-8"?>')
716
+ body.append(
717
+ f'<?xml-stylesheet href="{self._xml(self.CSS_FILE)}" '
718
+ f'type="text/css" media="screen"?>'
719
+ )
720
+ body.append(
721
+ f'<?xml-stylesheet href="{self._xml(self.XSL_FILE)}" '
722
+ f'type="text/xsl" media="screen"?>'
723
+ )
724
+ body.append(
725
+ '<!DOCTYPE dtbook PUBLIC "-//NISO//DTD dtbook 2005-3//EN" '
726
+ '"dtbook-2005-3.dtd">'
727
+ )
728
+ body.append(
729
+ f'<dtbook xml:lang="{self._xml(self.language)}" version="2005-3" '
730
+ 'xmlns="http://www.daisy.org/z3986/2005/dtbook/">'
731
+ )
732
+ body.append(" <head>")
733
+ body.append(f' <meta name="dc:Title" content="{self._xml(self.title)}" />')
734
+ body.append(f' <meta name="dtb:uid" content="{self._xml(self.identifier)}" />')
735
+ body.append(f' <meta name="dtb:generator" content="{self._xml(self.generator)}" />')
736
+ body.append(" </head>")
737
+ body.append(" <book>")
738
+ body.append(" <bodymatter>")
739
+ body.append(" <level1>")
740
+
741
+ for block in section.get("blocks", []):
742
+ phrases = block.get("phrases", [])
743
+ if not phrases and not block.get("is_figure"):
744
+ continue
745
+
746
+ if block.get("is_figure"):
747
+ body.extend(self._build_dtbook_figure_block(block))
748
+ if not phrases:
749
+ continue
750
+
751
+ body.append(' <p class="figure-description">')
752
+ for phrase in phrases:
753
+ body.append(
754
+ f' <sent id="{phrase["text_id"]}" '
755
+ f'smilref="{section["smil_file"]}#{phrase["par_id"]}">'
756
+ f'{self._xml(phrase["text"])}'
757
+ f'</sent>'
758
+ )
759
+ body.append(" </p>")
760
+ continue
761
+
762
+ tag = block.get("tag", "p")
763
+ body.append(f" <{tag}>")
764
+ for phrase in phrases:
765
+ body.append(
766
+ f' <sent id="{phrase["text_id"]}" '
767
+ f'smilref="{section["smil_file"]}#{phrase["par_id"]}">'
768
+ f'{self._xml(phrase["text"])}'
769
+ f'</sent>'
770
+ )
771
+ body.append(f" </{tag}>")
772
+
773
+ body.append(" </level1>")
774
+ body.append(" </bodymatter>")
775
+ body.append(" </book>")
776
+ body.append("</dtbook>")
777
+
778
+ return "\n".join(body) + "\n"
779
+
780
+ def _build_dtbook_figure_block(self, block: Dict[str, Any]) -> List[str]:
781
+ figure = block.get("figure", {}) or {}
782
+ figure_id = self._xml(f'img_{block.get("id", "figure")}')
783
+ src = self._xml(figure.get("src", self.FIGURE_PLACEHOLDER_FILE))
784
+ alt = self._xml(figure.get("alt", self.FIGURE_BLOCK_TYPE) or self.FIGURE_BLOCK_TYPE)
785
+
786
+ attrs = [
787
+ f'id="{figure_id}"',
788
+ f'src="{src}"',
789
+ f'alt="{alt}"',
790
+ ]
791
+
792
+ # 元XMLの座標を DTBook の妥当性に影響しない class/title 等へは入れず、
793
+ # 必要最小限の img 属性に限定する。詳細説明は後続 p/sent 側で同期する。
794
+ return [
795
+ ' <imggroup>',
796
+ f' <img {" ".join(attrs)} />',
797
+ ' </imggroup>',
798
+ ]
799
+
800
+ def _sections_have_figures(self, sections: List[Dict[str, Any]]) -> bool:
801
+ return any(
802
+ bool(block.get("is_figure"))
803
+ for section in sections
804
+ for block in section.get("blocks", [])
805
+ )
806
+
807
+ def _build_figure_placeholder_svg(self) -> str:
808
+ return "\n".join(
809
+ [
810
+ '<?xml version="1.0" encoding="UTF-8"?>',
811
+ '<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1" viewBox="0 0 1 1">',
812
+ ' <title>図版</title>',
813
+ ' <desc>NDLOCR-Lite XML の BLOCK TYPE="図版" に対応するプレースホルダー画像です。</desc>',
814
+ '</svg>',
815
+ '',
816
+ ]
817
+ )
818
+
819
+ def _build_smil(self, section: Dict[str, Any]) -> str:
820
+ body: List[str] = []
821
+ phrases = section.get("phrases", [])
822
+
823
+ body.append('<?xml version="1.0" encoding="utf-8"?>')
824
+ body.append(
825
+ '<!DOCTYPE smil PUBLIC "-//NISO//DTD dtbsmil 2005-1//EN" '
826
+ '"dtbsmil-2005-2.dtd">'
827
+ )
828
+ body.append('<smil xmlns="http://www.w3.org/2001/SMIL20/">')
829
+ body.append(" <head>")
830
+ body.append(f' <meta name="dtb:uid" content="{self._xml(self.identifier)}" />')
831
+ body.append(f' <meta name="dtb:generator" content="{self._xml(self.generator)}" />')
832
+ body.append(' <meta name="dtb:totalElapsedTime" content="0:00:00.000" />')
833
+ body.append(" <customAttributes>")
834
+
835
+ for custom_test_id in [
836
+ "normal",
837
+ "front",
838
+ "special",
839
+ "note",
840
+ "noteref",
841
+ "annotation",
842
+ "linenum",
843
+ "sidebar",
844
+ "prodnote",
845
+ ]:
846
+ body.append(
847
+ f' <customTest id="{custom_test_id}" '
848
+ f'defaultState="true" override="visible" />'
849
+ )
850
+
851
+ body.append(" </customAttributes>")
852
+ body.append(" </head>")
853
+ body.append(" <body>")
854
+ body.append(' <seq id="seq1">')
855
+
856
+ for phrase in phrases:
857
+ body.append(f' <par id="{phrase["par_id"]}">')
858
+ body.append(
859
+ f' <text src="{section["dtbook_file"]}#{phrase["text_id"]}" />'
860
+ )
861
+ body.append(" </par>")
862
+
863
+ body.append(" </seq>")
864
+ body.append(" </body>")
865
+ body.append("</smil>")
866
+
867
+ return "\n".join(body) + "\n"
868
+
869
+ def _build_ncx(
870
+ self,
871
+ pages: List[Dict[str, Any]],
872
+ sections: List[Dict[str, Any]],
873
+ phrases: List[Dict[str, Any]],
874
+ ) -> str:
875
+ page_count = len(pages)
876
+ first_phrase = phrases[0] if phrases else None
877
+ nav_entries = self._collect_nav_entries(sections)
878
+
879
+ body: List[str] = []
880
+
881
+ body.append('<?xml version="1.0" encoding="UTF-8"?>')
882
+ body.append(
883
+ '<!DOCTYPE ncx PUBLIC "-//NISO//DTD ncx 2005-1//EN" '
884
+ '"ncx-2005-1.dtd">'
885
+ )
886
+ body.append(
887
+ f'<ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" '
888
+ f'version="2005-1" xml:lang="{self._xml(self.language)}">'
889
+ )
890
+ body.append(" <head>")
891
+ body.append(f' <meta name="dtb:uid" content="{self._xml(self.identifier)}"/>')
892
+ body.append(' <meta name="dtb:depth" content="1"/>')
893
+ body.append(f' <meta name="dtb:totalPageCount" content="{page_count}"/>')
894
+ body.append(f' <meta name="dtb:maxPageNumber" content="{page_count}"/>')
895
+ body.append(f' <meta name="dtb:generator" content="{self._xml(self.generator)}"/>')
896
+ body.append(" </head>")
897
+ body.append(f" <docTitle><text>{self._xml(self.title)}</text></docTitle>")
898
+ body.append(" <navMap>")
899
+
900
+ for play_order, entry in enumerate(nav_entries, start=1):
901
+ body.append(
902
+ f' <navPoint id="nav_{play_order:05d}" playOrder="{play_order}">'
903
+ )
904
+ body.append(f" <navLabel><text>{self._xml(entry['label'])}</text></navLabel>")
905
+ body.append(f' <content src="{entry["smil_file"]}#{entry["par_id"]}"/>')
906
+ body.append(" </navPoint>")
907
+
908
+ body.append(" </navMap>")
909
+ body.append(' <pageList id="pages">')
910
+ body.append(" <navLabel><text>Pages</text></navLabel>")
911
+
912
+ page_play_order_start = len(nav_entries) + 1
913
+ for offset, page in enumerate(pages):
914
+ pageno = int(page.get("page_no", offset + 1))
915
+ page_phrase = page.get("first_phrase") or first_phrase
916
+ if page_phrase is None:
917
+ continue
918
+ play_order = page_play_order_start + offset
919
+
920
+ body.append(
921
+ f' <pageTarget id="pagetarget_{pageno:05d}" '
922
+ f'type="normal" value="{pageno}" playOrder="{play_order}">'
923
+ )
924
+ body.append(f" <navLabel><text>{pageno}</text></navLabel>")
925
+ body.append(
926
+ f' <content src="{page_phrase["smil_file"]}#{page_phrase["par_id"]}"/>'
927
+ )
928
+ body.append(" </pageTarget>")
929
+
930
+ body.append(" </pageList>")
931
+ body.append("</ncx>")
932
+
933
+ return "\n".join(body) + "\n"
934
+
935
+ def _collect_nav_entries(self, sections: List[Dict[str, Any]]) -> List[Dict[str, str]]:
936
+ entries: List[Dict[str, str]] = []
937
+
938
+ for section in sections:
939
+ heading_blocks = section.get("heading_blocks", [])
940
+ label = ""
941
+ par_id = ""
942
+
943
+ if heading_blocks:
944
+ phrases = heading_blocks[0].get("phrases", [])
945
+ label = "".join(str(phrase.get("text", "")) for phrase in phrases).strip()
946
+ if phrases:
947
+ par_id = phrases[0]["par_id"]
948
+ elif section.get("first_phrase"):
949
+ label = self.title
950
+ par_id = section["first_phrase"]["par_id"]
951
+
952
+ if not label:
953
+ label = self.title
954
+ if not par_id and section.get("phrases"):
955
+ par_id = section["phrases"][0]["par_id"]
956
+ if not par_id:
957
+ continue
958
+
959
+ entries.append(
960
+ {
961
+ "label": label,
962
+ "smil_file": section["smil_file"],
963
+ "par_id": par_id,
964
+ }
965
+ )
966
+
967
+ return entries
968
+
969
+ def _build_opf(self, sections: List[Dict[str, Any]]) -> str:
970
+ body: List[str] = []
971
+
972
+ body.append('<?xml version="1.0" encoding="UTF-8"?>')
973
+ body.append(
974
+ '<!DOCTYPE package PUBLIC "+//ISBN 0-9673008-1-9//DTD OEB 1.2 Package//EN"'
975
+ )
976
+ body.append(' "http://openebook.org/dtds/oeb-1.2/oebpkg12.dtd">')
977
+ body.append(
978
+ '<package xmlns="http://openebook.org/namespaces/oeb-package/1.0/" '
979
+ 'unique-identifier="uid">'
980
+ )
981
+ body.append(" <metadata>")
982
+ body.append(' <dc-metadata xmlns:dc="http://purl.org/dc/elements/1.1/"')
983
+ body.append(
984
+ ' xmlns:oebpackage="http://openebook.org/namespaces/oeb-package/1.0/">'
985
+ )
986
+ body.append(f" <dc:Title>{self._xml(self.title)}</dc:Title>")
987
+ body.append(
988
+ f' <dc:Identifier id="uid" scheme="DTB">'
989
+ f'{self._xml(self.identifier)}'
990
+ f'</dc:Identifier>'
991
+ )
992
+ body.append(f" <dc:Language>{self._xml(self.language)}</dc:Language>")
993
+ body.append(f" <dc:Publisher>{self._xml(self.producer)}</dc:Publisher>")
994
+ body.append(f" <dc:Date>{self._xml(self.produced_date)}</dc:Date>")
995
+ body.append(" <dc:Format>ANSI/NISO Z39.86-2005</dc:Format>")
996
+ body.append(" </dc-metadata>")
997
+ body.append(" <x-metadata>")
998
+ body.append(' <meta name="dtb:multimediaContent" content="text"/>')
999
+ body.append(' <meta name="dtb:multimediaType" content="textNCX"/>')
1000
+ body.append(' <meta name="dtb:totalTime" content="0:00:00.000"/>')
1001
+ body.append(f' <meta name="dtb:producer" content="{self._xml(self.producer)}"/>')
1002
+ body.append(
1003
+ f' <meta name="dtb:producedDate" content="{self._xml(self.produced_date)}"/>'
1004
+ )
1005
+ body.append(" </x-metadata>")
1006
+ body.append(" </metadata>")
1007
+ body.append(" <manifest>")
1008
+ body.append(f' <item id="opf" href="{self.OPF_FILE}" media-type="text/xml"/>')
1009
+ body.append(
1010
+ f' <item id="ncx" href="{self.NCX_FILE}" '
1011
+ f'media-type="application/x-dtbncx+xml"/>'
1012
+ )
1013
+
1014
+ for section in sections:
1015
+ index = section["index"]
1016
+ body.append(
1017
+ f' <item id="dtbook{index:05d}" href="{section["dtbook_file"]}" '
1018
+ f'media-type="application/x-dtbook+xml"/>'
1019
+ )
1020
+ body.append(
1021
+ f' <item id="smil{index:05d}" href="{section["smil_file"]}" '
1022
+ f'media-type="application/smil"/>'
1023
+ )
1024
+
1025
+ if self._sections_have_figures(sections):
1026
+ body.append(
1027
+ f' <item id="figure_placeholder" href="{self.FIGURE_PLACEHOLDER_FILE}" '
1028
+ f'media-type="image/svg+xml"/>'
1029
+ )
1030
+
1031
+ body.append(f' <item id="css" href="{self.CSS_FILE}" media-type="text/css"/>')
1032
+ body.append(f' <item id="xsl" href="{self.XSL_FILE}" media-type="text/xsl"/>')
1033
+ body.append(" </manifest>")
1034
+ body.append(" <spine>")
1035
+ for section in sections:
1036
+ body.append(f' <itemref idref="smil{section["index"]:05d}"/>')
1037
+ body.append(" </spine>")
1038
+ body.append("</package>")
1039
+
1040
+ return "\n".join(body) + "\n"
1041
+
1042
+ def _build_css(self) -> str:
1043
+ return "\n".join(
1044
+ [
1045
+ "dtbook { display: block; }",
1046
+ "book, bodymatter, level1, p, h1, imggroup { display: block; }",
1047
+ "h1 { font-size: 1.6em; font-weight: bold; margin: 1em 0; }",
1048
+ "p { margin: 0.5em 0; }",
1049
+ "imggroup { margin: 1em 0; }",
1050
+ "img { max-width: 100%; }",
1051
+ "sent { display: inline; }",
1052
+ "",
1053
+ ]
1054
+ )
1055
+
1056
+ def _build_xsl(self) -> str:
1057
+ return "\n".join(
1058
+ [
1059
+ '<?xml version="1.0" encoding="UTF-8"?>',
1060
+ '<xsl:stylesheet version="1.0" ',
1061
+ ' xmlns:xsl="http://www.w3.org/1999/XSL/Transform"',
1062
+ ' xmlns:dtb="http://www.daisy.org/z3986/2005/dtbook/">',
1063
+ ' <xsl:output method="html" encoding="UTF-8"/>',
1064
+ ' <xsl:template match="/">',
1065
+ ' <html><body><xsl:apply-templates select="//dtb:bodymatter"/></body></html>',
1066
+ ' </xsl:template>',
1067
+ ' <xsl:template match="dtb:h1"><h1><xsl:apply-templates/></h1></xsl:template>',
1068
+ ' <xsl:template match="dtb:p"><p><xsl:apply-templates/></p></xsl:template>',
1069
+ ' <xsl:template match="dtb:imggroup"><div class="imggroup"><xsl:apply-templates/></div></xsl:template>',
1070
+ ' <xsl:template match="dtb:img"><img src="{@src}" alt="{@alt}"/></xsl:template>',
1071
+ ' <xsl:template match="dtb:sent"><xsl:value-of select="."/></xsl:template>',
1072
+ '</xsl:stylesheet>',
1073
+ "",
1074
+ ]
1075
+ )
1076
+
1077
+ def _local_name(self, tag: str) -> str:
1078
+ return tag.rsplit("}", 1)[-1] if "}" in tag else tag
1079
+
1080
+ def _xml(self, value: Any) -> str:
1081
+ return escape(str(value), {'"': "&quot;"})
1082
+
1083
+ def _safe_identifier_for_asset_name(self, identifier: str) -> str:
1084
+ candidate = identifier.rsplit(":", 1)[-1].strip() or "textdaisy"
1085
+ return self._safe_filename(candidate)
1086
+
1087
+ def _safe_filename(self, value: str) -> str:
1088
+ # DAISY 3 の URI 互換性を考慮し、出力フォルダ名・参照ファイル名を ASCII 中心に寄せる。
1089
+ value = value.strip() or "textdaisy"
1090
+ value = quote(value, safe="-_.")
1091
+ value = re.sub(r"%", "_", value)
1092
+ value = re.sub(r"[^A-Za-z0-9._-]+", "_", value)
1093
+ return value[:120] or "textdaisy"