Datasets:

Modalities:
Image
Languages:
English
Libraries:
Datasets
License:
File size: 7,361 Bytes
9e430eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
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)