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.
- cli.py +15 -0
- config/NDLmoji.yaml +4 -0
- config/__init__.py +0 -0
- config/ndl.yaml +21 -0
- deim.py +169 -0
- model/__init__.py +0 -0
- model_download.py +87 -0
- ndl_parser.py +1083 -0
- ndlocr_lite-1.4.0.dev0.dist-info/METADATA +182 -0
- ndlocr_lite-1.4.0.dev0.dist-info/RECORD +43 -0
- ndlocr_lite-1.4.0.dev0.dist-info/WHEEL +5 -0
- ndlocr_lite-1.4.0.dev0.dist-info/entry_points.txt +2 -0
- ndlocr_lite-1.4.0.dev0.dist-info/licenses/LICENCE +395 -0
- ndlocr_lite-1.4.0.dev0.dist-info/licenses/LICENCE_DEPENDENCEIES +1891 -0
- ndlocr_lite-1.4.0.dev0.dist-info/top_level.txt +16 -0
- ndlocr_lite_gui/__init__.py +12 -0
- ndlocr_lite_gui/assets/icon.png +0 -0
- ndlocr_lite_gui/gui_config.py +21 -0
- ndlocr_lite_gui/main.py +2105 -0
- ocr.py +1425 -0
- optional_features/__init__.py +52 -0
- parseq.py +74 -0
- pdf_output_utils.py +71 -0
- reading_order/__init__.py +0 -0
- reading_order/order/__init__.py +0 -0
- reading_order/order/parse_xml.py +143 -0
- reading_order/order/reorder.py +211 -0
- reading_order/order/smooth_order.py +110 -0
- reading_order/order/warichu_block.py +178 -0
- reading_order/order/wrap_dataset.py +13 -0
- reading_order/utils/__init__.py +0 -0
- reading_order/utils/file.py +21 -0
- reading_order/utils/logger.py +29 -0
- reading_order/utils/time.py +63 -0
- reading_order/utils/xml.py +97 -0
- reading_order/xy_cut/__init__.py +0 -0
- reading_order/xy_cut/block_xy_cut.py +366 -0
- reading_order/xy_cut/eval.py +55 -0
- tcy_wrapper.py +202 -0
- tools/ndlkoten2tei.py +115 -0
- uicomponent/localelabel.py +118 -0
- uicomponent/textdaisy.py +1093 -0
- version.py +3 -0
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
import importlib.util
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
import sys
|
|
5
|
+
from types import ModuleType
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
FEATURE_NAMES = ('data_pool', 'llm', 'table_structure')
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True)
|
|
12
|
+
class OptionalFeatures:
|
|
13
|
+
data_pool: ModuleType | None = None
|
|
14
|
+
llm: ModuleType | None = None
|
|
15
|
+
table_structure: ModuleType | None = None
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def load_optional_features(feature_dir: Path | None = None) -> OptionalFeatures:
|
|
19
|
+
"""Load only feature modules whose source files are present."""
|
|
20
|
+
directory = Path(feature_dir) if feature_dir is not None else Path(__file__).resolve().parent
|
|
21
|
+
loaded = {}
|
|
22
|
+
|
|
23
|
+
for name in FEATURE_NAMES:
|
|
24
|
+
module_path = next(
|
|
25
|
+
(
|
|
26
|
+
candidate
|
|
27
|
+
for candidate in (
|
|
28
|
+
directory / f'{name}.py',
|
|
29
|
+
directory / f'{name}.pyc',
|
|
30
|
+
)
|
|
31
|
+
if candidate.is_file()
|
|
32
|
+
),
|
|
33
|
+
None,
|
|
34
|
+
)
|
|
35
|
+
if module_path is None:
|
|
36
|
+
loaded[name] = None
|
|
37
|
+
continue
|
|
38
|
+
|
|
39
|
+
module_name = f'ndlocr_optional_features.{name}.{abs(hash(module_path.resolve()))}'
|
|
40
|
+
spec = importlib.util.spec_from_file_location(module_name, module_path)
|
|
41
|
+
if spec is None or spec.loader is None:
|
|
42
|
+
raise ImportError(f'Cannot load optional feature module: {module_path}')
|
|
43
|
+
module = importlib.util.module_from_spec(spec)
|
|
44
|
+
sys.modules[module_name] = module
|
|
45
|
+
try:
|
|
46
|
+
spec.loader.exec_module(module)
|
|
47
|
+
except Exception:
|
|
48
|
+
sys.modules.pop(module_name, None)
|
|
49
|
+
raise
|
|
50
|
+
loaded[name] = module
|
|
51
|
+
|
|
52
|
+
return OptionalFeatures(**loaded)
|
parseq.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
from PIL import Image
|
|
2
|
+
import time
|
|
3
|
+
import yaml
|
|
4
|
+
import onnxruntime
|
|
5
|
+
import numpy as np
|
|
6
|
+
import cv2
|
|
7
|
+
from typing import Tuple, List
|
|
8
|
+
|
|
9
|
+
class PARSEQ:
|
|
10
|
+
def __init__(self,
|
|
11
|
+
model_path: str,
|
|
12
|
+
charlist: [str],
|
|
13
|
+
original_size: Tuple[int, int] = (384, 32),
|
|
14
|
+
device: str = "CPU") -> None:
|
|
15
|
+
self.model_path = model_path
|
|
16
|
+
self.charlist = charlist
|
|
17
|
+
|
|
18
|
+
self.device = device
|
|
19
|
+
self.image_width, self.image_height = original_size
|
|
20
|
+
self.create_session()
|
|
21
|
+
|
|
22
|
+
def create_session(self) -> None:
|
|
23
|
+
opt_session = onnxruntime.SessionOptions()
|
|
24
|
+
opt_session.graph_optimization_level = onnxruntime.GraphOptimizationLevel.ORT_ENABLE_ALL
|
|
25
|
+
#opt_session.enable_cpu_mem_arena = False
|
|
26
|
+
#opt_session.execution_mode = onnxruntime.ExecutionMode.ORT_PARALLEL
|
|
27
|
+
#opt_session.graph_optimization_level = onnxruntime.GraphOptimizationLevel.ORT_DISABLE_ALL
|
|
28
|
+
providers = ['CPUExecutionProvider']
|
|
29
|
+
if self.device.casefold() == "cpu":
|
|
30
|
+
opt_session.intra_op_num_threads = 1
|
|
31
|
+
opt_session.inter_op_num_threads = 1
|
|
32
|
+
elif self.device.casefold() == "cuda":
|
|
33
|
+
providers = [('CUDAExecutionProvider', {'device_id': 0}), 'CPUExecutionProvider']
|
|
34
|
+
session = onnxruntime.InferenceSession(self.model_path,opt_session, providers=providers)
|
|
35
|
+
if self.device.casefold() == "cuda" and 'CUDAExecutionProvider' not in session.get_providers():
|
|
36
|
+
print('警告: CUDAExecutionProvider が利用できないため CPUExecutionProvider にフォールバックしました。onnxruntime-gpu と CUDA 環境を確認してください。')
|
|
37
|
+
self.session = session
|
|
38
|
+
self.model_inputs = self.session.get_inputs()
|
|
39
|
+
self.input_names = [self.model_inputs[i].name for i in range(len(self.model_inputs))]
|
|
40
|
+
self.input_shape = self.model_inputs[0].shape
|
|
41
|
+
self.model_output = self.session.get_outputs()
|
|
42
|
+
self.output_names = [self.model_output[i].name for i in range(len(self.model_output))]
|
|
43
|
+
self.input_height, self.input_width = self.input_shape[2:]
|
|
44
|
+
|
|
45
|
+
def postprocess(self, outputs):
|
|
46
|
+
predictions = np.squeeze(outputs).T
|
|
47
|
+
scores = np.max(predictions[:, 4:], axis=1)
|
|
48
|
+
predictions = predictions[scores > self.conf_thresold, :]
|
|
49
|
+
scores = scores[scores > self.conf_thresold]
|
|
50
|
+
class_ids = np.argmax(predictions[:, 4:], axis=1)
|
|
51
|
+
|
|
52
|
+
def preprocess(self, img: np.ndarray) -> np.ndarray:
|
|
53
|
+
h,w=img.shape[:2]
|
|
54
|
+
if h>w*0.8:
|
|
55
|
+
img=cv2.rotate(img,cv2.ROTATE_90_COUNTERCLOCKWISE)
|
|
56
|
+
resized=cv2.resize(img,(self.input_width, self.input_height),interpolation=cv2.INTER_LINEAR)
|
|
57
|
+
input_image=np.ascontiguousarray(resized[:,:,::-1]).astype(np.float32)
|
|
58
|
+
input_image/=127.5
|
|
59
|
+
input_image-=1.0
|
|
60
|
+
input_image = input_image.transpose(2,0,1)
|
|
61
|
+
return input_image[np.newaxis, :, :, :]
|
|
62
|
+
|
|
63
|
+
def read(self, img: np.ndarray) -> List:
|
|
64
|
+
if img is None or img.size == 0:
|
|
65
|
+
return ""
|
|
66
|
+
input_tensor = self.preprocess(img)
|
|
67
|
+
outputs = self.session.run(self.output_names, {self.input_names[0]: input_tensor})[0]
|
|
68
|
+
indices = np.argmax(outputs[0], axis=1)
|
|
69
|
+
#print(indices.size,indices)
|
|
70
|
+
stop_idx = np.where(indices == 0)[0]
|
|
71
|
+
end_pos = stop_idx[0] if stop_idx.size > 0 else len(indices)
|
|
72
|
+
resval = indices[:end_pos].tolist()
|
|
73
|
+
resstr = "".join([self.charlist[i - 1] for i in resval])
|
|
74
|
+
return resstr
|
pdf_output_utils.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def should_output_pdf_pages_separately(page_count: int, enabled: bool) -> bool:
|
|
6
|
+
return bool(enabled) and int(page_count) > 1
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def build_pdf_page_output_stem(output_stem: str, page_index: int) -> str:
|
|
10
|
+
return f"{output_stem}_{page_index + 1:05}"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def build_single_page_xml(page_xml: str) -> str:
|
|
14
|
+
return f"<OCRDATASET>\n{page_xml}\n</OCRDATASET>"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def build_pdf_page_json_obj(page_result: dict, source_path: str, include_xml: bool = False) -> dict:
|
|
18
|
+
page_json_obj = {
|
|
19
|
+
"contents": [page_result["json_lines"]],
|
|
20
|
+
"imginfo": {
|
|
21
|
+
"img_width": page_result["img_width"],
|
|
22
|
+
"img_height": page_result["img_height"],
|
|
23
|
+
"img_path": source_path,
|
|
24
|
+
"img_name": page_result["img_name"],
|
|
25
|
+
},
|
|
26
|
+
}
|
|
27
|
+
if include_xml:
|
|
28
|
+
page_json_obj["xml"] = build_single_page_xml(page_result["page_xml"])
|
|
29
|
+
return page_json_obj
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def write_pdf_page_outputs(
|
|
33
|
+
output_dir: str,
|
|
34
|
+
output_stem: str,
|
|
35
|
+
page_index: int,
|
|
36
|
+
page_result: dict,
|
|
37
|
+
*,
|
|
38
|
+
source_path: str,
|
|
39
|
+
write_json: bool,
|
|
40
|
+
write_xml: bool,
|
|
41
|
+
write_txt: bool,
|
|
42
|
+
write_tei: bool = False,
|
|
43
|
+
convert_tei_func=None,
|
|
44
|
+
include_xml_in_json: bool = False,
|
|
45
|
+
) -> dict:
|
|
46
|
+
page_output_stem = build_pdf_page_output_stem(output_stem, page_index)
|
|
47
|
+
page_json_obj = build_pdf_page_json_obj(
|
|
48
|
+
page_result,
|
|
49
|
+
source_path=source_path,
|
|
50
|
+
include_xml=include_xml_in_json,
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
if write_xml:
|
|
54
|
+
with open(os.path.join(output_dir, page_output_stem + ".xml"), "w", encoding="utf-8") as wf:
|
|
55
|
+
wf.write(build_single_page_xml(page_result["page_xml"]))
|
|
56
|
+
|
|
57
|
+
if write_txt:
|
|
58
|
+
with open(os.path.join(output_dir, page_output_stem + ".txt"), "w", encoding="utf-8") as wf:
|
|
59
|
+
wf.write(page_result["text"])
|
|
60
|
+
|
|
61
|
+
if write_json:
|
|
62
|
+
with open(os.path.join(output_dir, page_output_stem + ".json"), "w", encoding="utf-8") as wf:
|
|
63
|
+
wf.write(json.dumps(page_json_obj, ensure_ascii=False, indent=2))
|
|
64
|
+
|
|
65
|
+
if write_tei:
|
|
66
|
+
if convert_tei_func is None:
|
|
67
|
+
raise ValueError("convert_tei_func is required when write_tei is True")
|
|
68
|
+
with open(os.path.join(output_dir, page_output_stem + "_tei.xml"), "wb") as wf:
|
|
69
|
+
wf.write(convert_tei_func([page_json_obj]))
|
|
70
|
+
|
|
71
|
+
return page_json_obj
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,143 @@
|
|
|
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
|
+
from pathlib import Path
|
|
8
|
+
import re
|
|
9
|
+
import xml.etree.ElementTree as et
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
LINE_TYPE_TEXT = 0
|
|
13
|
+
LINE_TYPE_CAPTION = 1
|
|
14
|
+
LINE_TYPE_TOCHU = 2
|
|
15
|
+
LINE_TYPE_WARICHU = 3
|
|
16
|
+
LINE_TYPE_ADTEXT = 4
|
|
17
|
+
LINE_TYPE_TITLE=5
|
|
18
|
+
LINE_TYPE_UNKNOWN = 6
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
LINE_TYPE_COLORS = [
|
|
22
|
+
(255, 0, 0), # LINE_TYPE_TEXT,
|
|
23
|
+
(0, 255, 0), # LINE_TYPE_CAPTION,
|
|
24
|
+
(255, 255, 0), # LINE_TYPE_TOCHU,
|
|
25
|
+
(0, 0, 255), # LINE_TYPE_WARICHU,
|
|
26
|
+
(0, 255, 255), # LINE_TYPE_ADTEXT,
|
|
27
|
+
(0, 0, 0), #LINE_TYPE_TITLE
|
|
28
|
+
(200, 200, 200), # LINE_TYPE_UNKNOWN
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def get_line_type(string_type):
|
|
33
|
+
return {
|
|
34
|
+
"本文": LINE_TYPE_TEXT,
|
|
35
|
+
"キャプション": LINE_TYPE_CAPTION,
|
|
36
|
+
"頭注": LINE_TYPE_TOCHU,
|
|
37
|
+
"割注": LINE_TYPE_WARICHU,
|
|
38
|
+
"広告文字": LINE_TYPE_ADTEXT,
|
|
39
|
+
"タイトル本文": LINE_TYPE_TITLE,
|
|
40
|
+
}.get(string_type, LINE_TYPE_UNKNOWN)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def parse_line(line, page_w, page_h, index, block_id=None, block_idx=None):
|
|
44
|
+
x = int(line.get("X", -1))
|
|
45
|
+
y = int(line.get("Y", -1))
|
|
46
|
+
w = int(line.get("WIDTH", -1))
|
|
47
|
+
h = int(line.get("HEIGHT", -1))
|
|
48
|
+
is_vertical = bool(line.get("DIRECTION", "縦" if w < h else "横") == "縦")
|
|
49
|
+
return {
|
|
50
|
+
"index": index,
|
|
51
|
+
"x": x,
|
|
52
|
+
"y": y,
|
|
53
|
+
"width": w,
|
|
54
|
+
"height": h,
|
|
55
|
+
"bbox": [x, y, x+w, y+h],
|
|
56
|
+
"unilm_bbox": [
|
|
57
|
+
min(999, max(0, x*1000//page_w)),
|
|
58
|
+
min(999, max(0, y*1000//page_h)),
|
|
59
|
+
min(999, max(0, (x+w)*1000//page_w)),
|
|
60
|
+
min(999, max(0, (y+h)*1000//page_h))],
|
|
61
|
+
"is_vertical": is_vertical,
|
|
62
|
+
"string": line.get("STRING", ""),
|
|
63
|
+
"type": get_line_type(line.get("TYPE", "")),
|
|
64
|
+
"is_title": bool(line.get("TITLE", "false").lower() == "true"),
|
|
65
|
+
"is_author": bool(line.get("AUTHOR", "false").lower() == "true"),
|
|
66
|
+
"order": float(line.get("ORDER", -1)),
|
|
67
|
+
"block_id": block_id,
|
|
68
|
+
"block_index": block_idx,
|
|
69
|
+
"obj": line,
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def parse_root(root, xml_path=None):
|
|
74
|
+
dat = dict()
|
|
75
|
+
dat["pages"] = list()
|
|
76
|
+
for i, page in enumerate(root.findall("PAGE")):
|
|
77
|
+
kyokaku = page.get("KYOKAKU")
|
|
78
|
+
if kyokaku is not None:
|
|
79
|
+
kyokaku = True if "true" == kyokaku.lower(
|
|
80
|
+
) else False if "false" == kyokaku.lower() else None
|
|
81
|
+
dat["pages"].append({
|
|
82
|
+
"index": i,
|
|
83
|
+
"pid": Path(xml_path).stem if xml_path else "unknown",
|
|
84
|
+
"width": int(page.get("WIDTH", -1)),
|
|
85
|
+
"height": int(page.get("HEIGHT", -1)),
|
|
86
|
+
"image": page.get("IMAGENAME"),
|
|
87
|
+
"kyokaku": kyokaku,
|
|
88
|
+
"lines": [],
|
|
89
|
+
"text_blocks": [],
|
|
90
|
+
"obj": page,
|
|
91
|
+
})
|
|
92
|
+
page_w = dat["pages"][-1]["width"]
|
|
93
|
+
page_h = dat["pages"][-1]["height"]
|
|
94
|
+
lines = dat["pages"][-1]["lines"]
|
|
95
|
+
|
|
96
|
+
def traverse(page_or_block, block_idx=0):
|
|
97
|
+
for child in page_or_block:
|
|
98
|
+
if "LINE" == child.tag:
|
|
99
|
+
lines.append(parse_line(child, page_w, page_h, len(lines)))
|
|
100
|
+
elif "TEXTBLOCK" == child.tag:
|
|
101
|
+
for shape in child.iter("SHAPE"):
|
|
102
|
+
for polygon in shape.iter("POLYGON"):
|
|
103
|
+
polygon = list(
|
|
104
|
+
map(int, polygon.get("POINTS").split(",")))
|
|
105
|
+
break
|
|
106
|
+
break
|
|
107
|
+
try:
|
|
108
|
+
block_id = int(child.get("BLOCKID"))
|
|
109
|
+
except TypeError:
|
|
110
|
+
block_id = block_idx
|
|
111
|
+
block_lines = list()
|
|
112
|
+
for line in child.findall("LINE"):
|
|
113
|
+
block_lines.append(parse_line(line, page_w, page_h,
|
|
114
|
+
len(lines) +
|
|
115
|
+
len(block_lines),
|
|
116
|
+
block_id=block_id, block_idx=block_idx))
|
|
117
|
+
lines.extend(block_lines)
|
|
118
|
+
num_vert_block_lines = sum(
|
|
119
|
+
int(block_line["is_vertical"]) for block_line in block_lines)
|
|
120
|
+
dat["pages"][-1]["text_blocks"].append({
|
|
121
|
+
"block_id": block_id,
|
|
122
|
+
"block_index": block_idx,
|
|
123
|
+
"polygon": polygon,
|
|
124
|
+
"is_vertical": bool(len(block_lines) < num_vert_block_lines * 2),
|
|
125
|
+
"obj": child,
|
|
126
|
+
})
|
|
127
|
+
block_idx += 1
|
|
128
|
+
elif "BLOCK" == child.tag:
|
|
129
|
+
traverse(child, block_idx)
|
|
130
|
+
traverse(page)
|
|
131
|
+
num_vert_lines = sum(int(line["is_vertical"]) for line in lines)
|
|
132
|
+
dat["pages"][-1].update({
|
|
133
|
+
"is_vertical": bool(len(lines) < num_vert_lines * 2)})
|
|
134
|
+
return dat
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def parse_xml(xml_path):
|
|
138
|
+
xml_path = xml_path
|
|
139
|
+
with open(xml_path, "r", encoding="utf-8") as f:
|
|
140
|
+
xml = f.read()
|
|
141
|
+
# Delete namespace.
|
|
142
|
+
root = et.fromstring(re.sub('xmlns=".*?"', '', xml, count=1))
|
|
143
|
+
return parse_root(root, xml_path=xml_path)
|
|
@@ -0,0 +1,211 @@
|
|
|
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 functools
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
from reading_order.utils.xml import ConstantNumberOfTags
|
|
12
|
+
from reading_order.order.smooth_order import smooth_order
|
|
13
|
+
from reading_order.order.warichu_block import GroupWarichu
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def check_iou(a, b):
|
|
17
|
+
"""
|
|
18
|
+
a: [xmin, ymin, xmax, ymax]
|
|
19
|
+
b: [xmin, ymin, xmax, ymax]
|
|
20
|
+
|
|
21
|
+
return: array(iou)
|
|
22
|
+
"""
|
|
23
|
+
b = np.asarray(b)
|
|
24
|
+
a_area = (a[ 2] - a[ 0]) * (a[ 3] - a[ 1])
|
|
25
|
+
b_area = (b[ 2] - b[ 0]) * (b[ 3] - b[ 1])
|
|
26
|
+
intersection_xmin = np.maximum(a[0], b[0])
|
|
27
|
+
intersection_ymin = np.maximum(a[1], b[1])
|
|
28
|
+
intersection_xmax = np.minimum(a[2], b[2])
|
|
29
|
+
intersection_ymax = np.minimum(a[3], b[3])
|
|
30
|
+
intersection_w = np.maximum(0, intersection_xmax - intersection_xmin)
|
|
31
|
+
intersection_h = np.maximum(0, intersection_ymax - intersection_ymin)
|
|
32
|
+
intersection_area = intersection_w * intersection_h
|
|
33
|
+
min_area=min(a_area,b_area)
|
|
34
|
+
#print(intersection_area/min_area)
|
|
35
|
+
sum_area=a_area+b_area-intersection_area
|
|
36
|
+
if min_area>0 and intersection_area/min_area>0.8:
|
|
37
|
+
return True
|
|
38
|
+
return False
|
|
39
|
+
|
|
40
|
+
def check_dup(aconf,bconf):
|
|
41
|
+
if check_iou(aconf[:4],bconf[:4]):
|
|
42
|
+
if aconf[-1]>=bconf[-1]:
|
|
43
|
+
return 1
|
|
44
|
+
else:
|
|
45
|
+
return 2
|
|
46
|
+
return 0
|
|
47
|
+
|
|
48
|
+
def remove_dup(childrenlist):
|
|
49
|
+
lines=list()
|
|
50
|
+
complines = list()
|
|
51
|
+
for element in childrenlist:
|
|
52
|
+
if element.tag in ["LINE", "WARICHUBLOCK"]:
|
|
53
|
+
w = float(element.get("WIDTH", -1))
|
|
54
|
+
h = float(element.get("HEIGHT", -1))
|
|
55
|
+
conf = float(element.get("CONF", -1))
|
|
56
|
+
x = float(element.get("X", -1))
|
|
57
|
+
y = float(element.get("Y", -1))
|
|
58
|
+
checkdupval=0
|
|
59
|
+
if len(lines)!=0 and lines[-1].tag in ["LINE", "WARICHUBLOCK"]:
|
|
60
|
+
checkdupval=check_dup(complines[-1],[x,y,x+w,y+h,conf])
|
|
61
|
+
if checkdupval==0:#重複なし
|
|
62
|
+
lines.append(element)
|
|
63
|
+
complines.append([x,y,x+w,y+h,conf])
|
|
64
|
+
elif checkdupval==1:#重複あり (今見ているlineをスキップ)
|
|
65
|
+
continue
|
|
66
|
+
elif checkdupval==2:#重複あり(比較対象を削除)
|
|
67
|
+
del lines[-1]
|
|
68
|
+
del complines[-1]
|
|
69
|
+
lines.append(element)
|
|
70
|
+
complines.append([x,y,x+w,y+h,conf])
|
|
71
|
+
else:
|
|
72
|
+
print("error!")
|
|
73
|
+
else:
|
|
74
|
+
lines.append(element)
|
|
75
|
+
return lines
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def sort_lines_local(root):
|
|
80
|
+
"""
|
|
81
|
+
Sorts LINE tags that exist directly under the `root`. This sorting is based
|
|
82
|
+
on the coordinates of the LINE tag and ignores their ORDER. The tag of
|
|
83
|
+
`root` can be anytGhing, but now I am considering of either TEXTBLOCK or
|
|
84
|
+
WARICHUBLOCK.
|
|
85
|
+
"""
|
|
86
|
+
|
|
87
|
+
num_vertical = 0
|
|
88
|
+
num_lines = 0
|
|
89
|
+
lines = list()
|
|
90
|
+
not_lines = list()
|
|
91
|
+
widths, heights = list(), list()
|
|
92
|
+
for element in root:
|
|
93
|
+
if element.tag in ["LINE", "WARICHUBLOCK"]:
|
|
94
|
+
w = float(element.get("WIDTH", -1))
|
|
95
|
+
h = float(element.get("HEIGHT", -1))
|
|
96
|
+
num_vertical += 1 if w < h else 0
|
|
97
|
+
num_lines += 1
|
|
98
|
+
widths.append(w)
|
|
99
|
+
heights.append(h)
|
|
100
|
+
x = float(element.get("X", -1))
|
|
101
|
+
y = float(element.get("Y", -1))
|
|
102
|
+
order = float(element.get("ORDER", np.nan))
|
|
103
|
+
lines.append((x+w/2, y+h/2, order, element))
|
|
104
|
+
else:
|
|
105
|
+
not_lines.append(element)
|
|
106
|
+
|
|
107
|
+
if not widths:
|
|
108
|
+
return root, -1
|
|
109
|
+
|
|
110
|
+
is_vertical = num_lines < num_vertical * 2
|
|
111
|
+
|
|
112
|
+
# Define comparison functions.
|
|
113
|
+
span_median = np.median(widths) if is_vertical else np.median(heights)
|
|
114
|
+
margin = span_median * 0.3
|
|
115
|
+
|
|
116
|
+
def cmp_v(a0, a1):
|
|
117
|
+
x0, y0, _, _, = a0 # Ignore order, obj
|
|
118
|
+
x1, y1, _, _, = a1 # Ignore order, obj
|
|
119
|
+
if margin < x1 - x0:
|
|
120
|
+
return 1
|
|
121
|
+
elif margin < x0 - x1:
|
|
122
|
+
return -1
|
|
123
|
+
else:
|
|
124
|
+
return y0 - y1
|
|
125
|
+
|
|
126
|
+
def cmp_h(a0, a1):
|
|
127
|
+
x0, y0, _, _, = a0 # Ignore order, obj
|
|
128
|
+
x1, y1, _, _, = a1 # Ignore order, obj
|
|
129
|
+
if margin < y0 - y1:
|
|
130
|
+
return 1
|
|
131
|
+
elif margin < y1 - y0:
|
|
132
|
+
return -1
|
|
133
|
+
else:
|
|
134
|
+
return x0 - x1
|
|
135
|
+
|
|
136
|
+
# Sort LINE by coordinates.
|
|
137
|
+
lines = sorted(lines, key=functools.cmp_to_key(
|
|
138
|
+
cmp_v if is_vertical else cmp_h))
|
|
139
|
+
sorted_lines = [line for _, _, _, line in lines]
|
|
140
|
+
if len(sorted_lines)>0:
|
|
141
|
+
sorted_lines =remove_dup(sorted_lines)
|
|
142
|
+
# Calc median.
|
|
143
|
+
valid_orders = [order for _, _, order, _ in lines if not np.isnan(order)]
|
|
144
|
+
median = sorted(valid_orders)[
|
|
145
|
+
len(valid_orders)//2] if valid_orders else np.nan
|
|
146
|
+
|
|
147
|
+
# Assign lines.
|
|
148
|
+
root[:] = sorted_lines + not_lines
|
|
149
|
+
return root, median
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def sort_lines(root, smoothing=True):
|
|
153
|
+
"""
|
|
154
|
+
An example of acceptable XML as input or intermediate states.
|
|
155
|
+
<PAGE> - One or more PAGE tags should exist in a file.
|
|
156
|
+
<TEXTBLOCK> - TEXTBLOCK must be placed right under PAGE tag.
|
|
157
|
+
<LINE ORDER="0.1"/> - LINE tags inside TEXTBOCK.
|
|
158
|
+
<WARICHUBLOCK> - WARICHUBLOCK is temporarily added to group up 割注s.
|
|
159
|
+
<LINE ORDER="0.2"/> - 割注 LINE tags.
|
|
160
|
+
<LINE ORDER="0.3"/>
|
|
161
|
+
</WARICHUBLOCK>
|
|
162
|
+
</TEXTBLOCK>
|
|
163
|
+
<LINE ORDER="0.8"/> - LINE tags can be also placed outside TEXTBLOCK.
|
|
164
|
+
</PAGE>
|
|
165
|
+
"""
|
|
166
|
+
|
|
167
|
+
def traverse(page_or_block):
|
|
168
|
+
tobe_sorted = list()
|
|
169
|
+
unsorted = list()
|
|
170
|
+
for element in page_or_block:
|
|
171
|
+
if "TEXTBLOCK" == element.tag:
|
|
172
|
+
# Sort 割注 block inside TEXTBLOCK.
|
|
173
|
+
for wari in element.findall("./WARICHUBLOCK"):
|
|
174
|
+
_, _ = sort_lines_local(wari)
|
|
175
|
+
# Sort LINEs inside TEXTBLOCK.
|
|
176
|
+
element, median = sort_lines_local(element)
|
|
177
|
+
tobe_sorted.append((median, element))
|
|
178
|
+
elif "LINE" == element.tag:
|
|
179
|
+
# Sort LINEs outside TEXTBLOCK.
|
|
180
|
+
order = float(element.get("ORDER", np.nan))
|
|
181
|
+
tobe_sorted.append((order, element))
|
|
182
|
+
elif "WARICHUBLOCK" == element.tag:
|
|
183
|
+
# Sort 割注 outside TEXTBLOCK.
|
|
184
|
+
element, median = sort_lines_local(element)
|
|
185
|
+
tobe_sorted.append((median, element))
|
|
186
|
+
elif "BLOCK" == element.tag:
|
|
187
|
+
traverse(element)
|
|
188
|
+
unsorted.append(element)
|
|
189
|
+
elif "PAGE" == element.tag:
|
|
190
|
+
traverse(element)
|
|
191
|
+
unsorted.append(element)
|
|
192
|
+
else:
|
|
193
|
+
unsorted.append(element)
|
|
194
|
+
sorted_children = sorted(tobe_sorted, key=lambda x: x[0])
|
|
195
|
+
sorted_children = [obj for _, obj in sorted_children]
|
|
196
|
+
if len(sorted_children)>0:
|
|
197
|
+
sorted_children =remove_dup(sorted_children)
|
|
198
|
+
page_or_block[:] = sorted_children + unsorted
|
|
199
|
+
|
|
200
|
+
# To check that the number of tags does not change by sorting.
|
|
201
|
+
"""
|
|
202
|
+
with ConstantNumberOfTags(root):
|
|
203
|
+
with GroupWarichu(root):
|
|
204
|
+
traverse(root)
|
|
205
|
+
if smoothing:
|
|
206
|
+
smooth_order(root)
|
|
207
|
+
"""
|
|
208
|
+
with GroupWarichu(root):
|
|
209
|
+
traverse(root)
|
|
210
|
+
if smoothing:
|
|
211
|
+
smooth_order(root)
|
|
@@ -0,0 +1,110 @@
|
|
|
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 networkx as nx
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def find_minimum_hamiltonian_path(graph):
|
|
12
|
+
"""
|
|
13
|
+
Return the minimum weight hamiltonian path in `graph`.
|
|
14
|
+
"""
|
|
15
|
+
min_weight = 99999
|
|
16
|
+
min_path = None
|
|
17
|
+
num_nodes = len(graph.nodes())
|
|
18
|
+
for path in nx.all_simple_paths(graph, source=0, target=num_nodes-1):
|
|
19
|
+
if len(path) == num_nodes:
|
|
20
|
+
path_weight = sum([graph[u][v]['weight']
|
|
21
|
+
for u, v in zip(path[:-1], path[1:])])
|
|
22
|
+
if path_weight < min_weight:
|
|
23
|
+
min_weight, min_path = path_weight, path
|
|
24
|
+
return min_path, min_weight
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def smooth_order_page(page):
|
|
28
|
+
w = float(page.get("WIDTH"))
|
|
29
|
+
h = float(page.get("HEIGHT"))
|
|
30
|
+
diam = np.sqrt(w*w + h*h)
|
|
31
|
+
|
|
32
|
+
def traverse(page_or_block):
|
|
33
|
+
tobe_sorted = list()
|
|
34
|
+
unsorted = list()
|
|
35
|
+
for element in page_or_block:
|
|
36
|
+
if "TEXTBLOCK" == element.tag:
|
|
37
|
+
orders = list()
|
|
38
|
+
is_first = True
|
|
39
|
+
beg_pos = (None, None)
|
|
40
|
+
end_pos = (None, None)
|
|
41
|
+
for line in element.findall("./LINE"):
|
|
42
|
+
orders.append(float(line.get("ORDER", np.nan)))
|
|
43
|
+
x = float(line.get("X", np.nan))
|
|
44
|
+
y = float(line.get("Y", np.nan))
|
|
45
|
+
w = float(line.get("WIDTH", np.nan))
|
|
46
|
+
h = float(line.get("HEIGHT", np.nan))
|
|
47
|
+
if is_first:
|
|
48
|
+
beg_pos = (x + w/2, y)
|
|
49
|
+
end_pos = (x + w/2, y + h)
|
|
50
|
+
if not orders:
|
|
51
|
+
continue
|
|
52
|
+
order = orders[len(orders) // 2]
|
|
53
|
+
tobe_sorted.append((order, beg_pos, end_pos, element))
|
|
54
|
+
|
|
55
|
+
elif "LINE" == element.tag:
|
|
56
|
+
order = float(element.get("ORDER", np.nan))
|
|
57
|
+
x = float(element.get("X", np.nan))
|
|
58
|
+
y = float(element.get("Y", np.nan))
|
|
59
|
+
w = float(element.get("WIDTH", np.nan))
|
|
60
|
+
h = float(element.get("HEIGHT", np.nan))
|
|
61
|
+
beg_pos = (x + w/2, y)
|
|
62
|
+
end_pos = (x + w/2, y + h)
|
|
63
|
+
tobe_sorted.append((order, beg_pos, end_pos, element))
|
|
64
|
+
|
|
65
|
+
elif "BLOCK" == element.tag:
|
|
66
|
+
traverse(element)
|
|
67
|
+
unsorted.append(element)
|
|
68
|
+
|
|
69
|
+
else:
|
|
70
|
+
unsorted.append(element)
|
|
71
|
+
|
|
72
|
+
# Build graph.
|
|
73
|
+
graph = nx.DiGraph()
|
|
74
|
+
num = len(tobe_sorted)
|
|
75
|
+
orders = [o for o, _, _, _ in tobe_sorted]
|
|
76
|
+
if 0 < num:
|
|
77
|
+
order_range = max(orders) - min(orders)
|
|
78
|
+
|
|
79
|
+
def calc_weight(i, j):
|
|
80
|
+
order_i, _, end, _ = tobe_sorted[i]
|
|
81
|
+
order_j, beg, _, _ = tobe_sorted[j]
|
|
82
|
+
order_d = abs(order_i - order_j) / order_range
|
|
83
|
+
x0, y0 = end
|
|
84
|
+
x1, y1 = beg
|
|
85
|
+
dist = np.sqrt((x1-x0) ** 2 + (y1-y0) ** 2)
|
|
86
|
+
return dist / diam + order_d
|
|
87
|
+
for i in range(num):
|
|
88
|
+
graph.add_node(i)
|
|
89
|
+
max_step = 3 if num < 20 else 2
|
|
90
|
+
for step in range(1, max_step):
|
|
91
|
+
for i in range(num-step):
|
|
92
|
+
graph.add_edge(
|
|
93
|
+
i, i+step, weight=calc_weight(i, i+step))
|
|
94
|
+
graph.add_edge(
|
|
95
|
+
i+step, i, weight=calc_weight(i+step, i))
|
|
96
|
+
if 0 < graph.number_of_nodes():
|
|
97
|
+
min_path, _ = find_minimum_hamiltonian_path(graph)
|
|
98
|
+
if min_path:
|
|
99
|
+
page_or_block[:] = [tobe_sorted[i][-1]
|
|
100
|
+
for i in min_path] + unsorted
|
|
101
|
+
|
|
102
|
+
traverse(page)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def smooth_order(root):
|
|
106
|
+
if "PAGE" == root.tag:
|
|
107
|
+
smooth_order_page(root)
|
|
108
|
+
else:
|
|
109
|
+
for page in root.findall(".//PAGE"):
|
|
110
|
+
smooth_order_page(page)
|