import os import errno import os.path as osp from typing import List, Set, Union import json from pathlib import Path from typing import List, Set, Union, Dict import torch from torch.utils.data import Dataset import seaborn as sns from pycocotools.coco import COCO """ load raw data """ def makedirs(path): try: os.makedirs(osp.expanduser(osp.normpath(path))) except OSError as e: if e.errno != errno.EEXIST and osp.isdir(path): raise e def files_exist(files): return all([osp.exists(f) for f in files]) def load_scipostlayout_data(raw_dir: str, max_num_elements: int, label_set: Union[List, Set], label2index: Dict): def is_valid(element): label = coco.cats[element['category_id']]['name'] if label not in set(label_set): return False x1, y1, width, height = element['bbox'] x2, y2 = x1 + width, y1 + height if x1 < 0 or y1 < 0 or W < x2 or H < y2: return False if x2 <= x1 or y2 <= y1: return False return True train_list, dev_list = None, None # raw_dir = osp.join(Path(raw_dir), 'scipostlayout') for split in ['train', 'dev', 'test']: dataset = [] coco = COCO(osp.join(raw_dir, f'{split}.json')) for img_id in sorted(coco.getImgIds()): ann_img = coco.loadImgs(img_id) W = float(ann_img[0]['width']) H = float(ann_img[0]['height']) name = ann_img[0]['file_name'] # if H < W: # continue elements = coco.loadAnns(coco.getAnnIds(imgIds=[img_id])) _elements = list(filter(is_valid, elements)) filtered = len(elements) != len(_elements) elements = _elements N = len(elements) if N == 0 or max_num_elements < N: continue bboxes = [] labels = [] for element in elements: # bbox x1, y1, width, height = element['bbox'] b = [x1 / W, y1 / H, width / W, height / H] # bbox format: ltwh bboxes.append(b) # label label = coco.cats[element['category_id']]['name'] labels.append(label2index[label]) bboxes = torch.tensor(bboxes, dtype=torch.float) labels = torch.tensor(labels, dtype=torch.long) data = { 'name': name, 'bboxes': bboxes, 'labels': labels, 'canvas_size': [W, H], 'filtered': filtered, } dataset.append(data) if split == 'train': train_list = dataset elif split == 'dev': dev_list = dataset else: test_list = dataset # shuffle train with seed generator = torch.Generator().manual_seed(0) indices = torch.randperm(len(train_list), generator=generator) train_list = [train_list[i] for i in indices] train_set = train_list dev_set = dev_list test_set = test_list split_dataset = [train_set, dev_set, test_set] return split_dataset class LayoutDataset(Dataset): _label2index = None _index2label = None _colors = None split_file_names = ['train.pt', 'dev.pt', 'test.pt'] def __init__(self, root: str, data_name: str, split: str, max_num_elements: int, label_set: Union[List, Set], online_process: bool = True): self.root = f'{root}/{data_name}/' self.raw_dir = osp.join(self.root, 'raw') self.max_num_elements = max_num_elements self.label_set = label_set self.pre_processed_dir = osp.join( self.root, 'pre_processed_{}_{}'.format(self.max_num_elements, len(self.label_set))) assert split in ['train', 'dev', 'test'] if files_exist(self.pre_processed_paths): idx = self.split_file_names.index('{}.pt'.format(split)) print(f'Loading {split}...') self.data = torch.load(self.pre_processed_paths[idx]) else: print(f'Pre-processing and loading {split}...') makedirs(self.pre_processed_dir) split_dataset = self.load_raw_data() self.save_split_dataset(split_dataset) idx = self.split_file_names.index('{}.pt'.format(split)) self.data = torch.load(self.pre_processed_paths[idx]) self.online_process = online_process if not self.online_process: self.data = [self.process(item) for item in self.data] @property def pre_processed_paths(self): return [ osp.join(self.pre_processed_dir, f) for f in self.split_file_names ] @classmethod def label2index(self, label_set): if self._label2index is None: self._label2index = dict() for idx, label in enumerate(label_set): self._label2index[label] = idx # HACK idx + 1 return self._label2index @classmethod def index2label(self, label_set): if self._index2label is None: self._index2label = dict() for idx, label in enumerate(label_set): self._index2label[idx] = label # HACK idx + 1 return self._index2label @property def colors(self): if self._colors is None: n_colors = len(self.label_set) + 1 colors = sns.color_palette('husl', n_colors=n_colors) self._colors = [ tuple(map(lambda x: int(x * 255), c)) for c in colors ] return self._colors def save_split_dataset(self, split_dataset): torch.save(split_dataset[0], self.pre_processed_paths[0]) torch.save(split_dataset[1], self.pre_processed_paths[1]) torch.save(split_dataset[2], self.pre_processed_paths[2]) def load_raw_data(self) -> list: raise NotImplementedError def process(self, data) -> dict: raise NotImplementedError def __len__(self): return len(self.data) def __getitem__(self, idx): if self.online_process: sample = self.process(self.data[idx]) else: sample = self.data[idx] return sample class SciPostLayoutDataset(LayoutDataset): labels = [ 'Title', 'Author Info', 'Section', 'List', 'Text', 'Caption', 'Figure', 'Table', 'Unknown' ] def __init__(self, root: str, split: str, max_num_elements: int, online_process: bool = True): data_name = 'scipostlayout' super().__init__(root, data_name, split, max_num_elements, label_set=self.labels, online_process=online_process) def load_raw_data(self) -> list: return load_scipostlayout_data(self.raw_dir, self.max_num_elements, self.label_set, self.label2index(self.label_set)) if __name__ == "__main__": dataset = SciPostLayoutDataset(root="./", split="dev", max_num_elements=50)