Datasets:

Tasks:
Other
Languages:
Chinese
ArXiv:
License:
File size: 10,589 Bytes
f689054
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
import os
import pathlib
from typing import List, TypedDict, Union, cast

import datasets as ds
from datasets.utils.logging import get_logger
from PIL import Image
from PIL.Image import Image as PilImage

logger = get_logger(__name__)

_DESCRIPTION = (
    "A New Dataset and Benchmark for Content-aware Visual-Textual Presentation Layout"
)

_CITATION = """\
@inproceedings{hsu2023posterlayout,
  title={PosterLayout: A New Benchmark and Approach for Content-aware Visual-Textual Presentation Layout},
  author={Hsu, Hsiao Yuan and He, Xiangteng and Peng, Yuxin and Kong, Hao and Zhang, Qing},
  booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition},
  pages={6018--6026},
  year={2023}
}
"""

_HOMEPAGE = "http://59.108.48.34/tiki/PosterLayout/"

_LICENSE = "Images in PKU PosterLayout are distributed under the CC BY-SA 4.0 license."


class TrainPoster(TypedDict):
    original: str
    inpainted: str


class TestPoster(TypedDict):
    canvas: str


class SaliencyMaps(TypedDict):
    pfpn: str
    basnet: str


class TrainDataset(TypedDict):
    poster: TrainPoster
    saliency_maps: SaliencyMaps


class TestDataset(TypedDict):
    poster: TestPoster
    saliency_maps: SaliencyMaps


class DatasetUrls(TypedDict):
    train: TrainDataset
    test: TestDataset


# The author of this loading script has uploaded the poster image and saliency maps to the HuggingFace's private repository to facilitate testing.
# If you are using this loading script, please download the annotations from the appropriate channels, such as the OneDrive link provided by the Magazine dataset's author.
# (To the author of Magazine dataset, if there are any issues regarding this matter, please contact us. We will address it promptly.)
_URLS: DatasetUrls = {
    "train": {
        "poster": {
            "original": "https://huggingface.co./datasets/shunk031/PKU-PosterLayout-private/resolve/main/train/original_poster.zip",
            "inpainted": "https://huggingface.co./datasets/shunk031/PKU-PosterLayout-private/resolve/main/train/inpainted_poster.zip",
        },
        "saliency_maps": {
            "pfpn": "https://huggingface.co./datasets/shunk031/PKU-PosterLayout-private/resolve/main/train/saliencymaps_pfpn.zip",
            "basnet": "https://huggingface.co./datasets/shunk031/PKU-PosterLayout-private/resolve/main/train/saliencymaps_basnet.zip",
        },
    },
    "test": {
        "poster": {
            "canvas": "https://huggingface.co./datasets/shunk031/PKU-PosterLayout-private/resolve/main/test/image_canvas.zip",
        },
        "saliency_maps": {
            "pfpn": "https://huggingface.co./datasets/shunk031/PKU-PosterLayout-private/resolve/main/test/saliencymaps_pfpn.zip",
            "basnet": "https://huggingface.co./datasets/shunk031/PKU-PosterLayout-private/resolve/main/test/saliencymaps_basnet.zip",
        },
    },
}


def file_sorter(f: pathlib.Path) -> int:
    idx, *_ = f.stem.split("_")
    return int(idx)


def load_image(file_path: pathlib.Path) -> PilImage:
    logger.info(f"Load from {file_path}")
    return Image.open(file_path)


def get_original_poster_files(base_dir: str) -> List[pathlib.Path]:
    poster_dir = pathlib.Path(base_dir) / "original_poster"
    return sorted(poster_dir.iterdir(), key=lambda f: int(f.stem))


def get_inpainted_poster_files(base_dir: str) -> List[pathlib.Path]:
    inpainted_dir = pathlib.Path(base_dir) / "inpainted_poster"
    return sorted(inpainted_dir.iterdir(), key=file_sorter)


def get_basnet_map_files(base_dir: str) -> List[pathlib.Path]:
    basnet_map_dir = pathlib.Path(base_dir) / "saliencymaps_basnet"
    return sorted(basnet_map_dir.iterdir(), key=file_sorter)


def get_pfpn_map_files(base_dir: str) -> List[pathlib.Path]:
    pfpn_map_dir = pathlib.Path(base_dir) / "saliencymaps_pfpn"
    return sorted(pfpn_map_dir.iterdir(), key=file_sorter)


def get_canvas_files(base_dir: str) -> List[pathlib.Path]:
    canvas_dir = pathlib.Path(base_dir) / "image_canvas"
    return sorted(canvas_dir.iterdir(), key=lambda f: int(f.stem))


