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,366 @@
1
+ # Copyright (c) 2023, National Diet Library, Japan
2
+ #
3
+ # This software is released under the CC BY 4.0.
4
+ # https://creativecommons.org/licenses/by/4.0/
5
+
6
+
7
+ import numpy as np
8
+
9
+
10
+ class BlockNode:
11
+ """
12
+ Node class for document block tree
13
+ """
14
+
15
+ def __init__(self, x0, y0, x1, y1, parent):
16
+ self.x0 = int(x0)
17
+ self.y0 = int(y0)
18
+ self.x1 = int(x1)
19
+ self.y1 = int(y1)
20
+ self.parent = parent
21
+ self.children = []
22
+ self.line_idx = []
23
+ self.num_lines = 0
24
+ self.num_vertical_lines = 0
25
+
26
+ def get_coords(self):
27
+ return self.x0, self.y0, self.x1, self.y1
28
+
29
+ def append(self, child):
30
+ self.children.append(child)
31
+
32
+ def is_x_split(self):
33
+ _, y0, _, y1 = self.get_coords()
34
+ for child in self.children:
35
+ _, c0, _, c1 = child.get_coords()
36
+ if (y0, y1) != (c0, c1):
37
+ return False
38
+ return True
39
+
40
+ def is_vertical(self):
41
+ return self.num_lines < self.num_vertical_lines * 2
42
+
43
+
44
+ def calc_max_gap(hist):
45
+ """
46
+ Experimental code to replace `calc_min_span` which is not functional yet.
47
+ ---
48
+ hist: [N], int
49
+ """
50
+ if 1 == hist.size:
51
+ return 0, 1, 0
52
+ is_positive = 0 < hist
53
+ if 0 == is_positive.sum():
54
+ return 0, len(hist), 0
55
+ m = np.median(hist[is_positive])
56
+ diff = np.diff(np.concatenate(([0], hist < m, [0])))
57
+ area_start = np.where(diff == 1)[0]
58
+ area_end = np.where(diff == -1)[0]
59
+ areas = [(m - hist[start:end]).sum()
60
+ for start, end in zip(area_start, area_end)]
61
+ if 0 == len(areas):
62
+ return 0, hist.size, 0
63
+ i_max = np.argmax(areas)
64
+ return area_start[i_max], area_end[i_max], areas[i_max]
65
+
66
+
67
+ def calc_min_span(hist):
68
+ """
69
+ hist: [N], int
70
+ """
71
+ if 1 == hist.size:
72
+ return 0, 1, hist
73
+ min_val = hist.min()
74
+ max_val = hist.max()
75
+ diff = np.diff(np.concatenate(([0], hist == min_val, [0])))
76
+ start_idx = np.where(diff == 1)[0]
77
+ end_idx = np.where(diff == -1)[0]
78
+ i = np.argmax(end_idx - start_idx)
79
+ return start_idx[i], end_idx[i], -min_val/max_val if 0. < max_val else 0.
80
+
81
+
82
+ def calc_hist(table, x0, y0, x1, y1):
83
+ """
84
+ table: [H, W], int
85
+ """
86
+ x_hist = table[y0:y1:, x0:x1].sum(axis=0)
87
+ y_hist = table[y0:y1:, x0:x1].sum(axis=1)
88
+ return x_hist, y_hist
89
+
90
+
91
+ def split(parent, table, x0=None, y0=None, x1=None, y1=None):
92
+ """
93
+ Call `block_xy_cut` recursively
94
+ """
95
+ x0 = parent.x0 if x0 is None else x0
96
+ y0 = parent.y0 if y0 is None else y0
97
+ x1 = parent.x1 if x1 is None else x1
98
+ y1 = parent.y1 if y1 is None else y1
99
+ if not (x0 < x1 and y0 < y1):
100
+ return
101
+ if (x0, y0, x1, y1) == parent.get_coords():
102
+ return
103
+ child = BlockNode(x0, y0, x1, y1, parent)
104
+ parent.append(child)
105
+ block_xy_cut(table, child)
106
+
107
+
108
+ def split_x(parent, table, val, x0, x1):
109
+ """
110
+ Call `split`
111
+ """
112
+ split(parent, table, x1=x0)
113
+ split(parent, table, x0=x0, x1=x1)
114
+ split(parent, table, x0=x1)
115
+
116
+
117
+ def split_y(parent, table, val, y0, y1):
118
+ """
119
+ Call `split`
120
+ """
121
+ split(parent, table, y1=y0)
122
+ split(parent, table, y0=y0, y1=y1)
123
+ split(parent, table, y0=y1)
124
+
125
+
126
+ def block_xy_cut(table, me_node):
127
+ """
128
+ table : [H, W], int
129
+ me_node: BlockNode
130
+ """
131
+ x0, y0, x1, y1 = me_node.get_coords()
132
+ x_hist, y_hist = calc_hist(table, x0, y0, x1, y1)
133
+ x_beg, x_end, x_val = calc_min_span(x_hist)
134
+ y_beg, y_end, y_val = calc_min_span(y_hist)
135
+ x_beg += x0
136
+ x_end += x0
137
+ y_beg += y0
138
+ y_end += y0
139
+ if (x0, x1, y0, y1) == (x_beg, x_end, y_beg, y_end):
140
+ return
141
+ if y_val < x_val:
142
+ split_x(me_node, table, x_val, x_beg, x_end)
143
+ elif x_val < y_val:
144
+ split_y(me_node, table, y_val, y_beg, y_end)
145
+ elif (x_end - x_beg) < (y_end - y_beg):
146
+ split_y(me_node, table, y_val, y_beg, y_end)
147
+ else:
148
+ split_x(me_node, table, x_val, x_beg, x_end)
149
+
150
+
151
+ def get_optimal_grid(bboxes):
152
+ """
153
+ Determine optimal grid size from bboxes
154
+ ---
155
+ num: int
156
+ """
157
+ num = len(bboxes)
158
+ grid_size = 100 * np.sqrt(num)
159
+ return grid_size
160
+
161
+
162
+ def normalize_bboxes(bboxes, grid, scale=1.0, tolerance=0.25):
163
+ """
164
+ bboxes: [N, 4], int
165
+ grid : int
166
+ """
167
+ # Make width and height non-negative
168
+ bboxes[:, 2] = np.where(bboxes[:, 0] < bboxes[:, 2],
169
+ bboxes[:, 2], bboxes[:, 0])
170
+ bboxes[:, 3] = np.where(bboxes[:, 1] < bboxes[:, 3],
171
+ bboxes[:, 3], bboxes[:, 1])
172
+ # Dilation (or erosion)
173
+ if 1.0 != scale:
174
+ w = bboxes[:, 2] - bboxes[:, 0]
175
+ h = bboxes[:, 3] - bboxes[:, 1]
176
+ m = np.median(np.minimum(w, h))
177
+ lower = m * (1.0 - tolerance)
178
+ upper = m * (1.0 + tolerance)
179
+ _x = np.logical_and(w < h, lower <= w, w < upper)
180
+ _y = np.logical_and(h < w, lower <= h, h < upper)
181
+ bboxes[_x, 0] -= ((scale-1.0) * w[_x] // 2).astype(np.int64)
182
+ bboxes[_x, 2] += ((scale-1.0) * w[_x] // 2).astype(np.int64)
183
+ bboxes[_y, 1] -= ((scale-1.0) * h[_y] // 2).astype(np.int64)
184
+ bboxes[_y, 3] += ((scale-1.0) * h[_y] // 2).astype(np.int64)
185
+ # Coarse-grain
186
+ x_min = bboxes[:, 0].min()
187
+ y_min = bboxes[:, 1].min()
188
+ w_page = bboxes[:, 2].max() - x_min
189
+ h_page = bboxes[:, 3].max() - y_min
190
+ x_grid = grid if w_page < h_page else grid * (w_page/h_page)
191
+ y_grid = grid if h_page < w_page else grid * (h_page/w_page)
192
+ bboxes[:, 0] = (bboxes[:, 0] - x_min) * x_grid // w_page
193
+ bboxes[:, 1] = (bboxes[:, 1] - y_min) * y_grid // h_page
194
+ bboxes[:, 2] = (bboxes[:, 2] - x_min) * x_grid // w_page
195
+ bboxes[:, 3] = (bboxes[:, 3] - y_min) * y_grid // h_page
196
+ # Avoid negative indices
197
+ bboxes = np.where(bboxes < 0, 0, bboxes)
198
+ return bboxes
199
+
200
+
201
+ def make_mesh_table(bboxes):
202
+ """
203
+ bboxes: [N, 4], int, normalized
204
+ """
205
+ x_grid = bboxes[:, 2].max() + 1
206
+ y_grid = bboxes[:, 3].max() + 1
207
+ table = np.zeros((y_grid, x_grid)).astype(np.int32)
208
+ for bbox in bboxes:
209
+ x0, y0, x1, y1 = bbox
210
+ table[y0:y1, x0:x1] = 1
211
+ return table
212
+
213
+
214
+ def get_ranking(node, ranks, rank=0):
215
+ """
216
+ node : BlockNode
217
+ ranks: [N], int, where N is number of bboxes
218
+ rank : int
219
+ """
220
+ for i in node.line_idx:
221
+ ranks[i] = rank
222
+ rank += 1
223
+ for child in node.children:
224
+ rank = get_ranking(child, ranks, rank)
225
+ return rank
226
+
227
+
228
+ def calc_iou(box, boxes):
229
+ """
230
+ IoU of 1 v.s. many
231
+ ---
232
+ box : [4], int
233
+ boxes: [N,4], int
234
+ """
235
+ x0 = np.maximum(box[0], boxes[:, 0])
236
+ y0 = np.maximum(box[1], boxes[:, 1])
237
+ x1 = np.minimum(box[2], boxes[:, 2])
238
+ y1 = np.minimum(box[3], boxes[:, 3])
239
+ inter_area = np.maximum(0, x1 - x0 + 1) * np.maximum(0, y1 - y0 + 1)
240
+ box_area = (box[2] - boxes[:, 0] + 1) * (box[3] - boxes[:, 1] + 1)
241
+ boxes_area = (boxes[:, 2] - box[0] + 1) * (boxes[:, 3] - box[1] + 1)
242
+ with np.errstate(divide='ignore', invalid='ignore'):
243
+ iou = inter_area / (box_area + boxes_area - inter_area)
244
+ return iou
245
+
246
+
247
+ def get_block_node_bboxes(root):
248
+ """
249
+ root: BlockNode
250
+ """
251
+ bboxes = []
252
+ routers = []
253
+
254
+ def collect(node, router):
255
+ if 0 == len(node.children):
256
+ bboxes.append(node.get_coords())
257
+ routers.append(router)
258
+ for i, child in enumerate(node.children):
259
+ collect(child, router + [i])
260
+ collect(root, [])
261
+ bboxes = np.array(bboxes)
262
+ return routers, bboxes
263
+
264
+
265
+ def route_tree(root, router):
266
+ """
267
+ root : BlockNode
268
+ router: list of int
269
+ """
270
+ node = root
271
+ for i in router:
272
+ node = node.children[i]
273
+ return node
274
+
275
+
276
+ def assign_bbox_to_node(root, bboxes):
277
+ """
278
+ Find optimal (= max IoU) node to assign a bbox
279
+ ---
280
+ root : BlockNode
281
+ bboxes: [N,4], int
282
+ """
283
+ routers, leaves = get_block_node_bboxes(root)
284
+ for i, bbox in enumerate(bboxes):
285
+ iou = calc_iou(bbox, leaves)
286
+ j = np.nanargmax(iou)
287
+ route_tree(root, routers[j]).line_idx.append(i)
288
+
289
+
290
+ def sort_nodes(node, bboxes):
291
+ """
292
+ Sort nodes based on assinged lines
293
+ ---
294
+ node : BlockNode
295
+ bboxes: [N,4], int
296
+ NOTE : When splitting up and down, the reading order is always up to down.
297
+ Branches should be made so that the upper side is first in depth first
298
+ order. When splitting left and right, the order changes depending on
299
+ whether the content is written vertically or horizontally.
300
+ """
301
+ if 0 < len(node.line_idx):
302
+ w = bboxes[node.line_idx, 2] - bboxes[node.line_idx, 0]
303
+ h = bboxes[node.line_idx, 3] - bboxes[node.line_idx, 1]
304
+ node.num_lines = len(node.line_idx)
305
+ node.num_vertical_lines = (w < h).sum()
306
+ if 1 < node.num_lines:
307
+ x0, y0, _, _ = bboxes[node.line_idx, :].T
308
+ perm = np.lexsort((y0, -x0) if node.is_vertical() else (x0, y0))
309
+ node.line_idx[:] = [node.line_idx[i] for i in perm]
310
+ else:
311
+ for child in node.children:
312
+ num, v_num = sort_nodes(child, bboxes)
313
+ node.num_lines += num
314
+ node.num_vertical_lines += v_num
315
+ if node.is_x_split() and node.is_vertical():
316
+ node.children = node.children[::-1]
317
+ return node.num_lines, node.num_vertical_lines
318
+
319
+
320
+ def draw_partition_tree(node, draw, color=[10, 10, 10]):
321
+ """
322
+ Visualization utility
323
+ ---
324
+ node: BlockNode
325
+ draw: ImageDraw.Draw
326
+ """
327
+ draw.rectangle(node.get_coords(), outline=(*map(int, color), 255), width=1)
328
+ for child in node.children:
329
+ draw_partition_tree(child, draw, color)
330
+
331
+
332
+ def solve(bboxes, grid=None, plot_path=None, logger=None, scale=1.0):
333
+ """
334
+ Library API
335
+ ---
336
+ bboxes : [N,4], int
337
+ grid : int, number of bins for shorter side
338
+ plot_path: str, path of partition plot
339
+ """
340
+ if 0 == len(bboxes):
341
+ return []
342
+ if grid is None:
343
+ grid = get_optimal_grid(bboxes)
344
+ if logger is None:
345
+ from reading_order.utils.logger import get_logger
346
+ logger = get_logger(__name__)
347
+
348
+ bboxes = normalize_bboxes(bboxes, grid, scale)
349
+ table = make_mesh_table(bboxes)
350
+ h, w = table.shape
351
+ root = BlockNode(0, 0, w, h, None)
352
+ block_xy_cut(table, root)
353
+ assign_bbox_to_node(root, bboxes)
354
+ sort_nodes(root, bboxes)
355
+ if root.num_lines != len(bboxes):
356
+ logger.warning("Num of lines do not match: %d, %d" % (
357
+ root.num_lines, len(bboxes)))
358
+ ranks = [-1 for _ in range(len(bboxes))]
359
+ get_ranking(root, ranks)
360
+ if plot_path:
361
+ from PIL import Image, ImageDraw
362
+ with Image.new("RGB", size=(w, h), color=(255, 255, 255)) as im:
363
+ draw = ImageDraw.Draw(im)
364
+ draw_partition_tree(root, draw)
365
+ im.save(plot_path)
366
+ return ranks
@@ -0,0 +1,55 @@
1
+ # Copyright (c) 2023, National Diet Library, Japan
2
+ #
3
+ # This software is released under the CC BY 4.0.
4
+ # https://creativecommons.org/licenses/by/4.0/
5
+
6
+
7
+ import numpy as np
8
+ import re
9
+ import xml.etree.ElementTree as ET
10
+
11
+
12
+ from reading_order.order.reorder import sort_lines
13
+ from reading_order.utils.logger import get_logger
14
+ from reading_order.utils.time import TimeKeeper
15
+ from reading_order.xy_cut.block_xy_cut import solve
16
+
17
+
18
+ def eval_xml(root, time_keeper=None, logger=None, plot_path=None, line_width_scale=1.0, smoothing=True, **_):
19
+ time_keeper = time_keeper or TimeKeeper()
20
+ logger = logger or get_logger(__name__)
21
+ num = 0
22
+ for i, page in enumerate(root.findall(".//PAGE")):
23
+ with time_keeper.measure_time("sorting page"):
24
+ lines = np.array([[
25
+ int(line.get("X")),
26
+ int(line.get("Y")),
27
+ int(line.get("X")) + int(line.get("WIDTH")),
28
+ int(line.get("Y")) + int(line.get("HEIGHT")),
29
+ ] for line in page.findall(".//LINE")])
30
+ new_plot_path = plot_path.with_suffix(
31
+ ".%d.jpg" % i) if plot_path else None
32
+ ranks = solve(lines, plot_path=new_plot_path,
33
+ logger=logger, scale=line_width_scale)
34
+ for line, rank in zip(page.findall(".//LINE"), ranks):
35
+ line.set("ORDER", str(rank))
36
+ sort_lines(page, smoothing=smoothing)
37
+ num += 1
38
+ return num
39
+
40
+
41
+ def eval_path(xml_path, out_path, logger=None, time_keeper=None, plot_partition=False, line_width_scale=1.0, smoothing=False, **_):
42
+ time_keeper = time_keeper or TimeKeeper()
43
+ logger = logger or get_logger(__name__)
44
+
45
+ # Parse xml
46
+ xml_str = open(xml_path, encoding="utf-8").read()
47
+ root = ET.fromstring(re.sub("xmlns=[\"'].*?[\"']", "", xml_str, count=1))
48
+
49
+ plot_path = xml_path.with_suffix(
50
+ ".xy-block.jpg") if plot_partition else None
51
+ num = eval_xml(root, time_keeper=time_keeper, logger=logger,
52
+ plot_path=plot_path, line_width_scale=line_width_scale, smoothing=smoothing)
53
+ ET.ElementTree(root).write(
54
+ out_path, encoding="utf-8", xml_declaration=True)
55
+ return num
tcy_wrapper.py ADDED
@@ -0,0 +1,202 @@
1
+ """Tate-Chuu-Yoko (縦中横) wrapper for PARSEQ recognizer.
2
+
3
+ Wraps a PARSEQ recognizer to detect and correctly OCR tate-chuu-yoko
4
+ (horizontal text embedded in vertical lines), commonly found in newspaper text.
5
+
6
+ Usage:
7
+ recognizer = PARSEQ(...)
8
+ recognizer = TateChuYokoWrapper(recognizer)
9
+ text = recognizer.read(img) # same interface as PARSEQ
10
+ """
11
+
12
+ import cv2
13
+ import numpy as np
14
+ from typing import Tuple, List
15
+
16
+
17
+ def _softmax(x, axis=-1):
18
+ e_x = np.exp(x - np.max(x, axis=axis, keepdims=True))
19
+ return e_x / np.sum(e_x, axis=axis, keepdims=True)
20
+
21
+
22
+ def add_tcy_arguments(parser):
23
+ tcy_parser = parser.__class__(add_help=False)
24
+ tcy_parser.add_argument("--tcy-min-line-width", type=int, dest="tcy_min_line_width")
25
+ tcy_parser.add_argument("--tcy-max-line-width", type=int, dest="tcy_max_line_width")
26
+ tcy_parser.add_argument("--tcy-det-margin-ratio", type=float, dest="tcy_det_margin_ratio")
27
+ tcy_parser.add_argument("--tcy-ocr-margin-ratio", type=float, dest="tcy_ocr_margin_ratio")
28
+ tcy_parser.add_argument("--tcy-min-components", type=int, dest="tcy_min_components")
29
+ tcy_parser.add_argument("--tcy-max-aspect-ratio", type=float, dest="tcy_max_aspect_ratio")
30
+ tcy_parser.add_argument("--tcy-seg-min-gap", type=int, dest="tcy_seg_min_gap")
31
+ tcy_parser.add_argument("--tcy-ink-threshold-ratio", type=float, dest="tcy_ink_threshold_ratio")
32
+ return tcy_parser
33
+
34
+
35
+ class TateChuYokoWrapper:
36
+ def __init__(self, recognizer,
37
+ tcy_min_line_width: int = 30,
38
+ tcy_max_line_width: int = 80,
39
+ tcy_det_margin_ratio: float = 0.1,
40
+ tcy_ocr_margin_ratio: float = 0.5,
41
+ tcy_min_components: int = 2,
42
+ tcy_max_aspect_ratio: float = 0.75,
43
+ tcy_seg_min_gap: int = 5,
44
+ tcy_ink_threshold_ratio: float = 0.10):
45
+ self._rec = recognizer
46
+ self.min_line_width = tcy_min_line_width
47
+ self.max_line_width = tcy_max_line_width
48
+ self.det_margin_ratio = tcy_det_margin_ratio
49
+ self.ocr_margin_ratio = tcy_ocr_margin_ratio
50
+ self.min_components = tcy_min_components
51
+ self.max_aspect_ratio = tcy_max_aspect_ratio
52
+ self.seg_min_gap = tcy_seg_min_gap
53
+ self.ink_threshold_ratio = tcy_ink_threshold_ratio
54
+
55
+ def read(self, img: np.ndarray) -> str:
56
+ if img is None or img.size == 0:
57
+ return ""
58
+ h, w = img.shape[:2]
59
+ if h > w:
60
+ return self._detect_and_fix_tatechuyoko(img)
61
+ return self._rec.read(img)
62
+
63
+ def _read_with_confidence(self, img: np.ndarray, rotate: bool = True) -> Tuple[str, List[float]]:
64
+ if img is None or img.size == 0:
65
+ return "", []
66
+ rec = self._rec
67
+ if rotate:
68
+ input_tensor = rec.preprocess(img)
69
+ else:
70
+ input_tensor = self._preprocess_no_rotation(img)
71
+ outputs = rec.session.run(rec.output_names, {rec.input_names[0]: input_tensor})[0]
72
+ probs = _softmax(outputs, axis=2)
73
+ indices = np.argmax(probs, axis=2)[0]
74
+ max_probs = np.max(probs, axis=2)[0]
75
+ stop_idx = np.where(indices == 0)[0]
76
+ end_pos = stop_idx[0] if stop_idx.size > 0 else len(indices)
77
+ char_indices = indices[:end_pos].tolist()
78
+ confidences = max_probs[:end_pos].tolist()
79
+ text = "".join([rec.charlist[i - 1] for i in char_indices])
80
+ return text, confidences
81
+
82
+ def _preprocess_no_rotation(self, img: np.ndarray) -> np.ndarray:
83
+ rec = self._rec
84
+ resized = cv2.resize(img, (rec.input_width, rec.input_height), interpolation=cv2.INTER_LINEAR)
85
+ input_image = np.ascontiguousarray(resized[:, :, ::-1]).astype(np.float32)
86
+ input_image /= 127.5
87
+ input_image -= 1.0
88
+ input_image = input_image.transpose(2, 0, 1)
89
+ return input_image[np.newaxis, :, :, :]
90
+
91
+ def _segment_blocks(self, img: np.ndarray) -> List[Tuple[int, int]]:
92
+ if img.ndim == 3:
93
+ gray = np.mean(img, axis=2).astype(np.uint8)
94
+ else:
95
+ gray = img
96
+ threshold = int(np.mean(gray))
97
+ binary = (gray < threshold).astype(np.int32)
98
+ proj = np.sum(binary, axis=1)
99
+ is_ink = proj > 0
100
+ blocks: List[Tuple[int, int]] = []
101
+ in_block = False
102
+ start = 0
103
+ for y in range(len(is_ink)):
104
+ if is_ink[y] and not in_block:
105
+ start = y
106
+ in_block = True
107
+ elif not is_ink[y] and in_block:
108
+ blocks.append((start, y))
109
+ in_block = False
110
+ if in_block:
111
+ blocks.append((start, len(is_ink)))
112
+ merged: List[Tuple[int, int]] = []
113
+ for b in blocks:
114
+ if merged and b[0] - merged[-1][1] < self.seg_min_gap:
115
+ merged[-1] = (merged[-1][0], b[1])
116
+ else:
117
+ merged.append(b)
118
+ return merged
119
+
120
+ def _count_horizontal_components(self, segment: np.ndarray) -> int:
121
+ if segment.ndim == 3:
122
+ gray = np.mean(segment, axis=2).astype(np.uint8)
123
+ else:
124
+ gray = segment
125
+ threshold = int(np.mean(gray))
126
+ binary = (gray < threshold).astype(np.int32)
127
+ col_sum = np.sum(binary, axis=0)
128
+ if col_sum.max() == 0:
129
+ return 0
130
+ ink_threshold = col_sum.max() * self.ink_threshold_ratio
131
+ is_ink = col_sum > ink_threshold
132
+ components = 0
133
+ in_component = False
134
+ for v in is_ink:
135
+ if v and not in_component:
136
+ components += 1
137
+ in_component = True
138
+ elif not v:
139
+ in_component = False
140
+ return components
141
+
142
+ def _detect_and_fix_tatechuyoko(self, img: np.ndarray) -> str:
143
+ h, w = img.shape[:2]
144
+ full_text, full_conf = self._read_with_confidence(img, rotate=True)
145
+ if not full_text:
146
+ return full_text
147
+ blocks = self._segment_blocks(img)
148
+ if not blocks or w < self.min_line_width:
149
+ return full_text
150
+
151
+ tcy_flags: List[bool] = []
152
+ for y_start, y_end in blocks:
153
+ block_height = y_end - y_start
154
+ det_margin = max(2, int(block_height * self.det_margin_ratio))
155
+ y0 = max(0, y_start - det_margin)
156
+ y1 = min(h, y_end + det_margin)
157
+ block_img = img[y0:y1, :, :] if img.ndim == 3 else img[y0:y1, :]
158
+ is_tcy = (block_height >= self.seg_min_gap
159
+ and self._count_horizontal_components(block_img) >= self.min_components
160
+ and block_height <= w * self.max_aspect_ratio)
161
+ tcy_flags.append(is_tcy)
162
+
163
+ if not any(tcy_flags):
164
+ return full_text
165
+
166
+ block_parts: List[str] = []
167
+ i = 0
168
+ n = len(blocks)
169
+ while i < n:
170
+ if tcy_flags[i]:
171
+ y_start, y_end = blocks[i]
172
+ block_height = y_end - y_start
173
+ ocr_margin = max(5, int(block_height * self.ocr_margin_ratio))
174
+ y0 = max(0, y_start - ocr_margin)
175
+ y1 = min(h, y_end + ocr_margin)
176
+ block_img = img[y0:y1, :, :] if img.ndim == 3 else img[y0:y1, :]
177
+ if block_img.ndim == 2:
178
+ block_img = np.stack([block_img] * 3, axis=-1)
179
+ seg_text, _ = self._read_with_confidence(block_img, rotate=False)
180
+ block_parts.append(seg_text)
181
+ i += 1
182
+ else:
183
+ group_start = i
184
+ while i < n and not tcy_flags[i]:
185
+ i += 1
186
+ if group_start > 0 and tcy_flags[group_start - 1]:
187
+ crop_y0 = blocks[group_start - 1][1]
188
+ else:
189
+ crop_y0 = blocks[group_start][0]
190
+ if i < n and tcy_flags[i]:
191
+ crop_y1 = blocks[i][0]
192
+ else:
193
+ crop_y1 = blocks[i - 1][1]
194
+ group_img = img[crop_y0:crop_y1, :, :] if img.ndim == 3 else img[crop_y0:crop_y1, :]
195
+ if group_img.shape[0] > 0 and group_img.shape[1] > 0:
196
+ group_text, _ = self._read_with_confidence(group_img, rotate=True)
197
+ block_parts.append(group_text)
198
+
199
+ block_text = "".join(block_parts)
200
+ if len(block_text) > len(full_text):
201
+ return block_text
202
+ return full_text