google-cloud-documentai-toolbox 0.15.0a0__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.
- google/cloud/documentai_toolbox/__init__.py +44 -0
- google/cloud/documentai_toolbox/constants.py +56 -0
- google/cloud/documentai_toolbox/converters/__init__.py +15 -0
- google/cloud/documentai_toolbox/converters/config/__init__.py +15 -0
- google/cloud/documentai_toolbox/converters/config/bbox_conversion.py +267 -0
- google/cloud/documentai_toolbox/converters/config/block.py +239 -0
- google/cloud/documentai_toolbox/converters/converter.py +439 -0
- google/cloud/documentai_toolbox/converters/vision_helpers.py +401 -0
- google/cloud/documentai_toolbox/py.typed +2 -0
- google/cloud/documentai_toolbox/templates/hocr_document_template.xml.j2 +31 -0
- google/cloud/documentai_toolbox/utilities/__init__.py +15 -0
- google/cloud/documentai_toolbox/utilities/docai_utilities.py +53 -0
- google/cloud/documentai_toolbox/utilities/gcs_utilities.py +378 -0
- google/cloud/documentai_toolbox/version.py +16 -0
- google/cloud/documentai_toolbox/wrappers/__init__.py +15 -0
- google/cloud/documentai_toolbox/wrappers/document.py +964 -0
- google/cloud/documentai_toolbox/wrappers/entity.py +106 -0
- google/cloud/documentai_toolbox/wrappers/page.py +489 -0
- google_cloud_documentai_toolbox-0.15.0a0.dist-info/LICENSE +202 -0
- google_cloud_documentai_toolbox-0.15.0a0.dist-info/METADATA +165 -0
- google_cloud_documentai_toolbox-0.15.0a0.dist-info/RECORD +23 -0
- google_cloud_documentai_toolbox-0.15.0a0.dist-info/WHEEL +5 -0
- google_cloud_documentai_toolbox-0.15.0a0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
# Copyright 2022 Google LLC
|
|
3
|
+
#
|
|
4
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
# you may not use this file except in compliance with the License.
|
|
6
|
+
# You may obtain a copy of the License at
|
|
7
|
+
#
|
|
8
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
#
|
|
10
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
# See the License for the specific language governing permissions and
|
|
14
|
+
# limitations under the License.
|
|
15
|
+
#
|
|
16
|
+
|
|
17
|
+
import sys
|
|
18
|
+
import warnings
|
|
19
|
+
|
|
20
|
+
from google.cloud.documentai_toolbox import version as package_version
|
|
21
|
+
|
|
22
|
+
__version__ = package_version.__version__
|
|
23
|
+
|
|
24
|
+
from .converters import converter
|
|
25
|
+
from .utilities import docai_utilities, gcs_utilities
|
|
26
|
+
from .wrappers import document, entity, page
|
|
27
|
+
|
|
28
|
+
__all__ = (document, page, entity, converter, docai_utilities, gcs_utilities)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Python37DeprecationWarning(DeprecationWarning): # pragma: NO COVER
|
|
32
|
+
"""
|
|
33
|
+
Deprecation warning raised when Python 3.7 runtime is detected.
|
|
34
|
+
Python 3.7 support will be dropped after January 1, 2024.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
# Checks if the current runtime is Python 3.7.
|
|
39
|
+
if sys.version_info.major == 3 and sys.version_info.minor == 7: # pragma: NO COVER
|
|
40
|
+
message = (
|
|
41
|
+
"After January 1, 2024, new releases of this library will drop support "
|
|
42
|
+
"for Python 3.7."
|
|
43
|
+
)
|
|
44
|
+
warnings.warn(message, Python37DeprecationWarning)
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
# Copyright 2022 Google LLC
|
|
3
|
+
#
|
|
4
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
# you may not use this file except in compliance with the License.
|
|
6
|
+
# You may obtain a copy of the License at
|
|
7
|
+
#
|
|
8
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
#
|
|
10
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
# See the License for the specific language governing permissions and
|
|
14
|
+
# limitations under the License.
|
|
15
|
+
#
|
|
16
|
+
|
|
17
|
+
from typing import Union
|
|
18
|
+
|
|
19
|
+
from google.cloud.documentai import Document
|
|
20
|
+
|
|
21
|
+
USER_AGENT_PRODUCT = "documentai-toolbox"
|
|
22
|
+
|
|
23
|
+
JSON_EXTENSION = ".json"
|
|
24
|
+
JSON_MIMETYPE = "application/json"
|
|
25
|
+
|
|
26
|
+
PDF_EXTENSION = ".pdf"
|
|
27
|
+
PDF_MIMETYPE = "application/pdf"
|
|
28
|
+
|
|
29
|
+
FILE_CHECK_REGEX = r"(.*[.].*$)"
|
|
30
|
+
|
|
31
|
+
# https://cloud.google.com/document-ai/quotas#content_limits
|
|
32
|
+
BATCH_MAX_FILES = 1000
|
|
33
|
+
# 1GB in Bytes
|
|
34
|
+
BATCH_MAX_FILE_SIZE = 1073741824
|
|
35
|
+
BATCH_MAX_REQUESTS = 5
|
|
36
|
+
|
|
37
|
+
# https://cloud.google.com/document-ai/docs/file-types
|
|
38
|
+
VALID_MIME_TYPES = {
|
|
39
|
+
PDF_MIMETYPE,
|
|
40
|
+
"image/bmp",
|
|
41
|
+
"image/gif",
|
|
42
|
+
"image/jpeg",
|
|
43
|
+
"image/png",
|
|
44
|
+
"image/tiff",
|
|
45
|
+
"image/webp",
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
IMAGE_ENTITIES = {"Portrait"}
|
|
49
|
+
|
|
50
|
+
ElementWithLayout = Union[
|
|
51
|
+
Document.Page.Paragraph,
|
|
52
|
+
Document.Page,
|
|
53
|
+
Document.Page.Token,
|
|
54
|
+
Document.Page.Block,
|
|
55
|
+
Document.Page.Symbol,
|
|
56
|
+
]
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
# Copyright 2023 Google LLC
|
|
3
|
+
#
|
|
4
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
# you may not use this file except in compliance with the License.
|
|
6
|
+
# You may obtain a copy of the License at
|
|
7
|
+
#
|
|
8
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
#
|
|
10
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
# See the License for the specific language governing permissions and
|
|
14
|
+
# limitations under the License.
|
|
15
|
+
#
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
# Copyright 2023 Google LLC
|
|
3
|
+
#
|
|
4
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
# you may not use this file except in compliance with the License.
|
|
6
|
+
# You may obtain a copy of the License at
|
|
7
|
+
#
|
|
8
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
#
|
|
10
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
# See the License for the specific language governing permissions and
|
|
14
|
+
# limitations under the License.
|
|
15
|
+
#
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
# Copyright 2023 Google LLC
|
|
3
|
+
#
|
|
4
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
# you may not use this file except in compliance with the License.
|
|
6
|
+
# You may obtain a copy of the License at
|
|
7
|
+
#
|
|
8
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
#
|
|
10
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
# See the License for the specific language governing permissions and
|
|
14
|
+
# limitations under the License.
|
|
15
|
+
#
|
|
16
|
+
|
|
17
|
+
from typing import Callable, List, Optional
|
|
18
|
+
|
|
19
|
+
from intervaltree import intervaltree
|
|
20
|
+
|
|
21
|
+
from google.cloud import documentai
|
|
22
|
+
from google.cloud.documentai_toolbox.converters.config.block import Block
|
|
23
|
+
|
|
24
|
+
PIXEL_CONVERSION_RATES = {
|
|
25
|
+
"pxl": 1,
|
|
26
|
+
"inch": 96,
|
|
27
|
+
"cm": 37.795,
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _midpoint_in_bpoly(
|
|
32
|
+
box_a: documentai.BoundingPoly, box_b: documentai.BoundingPoly
|
|
33
|
+
) -> bool:
|
|
34
|
+
"""Returns whether the midpoint in box_a is inside box_b."""
|
|
35
|
+
|
|
36
|
+
# Calculate the midpoint of box_a.
|
|
37
|
+
mid_x_a = (_get_norm_x_max(box_a) + _get_norm_x_min(box_a)) / 2.0
|
|
38
|
+
mid_y_a = (_get_norm_y_max(box_a) + _get_norm_y_min(box_a)) / 2.0
|
|
39
|
+
|
|
40
|
+
max_x_b = _get_norm_x_max(box_b)
|
|
41
|
+
min_x_b = _get_norm_x_min(box_b)
|
|
42
|
+
max_y_b = _get_norm_y_max(box_b)
|
|
43
|
+
min_y_b = _get_norm_y_min(box_b)
|
|
44
|
+
|
|
45
|
+
return min_x_b < mid_x_a < max_x_b and min_y_b < mid_y_a < max_y_b
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _merge_text_anchors(
|
|
49
|
+
text_anchor_1: documentai.Document.TextAnchor,
|
|
50
|
+
text_anchor_2: documentai.Document.TextAnchor,
|
|
51
|
+
) -> documentai.Document.TextAnchor:
|
|
52
|
+
"""Merges two TextAnchor objects into one ascending sorted TextAnchor."""
|
|
53
|
+
intervals = []
|
|
54
|
+
for text_segment in text_anchor_1.text_segments:
|
|
55
|
+
intervals.append(
|
|
56
|
+
intervaltree.Interval(text_segment.start_index, text_segment.end_index)
|
|
57
|
+
)
|
|
58
|
+
for text_segment in text_anchor_2.text_segments:
|
|
59
|
+
intervals.append(
|
|
60
|
+
intervaltree.Interval(text_segment.start_index, text_segment.end_index)
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
merged_tree = intervaltree.IntervalTree(intervals)
|
|
64
|
+
merged_tree.merge_overlaps(strict=False)
|
|
65
|
+
|
|
66
|
+
merged_text_segments = [
|
|
67
|
+
documentai.Document.TextAnchor.TextSegment(
|
|
68
|
+
start_index=iv.begin, end_index=iv.end
|
|
69
|
+
)
|
|
70
|
+
for iv in sorted(merged_tree)
|
|
71
|
+
]
|
|
72
|
+
|
|
73
|
+
return documentai.Document.TextAnchor(text_segments=merged_text_segments)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def get_text_anchor_in_bbox(
|
|
77
|
+
bbox: documentai.BoundingPoly,
|
|
78
|
+
page: documentai.Document.Page,
|
|
79
|
+
token_in_bounding_box_function: Callable[
|
|
80
|
+
[documentai.BoundingPoly, documentai.BoundingPoly], bool
|
|
81
|
+
] = _midpoint_in_bpoly,
|
|
82
|
+
) -> documentai.Document.TextAnchor:
|
|
83
|
+
"""Gets mergedTextAnchor of Tokens in `page` that fall inside the `bbox`."""
|
|
84
|
+
|
|
85
|
+
text_anchor = documentai.Document.TextAnchor()
|
|
86
|
+
for token in page.tokens:
|
|
87
|
+
if token_in_bounding_box_function(token.layout.bounding_poly, bbox):
|
|
88
|
+
text_anchor = _merge_text_anchors(text_anchor, token.layout.text_anchor)
|
|
89
|
+
return text_anchor
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _get_norm_x_max(bbox: documentai.BoundingPoly) -> float:
|
|
93
|
+
return max([vertex.x for vertex in bbox.normalized_vertices])
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _get_norm_x_min(bbox: documentai.BoundingPoly) -> float:
|
|
97
|
+
return min([vertex.x for vertex in bbox.normalized_vertices])
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _get_norm_y_max(bbox: documentai.BoundingPoly) -> float:
|
|
101
|
+
return max([vertex.y for vertex in bbox.normalized_vertices])
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _get_norm_y_min(bbox: documentai.BoundingPoly) -> float:
|
|
105
|
+
return min([vertex.y for vertex in bbox.normalized_vertices])
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _normalize_coordinates(x, y) -> float:
|
|
109
|
+
return round(float(x / y), 9)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _convert_to_pixels(x: float, conversion_rate: float) -> float:
|
|
113
|
+
return x * conversion_rate
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _convert_bbox_units(
|
|
117
|
+
coordinate: float,
|
|
118
|
+
input_bbox_units: str,
|
|
119
|
+
width: Optional[float] = None,
|
|
120
|
+
height: Optional[float] = None,
|
|
121
|
+
multiplier: float = 1.0,
|
|
122
|
+
) -> float:
|
|
123
|
+
r"""Returns a converted coordinate.
|
|
124
|
+
|
|
125
|
+
Args:
|
|
126
|
+
coordinate (float):
|
|
127
|
+
Required.The coordinate from document.proto
|
|
128
|
+
input_bbox_units (str):
|
|
129
|
+
Required. The bounding box units.
|
|
130
|
+
width (float):
|
|
131
|
+
Optional.
|
|
132
|
+
height (float):
|
|
133
|
+
Optional.
|
|
134
|
+
multiplier (float):
|
|
135
|
+
Optional.
|
|
136
|
+
|
|
137
|
+
Returns:
|
|
138
|
+
float:
|
|
139
|
+
A converted coordinate.
|
|
140
|
+
|
|
141
|
+
"""
|
|
142
|
+
|
|
143
|
+
if input_bbox_units == "normalized":
|
|
144
|
+
return coordinate * multiplier
|
|
145
|
+
|
|
146
|
+
x = _convert_to_pixels(coordinate, PIXEL_CONVERSION_RATES.get(input_bbox_units, 1))
|
|
147
|
+
y = width or height
|
|
148
|
+
|
|
149
|
+
return _normalize_coordinates(x, y) * multiplier
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _get_multiplier(
|
|
153
|
+
docproto_coordinate: float, external_coordinate: float, input_bbox_units: str
|
|
154
|
+
) -> float:
|
|
155
|
+
r"""Returns a multiplier to use when converting bounding boxes.
|
|
156
|
+
|
|
157
|
+
Args:
|
|
158
|
+
docproto_coordinate (float):
|
|
159
|
+
Required.The coordinate from document.proto
|
|
160
|
+
external_coordinate (float):
|
|
161
|
+
Required.The coordinate from external annotations.
|
|
162
|
+
input_bbox_units (str):
|
|
163
|
+
Required. The bounding box units.
|
|
164
|
+
Returns:
|
|
165
|
+
float:
|
|
166
|
+
multiplier to use when converting bounding boxes.
|
|
167
|
+
|
|
168
|
+
"""
|
|
169
|
+
converted_coordinate = _convert_to_pixels(
|
|
170
|
+
external_coordinate, PIXEL_CONVERSION_RATES.get(input_bbox_units, 1)
|
|
171
|
+
)
|
|
172
|
+
return docproto_coordinate / converted_coordinate
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def convert_bbox_to_docproto_bbox(block: Block) -> documentai.BoundingPoly:
|
|
176
|
+
r"""Returns a converted bounding box from Block.
|
|
177
|
+
|
|
178
|
+
Args:
|
|
179
|
+
block (Block):
|
|
180
|
+
Required.
|
|
181
|
+
Returns:
|
|
182
|
+
documentai.BoundingPoly:
|
|
183
|
+
A documentai.BoundingPoly from bounding box.
|
|
184
|
+
|
|
185
|
+
"""
|
|
186
|
+
if block.bounding_box == []:
|
|
187
|
+
return documentai.BoundingPoly()
|
|
188
|
+
|
|
189
|
+
x_multiplier = 1.0
|
|
190
|
+
y_multiplier = 1.0
|
|
191
|
+
normalized_vertices: List[documentai.NormalizedVertex] = []
|
|
192
|
+
|
|
193
|
+
if block.page_width and block.page_height:
|
|
194
|
+
x_multiplier = _get_multiplier(
|
|
195
|
+
docproto_coordinate=block.docproto_width,
|
|
196
|
+
external_coordinate=block.page_width,
|
|
197
|
+
input_bbox_units=block.bounding_unit,
|
|
198
|
+
)
|
|
199
|
+
y_multiplier = _get_multiplier(
|
|
200
|
+
docproto_coordinate=block.docproto_height,
|
|
201
|
+
external_coordinate=block.page_height,
|
|
202
|
+
input_bbox_units=block.bounding_unit,
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
if block.bounding_type == "1":
|
|
206
|
+
# Type 1 : bounding box has 4 (x,y) coordinates
|
|
207
|
+
if isinstance(block.bounding_box, list):
|
|
208
|
+
for coordinate in block.bounding_box:
|
|
209
|
+
x = _convert_bbox_units(
|
|
210
|
+
coordinate[f"{block.bounding_x}"],
|
|
211
|
+
input_bbox_units=block.bounding_unit,
|
|
212
|
+
width=block.docproto_width,
|
|
213
|
+
multiplier=x_multiplier,
|
|
214
|
+
)
|
|
215
|
+
y = _convert_bbox_units(
|
|
216
|
+
coordinate[f"{block.bounding_y}"],
|
|
217
|
+
input_bbox_units=block.bounding_unit,
|
|
218
|
+
height=block.docproto_height,
|
|
219
|
+
multiplier=y_multiplier,
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
normalized_vertices.append(documentai.NormalizedVertex(x=x, y=y))
|
|
223
|
+
|
|
224
|
+
elif block.bounding_type == "2":
|
|
225
|
+
# Type 2 : bounding box has 1 (x,y) coordinates for the top left corner
|
|
226
|
+
# and (width, height)
|
|
227
|
+
x_min = _convert_bbox_units(
|
|
228
|
+
block.bounding_box[f"{block.bounding_x}"],
|
|
229
|
+
input_bbox_units=block.bounding_unit,
|
|
230
|
+
width=block.page_width,
|
|
231
|
+
multiplier=x_multiplier,
|
|
232
|
+
)
|
|
233
|
+
y_min = _convert_bbox_units(
|
|
234
|
+
block.bounding_box[f"{block.bounding_y}"],
|
|
235
|
+
input_bbox_units=block.bounding_unit,
|
|
236
|
+
width=block.page_height,
|
|
237
|
+
multiplier=y_multiplier,
|
|
238
|
+
)
|
|
239
|
+
x_max = x_min + block.bounding_width
|
|
240
|
+
y_max = y_min + block.bounding_height
|
|
241
|
+
normalized_vertices.extend(
|
|
242
|
+
[
|
|
243
|
+
documentai.NormalizedVertex(x=x_min, y=y_min),
|
|
244
|
+
documentai.NormalizedVertex(x=x_max, y=y_min),
|
|
245
|
+
documentai.NormalizedVertex(x=x_max, y=y_max),
|
|
246
|
+
documentai.NormalizedVertex(x=x_min, y=y_max),
|
|
247
|
+
]
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
elif block.bounding_type == "3":
|
|
251
|
+
# Type 3 : bounding_box: [x1, y1, x2, y2, x3, y3, x4, y4]
|
|
252
|
+
for idx in range(0, len(block.bounding_box), 2):
|
|
253
|
+
x = _convert_bbox_units(
|
|
254
|
+
block.bounding_box[idx],
|
|
255
|
+
input_bbox_units=block.bounding_unit,
|
|
256
|
+
width=block.docproto_width,
|
|
257
|
+
multiplier=x_multiplier,
|
|
258
|
+
)
|
|
259
|
+
y = _convert_bbox_units(
|
|
260
|
+
block.bounding_box[idx + 1],
|
|
261
|
+
input_bbox_units=block.bounding_unit,
|
|
262
|
+
width=block.docproto_height,
|
|
263
|
+
multiplier=y_multiplier,
|
|
264
|
+
)
|
|
265
|
+
normalized_vertices.append(documentai.NormalizedVertex(x=x, y=y))
|
|
266
|
+
|
|
267
|
+
return documentai.BoundingPoly(normalized_vertices=normalized_vertices)
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
# Copyright 2023 Google LLC
|
|
3
|
+
#
|
|
4
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
# you may not use this file except in compliance with the License.
|
|
6
|
+
# You may obtain a copy of the License at
|
|
7
|
+
#
|
|
8
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
#
|
|
10
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
# See the License for the specific language governing permissions and
|
|
14
|
+
# limitations under the License.
|
|
15
|
+
#
|
|
16
|
+
|
|
17
|
+
import dataclasses
|
|
18
|
+
import json
|
|
19
|
+
from types import SimpleNamespace
|
|
20
|
+
from typing import List, Optional, Type
|
|
21
|
+
|
|
22
|
+
from google.cloud import documentai
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _get_target_object(json_data: any, target_object: str) -> Optional[SimpleNamespace]:
|
|
26
|
+
r"""Returns SimpleNamespace of target_object.
|
|
27
|
+
|
|
28
|
+
Args:
|
|
29
|
+
json_data (str):
|
|
30
|
+
Required. data from JSON.loads .
|
|
31
|
+
target_object (str):
|
|
32
|
+
Required. The path to the target object.
|
|
33
|
+
|
|
34
|
+
Returns:
|
|
35
|
+
Optional[SimpleNamespace].
|
|
36
|
+
|
|
37
|
+
"""
|
|
38
|
+
json_data_s = SimpleNamespace(**json_data)
|
|
39
|
+
|
|
40
|
+
target_object_parts = target_object.split(".")
|
|
41
|
+
|
|
42
|
+
if not hasattr(json_data_s, target_object_parts[0]):
|
|
43
|
+
return None
|
|
44
|
+
|
|
45
|
+
for part in target_object_parts:
|
|
46
|
+
if type(json_data_s) is dict:
|
|
47
|
+
json_data_s = SimpleNamespace(**json_data_s)
|
|
48
|
+
elif type(json_data_s) is list and part.isnumeric():
|
|
49
|
+
json_data_s = json_data_s[int(part)]
|
|
50
|
+
continue
|
|
51
|
+
json_data_s = getattr(json_data_s, part)
|
|
52
|
+
return json_data_s
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclasses.dataclass
|
|
56
|
+
class Block:
|
|
57
|
+
r"""Represents a Block from OCR data.
|
|
58
|
+
|
|
59
|
+
Attributes:
|
|
60
|
+
bounding_box (str):
|
|
61
|
+
Required.
|
|
62
|
+
block_references:
|
|
63
|
+
Optional.
|
|
64
|
+
block_id:
|
|
65
|
+
Optional.
|
|
66
|
+
confidence:
|
|
67
|
+
Optional.
|
|
68
|
+
type_:
|
|
69
|
+
Required.
|
|
70
|
+
text:
|
|
71
|
+
Required.
|
|
72
|
+
page_number:
|
|
73
|
+
Optional.
|
|
74
|
+
"""
|
|
75
|
+
type_: SimpleNamespace = dataclasses.field(init=True, repr=False)
|
|
76
|
+
text: SimpleNamespace = dataclasses.field(init=True, repr=False)
|
|
77
|
+
bounding_box: Optional[SimpleNamespace] = dataclasses.field(
|
|
78
|
+
init=True, repr=False, default=None
|
|
79
|
+
)
|
|
80
|
+
block_references: Optional[SimpleNamespace] = dataclasses.field(
|
|
81
|
+
init=True, repr=False, default=None
|
|
82
|
+
)
|
|
83
|
+
block_id: Optional[SimpleNamespace] = dataclasses.field(
|
|
84
|
+
init=False, repr=False, default=None
|
|
85
|
+
)
|
|
86
|
+
confidence: Optional[SimpleNamespace] = dataclasses.field(
|
|
87
|
+
init=False, repr=False, default=None
|
|
88
|
+
)
|
|
89
|
+
page_number: Optional[SimpleNamespace] = dataclasses.field(
|
|
90
|
+
init=False, repr=False, default=None
|
|
91
|
+
)
|
|
92
|
+
page_width: Optional[SimpleNamespace] = dataclasses.field(
|
|
93
|
+
init=False, repr=False, default=None
|
|
94
|
+
)
|
|
95
|
+
page_height: Optional[SimpleNamespace] = dataclasses.field(
|
|
96
|
+
init=False, repr=False, default=None
|
|
97
|
+
)
|
|
98
|
+
bounding_width: Optional[SimpleNamespace] = dataclasses.field(
|
|
99
|
+
init=False, repr=False, default=None
|
|
100
|
+
)
|
|
101
|
+
bounding_height: Optional[SimpleNamespace] = dataclasses.field(
|
|
102
|
+
init=False, repr=False, default=None
|
|
103
|
+
)
|
|
104
|
+
bounding_type: Optional[SimpleNamespace] = dataclasses.field(
|
|
105
|
+
init=False, repr=False, default=None
|
|
106
|
+
)
|
|
107
|
+
bounding_unit: Optional[SimpleNamespace] = dataclasses.field(
|
|
108
|
+
init=False, repr=False, default=None
|
|
109
|
+
)
|
|
110
|
+
bounding_x: Optional[SimpleNamespace] = dataclasses.field(
|
|
111
|
+
init=False, repr=False, default=None
|
|
112
|
+
)
|
|
113
|
+
bounding_y: Optional[SimpleNamespace] = dataclasses.field(
|
|
114
|
+
init=False, repr=False, default=None
|
|
115
|
+
)
|
|
116
|
+
docproto_width: Optional[float] = dataclasses.field(
|
|
117
|
+
init=False, repr=False, default=None
|
|
118
|
+
)
|
|
119
|
+
docproto_height: Optional[float] = dataclasses.field(
|
|
120
|
+
init=False, repr=False, default=None
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
@classmethod
|
|
124
|
+
def load_blocks_from_schema(
|
|
125
|
+
cls: Type["Block"],
|
|
126
|
+
input_data: bytes,
|
|
127
|
+
input_config: bytes,
|
|
128
|
+
base_docproto: documentai.Document,
|
|
129
|
+
) -> List["Block"]:
|
|
130
|
+
r"""Loads Blocks from original annotation data and provided config.
|
|
131
|
+
|
|
132
|
+
Args:
|
|
133
|
+
input_data (bytes):
|
|
134
|
+
Required.The bytes of the annotated data.
|
|
135
|
+
input_config (bytes):
|
|
136
|
+
Required.The bytes of config data.
|
|
137
|
+
base_docproto (bytes):
|
|
138
|
+
Required. The bytes of the original pdf.
|
|
139
|
+
|
|
140
|
+
Returns:
|
|
141
|
+
List[Block]:
|
|
142
|
+
From original annotation data and provided config.
|
|
143
|
+
|
|
144
|
+
"""
|
|
145
|
+
objects = json.loads(input_data)
|
|
146
|
+
schema_json = json.loads(
|
|
147
|
+
input_config, object_hook=lambda d: SimpleNamespace(**d)
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
entities = schema_json.entity_object
|
|
151
|
+
type_ = schema_json.entity.type_
|
|
152
|
+
|
|
153
|
+
mention_text = schema_json.entity.mention_text
|
|
154
|
+
|
|
155
|
+
id_ = getattr(schema_json.entity, "id", None)
|
|
156
|
+
document_height = (
|
|
157
|
+
getattr(schema_json.page, "height", None)
|
|
158
|
+
if hasattr(schema_json, "page")
|
|
159
|
+
else None
|
|
160
|
+
)
|
|
161
|
+
document_width = (
|
|
162
|
+
getattr(schema_json.page, "width", None)
|
|
163
|
+
if hasattr(schema_json, "page")
|
|
164
|
+
else None
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
confidence = getattr(schema_json.entity, "confidence", None)
|
|
168
|
+
page_number = getattr(schema_json.entity, "page_number", None)
|
|
169
|
+
normalized_vertices = getattr(
|
|
170
|
+
schema_json.entity.normalized_vertices, "base", None
|
|
171
|
+
)
|
|
172
|
+
bounding_width = getattr(schema_json.entity.normalized_vertices, "width", None)
|
|
173
|
+
bounding_height = getattr(
|
|
174
|
+
schema_json.entity.normalized_vertices, "height", None
|
|
175
|
+
)
|
|
176
|
+
bounding_type = getattr(schema_json.entity.normalized_vertices, "type", None)
|
|
177
|
+
bounding_unit = getattr(schema_json.entity.normalized_vertices, "unit", None)
|
|
178
|
+
bounding_x = getattr(schema_json.entity.normalized_vertices, "x", None)
|
|
179
|
+
bounding_y = getattr(schema_json.entity.normalized_vertices, "y", None)
|
|
180
|
+
|
|
181
|
+
blocks: List[Block] = []
|
|
182
|
+
ens = _get_target_object(objects, entities)
|
|
183
|
+
for i in ens:
|
|
184
|
+
entity = i
|
|
185
|
+
|
|
186
|
+
block_text = ""
|
|
187
|
+
|
|
188
|
+
if type_ == f"{entities}:self":
|
|
189
|
+
block_type = i
|
|
190
|
+
entity = _get_target_object(objects, f"{entities}.{i}")
|
|
191
|
+
else:
|
|
192
|
+
block_type = _get_target_object(entity, type_)
|
|
193
|
+
|
|
194
|
+
if "||" in mention_text:
|
|
195
|
+
text_commands = mention_text.split("||")
|
|
196
|
+
for command in text_commands:
|
|
197
|
+
if command in entity:
|
|
198
|
+
block_text = _get_target_object(entity, command)
|
|
199
|
+
continue
|
|
200
|
+
else:
|
|
201
|
+
block_text = _get_target_object(entity, mention_text)
|
|
202
|
+
|
|
203
|
+
b = Block(
|
|
204
|
+
type_=block_type,
|
|
205
|
+
text=block_text,
|
|
206
|
+
bounding_box=_get_target_object(entity, normalized_vertices),
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
if id_:
|
|
210
|
+
b.id_ = _get_target_object(entity, id_)
|
|
211
|
+
if confidence:
|
|
212
|
+
b.confidence = _get_target_object(entity, confidence)
|
|
213
|
+
if page_number and page_number in entity:
|
|
214
|
+
b.page_number = _get_target_object(entity, page_number)
|
|
215
|
+
if bounding_width:
|
|
216
|
+
b.bounding_width = _get_target_object(b.bounding_box, bounding_width)
|
|
217
|
+
if bounding_height:
|
|
218
|
+
b.bounding_height = _get_target_object(b.bounding_box, bounding_height)
|
|
219
|
+
if document_height:
|
|
220
|
+
b.page_height = _get_target_object(objects, document_height)
|
|
221
|
+
if document_width:
|
|
222
|
+
b.page_width = _get_target_object(objects, document_width)
|
|
223
|
+
if bounding_type:
|
|
224
|
+
b.bounding_type = bounding_type
|
|
225
|
+
if bounding_unit:
|
|
226
|
+
b.bounding_unit = bounding_unit
|
|
227
|
+
if bounding_x:
|
|
228
|
+
b.bounding_x = bounding_x
|
|
229
|
+
if bounding_y:
|
|
230
|
+
b.bounding_y = bounding_y
|
|
231
|
+
|
|
232
|
+
if b.page_number is None:
|
|
233
|
+
b.page_number = 0
|
|
234
|
+
|
|
235
|
+
b.docproto_width = base_docproto.pages[int(b.page_number)].dimension.width
|
|
236
|
+
b.docproto_height = base_docproto.pages[int(b.page_number)].dimension.height
|
|
237
|
+
|
|
238
|
+
blocks.append(b)
|
|
239
|
+
return blocks
|