class PosterLayoutDataset(ds.GeneratorBasedBuilder):
    VERSION = ds.Version("1.0.0")
    BUILDER_CONFIGS = [ds.BuilderConfig(version=VERSION)]

    def _info(self) -> ds.DatasetInfo:
        features = ds.Features(
            {
                "original_poster": ds.Image(),
                "inpainted_poster": ds.Image(),
                "basnet_saliency_map": ds.Image(),
                "pfpn_saliency_map": ds.Image(),
                "canvas": ds.Image(),
            }
        )
        return ds.DatasetInfo(
            description=_DESCRIPTION,
            citation=_CITATION,
            homepage=_HOMEPAGE,
            license=_LICENSE,
            features=features,
        )

    @property
    def _manual_download_instructions(self) -> str:
        return (
            "To use PKU-PosterLayout dataset, you need to download the poster image "
            "and saliency maps via [PKU Netdisk](https://disk.pku.edu.cn/link/999C6E97BB354DF8AD0F9E1F9003BE05) "
            "or [Google Drive](https://drive.google.com/drive/folders/1Gk202RVs9Qy2zbJUNeurC1CaQYNU-Vuv?usp=share_link)."
        )

    def _download_from_hf(self, dl_manager: ds.DownloadManager) -> DatasetUrls:
        return dl_manager.download_and_extract(_URLS)

    def _download_from_local(self, dl_manager: ds.DownloadManager) -> DatasetUrls:
        assert dl_manager.manual_dir is not None, dl_manager.manual_dir
        dir_path = os.path.expanduser(dl_manager.manual_dir)

        tng_dir_path = os.path.join(dir_path, "train")
        tst_dir_path = os.path.join(dir_path, "test")

        if not os.path.exists(dir_path):
            raise FileNotFoundError(
                "Make sure you have downloaded and placed the PKU-PosterLayout dataset correctly. "
                'Furthermore, you shoud check that a manual dir via `datasets.load_dataset("shunk031/PKU-PosterLayout", data_dir=...)` '
                "that include zip files from the downloaded files. "
                f"Manual downloaded instructions: {self._manual_download_instructions}"
            )
        return dl_manager.extract(
            path_or_paths={
                "train": {
                    "poster": {
                        "original": os.path.join(tng_dir_path, "inpainted_poster.zip"),
                        "inpainted": os.path.join(tng_dir_path, "inpainted_poster.zip"),
                    },
                    "saliency_maps": {
                        "pfpn": os.path.join(tng_dir_path, "saliencymaps_pfpn.zip"),
                        "basnet": os.path.join(tng_dir_path, "saliencymaps_basnet.zip"),
                    },
                },
                "test": {
                    "poster": {
                        "canvas": os.path.join(tst_dir_path, "image_canvas.zip"),
                    },
                    "saliency_maps": {
                        "pfpn": os.path.join(tst_dir_path, "salieycmaps_pfpn.zip"),
                        "basnet": os.path.join(tst_dir_path, "saliencymaps_basnet.zip"),
                    },
                },
            }
        )

    def _split_generators(self, dl_manager: ds.DownloadManager):
        file_paths = (
            self._download_from_hf(dl_manager)
            if dl_manager.download_config.token
            else self._download_from_local(dl_manager)
        )

        tng_files = file_paths["train"]
        tst_files = file_paths["test"]

        return [
            ds.SplitGenerator(
                name=ds.Split.TRAIN,
                gen_kwargs={
                    "poster": tng_files["poster"],
                    "saliency_maps": tng_files["saliency_maps"],
                },
            ),
            ds.SplitGenerator(
                name=ds.Split.TEST,
                gen_kwargs={
                    "poster": tst_files["poster"],
                    "saliency_maps": tst_files["saliency_maps"],
                },
            ),
        ]

    def _generate_train_examples(
        self, poster: TrainPoster, saliency_maps: SaliencyMaps
    ):
        poster_files = get_original_poster_files(base_dir=poster["original"])
        inpainted_files = get_inpainted_poster_files(base_dir=poster["inpainted"])

        basnet_map_files = get_basnet_map_files(base_dir=saliency_maps["basnet"])
        pfpn_map_files = get_pfpn_map_files(base_dir=saliency_maps["pfpn"])

        assert (
            len(poster_files)
            == len(inpainted_files)
            == len(basnet_map_files)
            == len(pfpn_map_files)
        )

        it = zip(poster_files, inpainted_files, basnet_map_files, pfpn_map_files)
        for i, (
            original_poster_path,
            inpainted_poster_path,
            basnet_map_path,
            pfpn_map_path,
        ) in enumerate(it):
            yield i, {
                "original_poster": load_image(original_poster_path),
                "inpainted_poster": load_image(inpainted_poster_path),
                "basnet_saliency_map": load_image(basnet_map_path),
                "pfpn_saliency_map": load_image(pfpn_map_path),
                "canvas": None,
            }

    def _generate_test_examples(self, poster: TestPoster, saliency_maps: SaliencyMaps):
        canvas_files = get_canvas_files(base_dir=poster["canvas"])

        basnet_map_files = get_basnet_map_files(base_dir=saliency_maps["basnet"])
        pfpn_map_files = get_pfpn_map_files(base_dir=saliency_maps["pfpn"])

        assert len(canvas_files) == len(basnet_map_files) == len(pfpn_map_files)
        it = zip(canvas_files, basnet_map_files, pfpn_map_files)
        for i, (canvas_path, basnet_map_path, pfpn_map_path) in enumerate(it):
            yield i, {
                "original_poster": None,
                "inpainted_poster": None,
                "basnet_saliency_map": load_image(basnet_map_path),
                "pfpn_saliency_map": load_image(pfpn_map_path),
                "canvas": load_image(canvas_path),
            }

    def _generate_examples(
        self, poster: Union[TrainPoster, TestPoster], saliency_maps: SaliencyMaps
    ):
        if "original" in poster and "inpainted" in poster:
            yield from self._generate_train_examples(
                poster=cast(TrainPoster, poster), saliency_maps=saliency_maps
            )
        elif "canvas" in poster:
            yield from self._generate_test_examples(
                poster=cast(TestPoster, poster), saliency_maps=saliency_maps
            )
        else:
            raise ValueError("Invalid dataset")