Mausul commited on
Commit
a004b67
·
verified ·
1 Parent(s): 48571a9

Upload release_loader.py

Browse files
Files changed (1) hide show
  1. release_loader.py +73 -0
release_loader.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Adapt the BaFCo release export to the structures the eval/inference pipeline expects."""
2
+ import json
3
+ import os
4
+ import shutil
5
+
6
+
7
+ def _load(path):
8
+ with open(path, "r", encoding="utf-8") as f:
9
+ return json.load(f)
10
+
11
+
12
+ def load_dla_targets(export_path):
13
+ targets = []
14
+ for f in _load(export_path):
15
+ result = []
16
+ for pg in f.get("pages", []):
17
+ ow, oh = pg.get("original_width"), pg.get("original_height")
18
+ for b in pg.get("boxes", []):
19
+ result.append({
20
+ "type": "rectanglelabels",
21
+ "id": b.get("id"),
22
+ "original_width": ow,
23
+ "original_height": oh,
24
+ "item_index": pg.get("page", 0),
25
+ "image_rotation": 0,
26
+ "value": {
27
+ "x": b.get("x"), "y": b.get("y"),
28
+ "width": b.get("width"), "height": b.get("height"),
29
+ "rotation": b.get("rotation", 0),
30
+ "rectanglelabels": [b.get("label")],
31
+ },
32
+ })
33
+ for r in f.get("relations", []):
34
+ result.append({"type": "relation", "from_id": r.get("from_id"),
35
+ "to_id": r.get("to_id"), "direction": r.get("direction")})
36
+ targets.append({
37
+ "id": f["id"],
38
+ "inner_id": f.get("inner_id", f["id"]),
39
+ "data": {"pages": list(f.get("local_images", []))},
40
+ "annotations": [{"result": result}],
41
+ })
42
+ return targets
43
+
44
+
45
+ def load_kie_forms(export_path):
46
+ forms = _load(export_path)
47
+ for f in forms:
48
+ if "id" not in f or "annotations" not in f:
49
+ raise ValueError(f"KIE form missing id/annotations: {f.get('id')}")
50
+ for pg in f["annotations"]:
51
+ if "page" not in pg or "annotations" not in pg:
52
+ raise ValueError(f"KIE form {f['id']} page block missing page/annotations")
53
+ return forms
54
+
55
+
56
+ def resolve_release_image(export_root, form, page_index):
57
+ rels = form.get("local_images") or []
58
+ if not 0 <= page_index < len(rels):
59
+ raise IndexError(f"page {page_index} out of range for form {form.get('id')}")
60
+ return os.path.join(export_root, *rels[page_index].split("/"))
61
+
62
+
63
+ def stage_kie_flat_images(export_path, dest_dir):
64
+ export_root = os.path.dirname(os.path.abspath(export_path))
65
+ os.makedirs(dest_dir, exist_ok=True)
66
+ n = 0
67
+ for f in _load(export_path):
68
+ for page_index, rel in enumerate(f.get("local_images", [])):
69
+ src = os.path.join(export_root, *rel.split("/"))
70
+ ext = os.path.splitext(rel)[1] or ".jpg"
71
+ shutil.copy2(src, os.path.join(dest_dir, f"{f['id']}_{page_index}{ext}"))
72
+ n += 1
73
+ return n