import json from itertools import chain from image_prediction.exceptions import InvalidBox from image_prediction.formatter.formatters.enum import EnumFormatter from image_prediction.info import Info def flatten_groups_once(groups): return chain.from_iterable(groups) def make_coord_getter(c): return { "x1": make_getter(Info.X1), "x2": make_getter(Info.X2), "y1": make_getter(Info.Y1), "y2": make_getter(Info.Y2), }[c] def make_getter(key): def getter(pair): return pair.metadata[key] return getter def make_length_getter(dim): return { "width": make_getter(Info.WIDTH), "height": make_getter(Info.HEIGHT), }[dim] def validate_box(box): validate_box_coords(box) validate_box_size(box) return box def validate_box_coords(box): x_diff = box[Info.WIDTH] - (box[Info.X2] - box[Info.X1]) y_diff = box[Info.HEIGHT] - (box[Info.Y2] - box[Info.Y1]) if x_diff: raise InvalidBox(f"Width and x-coordinates differ by {x_diff} units: {format_box(box)}") if y_diff: raise InvalidBox(f"Width and y-coordinates differ by {y_diff} units: {format_box(box)}") return box def validate_box_size(box): if not box[Info.WIDTH]: raise InvalidBox(f"Zero width box: {format_box(box)}") if not box[Info.HEIGHT]: raise InvalidBox(f"Zero height box: {format_box(box)}") return box def format_box(box): return json.dumps(EnumFormatter()(box), indent=2)