File size: 3,243 Bytes
4d1c378
 
 
 
 
e8fb686
4d1c378
 
 
 
 
 
 
 
e8fb686
4d1c378
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8fb686
 
 
 
 
 
 
4d1c378
e8fb686
 
 
 
 
 
 
4d1c378
e8fb686
4d1c378
 
 
 
 
 
 
 
 
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
import os

from datasets import load_dataset
from dataclasses import dataclass, field
import tqdm.auto as tqdm
from typing import List, Dict
from jinja2 import Environment, FileSystemLoader
from shapely.geometry import Polygon
import itertools

# Load the Jinja2 template
env = Environment(loader=FileSystemLoader('.'))
template = env.get_template('template.xml')

ds = load_dataset("../data")

RATIO = .05


@dataclass
class Tag:
    idx: str
    label: str
    element_type: str


@dataclass
class Line:
    idx: str
    bbox: List[int]
    polygons: List[int]
    category: str
    baseline: List[int]

    @property
    def simple_polygon(self):
        x = list(
            map(
                int,
                itertools.chain(
                    *Polygon(
                        list(zip(self.polygons[::2], self.polygons[1::2]))  # Flat list to list of points
                    ).simplify(RATIO * self.height).exterior.coords
                )
            )
        )[:-2]  # Polygon repeats the starting point
        return x

    @property
    def hpos(self):
        return self.bbox[0]

    @property
    def vpos(self):
        return self.bbox[1]

    @property
    def width(self):
        return self.bbox[2] - self.bbox[0]

    @property
    def height(self):
        return self.bbox[3] - self.bbox[1]


@dataclass
class Block:
    idx: str
    bbox: List[int]
    polygons: List[int]
    category: str
    lines: List[Line] = field(default_factory=list)

    @property
    def hpos(self):
        return self.bbox[0]

    @property
    def vpos(self):
        return self.bbox[1]

    @property
    def width(self):
        return self.bbox[2] - self.bbox[0]

    @property
    def height(self):
        return self.bbox[3] - self.bbox[1]


for split in ds:
    os.makedirs(f"altos/{split}", exist_ok=True)
    for image_idx, image in enumerate(tqdm.tqdm(ds[split])):
        blocks: Dict[str, Block] = {}
        tags: Dict[str, Tag] = {}
        objs = image["objects"]
        for i, idx in enumerate(objs["id"]):
            if objs["category"][i] and objs["category"][i] not in tags:
                tags[objs["category"][i]] = Tag(f"LABEL_{len(tags)}", objs["category"][i], objs["type"][i])

            if objs["type"][i] == "block":
                blocks[idx] = Block(idx, objs["bbox"][i], objs["polygons"][i], objs["category"][i])
            else:
                if objs["parent"][i] == "":
                    blocks[""] = Block(None, [], [], "")
                if objs["baseline"][i] is None:
                    print(f"Line broken ? {image['shelfmark']} {idx} {objs['polygons'][i]}")
                    continue
                blocks[objs["parent"][i]].lines.append(
                    Line(idx, objs["bbox"][i], objs["polygons"][i], objs["category"][i], objs['baseline'][i])
                )
        image["image"].convert('RGB').save(f"./altos/{split}/image-{image_idx:04}.jpg")
        with open(f"./altos/{split}/image-{image_idx:04}.xml", "w") as f:
            f.write(
                template.render(
                    blocks=blocks,
                    image=image,
                    path=f"image-{image_idx:04}.jpg",
                    tags=tags
                )
            )