import datasets import json import itertools 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/fact-40/pcbm_metashift/resolve/main" _IMAGES_DIR = Path("data") class PCBMMetashiftConfig(datasets.BuilderConfig): """Builder Config for PCBM Metashift""" def __init__( self, metadata_path: str, selected_classes: list[str], spurious_class: str, source_context: str, target_context: str, **kwargs, ): super(PCBMMetashiftConfig, self).__init__( version=datasets.Version("2.0.3"), **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): """PCBM Metashift dataset""" setups = ["cherrypicked", "seed42"] BUILDER_CONFIGS = list( itertools.chain( *[ [ PCBMMetashiftConfig( name=f"{setup}_task_1_bed_cat_dog", description=f"[{setup}] Task 1: bed(cat) -> bed(dog)", metadata_path=f"scenarios/{setup}/task_1_bed_cat_dog.json", selected_classes=["airplane", "bed", "car", "cow", "keyboard"], spurious_class="bed", source_context="cat", target_context="dog", ), PCBMMetashiftConfig( name=f"{setup}_task_1_bed_dog_cat", description=f"[{setup}] Task 1: bed(dog) -> bed(cat)", metadata_path=f"scenarios/{setup}/task_1_bed_dog_cat.json", selected_classes=["airplane", "bed", "car", "cow", "keyboard"], spurious_class="bed", source_context="dog", target_context="cat", ), PCBMMetashiftConfig( name=f"{setup}_task_2_table_books_cat", description=f"[{setup}] Task 2: table(books) -> table(cat)", metadata_path=f"scenarios/{setup}/task_2_table_books_cat.json", selected_classes=[ "beach", "computer", "motorcycle", "stove", "table", ], spurious_class="table", source_context="books", target_context="cat", ), PCBMMetashiftConfig( name=f"{setup}_task_2_table_books_dog", description=f"[{setup}] Task 2: table(books) -> table(dog)", metadata_path=f"scenarios/{setup}/task_2_table_books_dog.json", selected_classes=[ "beach", "computer", "motorcycle", "stove", "table", ], spurious_class="table", source_context="books", target_context="dog", ), PCBMMetashiftConfig( name=f"{setup}_task_2_table_cat_dog", description=f"[{setup}] Task 2: table(cat) -> table(dog)", metadata_path=f"scenarios/{setup}/task_2_table_cat_dog.json", selected_classes=[ "beach", "computer", "motorcycle", "stove", "table", ], spurious_class="table", source_context="cat", target_context="dog", ), PCBMMetashiftConfig( name=f"{setup}_task_2_table_dog_cat", description=f"[{setup}] Task 2: table(dog) -> table(cat)", metadata_path=f"scenarios/{setup}/task_2_table_dog_cat.json", selected_classes=[ "beach", "computer", "motorcycle", "stove", "table", ], spurious_class="table", source_context="dog", target_context="cat", ), ] for setup in setups ] ) ) 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, }