|
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 |
|
|
|
|
|
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])) |
|
).simplify(RATIO * self.height).exterior.coords |
|
) |
|
) |
|
)[:-2] |
|
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 |
|
) |
|
) |
|
|