File size: 10,355 Bytes
1ab989d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc996d0
 
 
 
 
 
5d786fe
 
 
 
 
 
1ab989d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c0354e0
1ab989d
c0354e0
 
1ab989d
 
 
 
 
 
 
11947d2
5d786fe
 
 
9182f57
c0354e0
5d786fe
 
 
 
 
 
 
 
 
11947d2
 
5d786fe
1ab989d
9182f57
1400a5e
315e2fe
1ab989d
 
 
 
 
 
 
 
 
11947d2
5d786fe
 
1ab989d
9182f57
c0354e0
1ab989d
 
 
 
 
 
11947d2
5d786fe
 
1ab989d
9182f57
c0354e0
1ab989d
 
 
 
 
5d786fe
 
1ab989d
 
 
 
 
11947d2
 
1ab989d
 
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
"""Visual similarities discovery (VSD) is an important task
with broad e-commerce applications. Given an image of
a certain object, the goal of VSD is to retrieve images of

different objects with high perceptual visual similarity. Al-
though being a highly addressed problem, the evaluation

of proposed methods for VSD is often based on a proxy of
an identification-retrieval task, evaluating the ability of a
model to retrieve different images of the same object. We
posit that evaluating VSD methods based on identification
tasks is limited, and faithful evaluation must rely on expert
annotations. In this paper, we introduce the first large-scale
fashion visual similarity benchmark dataset, consisting of
more than 110K expert-annotated image pairs."""


import csv
import json
import os
from typing import Optional, Union

import datasets
from pathlib import Path
from datasets.data_files import DataFilesDict
from datasets.features import Features
from datasets.info import DatasetInfo
from huggingface_hub import snapshot_download

# TODO: Add BibTeX citation
# Find for instance the citation on arxiv or on the dataset repo/website
_CITATION = """\
@InProceedings{huggingface:dataset,
title = {A great new dataset},
author={huggingface, Inc.
},
year={2020}
}
"""

_DESCRIPTION = """\
Visual similarities discovery (VSD) is an important task
with broad e-commerce applications. Given an image of
a certain object, the goal of VSD is to retrieve images of

different objects with high perceptual visual similarity. Al-
though being a highly addressed problem, the evaluation

of proposed methods for VSD is often based on a proxy of
an identification-retrieval task, evaluating the ability of a
model to retrieve different images of the same object. We
posit that evaluating VSD methods based on identification
tasks is limited, and faithful evaluation must rely on expert
annotations. In this paper, we introduce the first large-scale
fashion visual similarity benchmark dataset, consisting of
more than 110K expert-annotated image pairs.
"""

# TODO: Add a link to an official homepage for the dataset here
_HOMEPAGE = "https://vsd-benchmark.github.io/vsd/"

# TODO: Add the licence for the dataset here if you can find it
_LICENSE = "MIT"
_URL = "https://huggingface.co/datasets/vsd-benchmark/vsd-fashion/tree/main"
_HF_DATASET_ID = 'vsd-benchmark/vsd-fashion'


class VSDFashionConfig(datasets.BuilderConfig):
    """BuilderConfig for VSDFashion."""

    def __init__(self, dataset_folder, split_folder, image_folder=None, **kwargs):
        """BuilderConfig for VSDFashion.

        Args:
        **kwargs: keyword arguments forwarded to super.
        """
        # Version history:
        # 0.0.21: Initial version.
        super(VSDFashionConfig, self).__init__(version=datasets.Version("0.0.1"), **kwargs)
        self.dataset_folder = dataset_folder
        self.split_folder = split_folder
        self.image_folder = image_folder

