-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathboxes_common.py
More file actions
52 lines (34 loc) · 1.47 KB
/
boxes_common.py
File metadata and controls
52 lines (34 loc) · 1.47 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
import json
import math
PARSED_JSON_TYPE = "JRW_PARSED_JSON"
def default_outputs():
return (0, 0, 0, 0, 0, 0)
def invalid_value(error_on_invalid, message, default_factory):
if error_on_invalid:
raise ValueError(message)
return default_factory()
def parse_json_string(json_string):
try:
parsed_json = json.loads(json_string) if json_string else None
except json.JSONDecodeError as exc:
return None, f"json_string is not valid JSON: {exc.msg}"
return parsed_json, None
def integer_box_values(x1, y1, x2, y2):
left = math.floor(min(x1, x2))
right = math.ceil(max(x1, x2))
top = math.floor(min(y1, y2))
bottom = math.ceil(max(y1, y2))
return (int(left), int(right), int(top), int(bottom), int(right - left), int(bottom - top))
def extract_box_values(parsed_json, index):
if not isinstance(parsed_json, (list, tuple)):
return None, "parsed_json must be a list of boxes."
if index < 0 or index >= len(parsed_json):
return None, "index must point to an existing box in parsed_json."
box = parsed_json[index]
if not isinstance(box, (list, tuple)) or len(box) != 4:
return None, "Selected box must contain exactly 4 values: [x1, y1, x2, y2]."
try:
x1, y1, x2, y2 = (float(value) for value in box)
except (TypeError, ValueError):
return None, "Selected box contains a value that cannot be converted to float."
return integer_box_values(x1, y1, x2, y2), None