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
ocr.py ADDED
@@ -0,0 +1,1425 @@
1
+ import sys
2
+ sys.setrecursionlimit(5000)
3
+ import os
4
+ import numpy as np
5
+ from PIL import Image
6
+ import xml.etree.ElementTree as ET
7
+ from pathlib import Path
8
+ from deim import DEIM
9
+ from parseq import PARSEQ
10
+
11
+ from yaml import safe_load
12
+ from concurrent.futures import ThreadPoolExecutor
13
+ import time
14
+ import shutil
15
+ import json
16
+ import glob
17
+ from functools import lru_cache
18
+ from reading_order.xy_cut.eval import eval_xml
19
+ from reading_order.xy_cut.block_xy_cut import solve as solve_reading_order
20
+ from ndl_parser import convert_to_xml_string3
21
+ from pdf_output_utils import should_output_pdf_pages_separately, write_pdf_page_outputs
22
+ from version import __version__
23
+
24
+
25
+ def _is_cjk_char(ch: str) -> bool:
26
+ """Return True for common Japanese/CJK characters.
27
+
28
+ This is only used to decide whether two OCR lines in the same layout
29
+ TEXTBLOCK need an inserted ASCII space when they are joined into one
30
+ paragraph for Markdown display.
31
+ """
32
+ if not ch:
33
+ return False
34
+ cp = ord(ch)
35
+ return (
36
+ 0x3040 <= cp <= 0x30FF # Hiragana / Katakana
37
+ or 0x3400 <= cp <= 0x4DBF # CJK Ext. A
38
+ or 0x4E00 <= cp <= 0x9FFF # CJK Unified Ideographs
39
+ or 0xF900 <= cp <= 0xFAFF # CJK Compatibility Ideographs
40
+ or 0xFF00 <= cp <= 0xFFEF # Full-width forms
41
+ )
42
+
43
+
44
+ def _join_textblock_lines(lines):
45
+ """Join physical OCR lines as one logical paragraph.
46
+
47
+ Layout TEXTBLOCK boundaries represent paragraph/block boundaries in the
48
+ result viewer. Physical line wraps inside a block are removed. A single
49
+ ASCII space is inserted only when it is likely needed between Latin words.
50
+ """
51
+ cleaned = [str(line).replace("\r", "").replace("\n", "").strip() for line in lines]
52
+ cleaned = [line for line in cleaned if line]
53
+ if not cleaned:
54
+ return ""
55
+
56
+ out = cleaned[0]
57
+ closing_punct = set(",.;:!?%)]}、。,.!?:;)]}〉》」』】%")
58
+ opening_punct = set("([{([{〈《「『【")
59
+ for nxt in cleaned[1:]:
60
+ prev = out[-1] if out else ""
61
+ first = nxt[0] if nxt else ""
62
+ need_space = (
63
+ bool(prev and first)
64
+ and not prev.isspace()
65
+ and not first.isspace()
66
+ and not _is_cjk_char(prev)
67
+ and not _is_cjk_char(first)
68
+ and prev not in opening_punct
69
+ and first not in closing_punct
70
+ and (prev.isalnum() or prev in "'\"")
71
+ and (first.isalnum() or first in "'\"")
72
+ )
73
+ out += (" " if need_space else "") + nxt
74
+ return out
75
+
76
+
77
+ def _escape_markdown_paragraph(text: str) -> str:
78
+ escaped = str(text).replace("\\", "\\\\")
79
+ for ch in ("`", "*", "_", "{", "}", "[", "]", "<", ">", "#", "+", "-", "!", "|"):
80
+ escaped = escaped.replace(ch, "\\" + ch)
81
+ return escaped
82
+
83
+
84
+ def _is_title_line_element(line) -> bool:
85
+ """Return True when an OCR LINE is the layout category 'タイトル本文'."""
86
+ line_type = str(line.get("TYPE") or "").strip()
87
+ normalized = line_type.lower().replace("-", "_")
88
+ return (
89
+ line_type == "タイトル本文"
90
+ or normalized in {"line_title", "title", "title_text"}
91
+ or "タイトル本文" in line_type
92
+ )
93
+
94
+
95
+ def _render_markdown_line_groups(lines) -> list[str]:
96
+ """Render ordered LINE elements as headings and body paragraphs.
97
+
98
+ Consecutive title lines are joined into one Markdown heading. Consecutive
99
+ ordinary lines are joined into one logical paragraph. A blank line between
100
+ returned fragments is added by the page-level builder, so TEXTBLOCK and
101
+ title/body boundaries are visually explicit in ft.Markdown.
102
+ """
103
+ fragments: list[str] = []
104
+ group_kind = None
105
+ group_texts: list[str] = []
106
+
107
+ def flush():
108
+ nonlocal group_kind, group_texts
109
+ text = _join_textblock_lines(group_texts)
110
+ if text:
111
+ escaped = _escape_markdown_paragraph(text)
112
+ if group_kind == "title":
113
+ fragments.append(f"## {escaped}")
114
+ else:
115
+ fragments.append(escaped)
116
+ group_kind = None
117
+ group_texts = []
118
+
119
+ for line in lines:
120
+ value = (line.get("STRING") or "").strip()
121
+ if not value:
122
+ continue
123
+ kind = "title" if _is_title_line_element(line) else "body"
124
+ if group_kind is not None and group_kind != kind:
125
+ flush()
126
+ group_kind = kind
127
+ group_texts.append(value)
128
+ flush()
129
+ return fragments
130
+
131
+
132
+ def _line_reading_order(line):
133
+ """Return numeric LINE@ORDER when xy-cut assigned one."""
134
+ try:
135
+ value = float(line.get("ORDER"))
136
+ except (TypeError, ValueError):
137
+ return None
138
+ return value if np.isfinite(value) else None
139
+
140
+
141
+ def _xml_element_bbox(elem):
142
+ """Return an axis-aligned bbox for a layout XML element when possible."""
143
+ try:
144
+ x = float(elem.get("X"))
145
+ y = float(elem.get("Y"))
146
+ w = float(elem.get("WIDTH"))
147
+ h = float(elem.get("HEIGHT"))
148
+ if w > 0 and h > 0:
149
+ return (x, y, x + w, y + h)
150
+ except (TypeError, ValueError):
151
+ pass
152
+
153
+ boxes = []
154
+ lines = [elem] if str(elem.tag).upper() == "LINE" else list(elem.findall(".//LINE"))
155
+ for line in lines:
156
+ try:
157
+ x = float(line.get("X"))
158
+ y = float(line.get("Y"))
159
+ w = float(line.get("WIDTH"))
160
+ h = float(line.get("HEIGHT"))
161
+ except (TypeError, ValueError):
162
+ continue
163
+ if w > 0 and h > 0:
164
+ boxes.append((x, y, x + w, y + h))
165
+ if boxes:
166
+ return (
167
+ min(b[0] for b in boxes),
168
+ min(b[1] for b in boxes),
169
+ max(b[2] for b in boxes),
170
+ max(b[3] for b in boxes),
171
+ )
172
+
173
+ # TEXTBLOCK normally has a SHAPE/POLYGON rather than X/Y/WIDTH/HEIGHT.
174
+ polygon = elem.find("./SHAPE/POLYGON")
175
+ if polygon is not None:
176
+ raw = str(polygon.get("POINTS") or "").strip()
177
+ try:
178
+ coords = [float(v) for v in raw.split(",") if v.strip()]
179
+ points = list(zip(coords[0::2], coords[1::2]))
180
+ except ValueError:
181
+ points = []
182
+ if points:
183
+ xs = [pt[0] for pt in points]
184
+ ys = [pt[1] for pt in points]
185
+ return (min(xs), min(ys), max(xs), max(ys))
186
+ return None
187
+
188
+
189
+ def _bbox_iou_for_layout(a, b):
190
+ if a is None or b is None:
191
+ return 0.0
192
+ ax1, ay1, ax2, ay2 = a
193
+ bx1, by1, bx2, by2 = b
194
+ ix1, iy1 = max(ax1, bx1), max(ay1, by1)
195
+ ix2, iy2 = min(ax2, bx2), min(ay2, by2)
196
+ iw, ih = max(0.0, ix2 - ix1), max(0.0, iy2 - iy1)
197
+ inter = iw * ih
198
+ union = max(0.0, ax2 - ax1) * max(0.0, ay2 - ay1) + max(0.0, bx2 - bx1) * max(0.0, by2 - by1) - inter
199
+ return inter / union if union > 0 else 0.0
200
+
201
+
202
+ def _normalize_table_markdown_entries(table_markdowns):
203
+ entries = []
204
+ for index, item in enumerate(list(table_markdowns or [])):
205
+ if isinstance(item, dict):
206
+ markdown = str(item.get("markdown") or item.get("text") or "").strip()
207
+ bbox = item.get("layout_bbox")
208
+ if bbox is None:
209
+ bbox = item.get("bbox")
210
+ try:
211
+ bbox = tuple(float(v) for v in bbox) if bbox is not None and len(bbox) == 4 else None
212
+ except (TypeError, ValueError):
213
+ bbox = None
214
+ raw_table_index = item.get("table_index")
215
+ try:
216
+ table_index = int(raw_table_index) if raw_table_index is not None else None
217
+ except (TypeError, ValueError):
218
+ table_index = None
219
+ entries.append({
220
+ "markdown": markdown,
221
+ "bbox": bbox,
222
+ "index": index,
223
+ "table_index": table_index,
224
+ "used": False,
225
+ })
226
+ else:
227
+ # Legacy v1.0.10 callers pass plain strings in the same order as
228
+ # extract_table_regions(); preserve that stable association.
229
+ entries.append({
230
+ "markdown": str(item).strip(),
231
+ "bbox": None,
232
+ "index": index,
233
+ "table_index": index + 1,
234
+ "used": False,
235
+ })
236
+ return entries
237
+
238
+
239
+ def _match_table_markdown(block, entries, table_index=None):
240
+ """Match a structured table result to its original XML table BLOCK.
241
+
242
+ ``table_index`` is preferred because it is generated from the exact same
243
+ XML table enumeration used by inference. This avoids the v1.0.11
244
+ regression where an empty/failed result could be paired with a different
245
+ table after bbox-based re-matching. Bbox IoU remains a compatibility
246
+ fallback when no explicit index is available.
247
+ """
248
+ if table_index is not None:
249
+ for entry in entries:
250
+ if entry["used"]:
251
+ continue
252
+ if entry.get("table_index") == table_index:
253
+ entry["used"] = True
254
+ return entry["markdown"]
255
+
256
+ block_bbox = _xml_element_bbox(block)
257
+ best = None
258
+ best_score = 0.0
259
+ if block_bbox is not None:
260
+ for entry in entries:
261
+ if entry["used"] or entry["bbox"] is None:
262
+ continue
263
+ score = _bbox_iou_for_layout(block_bbox, entry["bbox"])
264
+ if score > best_score:
265
+ best = entry
266
+ best_score = score
267
+ if best is not None and best_score >= 0.5:
268
+ best["used"] = True
269
+ return best["markdown"]
270
+
271
+ # Final compatibility fallback. This is intentionally last so sorting PAGE
272
+ # children for display can never change which inference result belongs to
273
+ # which original table block.
274
+ for entry in entries:
275
+ if not entry["used"]:
276
+ entry["used"] = True
277
+ return entry["markdown"]
278
+ return None
279
+
280
+
281
+ def _layout_child_order(child):
282
+ """Use descendant LINE@ORDER as the reading-order anchor of a layout item."""
283
+ lines = [child] if str(child.tag).upper() == "LINE" else list(child.findall(".//LINE"))
284
+ orders = [value for value in (_line_reading_order(line) for line in lines) if value is not None]
285
+ return min(orders) if orders else None
286
+
287
+
288
+ def _sort_page_layout_children(page_elem):
289
+ """Sort PAGE children in reading order, including BLOCK TYPE='表組'.
290
+
291
+ ``reading_order.order.reorder.sort_lines`` intentionally leaves generic
292
+ BLOCK elements in an unsorted bucket after TEXTBLOCK/LINE elements. That is
293
+ correct for its line-oriented XML task but made table Markdown drift to the
294
+ end of the GUI document. Here a table BLOCK is anchored by the ORDER of its
295
+ descendant OCR lines. If an empty table has no LINE@ORDER, xy-cut is run on
296
+ the top-level layout bboxes so its detected position can still be inserted
297
+ among surrounding text.
298
+ """
299
+ children = list(page_elem)
300
+ if len(children) <= 1:
301
+ return children
302
+
303
+ records = []
304
+ any_missing = False
305
+ for original_index, child in enumerate(children):
306
+ order = _layout_child_order(child)
307
+ bbox = _xml_element_bbox(child)
308
+ records.append({
309
+ "child": child,
310
+ "order": order,
311
+ "bbox": bbox,
312
+ "original_index": original_index,
313
+ "geo_order": None,
314
+ })
315
+ any_missing = any_missing or order is None
316
+
317
+ # Normal case: every rendered item contains OCR lines and already has the
318
+ # authoritative xy-cut LINE@ORDER. This directly fixes table BLOCKs that
319
+ # eval_xml() moved after all TEXTBLOCKs.
320
+ if not any_missing:
321
+ return [r["child"] for r in sorted(records, key=lambda r: (r["order"], r["original_index"]))]
322
+
323
+ # Empty table blocks have no descendant line rank. Re-run the same xy-cut
324
+ # solver on layout-item rectangles so those blocks still obtain a spatial
325
+ # reading-order position. Items without any usable geometry remain last.
326
+ boxed = [r for r in records if r["bbox"] is not None]
327
+ if boxed:
328
+ try:
329
+ boxes = np.asarray([[int(round(v)) for v in r["bbox"]] for r in boxed], dtype=np.int32)
330
+ ranks = solve_reading_order(boxes, logger=None)
331
+ for record, rank in zip(boxed, ranks):
332
+ record["geo_order"] = float(rank)
333
+ except Exception:
334
+ pass
335
+
336
+ # Where LINE@ORDER exists, keep it authoritative. For missing items, use
337
+ # geometry rank and interpolate against known neighbors in that rank order.
338
+ geo_sorted = sorted(
339
+ records,
340
+ key=lambda r: (
341
+ r["geo_order"] is None,
342
+ float("inf") if r["geo_order"] is None else r["geo_order"],
343
+ r["original_index"],
344
+ ),
345
+ )
346
+ for pos, record in enumerate(geo_sorted):
347
+ if record["order"] is not None:
348
+ continue
349
+ prev_known = next((geo_sorted[i] for i in range(pos - 1, -1, -1) if geo_sorted[i]["order"] is not None), None)
350
+ next_known = next((geo_sorted[i] for i in range(pos + 1, len(geo_sorted)) if geo_sorted[i]["order"] is not None), None)
351
+ if prev_known is not None and next_known is not None:
352
+ left = float(prev_known["order"])
353
+ right = float(next_known["order"])
354
+ if right > left:
355
+ span = sum(1 for item in geo_sorted[geo_sorted.index(prev_known) + 1:geo_sorted.index(next_known)] if item["order"] is None) + 1
356
+ offset = sum(1 for item in geo_sorted[geo_sorted.index(prev_known) + 1:pos + 1] if item["order"] is None)
357
+ record["order"] = left + (right - left) * offset / span
358
+ else:
359
+ record["order"] = left + 0.001 * (pos + 1)
360
+ elif prev_known is not None:
361
+ record["order"] = float(prev_known["order"]) + 0.001 * (pos + 1)
362
+ elif next_known is not None:
363
+ record["order"] = float(next_known["order"]) - 0.001 * (len(geo_sorted) - pos)
364
+ elif record["geo_order"] is not None:
365
+ record["order"] = float(record["geo_order"])
366
+ else:
367
+ record["order"] = float("inf")
368
+
369
+ return [r["child"] for r in sorted(records, key=lambda r: (r["order"], r["original_index"]))]
370
+
371
+
372
+ def build_markdown_text_from_page(page_elem, table_markdowns=None) -> str:
373
+ """Build GUI Markdown in true layout reading order.
374
+
375
+ Display rules:
376
+ * ``LINE TYPE="タイトル本文"`` is rendered as a Markdown heading.
377
+ * Each ordinary TEXTBLOCK is rendered as one paragraph, with a blank line
378
+ between blocks.
379
+ * A ``BLOCK TYPE="表組"`` is inserted at its LINE@ORDER / detected-bbox
380
+ position and replaced by the matching Markdown table.
381
+
382
+ ``eval_xml()`` sorts LINE/TEXTBLOCK objects but deliberately leaves generic
383
+ BLOCK objects after them. Therefore PAGE child order must not be used as the
384
+ reading order for tables.
385
+ """
386
+ if page_elem is None:
387
+ return ""
388
+
389
+ table_entries = _normalize_table_markdown_entries(table_markdowns)
390
+ # Preserve the exact table enumeration used by extract_table_regions().
391
+ # Sorting children below changes only display order, never table identity.
392
+ table_block_indexes = {}
393
+ table_counter = 0
394
+ for block in page_elem.findall(".//BLOCK"):
395
+ if str(block.get("TYPE") or "").strip() == "表組":
396
+ table_counter += 1
397
+ table_block_indexes[id(block)] = table_counter
398
+
399
+ fragments: list[str] = []
400
+ consumed = set()
401
+
402
+ def collect_lines(elem):
403
+ lines = list(elem.findall(".//LINE"))
404
+ if str(elem.tag).upper() == "LINE":
405
+ lines = [elem]
406
+ for line in lines:
407
+ consumed.add(id(line))
408
+ return lines
409
+
410
+ def append_lines(lines):
411
+ fragments.extend(_render_markdown_line_groups(lines))
412
+
413
+ for child in _sort_page_layout_children(page_elem):
414
+ tag = str(child.tag).upper()
415
+ if tag == "TEXTBLOCK":
416
+ append_lines(collect_lines(child))
417
+ elif tag == "BLOCK":
418
+ block_type = str(child.get("TYPE") or "").strip()
419
+ if block_type == "表組":
420
+ table_lines = collect_lines(child)
421
+ table_md = _match_table_markdown(
422
+ child, table_entries, table_index=table_block_indexes.get(id(child))
423
+ )
424
+ if table_md:
425
+ fragments.append(str(table_md).strip())
426
+ else:
427
+ append_lines(table_lines)
428
+ else:
429
+ nested_blocks = child.findall(".//TEXTBLOCK")
430
+ if nested_blocks:
431
+ for block in nested_blocks:
432
+ append_lines(collect_lines(block))
433
+ else:
434
+ append_lines(collect_lines(child))
435
+ elif tag == "WARICHUBLOCK":
436
+ append_lines(collect_lines(child))
437
+ elif tag == "LINE":
438
+ append_lines(collect_lines(child))
439
+
440
+ # Be conservative: never lose OCR text just because an unfamiliar XML
441
+ # nesting pattern is encountered. These residual lines are sorted by their
442
+ # own reading-order rank before rendering.
443
+ residual = [line for line in page_elem.findall(".//LINE") if id(line) not in consumed]
444
+ residual.sort(key=lambda line: (_line_reading_order(line) is None, _line_reading_order(line) or float("inf")))
445
+ for line in residual:
446
+ append_lines([line])
447
+
448
+ return "\n\n".join(fragment for fragment in fragments if fragment.strip())
449
+
450
+ def build_markdown_text_from_xml(page_xml: str, table_markdowns=None) -> str:
451
+ """Parse a PAGE XML fragment and build viewer Markdown."""
452
+ if not page_xml:
453
+ return ""
454
+ try:
455
+ root = ET.fromstring(page_xml)
456
+ except ET.ParseError:
457
+ return ""
458
+ page_elem = root if str(root.tag).upper() == "PAGE" else root.find("PAGE")
459
+ return build_markdown_text_from_page(page_elem, table_markdowns=table_markdowns)
460
+
461
+ class RecogLine:
462
+ def __init__(self,npimg:np.ndarray,idx:int,pred_char_cnt:int,pred_str:str=""):
463
+ self.npimg = npimg
464
+ self.idx = idx
465
+ self.pred_char_cnt = pred_char_cnt
466
+ self.pred_str = pred_str
467
+ def __lt__(self, other):
468
+ return self.idx < other.idx
469
+
470
+ def process_cascade(alllineobj:RecogLine,recognizer30,recognizer50,recognizer100,is_cascade=True):
471
+ targetdflist30,targetdflist50,targetdflist100=[],[],[]
472
+ for lineobj in alllineobj:
473
+ if lineobj.pred_char_cnt==3 and is_cascade:
474
+ targetdflist30.append(lineobj)
475
+ elif lineobj.pred_char_cnt==2 and is_cascade:
476
+ targetdflist50.append(lineobj)
477
+ else:
478
+ targetdflist100.append(lineobj)
479
+
480
+ targetdflistall=[]
481
+ with ThreadPoolExecutor(thread_name_prefix="recognizer") as executor:
482
+ # The three recognizer models are independent. Start their initial jobs
483
+ # together, then submit only the lines that overflow into the next tier.
484
+ jobs30=[(lineobj,executor.submit(recognizer30.read,lineobj.npimg)) for lineobj in targetdflist30]
485
+ jobs50=[(lineobj,executor.submit(recognizer50.read,lineobj.npimg)) for lineobj in targetdflist50]
486
+ jobs100=[(lineobj,executor.submit(recognizer100.read,lineobj.npimg)) for lineobj in targetdflist100]
487
+
488
+ for lineobj,future in jobs30:
489
+ pred_str=future.result()
490
+ if len(pred_str)>=25:
491
+ jobs50.append((lineobj,executor.submit(recognizer50.read,lineobj.npimg)))
492
+ else:
493
+ lineobj.pred_str=pred_str
494
+ targetdflistall.append(lineobj)
495
+
496
+ for lineobj,future in jobs50:
497
+ pred_str=future.result()
498
+ if len(pred_str)>=45:
499
+ jobs100.append((lineobj,executor.submit(recognizer100.read,lineobj.npimg)))
500
+ else:
501
+ lineobj.pred_str=pred_str
502
+ targetdflistall.append(lineobj)
503
+
504
+ targetdflist200=[]
505
+ for lineobj,future in jobs100:
506
+ pred_str=future.result()
507
+ lineobj.pred_str=pred_str
508
+ if len(pred_str)>=98 and lineobj.npimg.shape[0]<lineobj.npimg.shape[1]:
509
+ baseimg=lineobj.npimg
510
+ targetdflist200.append(RecogLine(
511
+ npimg=baseimg[:,:baseimg.shape[1]//2,:],
512
+ idx=lineobj.idx,
513
+ pred_char_cnt=100,
514
+ ))
515
+ targetdflist200.append(RecogLine(
516
+ npimg=baseimg[:,baseimg.shape[1]//2:,:],
517
+ idx=lineobj.idx,
518
+ pred_char_cnt=100,
519
+ ))
520
+ else:
521
+ targetdflistall.append(lineobj)
522
+
523
+ jobs200=[(lineobj,executor.submit(recognizer100.read,lineobj.npimg)) for lineobj in targetdflist200]
524
+ resultlines200=[future.result() for _,future in jobs200]
525
+ for i in range(0,len(targetdflist200)-1,2):
526
+ ia=targetdflist200[i]
527
+ targetdflistall.append(RecogLine(
528
+ npimg=None,
529
+ idx=ia.idx,
530
+ pred_char_cnt=100,
531
+ pred_str=resultlines200[i]+resultlines200[i+1],
532
+ ))
533
+
534
+ targetdflistall=sorted(targetdflistall)
535
+ return [t.pred_str for t in targetdflistall]
536
+
537
+ def get_detector(args):
538
+ weights_path = args.det_weights
539
+ classes_path = args.det_classes
540
+ assert os.path.isfile(weights_path), f"There's no weight file with name {weights_path}"
541
+ assert os.path.isfile(classes_path), f"There's no classes file with name {weights_path}"
542
+ detector = DEIM(model_path=weights_path,
543
+ class_mapping_path=classes_path,
544
+ score_threshold=args.det_score_threshold,
545
+ conf_threshold=args.det_conf_threshold,
546
+ iou_threshold=args.det_iou_threshold,
547
+ device=args.device)
548
+ return detector
549
+
550
+ @lru_cache(maxsize=8)
551
+ def _load_charlist(classes_path):
552
+ with open(classes_path,encoding="utf-8") as f:
553
+ charobj=safe_load(f)
554
+ return tuple(charobj["model"]["charset_train"])
555
+
556
+ def get_recognizer(args,weights_path=None):
557
+ if weights_path is None:
558
+ weights_path = args.rec_weights
559
+ classes_path = args.rec_classes
560
+
561
+ assert os.path.isfile(weights_path), f"There's no weight file with name {weights_path}"
562
+ assert os.path.isfile(classes_path), f"There's no classes file with name {weights_path}"
563
+
564
+ charlist=list(_load_charlist(os.path.abspath(classes_path)))
565
+
566
+ recognizer = PARSEQ(model_path=weights_path,charlist=charlist,device=args.device)
567
+ if getattr(args, 'enable_tcy', False):
568
+ from tcy_wrapper import TateChuYokoWrapper
569
+ tcy_kwargs = {k: v for k, v in vars(args).items() if k.startswith('tcy_') and k != 'enable_tcy' and v is not None}
570
+ recognizer = TateChuYokoWrapper(recognizer, **tcy_kwargs)
571
+ return recognizer
572
+
573
+ def inference_on_detector(args,inputname:str,npimage:np.ndarray,outputpath:str,issaveimg:bool=True):
574
+ print("[INFO] Intialize Model")
575
+ detector = get_detector(args)
576
+ print("[INFO] Inference Image")
577
+ detections = detector.detect(npimage)
578
+ classeslist=list(detector.classes.values())
579
+ if issaveimg:
580
+ drawimage = npimage.copy()
581
+ pil_image =detector.draw_detections(drawimage, detections=detections)
582
+ os.makedirs(outputpath,exist_ok=True)
583
+ output_filepath = os.path.join(outputpath,f"viz_{Path(inputname).name}")
584
+ if output_filepath.split(".")[-1]=="jp2":
585
+ output_filepath=output_filepath[:-4]+".jpg"
586
+ print(f"[INFO] Saving result on {output_filepath}")
587
+ pil_image.save(output_filepath)
588
+ return detections,classeslist
589
+
590
+ def process_detector(detector,inputname:str,npimage:np.ndarray,outputpath:str,issaveimg:bool=True):
591
+ detections = detector.detect(npimage)
592
+ classeslist=list(detector.classes.values())
593
+ if issaveimg:
594
+ drawimage = npimage.copy()
595
+ pil_image =detector.draw_detections(drawimage, detections=detections)
596
+ os.makedirs(outputpath,exist_ok=True)
597
+ output_filepath = os.path.join(outputpath,f"viz_{Path(inputname).name}")
598
+ if output_filepath.split(".")[-1]=="jp2":
599
+ output_filepath=output_filepath[:-4]+".jpg"
600
+ print(f"[INFO] Saving result on {output_filepath}")
601
+ pil_image.save(output_filepath)
602
+ return detections,classeslist
603
+
604
+ def _run_ocr_on_image_array(
605
+ detector,
606
+ recognizer30,
607
+ recognizer50,
608
+ recognizer100,
609
+ inputname: str,
610
+ img: np.ndarray,
611
+ outputpath: str,
612
+ save_viz: bool = False,
613
+ ):
614
+ img_h, img_w = img.shape[:2]
615
+ detections, classeslist = process_detector(
616
+ detector=detector,
617
+ inputname=inputname,
618
+ npimage=img,
619
+ outputpath=outputpath,
620
+ issaveimg=save_viz,
621
+ )
622
+ resultobj = [dict(), dict()]
623
+ resultobj[0][0] = list()
624
+ for i in range(17):
625
+ resultobj[1][i] = []
626
+ for det in detections:
627
+ xmin, ymin, xmax, ymax = det["box"]
628
+ conf = det["confidence"]
629
+ if det["class_index"] == 0:
630
+ resultobj[0][0].append([xmin, ymin, xmax, ymax])
631
+ resultobj[1][det["class_index"]].append([xmin, ymin, xmax, ymax, conf, det["pred_char_count"]])
632
+
633
+ xmlstr = convert_to_xml_string3(img_w, img_h, inputname, classeslist, resultobj)
634
+ xmlstr = xmlstr.replace("&", "&amp;")
635
+ xmlstr = "<OCRDATASET>" + xmlstr + "</OCRDATASET>"
636
+ root = ET.fromstring(xmlstr)
637
+ eval_xml(root, logger=None)
638
+
639
+ alllineobj = []
640
+ tatelinecnt = 0
641
+ alllinecnt = 0
642
+
643
+ for idx, lineobj in enumerate(root.findall(".//LINE")):
644
+ xmin = int(lineobj.get("X"))
645
+ ymin = int(lineobj.get("Y"))
646
+ line_w = int(lineobj.get("WIDTH"))
647
+ line_h = int(lineobj.get("HEIGHT"))
648
+ try:
649
+ pred_char_cnt = float(lineobj.get("PRED_CHAR_CNT"))
650
+ except Exception:
651
+ pred_char_cnt = 100.0
652
+ if line_h > line_w:
653
+ tatelinecnt += 1
654
+ alllinecnt += 1
655
+ lineimg = img[ymin:ymin + line_h, xmin:xmin + line_w, :]
656
+ alllineobj.append(RecogLine(lineimg, idx, pred_char_cnt))
657
+
658
+ if len(alllineobj) == 0 and len(detections) > 0:
659
+ page = root.find("PAGE")
660
+ for idx, det in enumerate(detections):
661
+ xmin, ymin, xmax, ymax = det["box"]
662
+ line_w = int(xmax - xmin)
663
+ line_h = int(ymax - ymin)
664
+ if line_w <= 0 or line_h <= 0:
665
+ continue
666
+ line_elem = ET.SubElement(page, "LINE")
667
+ c_idx = int(det["class_index"])
668
+ type_name = "本文"
669
+ line_elem.set("TYPE", type_name)
670
+ line_elem.set("X", str(int(xmin)))
671
+ line_elem.set("Y", str(int(ymin)))
672
+ line_elem.set("WIDTH", str(line_w))
673
+ line_elem.set("HEIGHT", str(line_h))
674
+ line_elem.set("CONF", f"{det['confidence']:0.3f}")
675
+ pred_char_cnt = det.get("pred_char_count", 100.0)
676
+ line_elem.set("PRED_CHAR_CNT", f"{pred_char_cnt:0.3f}")
677
+ if line_h > line_w:
678
+ tatelinecnt += 1
679
+ alllinecnt += 1
680
+ lineimg = img[int(ymin):int(ymax), int(xmin):int(xmax), :]
681
+ alllineobj.append(RecogLine(lineimg, idx, pred_char_cnt))
682
+
683
+ resultlinesall = process_cascade(
684
+ alllineobj,
685
+ recognizer30,
686
+ recognizer50,
687
+ recognizer100,
688
+ is_cascade=True,
689
+ )
690
+
691
+ resjsonarray = []
692
+ text_layer_lines = []
693
+ for idx, lineobj in enumerate(root.findall(".//LINE")):
694
+ text = resultlinesall[idx] if idx < len(resultlinesall) else ""
695
+ lineobj.set("STRING", text)
696
+ xmin = int(lineobj.get("X"))
697
+ ymin = int(lineobj.get("Y"))
698
+ line_w = int(lineobj.get("WIDTH"))
699
+ line_h = int(lineobj.get("HEIGHT"))
700
+ is_vertical = line_h > line_w
701
+ try:
702
+ conf = float(lineobj.get("CONF"))
703
+ except Exception:
704
+ conf = 0.0
705
+
706
+ type_str = lineobj.get("TYPE", "")
707
+ c_idx = classeslist.index(type_str) if type_str in classeslist else 1
708
+ resjsonarray.append({
709
+ "boundingBox": [
710
+ [xmin, ymin],
711
+ [xmin, ymin + line_h],
712
+ [xmin + line_w, ymin],
713
+ [xmin + line_w, ymin + line_h],
714
+ ],
715
+ "id": idx,
716
+ "isVertical": "true" if is_vertical else "false",
717
+ "text": text,
718
+ "isTextline": "true",
719
+ "confidence": conf,
720
+ "class_index": c_idx,
721
+ })
722
+ text_layer_lines.append({
723
+ "x": xmin,
724
+ "y": ymin,
725
+ "width": line_w,
726
+ "height": line_h,
727
+ "text": text,
728
+ "is_vertical": is_vertical,
729
+ })
730
+
731
+ page_elem = root.find("PAGE")
732
+ page_xml = ET.tostring(page_elem, encoding="unicode")
733
+ page_text = "\n".join(resultlinesall)
734
+ markdown_text = build_markdown_text_from_page(page_elem)
735
+ return {
736
+ "page_xml": page_xml,
737
+ "text": page_text,
738
+ "markdown_text": markdown_text,
739
+ "json_lines": resjsonarray,
740
+ "text_layer_lines": text_layer_lines,
741
+ "img_width": img_w,
742
+ "img_height": img_h,
743
+ "img_name": inputname,
744
+ "line_count": alllinecnt,
745
+ "vertical_line_count": tatelinecnt,
746
+ }
747
+
748
+ def _text_layer_font_size(
749
+ width: float,
750
+ height: float,
751
+ text: str,
752
+ is_vertical: bool,
753
+ ):
754
+ """
755
+ フォントサイズは「行の進行方向」ではなく、
756
+ 文字の大きさを表す方向から決める。
757
+
758
+ 横書き: bbox の高さ
759
+ 縦書き: bbox の幅
760
+
761
+ 行全体の長さは _draw_text_layer_line() 側で別途調整する。
762
+ """
763
+ cross_size = width if is_vertical else height
764
+
765
+ # 元実装の 72pt 上限は、大きい見出し等で
766
+ # bbox と文字サイズが合わなくなるので撤廃する。
767
+ return max(1.0, cross_size * 0.95)
768
+
769
+
770
+ def _draw_text_layer_line(
771
+ canvas_obj,
772
+ line: dict,
773
+ img_width: int,
774
+ img_height: int,
775
+ page_width: float,
776
+ page_height: float,
777
+ visible: bool,
778
+ ):
779
+ """
780
+ OCR bbox に合わせて透明テキストを配置する。
781
+
782
+ 横書き:
783
+ - fontsize は bbox 高さから決める
784
+ - 実際の文字列幅を pdfmetrics.stringWidth() で取得
785
+ - setHorizScale() で bbox 幅に合わせる
786
+
787
+ 縦書き:
788
+ - fontsize は bbox 幅から決める
789
+ - bbox 高さ / 文字数 から目標の文字送りを求める
790
+ - setCharSpace() で縦方向の文字送りを合わせる
791
+
792
+ これにより、行頭だけでなく行末まで OCR bbox と
793
+ 埋め込みテキストの位置が合うようにする。
794
+ """
795
+ from reportlab.pdfbase import pdfmetrics
796
+
797
+ text = line["text"]
798
+ if not text:
799
+ return
800
+
801
+ scale_x = page_width / max(img_width, 1)
802
+ scale_y = page_height / max(img_height, 1)
803
+
804
+ # OCR画像座標 -> PDF座標
805
+ x = line["x"] * scale_x
806
+ y_top = page_height - line["y"] * scale_y
807
+
808
+ width = line["width"] * scale_x
809
+ height = line["height"] * scale_y
810
+
811
+ if width <= 0 or height <= 0:
812
+ return
813
+
814
+ is_vertical = bool(line["is_vertical"])
815
+
816
+ if is_vertical:
817
+ font_name = "HeiseiMin-W3"
818
+ else:
819
+ font_name = "HeiseiKakuGo-W5"
820
+
821
+ fontsize = _text_layer_font_size(
822
+ width=width,
823
+ height=height,
824
+ text=text,
825
+ is_vertical=is_vertical,
826
+ )
827
+
828
+ canvas_obj.saveState()
829
+
830
+ try:
831
+ # 可視化モードでは青色表示。
832
+ if visible:
833
+ canvas_obj.setFillColorRGB(0, 0, 1)
834
+
835
+ text_obj = canvas_obj.beginText()
836
+ text_obj.setFont(font_name, fontsize)
837
+
838
+ # PDFの透明テキストとしては alpha=0 だけに頼らず、
839
+ # Text Rendering Mode 3 (Invisible) を使う。
840
+ #
841
+ # visible=True のデバッグ表示時は通常描画。
842
+ text_obj.setTextRenderMode(0 if visible else 3)
843
+
844
+ if is_vertical:
845
+ #
846
+ # 縦書き
847
+ #
848
+ # 縦書きCIDフォントは text origin の x が
849
+ # おおむね文字セル中央になるので bbox 中央に配置。
850
+ #
851
+ draw_x = x + width * 0.5
852
+ draw_y = y_top
853
+
854
+ text_obj.setTextOrigin(draw_x, draw_y)
855
+
856
+ text_len = len(text)
857
+
858
+ if text_len > 1:
859
+ # OCR bbox が表す縦方向の1文字分のピッチ
860
+ target_pitch = height / text_len
861
+
862
+ # ReportLab の縦書きCIDフォントでは通常、
863
+ # fontsize が縦方向の基本 advance になる。
864
+ #
865
+ # vertical writing mode では charSpace の正方向が
866
+ # 下方向の advance を小さくする側に作用するため、
867
+ #
868
+ # actual_pitch = fontsize - char_space
869
+ #
870
+ # となるよう設定する。
871
+ vertical_char_space = fontsize - target_pitch
872
+
873
+ text_obj.setCharSpace(vertical_char_space)
874
+
875
+ text_obj.textOut(text)
876
+
877
+ else:
878
+ #
879
+ # 横書き
880
+ #
881
+ draw_x = x
882
+
883
+ # 横方向の累積ズレとは独立なので、
884
+ # baseline は従来の配置を基本的に維持する。
885
+ draw_y = (
886
+ y_top
887
+ - height
888
+ + max((height - fontsize) * 0.5, 0)
889
+ )
890
+
891
+ text_obj.setTextOrigin(draw_x, draw_y)
892
+
893
+ # この fontsize / font で本来必要になる文字列幅。
894
+ natural_width = pdfmetrics.stringWidth(
895
+ text,
896
+ font_name,
897
+ fontsize,
898
+ )
899
+
900
+ if natural_width > 1e-6:
901
+ # bbox 幅と完全に同じ advance にする。
902
+ #
903
+ # フォントサイズ(高さ)は変えず、
904
+ # 横方向だけを調整するのがポイント。
905
+ horiz_scale = (
906
+ 100.0 * width / natural_width
907
+ )
908
+
909
+ text_obj.setHorizScale(horiz_scale)
910
+
911
+ text_obj.textOut(text)
912
+
913
+ canvas_obj.drawText(text_obj)
914
+
915
+ finally:
916
+ canvas_obj.restoreState()
917
+
918
+ def _detach_pdf_page(page):
919
+ """
920
+ 1ページだけのPDFへ書き出して再読込し、
921
+ 他ページとの間接参照共有を切り離す。
922
+ """
923
+ from io import BytesIO
924
+ from pypdf import PdfReader, PdfWriter
925
+
926
+ buffer = BytesIO()
927
+
928
+ writer = PdfWriter()
929
+ writer.add_page(page)
930
+ writer.write(buffer)
931
+
932
+ buffer.seek(0)
933
+
934
+ reader = PdfReader(buffer)
935
+
936
+ # bufferとreaderの寿命をページ処理中まで維持するため、
937
+ # 両方を返す。
938
+ return reader.pages[0], reader, buffer
939
+ def embed_text_layer_pdf(
940
+ input_pdf: str,
941
+ output_pdf: str,
942
+ page_results: list,
943
+ visible_text: bool = False,
944
+ ):
945
+ try:
946
+ from io import BytesIO
947
+ from pathlib import Path
948
+
949
+ from pypdf import PdfReader, PdfWriter
950
+ from reportlab.pdfgen import canvas
951
+ from reportlab.pdfbase import pdfmetrics
952
+ from reportlab.pdfbase.cidfonts import UnicodeCIDFont
953
+ except ImportError as exc:
954
+ raise RuntimeError(
955
+ "PDF text-layer output requires pypdf and reportlab. "
956
+ "Install dependencies from requirements.txt."
957
+ ) from exc
958
+
959
+ output_path = Path(output_pdf)
960
+ input_path = Path(input_pdf)
961
+
962
+ output_path.parent.mkdir(parents=True, exist_ok=True)
963
+
964
+ if output_path.resolve() == input_path.resolve():
965
+ raise ValueError(
966
+ "Output PDF must be different from the input PDF."
967
+ )
968
+
969
+ pdfmetrics.registerFont(
970
+ UnicodeCIDFont("HeiseiKakuGo-W5", isVertical=False)
971
+ )
972
+ pdfmetrics.registerFont(
973
+ UnicodeCIDFont("HeiseiMin-W3", isVertical=True)
974
+ )
975
+
976
+ source_reader = PdfReader(str(input_path))
977
+
978
+ if len(source_reader.pages) != len(page_results):
979
+ raise ValueError(
980
+ "PDF page count mismatch: "
981
+ f"{len(source_reader.pages)} pages, "
982
+ f"{len(page_results)} OCR results"
983
+ )
984
+
985
+ #
986
+ # 1. 入力PDFを一度メモリ上へ再書き出しする。
987
+ #
988
+ # 問題のあるPDFでページ間共有されているContentsやリソースを、
989
+ # pypdfが扱いやすい形へ正規化する。
990
+ #
991
+ normalized_buffer = BytesIO()
992
+ normalized_writer = PdfWriter()
993
+
994
+ for source_page in source_reader.pages:
995
+ normalized_writer.add_page(source_page)
996
+
997
+ normalized_writer.write(normalized_buffer)
998
+ normalized_buffer.seek(0)
999
+
1000
+ normalized_reader = PdfReader(normalized_buffer)
1001
+
1002
+ #
1003
+ # 2. 全ページ分のオーバーレイを1つのPDFとして生成する。
1004
+ #
1005
+ # ページごとにCanvas/PdfReaderを作らず、
1006
+ # ReportLabのページ境界を明確にする。
1007
+ #
1008
+ overlay_buffer = BytesIO()
1009
+
1010
+ first_page = normalized_reader.pages[0]
1011
+ first_width = float(first_page.mediabox.width)
1012
+ first_height = float(first_page.mediabox.height)
1013
+
1014
+ overlay_canvas = canvas.Canvas(
1015
+ overlay_buffer,
1016
+ pagesize=(first_width, first_height),
1017
+ )
1018
+
1019
+ for page_index, (page, page_result) in enumerate(
1020
+ zip(normalized_reader.pages, page_results)
1021
+ ):
1022
+ page_width = float(page.mediabox.width)
1023
+ page_height = float(page.mediabox.height)
1024
+
1025
+ overlay_canvas.setPageSize((page_width, page_height))
1026
+
1027
+ for line in page_result["text_layer_lines"]:
1028
+ _draw_text_layer_line(
1029
+ canvas_obj=overlay_canvas,
1030
+ line=line,
1031
+ img_width=page_result["img_width"],
1032
+ img_height=page_result["img_height"],
1033
+ page_width=page_width,
1034
+ page_height=page_height,
1035
+ visible=visible_text,
1036
+ )
1037
+
1038
+ #
1039
+ # 最終ページも含めて必ずページを確定する。
1040
+ #
1041
+ overlay_canvas.showPage()
1042
+
1043
+ overlay_canvas.save()
1044
+ overlay_buffer.seek(0)
1045
+
1046
+ overlay_reader = PdfReader(overlay_buffer)
1047
+
1048
+ if len(overlay_reader.pages) != len(normalized_reader.pages):
1049
+ raise RuntimeError(
1050
+ "Overlay PDF page count mismatch: "
1051
+ f"{len(overlay_reader.pages)} overlay pages, "
1052
+ f"{len(normalized_reader.pages)} source pages"
1053
+ )
1054
+
1055
+ #
1056
+ # 3. ページごとに対応するオーバーレイをマージする。
1057
+ #
1058
+ # writer.add_page()の戻り値を使うことで、
1059
+ # reader側のページを直接変更しない。
1060
+ #
1061
+ output_writer = PdfWriter()
1062
+
1063
+ detached_objects = []
1064
+
1065
+ for page_index in range(len(normalized_reader.pages)):
1066
+ detached_page, detached_reader, detached_buffer = _detach_pdf_page(
1067
+ normalized_reader.pages[page_index]
1068
+ )
1069
+
1070
+ # write完了までReaderとBufferを生存させる。
1071
+ detached_objects.append(
1072
+ (detached_reader, detached_buffer)
1073
+ )
1074
+
1075
+ output_page = output_writer.add_page(detached_page)
1076
+
1077
+ output_page.merge_page(
1078
+ overlay_reader.pages[page_index],
1079
+ expand=False,
1080
+ )
1081
+
1082
+ with output_path.open("wb") as wf:
1083
+ output_writer.write(wf)
1084
+
1085
+
1086
+
1087
+ def process_pdf_documents(args, pdf_paths: list[str]):
1088
+ try:
1089
+ import pypdfium2
1090
+ except ImportError as exc:
1091
+ raise RuntimeError(
1092
+ "PDF input requires pypdfium2. Install dependencies from requirements.txt."
1093
+ ) from exc
1094
+ try:
1095
+ import pypdf # noqa: F401
1096
+ except ImportError as exc:
1097
+ raise RuntimeError(
1098
+ "PDF text-layer output requires pypdf. Install dependencies from requirements.txt."
1099
+ ) from exc
1100
+
1101
+ if len(pdf_paths) > 1 and getattr(args, "pdf_output", None):
1102
+ print("--pdf-output can only be used with a single PDF input.")
1103
+ return
1104
+
1105
+ if not os.path.exists(args.output):
1106
+ print("Output Directory is not found.")
1107
+ return
1108
+
1109
+ print("[INFO] Intialize Model")
1110
+ detector = get_detector(args)
1111
+ recognizer100 = get_recognizer(args=args)
1112
+ recognizer30 = get_recognizer(args=args, weights_path=args.rec_weights30)
1113
+ recognizer50 = get_recognizer(args=args, weights_path=args.rec_weights50)
1114
+
1115
+ render_scale = max(float(getattr(args, "pdf_render_dpi", 150)), 1.0) / 72.0
1116
+
1117
+ for pdf_path in pdf_paths:
1118
+ start = time.time()
1119
+ pdf_path_obj = Path(pdf_path)
1120
+ output_stem = pdf_path_obj.stem
1121
+ pdf_doc = pypdfium2.PdfDocument(str(pdf_path_obj))
1122
+ page_results = []
1123
+ all_json_contents = []
1124
+ page_infos = []
1125
+ all_text_pages = []
1126
+ all_page_xml = []
1127
+ separate_page_outputs = should_output_pdf_pages_separately(
1128
+ len(pdf_doc),
1129
+ getattr(args, "pdf_page_output", True),
1130
+ )
1131
+
1132
+ for page_index in range(len(pdf_doc)):
1133
+ page_name = f"{output_stem}_{page_index + 1:05}.png"
1134
+ print(f"[INFO] OCR PDF page {page_index + 1}/{len(pdf_doc)}: {pdf_path_obj.name}")
1135
+ rendered_pages = pdf_doc.render(
1136
+ pypdfium2.PdfBitmap.to_pil,
1137
+ page_indices=[page_index],
1138
+ scale=render_scale,
1139
+ )
1140
+ pil_image = next(iter(rendered_pages)).convert("RGB")
1141
+ img = np.array(pil_image)
1142
+ page_result = _run_ocr_on_image_array(
1143
+ detector=detector,
1144
+ recognizer30=recognizer30,
1145
+ recognizer50=recognizer50,
1146
+ recognizer100=recognizer100,
1147
+ inputname=page_name,
1148
+ img=img,
1149
+ outputpath=args.output,
1150
+ save_viz=args.viz,
1151
+ )
1152
+ page_results.append(page_result)
1153
+ all_json_contents.append(page_result["json_lines"])
1154
+ page_infos.append({
1155
+ "page_index": page_index,
1156
+ "img_width": page_result["img_width"],
1157
+ "img_height": page_result["img_height"],
1158
+ "img_name": page_result["img_name"],
1159
+ })
1160
+ all_text_pages.append(page_result["text"])
1161
+ all_page_xml.append(page_result["page_xml"])
1162
+ write_pdf_page_outputs(
1163
+ args.output,
1164
+ output_stem,
1165
+ page_index,
1166
+ page_result,
1167
+ source_path=str(pdf_path_obj),
1168
+ write_json=separate_page_outputs,
1169
+ write_xml=separate_page_outputs and not getattr(args, "json_only", False),
1170
+ write_txt=separate_page_outputs and not getattr(args, "json_only", False),
1171
+ )
1172
+
1173
+ pdf_doc.close()
1174
+
1175
+ if not getattr(args, "json_only", False) and not separate_page_outputs:
1176
+ with open(os.path.join(args.output, output_stem + ".xml"), "w", encoding="utf-8") as wf:
1177
+ wf.write("<OCRDATASET>\n")
1178
+ wf.write("\n".join(all_page_xml))
1179
+ wf.write("\n</OCRDATASET>")
1180
+ with open(os.path.join(args.output, output_stem + ".txt"), "w", encoding="utf-8") as wtf:
1181
+ wtf.write("\n\n".join(all_text_pages))
1182
+
1183
+ if not separate_page_outputs:
1184
+ with open(os.path.join(args.output, output_stem + ".json"), "w", encoding="utf-8") as wf:
1185
+ alljsonobj = {
1186
+ "contents": all_json_contents,
1187
+ "pdfinfo": {
1188
+ "pdf_path": str(pdf_path_obj),
1189
+ "pdf_name": pdf_path_obj.name,
1190
+ "page_count": len(page_results),
1191
+ "render_dpi": float(getattr(args, "pdf_render_dpi", 150)),
1192
+ },
1193
+ "pages": page_infos,
1194
+ }
1195
+ wf.write(json.dumps(alljsonobj, ensure_ascii=False, indent=2))
1196
+
1197
+ output_pdf = getattr(args, "pdf_output", None)
1198
+ if not output_pdf:
1199
+ output_pdf = os.path.join(args.output, output_stem + "_text.pdf")
1200
+ print(f"[INFO] Writing text-layer PDF: {output_pdf}")
1201
+ embed_text_layer_pdf(
1202
+ input_pdf=str(pdf_path_obj),
1203
+ output_pdf=output_pdf,
1204
+ page_results=page_results,
1205
+ visible_text=getattr(args, "pdf_visible_text", False),
1206
+ )
1207
+ print("Total PDF calculation time:", time.time() - start)
1208
+
1209
+ def process(args):
1210
+ rawinputpathlist=[]
1211
+ inputpathlist=[]
1212
+ pdfpathlist=[]
1213
+ if args.sourcedir is not None:
1214
+ for inputpath in glob.glob(os.path.join(args.sourcedir,"*")):
1215
+ rawinputpathlist.append(inputpath)
1216
+ if args.sourceimg is not None:
1217
+ rawinputpathlist.append(args.sourceimg)
1218
+ if args.sourcepdf is not None:
1219
+ pdfpathlist.append(args.sourcepdf)
1220
+ for inputpath in rawinputpathlist:
1221
+ ext=inputpath.split(".")[-1]
1222
+ if ext.lower() in ["jpg","png","tiff","jp2","tif","jpeg","bmp","webp"]:
1223
+ inputpathlist.append(inputpath)
1224
+ elif ext.lower() in ["pdf",]:
1225
+ pdfpathlist.append(inputpath)
1226
+
1227
+ if len(pdfpathlist) > 0:
1228
+ process_pdf_documents(args, pdfpathlist)
1229
+ if len(inputpathlist) == 0:
1230
+ return
1231
+ if len(inputpathlist)==0:
1232
+ print("Images are not found.")
1233
+ return
1234
+ if not os.path.exists(args.output):
1235
+ print("Output Directory is not found.")
1236
+ return
1237
+
1238
+ detector=get_detector(args)
1239
+ recognizer100=get_recognizer(args=args)
1240
+ recognizer30=get_recognizer(args=args,weights_path=args.rec_weights30)
1241
+ recognizer50=get_recognizer(args=args,weights_path=args.rec_weights50)
1242
+ tatelinecnt=0
1243
+ alllinecnt=0
1244
+
1245
+ for inputpath in inputpathlist:
1246
+ ext=inputpath.split(".")[-1]
1247
+ pil_image = Image.open(inputpath).convert('RGB')
1248
+ img = np.array(pil_image)
1249
+ start = time.time()
1250
+ allxmlstr="<OCRDATASET>\n"
1251
+ alltextlist=[]
1252
+ resjsonarray=[]
1253
+ imgname=os.path.basename(inputpath)
1254
+ img_h,img_w=img.shape[:2]
1255
+ detections,classeslist=process_detector(detector,inputname=imgname,npimage=img,outputpath=args.output,issaveimg=args.viz)
1256
+ e1=time.time()
1257
+ resultobj=[dict(),dict()]
1258
+ resultobj[0][0]=list()
1259
+ for i in range(17):
1260
+ resultobj[1][i]=[]
1261
+ for det in detections:
1262
+ xmin,ymin,xmax,ymax=det["box"]
1263
+ conf=det["confidence"]
1264
+ char_count=det["pred_char_count"]
1265
+ if det["class_index"]==0:
1266
+ resultobj[0][0].append([xmin,ymin,xmax,ymax])
1267
+ resultobj[1][det["class_index"]].append([xmin,ymin,xmax,ymax,conf,char_count])
1268
+ xmlstr=convert_to_xml_string3(img_w, img_h, imgname, classeslist, resultobj)
1269
+ xmlstr = xmlstr.replace("&", "&amp;")
1270
+ xmlstr="<OCRDATASET>"+xmlstr+"</OCRDATASET>"
1271
+ # print(xmlstr)
1272
+ root = ET.fromstring(xmlstr)
1273
+ eval_xml(root, logger=None)
1274
+ alllineobj = []
1275
+ alltextlist = []
1276
+
1277
+ for idx, lineobj in enumerate(root.findall(".//LINE")):
1278
+ xmin = int(lineobj.get("X"))
1279
+ ymin = int(lineobj.get("Y"))
1280
+ line_w = int(lineobj.get("WIDTH"))
1281
+ line_h = int(lineobj.get("HEIGHT"))
1282
+ try:
1283
+ pred_char_cnt = float(lineobj.get("PRED_CHAR_CNT"))
1284
+ except:
1285
+ pred_char_cnt = 100.0
1286
+
1287
+ if line_h > line_w:
1288
+ tatelinecnt += 1
1289
+ alllinecnt += 1
1290
+ # 部分画像の切り出し
1291
+ lineimg = img[ymin:ymin+line_h, xmin:xmin+line_w, :]
1292
+ linerecogobj = RecogLine(lineimg, idx, pred_char_cnt)
1293
+ alllineobj.append(linerecogobj)
1294
+
1295
+ if len(alllineobj) == 0 and len(detections) > 0:
1296
+ # LINE 要素がないが検出がある場合は検出領域を LINE として扱う
1297
+ page = root.find("PAGE")
1298
+ for idx, det in enumerate(detections):
1299
+ xmin, ymin, xmax, ymax = det["box"]
1300
+ line_w = int(xmax - xmin)
1301
+ line_h = int(ymax - ymin)
1302
+ if line_w > 0 and line_h > 0:
1303
+ line_elem = ET.SubElement(page, "LINE")
1304
+ c_idx = int(det["class_index"])
1305
+ type_name = "本文"
1306
+ line_elem.set("TYPE", type_name)
1307
+ line_elem.set("X", str(int(xmin)))
1308
+ line_elem.set("Y", str(int(ymin)))
1309
+ line_elem.set("WIDTH", str(line_w))
1310
+ line_elem.set("HEIGHT", str(line_h))
1311
+ line_elem.set("CONF", f"{det['confidence']:0.3f}")
1312
+ pred_char_cnt = det.get("pred_char_count", 100.0)
1313
+ line_elem.set("PRED_CHAR_CNT", f"{pred_char_cnt:0.3f}")
1314
+ if line_h > line_w:
1315
+ tatelinecnt += 1
1316
+ alllinecnt += 1
1317
+ lineimg = img[int(ymin):int(ymax), int(xmin):int(xmax), :]
1318
+ linerecogobj = RecogLine(lineimg, idx, pred_char_cnt)
1319
+ alllineobj.append(linerecogobj)
1320
+
1321
+ # 認識プロセス
1322
+ resultlinesall = process_cascade(
1323
+ alllineobj, recognizer30, recognizer50, recognizer100, is_cascade=True
1324
+ )
1325
+ alltextlist.append("\n".join(resultlinesall))
1326
+
1327
+ for idx,lineobj in enumerate(root.findall(".//LINE")):
1328
+ lineobj.set("STRING",resultlinesall[idx])
1329
+ xmin=int(lineobj.get("X"))
1330
+ ymin=int(lineobj.get("Y"))
1331
+ line_w=int(lineobj.get("WIDTH"))
1332
+ line_h=int(lineobj.get("HEIGHT"))
1333
+ try:
1334
+ conf=float(lineobj.get("CONF"))
1335
+ except:
1336
+ conf=0.0
1337
+
1338
+ # XML TYPE -> c_idx
1339
+ type_str = lineobj.get("TYPE", "")
1340
+ c_idx = classeslist.index(type_str) if type_str in classeslist else 1
1341
+
1342
+ jsonobj={"boundingBox": [[xmin,ymin],[xmin,ymin+line_h],[xmin+line_w,ymin],[xmin+line_w,ymin+line_h]],
1343
+ "id": idx,"isVertical": "true" if line_h > line_w else "false","text": resultlinesall[idx],"isTextline": "true","confidence": conf, "class_index": c_idx}
1344
+ resjsonarray.append(jsonobj)
1345
+
1346
+ allxmlstr+=(ET.tostring(root.find("PAGE"), encoding='unicode')+"\n")
1347
+ allxmlstr+="</OCRDATASET>"
1348
+ if alllinecnt>0 and tatelinecnt/alllinecnt>0.5:
1349
+ alltextlist=alltextlist[::-1]
1350
+ output_stem = os.path.splitext(os.path.basename(inputpath))[0]
1351
+
1352
+ if not getattr(args, "json_only", False):
1353
+ with open(os.path.join(args.output,output_stem+".xml"),"w",encoding="utf-8") as wf:
1354
+ wf.write(allxmlstr)
1355
+
1356
+ with open(os.path.join(args.output,output_stem+".json"),"w",encoding="utf-8") as wf:
1357
+ alljsonobj={
1358
+ "contents":[resjsonarray],
1359
+ "imginfo": {
1360
+ "img_width": img_w,
1361
+ "img_height": img_h,
1362
+ "img_path":inputpath,
1363
+ "img_name":os.path.basename(inputpath)
1364
+ }
1365
+ }
1366
+ alljsonstr=json.dumps(alljsonobj,ensure_ascii=False,indent=2)
1367
+ wf.write(alljsonstr)
1368
+
1369
+ if not getattr(args, "json_only", False):
1370
+ with open(os.path.join(args.output,output_stem+".txt"),"w",encoding="utf-8") as wtf:
1371
+ wtf.write("\n".join(alltextlist))
1372
+ print("Total calculation time (Detection + Recognition):",time.time()-start)
1373
+
1374
+ def main(*, download_models=False):
1375
+ import argparse
1376
+ from pathlib import Path
1377
+ base_dir = Path(__file__).resolve().parent
1378
+ parser = argparse.ArgumentParser(
1379
+ description="Arguments for NDLkotenOCR-Lite",
1380
+ epilog="Run 'ndlocr-lite gui' to launch the desktop GUI." if download_models else None,
1381
+ )
1382
+
1383
+ parser.add_argument("--sourcedir", type=str, required=False, help="Path to image directory")
1384
+ parser.add_argument("--sourceimg", type=str, required=False, help="Path to image directory")
1385
+ parser.add_argument("--sourcepdf", type=str, required=False, help="Path to source PDF")
1386
+ parser.add_argument("--output", type=str, required=True, help="Path to output directory")
1387
+ parser.add_argument("--viz", type=bool, required=False, help="Save visualized image",default=False)
1388
+ parser.add_argument("--pdf-output", type=str, required=False, help="Path to output text-layer PDF")
1389
+ parser.add_argument("--pdf-render-dpi", "--pdf-dpi", dest="pdf_render_dpi", type=float, required=False, default=150.0, help="DPI used to render PDF pages for OCR")
1390
+ parser.add_argument("--pdf-page-output", action=argparse.BooleanOptionalAction, default=True, help="When a multi-page PDF is input, output TXT/JSON/XML per page")
1391
+ parser.add_argument("--pdf-visible-text", action="store_true", help="Draw PDF text layer visibly in blue for debugging")
1392
+ parser.add_argument("--det-weights", type=str, required=False, help="Path to deim onnx file", default=None if download_models else str(base_dir / "model" / "deim-s-1024x1024.onnx"))
1393
+ parser.add_argument("--det-classes", type=str, required=False, help="Path to list of class in yaml file", default=str(base_dir / "config" / "ndl.yaml"))
1394
+ parser.add_argument("--det-score-threshold", type=float, required=False, default=0.2)
1395
+ parser.add_argument("--det-conf-threshold", type=float, required=False, default=0.25)
1396
+ parser.add_argument("--det-iou-threshold", type=float, required=False, default=0.2)
1397
+ parser.add_argument("--simple-mode", type=bool, required=False, help="Read line with one model(Setting this option to True will slow down processing, but it simplifies the architecture and may slightly improve accuracy.)",default=False)
1398
+ parser.add_argument("--rec-weights30", type=str, required=False, help="Path to parseq-tiny onnx file", default=None if download_models else str(base_dir / "model" / "parseq-ndl-24x256-30-tiny-189epoch-tegaki3-r8data-202604.onnx"))
1399
+ parser.add_argument("--rec-weights50", type=str, required=False, help="Path to parseq-tiny onnx file", default=None if download_models else str(base_dir / "model" / "parseq-ndl-24x384-50-tiny-300epoch-tegaki3-r8data-202604.onnx"))
1400
+ parser.add_argument("--rec-weights", type=str, required=False, help="Path to parseq-tiny onnx file", default=None if download_models else str(base_dir / "model" / "parseq-ndl-24x768-100-tiny-153epoch-tegaki3-r8data-202604.onnx"))
1401
+ parser.add_argument("--rec-classes", type=str, required=False, help="Path to list of class in yaml file", default=str(base_dir / "config" / "NDLmoji.yaml"))
1402
+ parser.add_argument("--device", type=str, required=False, help="Device use (cpu or cuda)", choices=["cpu", "cuda"], default="cpu")
1403
+ parser.add_argument("--enable-tcy", action="store_true", dest="enable_tcy", default=False, help="Enable tate-chuu-yoko (縦中横) detection for vertical text (e.g. newspaper OCR)")
1404
+ parser.add_argument("--json-only", action="store_true", help="Disable .xml and .txt output and only output JSON")
1405
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
1406
+ args, remaining = parser.parse_known_args()
1407
+ if args.enable_tcy and remaining:
1408
+ from tcy_wrapper import add_tcy_arguments
1409
+ tcy_parser = add_tcy_arguments(parser)
1410
+ tcy_args = tcy_parser.parse_args(remaining)
1411
+ for k, v in vars(tcy_args).items():
1412
+ if v is not None:
1413
+ setattr(args, k, v)
1414
+ elif remaining:
1415
+ parser.error("unrecognized arguments: " + " ".join(remaining))
1416
+ if download_models:
1417
+ from model_download import resolve_model_paths
1418
+ try:
1419
+ resolve_model_paths(args, base_dir / "model")
1420
+ except RuntimeError as error:
1421
+ parser.error(str(error))
1422
+ process(args)
1423
+
1424
+ if __name__=="__main__":
1425
+ main()