"""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', ), ] 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): # TODO: This method is tasked with downloading/extracting the data and defining the splits depending on the configuration # If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name # dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLS # It can accept any type or nested list/dict and will give back the same structure with the url replaced with path to local files. # By default the archives will be extracted and a path to a cached folder where they are extracted is returned instead of the archive # urls = _URLS[self.config.name] # data_dir = dl_manager.download_and_extract(urls) # dataset_path = Path(snapshot_download(repo_id=HF_DATASET_ID, repo_type='datasets')) # dataset_path = Path(dl_manager.download_and_extract(_URL + f"/{self.config.dataset_folder}/{self.config.split_folder}")) dataset_path = Path(snapshot_download(_HF_DATASET_ID, repo_type='dataset')) task_data_path = dataset_path/self.config.dataset_folder/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": task_data_path/'mainifest.json', "seeds": task_data_path/'seeds.json', "annotations": task_data_path/'in_fashion_tags_dict.json', "split": "test", }, ), ] else: return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, # These kwargs will be passed to _generate_examples gen_kwargs={ "manifest": task_data_path/'mainifest_train.json', "seeds": task_data_path/'seeds_train.json', "annotations": task_data_path/'in_fashion_tags_dict_train.json', "split": "train", }, ), datasets.SplitGenerator( name=datasets.Split.TEST, # These kwargs will be passed to _generate_examples gen_kwargs={ "manifest": task_data_path/'mainifest_test.json', "seeds": task_data_path/'seeds_test.json', "annotations": task_data_path/'in_fashion_tags_dict_test.json', "split": "test", }, ), ] # method parameters are unpacked from `gen_kwargs` as given in `_split_generators` def _generate_examples(self, annotations, **kwargs): # TODO: This method handles input defined in _split_generators to yield (key, example) tuples from the dataset. # The `key` is for legacy reasons (tfds) and is not important in itself, but must be unique for each example. print("Opening ", annotations) with open(annotations, 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/self.config.dataset_folder/row['key'][0]), "candidate": str(self.image_folder/self.config.dataset_folder/row['key'][1]), "value": row['value'], }