From 576e3c9452da7576c12a4cfa70d84cf3745cf6fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Miquel?= Date: Sat, 22 Aug 2026 13:52:24 +0200 Subject: [PATCH] Fix bug de tri des labels dans le fichier .json --- copienator/commands/plotting.py | 34 ++++++++++++++++++++++++++++----- 1 file changed, 29 insertions(+), 5 deletions(-) diff --git a/copienator/commands/plotting.py b/copienator/commands/plotting.py index c8c33ad..129fdf4 100644 --- a/copienator/commands/plotting.py +++ b/copienator/commands/plotting.py @@ -37,6 +37,19 @@ def page_number(b, nb_pages): center_x = (b[1] + b[3]) // 2 return center_x // column_width + +def sort_bounding_boxes(bounding_boxes, nb_pages): + """Return label boxes in reading order: columns first, then top to bottom.""" + return sorted( + bounding_boxes, + key=lambda entry: ( + page_number(entry["box_2d"], nb_pages), + entry["box_2d"][0], + entry["box_2d"][1], + ), + ) + + def convert_box2d(b, pn_ori, npn, tot_ori, tot_dest): l = b.copy() l[1] = (l[1] - (1000 // tot_ori) * (pn_ori-1)) * tot_ori // tot_dest\ @@ -75,9 +88,8 @@ def prepare_image(image_path: str, bounding_boxes, all_labels, nb_pages, last_la new_im = Image.new(im.mode, (width + padding, height), "white") new_im.paste(im, (0, 0)) draw = ImageDraw.Draw(new_im) - bounding_boxes.sort(key=lambda b: (page_number(b["box_2d"], nb_pages), b["box_2d"][0])) - for bbox in bounding_boxes: + for bbox in sort_bounding_boxes(bounding_boxes, nb_pages): raw_y_min = int(bbox["box_2d"][0] * height / 1000) raw_x_min = int(bbox["box_2d"][1] * width / 1000) raw_y_max = int(bbox["box_2d"][2] * height / 1000) @@ -321,15 +333,28 @@ class ImageViewer: try: current_data = read_json(self.current_json_path) + nb_pages = self.current_meta["schema"]["columns_per_file"][ + self.current_meta["part"] - 1 + ] + original_items = current_data["list"] + ordered_items = sort_bounding_boxes(original_items, nb_pages) + + if ordered_items != original_items: + current_data["list"] = ordered_items + atomic_write_json(self.current_json_path, current_data) + print( + f"Reordered labels by column in " + f"{self.current_json_path.name}." + ) # Perform the conversion now, post-edit converted_items = convert_list( - current_data["list"], + ordered_items, self.current_meta["part"], self.current_meta["schema"] ) - labels = normalized_labels(current_data["list"]) + labels = normalized_labels(ordered_items) false_labels = [ label for label in labels if label not in self.valid_labels ] @@ -472,4 +497,3 @@ def main(argv: Sequence[str] | None = None) -> int: if __name__ == "__main__": raise SystemExit(main()) -