import datasets import json from string import Template from pathlib import Path _HOMEPAGE = "" _CITATION = "" _LICENSE = "" _DESCRIPTION_TEMPLATE = Template( "$num_classes-way image classification task " "to test domain shift of class $spurious_class from " "context $source_context to $target_context. " "Selected classes: $selected_classes" ) _REPO = "https://huggingface.co/datasets/dgcnz/pcbm-metashift/resolve/main" _IMAGES_DIR = Path("data") class PCBMMetashiftConfig(datasets.BuilderConfig): """Builder Config for Food-101""" def __init__( self, metadata_path: str, selected_classes: list[str], spurious_class: str, source_context: str, target_context: str, **kwargs, ): """BuilderConfig for Food-101. Args: data_url: `string`, url to download the zip file from. metadata_urls: dictionary with keys 'train' and 'validation' containing the archive metadata URLs **kwargs: keyword arguments forwarded to super. """ super(PCBMMetashiftConfig, self).__init__( version=datasets.Version("1.0.0"), **kwargs ) self.metadata_path = metadata_path self.selected_classes = selected_classes self.spurious_class = spurious_class self.source_context = source_context self.target_context = target_context class PCBMMetashift(datasets.GeneratorBasedBuilder): """Food-101 Images dataset""" BUILDER_CONFIGS = [ PCBMMetashiftConfig( name="task_abcck_bed_cat_dog", description="Task 1: bed(cat) -> bed(dog)", metadata_path="configs/task_abcck_bed_cat_dog.json", selected_classes=["airplane", "bed", "car", "cow", "keyboard"], spurious_class="bed", source_context="cat", target_context="dog", ), PCBMMetashiftConfig( name="task_abcck_bed_dog_cat", description="Task 1: bed(dog) -> bed(cat)", metadata_path="configs/task_abcck_bed_dog_cat.json", selected_classes=["airplane", "bed", "car", "cow", "keyboard"], spurious_class="bed", source_context="dog", target_context="cat", ), PCBMMetashiftConfig( name="task_abcck_car_cat_dog", description="Task 1: car(cat) -> car(dog)", metadata_path="configs/task_abcck_car_cat_dog.json", selected_classes=["airplane", "bed", "car", "cow", "keyboard"], spurious_class="car", source_context="cat", target_context="dog", ), PCBMMetashiftConfig( name="task_abcck_car_dog_cat", description="Task 1: car(dog) -> car(cat)", metadata_path="configs/task_abcck_car_dog_cat.json", selected_classes=["airplane", "bed", "car", "cow", "keyboard"], spurious_class="car", source_context="dog", target_context="cat", ), PCBMMetashiftConfig( name="task_bcmst_table_books_cat", description="Task 2: table(books) -> table(cat)", metadata_path="configs/task_bcmst_table_books_cat.json", selected_classes=["beach", "computer", "motorcycle", "stove", "table"], spurious_class="table", source_context="books", target_context="cat", ), PCBMMetashiftConfig( name="task_bcmst_table_books_dog", description="Task 2: table(books) -> table(dog)", metadata_path="configs/task_bcmst_table_books_dog.json", selected_classes=["beach", "computer", "motorcycle", "stove", "table"], spurious_class="table", source_context="books", target_context="dog", ), PCBMMetashiftConfig( name="task_bcmst_table_cat_dog", description="Task 2: table(cat) -> table(dog)", metadata_path="configs/task_bcmst_table_cat_dog.json", selected_classes=["beach", "computer", "motorcycle", "stove", "table"], spurious_class="table", source_context="cat", target_context="dog", ), PCBMMetashiftConfig( name="task_bcmst_table_dog_cat", description="Task 2: table(dog) -> table(cat)", metadata_path="configs/task_bcmst_table_dog_cat.json", selected_classes=["beach", "computer", "motorcycle", "stove", "table"], spurious_class="table", source_context="dog", target_context="cat", ), ] def _info(self): return datasets.DatasetInfo( description=_DESCRIPTION_TEMPLATE.substitute( num_classes=len(self.config.selected_classes), spurious_class=self.config.spurious_class, source_context=self.config.source_context, target_context=self.config.target_context, selected_classes=", ".join(self.config.selected_classes), ), features=datasets.Features( { "image": datasets.Image(), "label": datasets.ClassLabel(names=self.config.selected_classes), } ), supervised_keys=("image", "label"), homepage=_HOMEPAGE, citation=_CITATION, license=_LICENSE, task_templates=[ datasets.ImageClassification(image_column="image", label_column="label") ], ) def _split_generators(self, dl_manager): archive_path = dl_manager.download(f"{_REPO}/data/images.tar.gz") metadata_path = dl_manager.download(f"{_REPO}/{self.config.metadata_path}") return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={ "images": dl_manager.iter_archive(archive_path), "metadata_path": metadata_path, "split": "train", }, ), datasets.SplitGenerator( name=datasets.Split.TEST, gen_kwargs={ "images": dl_manager.iter_archive(archive_path), "metadata_path": metadata_path, "split": "test", }, ), ] def _generate_examples(self, images, metadata_path: str, split: str): """Generate images and labels for splits.""" with open(metadata_path, encoding="utf-8") as f: metadata = json.load(f) split_data = metadata["data_splits"][split] ids_to_keep = set() for _, ids in split_data.items(): ids_to_keep.update([Path(id).stem for id in ids]) files = dict() for file_path, file_obj in images: image_id = Path(file_path).stem if image_id in ids_to_keep: files[image_id] = (file_obj.read(), file_path) for cls, ids in split_data.items(): for image_id in ids: image_id = Path(image_id).stem file_obj, file_path = files[image_id] yield f"{cls}_{image_id}", { "image": {"path": file_path, "bytes": file_obj}, "label": cls, }