# TODO: Name of the dataset usually matches the script name with CamelCase instead of snake_case
class VSDFashion(datasets.GeneratorBasedBuilder):
    def __init__(
        self,
        cache_dir: Optional[str] = None,
        dataset_name: Optional[str] = None,
        config_name: Optional[str] = None,
        hash: Optional[str] = None,
        base_path: Optional[str] = None,
        info: Optional[DatasetInfo] = None,
        features: Optional[Features] = None,
        token: Optional[Union[bool, str]] = None,
        use_auth_token="deprecated",
        repo_id: Optional[str] = None,
        data_files: Optional[Union[str, list, dict, DataFilesDict]] = None,
        data_dir: Optional[str] = None,
        storage_options: Optional[dict] = None,
        writer_batch_size: Optional[int] = None,
        name="deprecated",
        image_folder: str = None,
        **config_kwargs):
            super().__init__(cache_dir, dataset_name, config_name, hash, base_path, info, features, token, use_auth_token, repo_id, data_files, data_dir, storage_options, writer_batch_size, name, **config_kwargs)

            self.image_folder = Path(image_folder)

    VERSION = datasets.Version("1.1.0")

    BUILDER_CONFIGS = [
        VSDFashionConfig(
            name="in_catalog_retrieval_zero_shot",
            description="Zero shot (no training) on fashion catalog query and candidates visual similairty",
            dataset_folder='in_fashion',
            split_folder='gt_tagging',
        ),
        VSDFashionConfig(
            name="in_catalog_open_catalog",
            description="Training task for VSD where the queries in the train and test may overlap.",
            dataset_folder='in_fashion',
            split_folder='gt_tagging_split_open_catalog',
        ),
        VSDFashionConfig(
            name="in_catalog_closed_catalog",
            description="Training task for VSD where the queries in the train and test DO NOT overlap.",
            dataset_folder='in_fashion',
            split_folder='gt_tagging_split_closed_catalog',
        ),
        VSDFashionConfig(
            name="consumer-catalog_wild_zero_shot",
            description="Zero shot task for matching a consumer taken photo of a clothing and visually matching with a catalog item. Pretraining on any data is allowed, except consumer photos (queries).",
            dataset_folder='in_fashion',
            split_folder='gt_tagging_wild',
        ),
    ]

    DEFAULT_CONFIG_NAME = "in_catalog_retrieval_zero_shot"

    def _info(self):
        features = datasets.Features(
            {
                "query": datasets.Image(),
                "candidate": datasets.Image(),
                "value": datasets.ClassLabel(num_classes=2, names=["neg", "pos"]),
            }
        )

        return datasets.DatasetInfo(
            # This is the description that will appear on the datasets page.
            description=_DESCRIPTION,
            # This defines the different columns of the dataset and their types
            features=features,  # Here we define them above because they are different between the two configurations
            # If there's a common (input, target) tuple from the features, uncomment supervised_keys line below and
            # specify them. They'll be used if as_supervised=True in builder.as_dataset.
            # supervised_keys=("query", "candidate", "value"),
            # Homepage of the dataset for documentation
            homepage=_HOMEPAGE,
            # License for the dataset if available
            license=_LICENSE,
            # Citation for the dataset
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager):
        dataset_root_path = Path(snapshot_download(_HF_DATASET_ID, repo_type='dataset'))

        dataset_path = dataset_root_path/self.config.dataset_folder
        task_data_path = dataset_path/self.config.split_folder

        if self.config.name == 'in_catalog_retrieval_zero_shot':
            return [
                datasets.SplitGenerator(
                    name=datasets.Split.TEST,
                    # These kwargs will be passed to _generate_examples
                    gen_kwargs={
                        "manifest_file": task_data_path/'manifest.json',
                        "seeds_file": task_data_path/'seeds.json',
                        "annotations_file": task_data_path/'in_fashion_tags_dict.json',
                        "split": "test",
                        "images_folder": self.image_folder,
                        "metadata_file": dataset_path/'dataset_metadata.json'
                    },
                ),
            ] 
        elif self.config.name == 'consumer-catalog_wild_zero_shot':
             return [
                datasets.SplitGenerator(
                    name=datasets.Split.TEST,
                    # These kwargs will be passed to _generate_examples
                    gen_kwargs={
                        "manifest_file": task_data_path/'manifest.json',
                        "seeds_file": None,
                        "annotations_file": task_data_path/'in_fashion_outshop_tags_dict.json',
                        "split": "test",
                        "images_folder": self.image_folder,
                        "metadata_file": dataset_path/'dataset_metadata_wild.json',
                        "gallery_phases": ['train']
                    },
                ),
            ] 
        else:
            return [
                datasets.SplitGenerator(
                    name=datasets.Split.TRAIN,
                    # These kwargs will be passed to _generate_examples
                    gen_kwargs={
                        "manifest_file": task_data_path/'manifest_train.json',
                        "seeds_file": task_data_path/'seeds_train.json',
                        "annotations_file": task_data_path/'in_fashion_tags_dict_train.json',
                        "split": "train",
                        "images_folder": self.image_folder,
                        "metadata_file": dataset_path/'dataset_metadata.json'
                    },
                ),
                datasets.SplitGenerator(
                    name=datasets.Split.TEST,
                    # These kwargs will be passed to _generate_examples
                    gen_kwargs={
                        "manifest_file": task_data_path/'manifest_test.json',
                        "seeds_file": task_data_path/'seeds_test.json',
                        "annotations_file": task_data_path/'in_fashion_tags_dict_test.json',
                        "split": "test",
                        "images_folder": self.image_folder,
                        "metadata_file": dataset_path/'dataset_metadata.json'
                    },
                ),
            ]

    # method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
    def _generate_examples(self, annotations_file, **kwargs):
        with open(annotations_file, encoding="utf-8") as f:
            data = json.load(f)

            for key, row in enumerate(data):
                # Yields examples as (key, example) tuples
                yield key, {
                    "query": str(self.image_folder/row['key'][0]),
                    "candidate": str(self.image_folder/row['key'][1]),
                    "value": row['value'],
                }