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,178 @@
|
|
|
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 xml.etree.ElementTree as et
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
from reading_order.utils.logger import get_logger
|
|
12
|
+
from reading_order.utils.xml import IndexedTags, insert_before
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def group_warichu(root):
|
|
16
|
+
"""
|
|
17
|
+
LINE tags of 割注 type are grouped through the dilation process. Generate a
|
|
18
|
+
new WARICHUBLOCK tag for each group and store the 割注 LINEs under it.
|
|
19
|
+
WARICHUBLOCK are intermediate products that should not be included in the
|
|
20
|
+
final output. When you are finished using them, discard them using
|
|
21
|
+
`ungroup_warichu`.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
logger = get_logger("ReadingOrder")
|
|
25
|
+
|
|
26
|
+
def parse_bbox(tag):
|
|
27
|
+
x = int(tag.get("X"))
|
|
28
|
+
y = int(tag.get("Y"))
|
|
29
|
+
w = int(tag.get("WIDTH"))
|
|
30
|
+
h = int(tag.get("HEIGHT"))
|
|
31
|
+
return (x, y, x+w, y+h)
|
|
32
|
+
|
|
33
|
+
def parse_order(tag):
|
|
34
|
+
f = float(tag.get("ORDER"))
|
|
35
|
+
return f
|
|
36
|
+
|
|
37
|
+
def dilate_bbox(data):
|
|
38
|
+
x0, y0, x1, y1 = data["bbox"]
|
|
39
|
+
w, h = x1 - x0, y1 - y0
|
|
40
|
+
is_vertical = w < h
|
|
41
|
+
if is_vertical:
|
|
42
|
+
step = w * 0.1
|
|
43
|
+
data["bbox"] = (x0 - step/2, y0, x1 + step/2, y1)
|
|
44
|
+
else:
|
|
45
|
+
step = h * 0.1
|
|
46
|
+
data["bbox"] = (x0, y0 - step/2, x1, y1 + step/2)
|
|
47
|
+
return data
|
|
48
|
+
|
|
49
|
+
def detect_parent(group):
|
|
50
|
+
for warichu in group:
|
|
51
|
+
parent = warichu["parent"]
|
|
52
|
+
if "TEXTBLOCK" == parent.tag:
|
|
53
|
+
return parent, warichu["obj"]
|
|
54
|
+
elif "PAGE" != parent.tag:
|
|
55
|
+
logger.warning("Warichu was found under: %s" % parent.tag)
|
|
56
|
+
if group:
|
|
57
|
+
return group[0]["parent"], group[0]["obj"]
|
|
58
|
+
else:
|
|
59
|
+
return None, None
|
|
60
|
+
|
|
61
|
+
def bounding_bbox(*bbox):
|
|
62
|
+
min_x = min(x0 for x0, _, _, _ in bbox)
|
|
63
|
+
min_y = min(y0 for _, y0, _, _ in bbox)
|
|
64
|
+
max_x = max(x1 for _, _, x1, _ in bbox)
|
|
65
|
+
max_y = max(y1 for _, _, _, y1 in bbox)
|
|
66
|
+
return (min_x, min_y, max_x, max_y)
|
|
67
|
+
|
|
68
|
+
def intersect_1d(line0, line1):
|
|
69
|
+
x0, x1 = line0
|
|
70
|
+
y0, y1 = line1
|
|
71
|
+
# line0 ---- cases
|
|
72
|
+
# / -- (1)
|
|
73
|
+
# | -- (2)
|
|
74
|
+
# line1 -- (3)
|
|
75
|
+
# | -- (4)
|
|
76
|
+
# ¥ -- (5)
|
|
77
|
+
if y1 < x0:
|
|
78
|
+
return 0 # (1)
|
|
79
|
+
elif y0 < x0:
|
|
80
|
+
return y1 - x0 # (2)
|
|
81
|
+
elif y1 < x1:
|
|
82
|
+
return y1 - y0 # (3)
|
|
83
|
+
elif y0 < x1:
|
|
84
|
+
return x1 - y0 # (4)
|
|
85
|
+
else:
|
|
86
|
+
return 0 # (5)
|
|
87
|
+
|
|
88
|
+
def intersect_bbox(bbox0, bbox1):
|
|
89
|
+
x00, y00, x01, y01 = bbox0
|
|
90
|
+
x10, y10, x11, y11 = bbox1
|
|
91
|
+
return (intersect_1d((x00, x01), (x10, x11)) *
|
|
92
|
+
intersect_1d((y00, y01), (y10, y11)))
|
|
93
|
+
|
|
94
|
+
def apply_page(page):
|
|
95
|
+
with IndexedTags(root) as it:
|
|
96
|
+
warichu_list = list()
|
|
97
|
+
|
|
98
|
+
for line in page.findall(".//LINE[@TYPE='割注']"):
|
|
99
|
+
index = int(line.get(it.key))
|
|
100
|
+
warichu_list.append({
|
|
101
|
+
"bbox": parse_bbox(line),
|
|
102
|
+
"bbox_orig": parse_bbox(line),
|
|
103
|
+
"obj": line,
|
|
104
|
+
"index": index,
|
|
105
|
+
"order": parse_order(line),
|
|
106
|
+
"parent": page.find(".//LINE[@%s='%d']/.." %
|
|
107
|
+
(it.key, index)),
|
|
108
|
+
})
|
|
109
|
+
|
|
110
|
+
for i, warichu in enumerate(warichu_list):
|
|
111
|
+
warichu_list[i] = dilate_bbox(warichu)
|
|
112
|
+
|
|
113
|
+
groups = list()
|
|
114
|
+
grouped = list()
|
|
115
|
+
for w0 in warichu_list:
|
|
116
|
+
if w0["index"] in grouped:
|
|
117
|
+
continue
|
|
118
|
+
groups.append([w0])
|
|
119
|
+
grouped.append(w0["index"])
|
|
120
|
+
for w1 in warichu_list:
|
|
121
|
+
if w1["index"] in grouped:
|
|
122
|
+
continue
|
|
123
|
+
if 0 < intersect_bbox(w0["bbox"], w1["bbox"]):
|
|
124
|
+
groups[-1].append(w1)
|
|
125
|
+
grouped.append(w1["index"])
|
|
126
|
+
|
|
127
|
+
for group in groups:
|
|
128
|
+
x0, y0, x1, y1 = bounding_bbox(
|
|
129
|
+
*[w["bbox_orig"] for w in group])
|
|
130
|
+
order = np.median([w["order"] for w in group])
|
|
131
|
+
block = et.Element("WARICHUBLOCK", attrib={
|
|
132
|
+
"X": str(x0),
|
|
133
|
+
"Y": str(y0),
|
|
134
|
+
"WIDTH": str(x1 - x0),
|
|
135
|
+
"HEIGHT": str(y1 - y0),
|
|
136
|
+
"ORDER": str(order),
|
|
137
|
+
})
|
|
138
|
+
for warichu in group:
|
|
139
|
+
block.append(warichu["obj"])
|
|
140
|
+
parent, child = detect_parent(group)
|
|
141
|
+
insert_before(parent, block, child)
|
|
142
|
+
for warichu in group:
|
|
143
|
+
warichu["parent"].remove(warichu["obj"])
|
|
144
|
+
|
|
145
|
+
if "PAGE" == root.tag:
|
|
146
|
+
apply_page(root)
|
|
147
|
+
else:
|
|
148
|
+
for page in root.findall(".//PAGE"):
|
|
149
|
+
apply_page(page)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def ungroup_warichu(root):
|
|
153
|
+
if "WARICHUBLOCK" == root.tag:
|
|
154
|
+
raise ValueError("Cannot move child elements outside the root element.")
|
|
155
|
+
def _ungroup_warichu(parent):
|
|
156
|
+
new_children = []
|
|
157
|
+
for child in parent:
|
|
158
|
+
_ungroup_warichu(child)
|
|
159
|
+
if "WARICHUBLOCK" == child.tag:
|
|
160
|
+
for tag in child:
|
|
161
|
+
new_children.append(tag)
|
|
162
|
+
else:
|
|
163
|
+
new_children.append(child)
|
|
164
|
+
parent[:] = new_children
|
|
165
|
+
_ungroup_warichu(root)
|
|
166
|
+
return root
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
class GroupWarichu:
|
|
170
|
+
def __init__(self, xml):
|
|
171
|
+
self.xml = xml
|
|
172
|
+
group_warichu(self.xml)
|
|
173
|
+
|
|
174
|
+
def __enter__(self):
|
|
175
|
+
pass
|
|
176
|
+
|
|
177
|
+
def __exit__(self, *_):
|
|
178
|
+
ungroup_warichu(self.xml)
|
|
@@ -0,0 +1,13 @@
|
|
|
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
|
+
def wrap_ocr_dataset(xml_file):
|
|
8
|
+
contents = open(xml_file, "r", encoding="utf-8").read()
|
|
9
|
+
with open(xml_file, "w", encoding="utf-8") as fo:
|
|
10
|
+
fo.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
|
|
11
|
+
"<OCRDATASET>\n")
|
|
12
|
+
fo.write(contents)
|
|
13
|
+
fo.write("</OCRDATASET>\n")
|
|
File without changes
|
|
@@ -0,0 +1,21 @@
|
|
|
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
|
+
def collect_files(path, only=None, skip=None, ext=""):
|
|
8
|
+
from itertools import chain
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from yaspin import yaspin
|
|
11
|
+
path = Path(path)
|
|
12
|
+
if path.is_file():
|
|
13
|
+
return [path]
|
|
14
|
+
files = list()
|
|
15
|
+
with yaspin(text="Collecting files"):
|
|
16
|
+
globs = chain(*[path.rglob("*"+e) for e in ext.split("|")])
|
|
17
|
+
for file_path in globs:
|
|
18
|
+
if (only and only not in file_path.name) or (skip and skip in file_path.name):
|
|
19
|
+
continue
|
|
20
|
+
files.append(file_path)
|
|
21
|
+
return files
|
|
@@ -0,0 +1,29 @@
|
|
|
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
|
+
def get_logger(key, level="DEBUG"):
|
|
8
|
+
import logging
|
|
9
|
+
|
|
10
|
+
level = {
|
|
11
|
+
"NOTSET": logging.NOTSET,
|
|
12
|
+
"DEBUG": logging.DEBUG,
|
|
13
|
+
"INFO": logging.INFO,
|
|
14
|
+
"WARN": logging.WARN,
|
|
15
|
+
"ERROR": logging.ERROR,
|
|
16
|
+
"CRITICAL": logging.CRITICAL,
|
|
17
|
+
}.get(level.upper(), logging.NOTSET)
|
|
18
|
+
|
|
19
|
+
logger = logging.getLogger(key)
|
|
20
|
+
logger.setLevel(level)
|
|
21
|
+
|
|
22
|
+
if not logger.hasHandlers():
|
|
23
|
+
handler = logging.StreamHandler()
|
|
24
|
+
formatter = logging.Formatter(
|
|
25
|
+
"%(asctime)s - %(name)s - %(levelname)s - %(message)s")
|
|
26
|
+
handler.setFormatter(formatter)
|
|
27
|
+
logger.addHandler(handler)
|
|
28
|
+
|
|
29
|
+
return logger
|
|
@@ -0,0 +1,63 @@
|
|
|
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
|
+
class TimeMeasuredScope:
|
|
8
|
+
def __init__(self, keeper, key):
|
|
9
|
+
from time import perf_counter
|
|
10
|
+
current_time = perf_counter()
|
|
11
|
+
self.keeper = keeper
|
|
12
|
+
self.key = key
|
|
13
|
+
self.beg = current_time
|
|
14
|
+
|
|
15
|
+
def __enter__(self):
|
|
16
|
+
return self
|
|
17
|
+
|
|
18
|
+
def __exit__(self, *_):
|
|
19
|
+
from time import perf_counter
|
|
20
|
+
current_time = perf_counter()
|
|
21
|
+
dur = current_time - self.beg
|
|
22
|
+
self.keeper.record(self.key, dur)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class TimeKeeper:
|
|
26
|
+
def __init__(self):
|
|
27
|
+
self.keys = list()
|
|
28
|
+
self.times = dict()
|
|
29
|
+
|
|
30
|
+
def measure_time(self, key):
|
|
31
|
+
if key not in self.keys:
|
|
32
|
+
self.keys.append(key)
|
|
33
|
+
self.times[key] = list()
|
|
34
|
+
return TimeMeasuredScope(self, key)
|
|
35
|
+
|
|
36
|
+
def record(self, key, time):
|
|
37
|
+
self.times[key].append(time)
|
|
38
|
+
|
|
39
|
+
def num(self, key):
|
|
40
|
+
return len(self.times[key])
|
|
41
|
+
|
|
42
|
+
def total(self, key):
|
|
43
|
+
return sum(self.times[key])
|
|
44
|
+
|
|
45
|
+
def mean(self, key):
|
|
46
|
+
return self.total(key) / self.num(key)
|
|
47
|
+
|
|
48
|
+
def median(self, key):
|
|
49
|
+
return sorted(self.times[key])[self.num(key) // 2]
|
|
50
|
+
|
|
51
|
+
def print(self, logger=None):
|
|
52
|
+
if not logger:
|
|
53
|
+
from .logger import get_logger
|
|
54
|
+
logger = get_logger(__name__)
|
|
55
|
+
for key in self.keys:
|
|
56
|
+
if 1 < self.num(key):
|
|
57
|
+
logger.info("Total time for %s [ms]: %.3f" %
|
|
58
|
+
(key, self.total(key) * 1e3))
|
|
59
|
+
logger.info("Average time for %s [ms]: %.3f" %
|
|
60
|
+
(key, self.mean(key) * 1e3))
|
|
61
|
+
elif 1 == self.num(key):
|
|
62
|
+
logger.info("Time for %s [ms]: %.3f" %
|
|
63
|
+
(key, self.times[key][0] * 1e3))
|
|
@@ -0,0 +1,97 @@
|
|
|
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 xml.etree.ElementTree as et
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class IndexedTags:
|
|
11
|
+
"""
|
|
12
|
+
Mark the order of each tag in a depth first order. This orders are used for
|
|
13
|
+
an algorithm that requires unique keys to point each xml tag. The marks are
|
|
14
|
+
removed after exiting from the `with` scope.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
def __init__(self, xml):
|
|
18
|
+
from uuid import uuid4
|
|
19
|
+
self.xml = xml
|
|
20
|
+
self.key = uuid4().hex
|
|
21
|
+
for i, elem in enumerate(self.xml.iter("*")):
|
|
22
|
+
elem.set(self.key, str(i))
|
|
23
|
+
|
|
24
|
+
def __enter__(self):
|
|
25
|
+
return self
|
|
26
|
+
|
|
27
|
+
def __exit__(self, *_):
|
|
28
|
+
for elem in self.xml.iter("*"):
|
|
29
|
+
if self.key in elem.attrib:
|
|
30
|
+
del elem.attrib[self.key]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class ConstantNumberOfTags:
|
|
34
|
+
"""
|
|
35
|
+
If an operation on xml does not change the number of tags before and after
|
|
36
|
+
it (e.g. sorting tags), it is recommended that the operation is enclosed by
|
|
37
|
+
this block. If the number of tags changes, an error is raised.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
def __init__(self, xml):
|
|
41
|
+
self.xml = xml
|
|
42
|
+
self.num = sum(1 for _ in self.xml.findall(".//*"))
|
|
43
|
+
|
|
44
|
+
def __enter__(self):
|
|
45
|
+
return self
|
|
46
|
+
|
|
47
|
+
def __exit__(self, *_):
|
|
48
|
+
num = sum(1 for _ in self.xml.findall(".//*"))
|
|
49
|
+
if self.num != num:
|
|
50
|
+
raise RuntimeError("Number of XML tags changed: %d -> %d" %
|
|
51
|
+
(self.num, num))
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def insert_before(parent: et.Element, element: et.Element, anchor: et.Element):
|
|
55
|
+
"""
|
|
56
|
+
Insert an element to the parent, right before the anchor.
|
|
57
|
+
"""
|
|
58
|
+
for i, child in enumerate(parent):
|
|
59
|
+
if child == anchor:
|
|
60
|
+
parent.insert(i, element)
|
|
61
|
+
break
|
|
62
|
+
else:
|
|
63
|
+
raise RuntimeError("Cannot find anchor tag: %s" % anchor.tag)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def insert_after(parent: et.Element, element: et.Element, anchor: et.Element):
|
|
67
|
+
"""
|
|
68
|
+
Insert an element to the parent, right after the anchor.
|
|
69
|
+
"""
|
|
70
|
+
for i, child in enumerate(parent):
|
|
71
|
+
if child == anchor:
|
|
72
|
+
parent.insert(i + 1, element)
|
|
73
|
+
break
|
|
74
|
+
else:
|
|
75
|
+
raise RuntimeError("Cannot find anchor tag: %s" % anchor.tag)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def shuffle_xml(xml: et.Element):
|
|
79
|
+
"""
|
|
80
|
+
Apply shuffling recursively
|
|
81
|
+
"""
|
|
82
|
+
from random import shuffle
|
|
83
|
+
for child in xml:
|
|
84
|
+
shuffle_xml(child)
|
|
85
|
+
if 1 < len(xml):
|
|
86
|
+
shuffle(xml)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def shuffle_xml_file(input_path, output_path):
|
|
90
|
+
"""
|
|
91
|
+
Randomly reorder tags in XML files. Each tag's parent-child relationships
|
|
92
|
+
are preserved.
|
|
93
|
+
"""
|
|
94
|
+
root = et.parse(input_path).getroot()
|
|
95
|
+
shuffle_xml(root)
|
|
96
|
+
et.ElementTree(root).write(
|
|
97
|
+
output_path, encoding="utf-8", xml_declaration=True)
|
|
File without changes
|