-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathbbox_conversion.py
More file actions
281 lines (228 loc) · 9.38 KB
/
bbox_conversion.py
File metadata and controls
281 lines (228 loc) · 9.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
# -*- coding: utf-8 -*-
# Copyright 2023 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from typing import Callable, List, Optional
from intervaltree import intervaltree
from google.cloud import documentai
from google.cloud.documentai_toolbox.converters.config.block import Block
PIXEL_CONVERSION_RATES = {
"pxl": 1,
"inch": 96,
"cm": 37.795,
}
def _midpoint_in_bpoly(
box_a: documentai.BoundingPoly, box_b: documentai.BoundingPoly
) -> bool:
"""Returns whether the midpoint in box_a is inside box_b."""
# Calculate the midpoint of box_a.
mid_x_a = (_get_norm_x_max(box_a) + _get_norm_x_min(box_a)) / 2.0
mid_y_a = (_get_norm_y_max(box_a) + _get_norm_y_min(box_a)) / 2.0
max_x_b = _get_norm_x_max(box_b)
min_x_b = _get_norm_x_min(box_b)
max_y_b = _get_norm_y_max(box_b)
min_y_b = _get_norm_y_min(box_b)
return min_x_b < mid_x_a < max_x_b and min_y_b < mid_y_a < max_y_b
def _merge_text_anchors(
text_anchor_1: documentai.Document.TextAnchor,
text_anchor_2: documentai.Document.TextAnchor,
) -> documentai.Document.TextAnchor:
"""Merges two TextAnchor objects into one ascending sorted TextAnchor."""
intervals = []
for text_segment in text_anchor_1.text_segments:
intervals.append(
intervaltree.Interval(text_segment.start_index, text_segment.end_index)
)
for text_segment in text_anchor_2.text_segments:
intervals.append(
intervaltree.Interval(text_segment.start_index, text_segment.end_index)
)
merged_tree = intervaltree.IntervalTree(intervals)
merged_tree.merge_overlaps(strict=False)
merged_text_segments = [
documentai.Document.TextAnchor.TextSegment(
start_index=iv.begin, end_index=iv.end
)
for iv in sorted(merged_tree)
]
return documentai.Document.TextAnchor(text_segments=merged_text_segments)
def get_text_anchor_in_bbox(
bbox: documentai.BoundingPoly,
page: documentai.Document.Page,
token_in_bounding_box_function: Callable[
[documentai.BoundingPoly, documentai.BoundingPoly], bool
] = _midpoint_in_bpoly,
) -> documentai.Document.TextAnchor:
"""Gets mergedTextAnchor of Tokens in `page` that fall inside the `bbox`."""
text_anchor = documentai.Document.TextAnchor()
for token in page.tokens:
if token_in_bounding_box_function(token.layout.bounding_poly, bbox):
text_anchor = _merge_text_anchors(text_anchor, token.layout.text_anchor)
return text_anchor
def _get_norm_x_max(bbox: documentai.BoundingPoly) -> float:
return max([vertex.x for vertex in bbox.normalized_vertices])
def _get_norm_x_min(bbox: documentai.BoundingPoly) -> float:
return min([vertex.x for vertex in bbox.normalized_vertices])
def _get_norm_y_max(bbox: documentai.BoundingPoly) -> float:
return max([vertex.y for vertex in bbox.normalized_vertices])
def _get_norm_y_min(bbox: documentai.BoundingPoly) -> float:
return min([vertex.y for vertex in bbox.normalized_vertices])
def _normalize_coordinates(x, y) -> float:
return round(float(x / y), 9)
def _convert_to_pixels(x: float, conversion_rate: float) -> float:
return x * conversion_rate
def _convert_bbox_units(
coordinate: float,
input_bbox_units: str,
width: Optional[float] = None,
height: Optional[float] = None,
multiplier: float = 1.0,
) -> float:
r"""Returns a converted coordinate.
Args:
coordinate (float):
Required.The coordinate from document.proto
input_bbox_units (str):
Required. The bounding box units.
width (float):
Optional.
height (float):
Optional.
multiplier (float):
Optional.
Returns:
float:
A converted coordinate.
"""
if input_bbox_units == "normalized":
return coordinate * multiplier
x = _convert_to_pixels(coordinate, PIXEL_CONVERSION_RATES.get(input_bbox_units, 1))
y = width or height
return _normalize_coordinates(x, y) * multiplier
def _get_multiplier(
docproto_coordinate: float, external_coordinate: float, input_bbox_units: str
) -> float:
r"""Returns a multiplier to use when converting bounding boxes.
Args:
docproto_coordinate (float):
Required.The coordinate from document.proto
external_coordinate (float):
Required.The coordinate from external annotations.
input_bbox_units (str):
Required. The bounding box units.
Returns:
float:
multiplier to use when converting bounding boxes.
"""
converted_coordinate = _convert_to_pixels(
external_coordinate, PIXEL_CONVERSION_RATES.get(input_bbox_units, 1)
)
return docproto_coordinate / converted_coordinate
def convert_bbox_to_docproto_bbox(block: Block) -> documentai.BoundingPoly:
r"""Returns a converted bounding box from Block.
Args:
block (Block):
Required.
Returns:
documentai.BoundingPoly:
A documentai.BoundingPoly from bounding box.
"""
if block.bounding_box == []:
return documentai.BoundingPoly()
x_multiplier = 1.0
y_multiplier = 1.0
normalized_vertices: List[documentai.NormalizedVertex] = []
if (
block.page_width
and block.page_height
and block.docproto_width is not None
and block.docproto_height is not None
):
x_multiplier = _get_multiplier(
docproto_coordinate=block.docproto_width,
external_coordinate=block.page_width,
input_bbox_units=block.bounding_unit or "normalized",
)
y_multiplier = _get_multiplier(
docproto_coordinate=block.docproto_height,
external_coordinate=block.page_height,
input_bbox_units=block.bounding_unit or "normalized",
)
if block.bounding_type == "1":
# Type 1 : bounding box has 4 (x,y) coordinates
if isinstance(block.bounding_box, list):
for coordinate in block.bounding_box:
x = _convert_bbox_units(
coordinate[f"{block.bounding_x}"],
input_bbox_units=block.bounding_unit or "normalized",
width=block.docproto_width,
multiplier=x_multiplier,
)
y = _convert_bbox_units(
coordinate[f"{block.bounding_y}"],
input_bbox_units=block.bounding_unit or "normalized",
height=block.docproto_height,
multiplier=y_multiplier,
)
normalized_vertices.append(documentai.NormalizedVertex(x=x, y=y))
elif block.bounding_type == "2":
# Type 2 : bounding box has 1 (x,y) coordinates for the top left corner
# and (width, height)
if not isinstance(block.bounding_box, dict):
raise TypeError("Expected dict for bounding_box in Type 2")
x_min = _convert_bbox_units(
block.bounding_box[f"{block.bounding_x}"],
input_bbox_units=block.bounding_unit or "normalized",
width=block.page_width,
multiplier=x_multiplier,
)
y_min = _convert_bbox_units(
block.bounding_box[f"{block.bounding_y}"],
input_bbox_units=block.bounding_unit or "normalized",
width=block.page_height,
multiplier=y_multiplier,
)
if block.bounding_width is None or block.bounding_height is None:
raise ValueError(
"bounding_width and bounding_height must be set for Type 2"
)
x_max = x_min + block.bounding_width
y_max = y_min + block.bounding_height
normalized_vertices.extend(
[
documentai.NormalizedVertex(x=x_min, y=y_min),
documentai.NormalizedVertex(x=x_max, y=y_min),
documentai.NormalizedVertex(x=x_max, y=y_max),
documentai.NormalizedVertex(x=x_min, y=y_max),
]
)
elif block.bounding_type == "3":
# Type 3 : bounding_box: [x1, y1, x2, y2, x3, y3, x4, y4]
if not isinstance(block.bounding_box, list):
raise TypeError("Expected list for bounding_box in Type 3")
for idx in range(0, len(block.bounding_box), 2):
x = _convert_bbox_units(
block.bounding_box[idx],
input_bbox_units=block.bounding_unit or "normalized",
width=block.docproto_width,
multiplier=x_multiplier,
)
y = _convert_bbox_units(
block.bounding_box[idx + 1],
input_bbox_units=block.bounding_unit or "normalized",
width=block.docproto_height,
multiplier=y_multiplier,
)
normalized_vertices.append(documentai.NormalizedVertex(x=x, y=y))
return documentai.BoundingPoly(normalized_vertices=normalized_vertices)