| import os |
| import json |
| import random |
| from datasets import ( |
| BuilderConfig, |
| DatasetInfo, |
| DownloadManager, |
| GeneratorBasedBuilder, |
| SplitGenerator, |
| Split, |
| Features, |
| Image, |
| Sequence, |
| Value, |
| ) |
|
|
| class ImageSubsetConfig(BuilderConfig): |
| """BuilderConfig for small vs. full dataset.""" |
| def __init__(self, name, sample_size=None, **kwargs): |
| super().__init__( |
| name=name, |
| version="1.0.0", |
| description=kwargs.get("description", "") |
| ) |
| self.sample_size = sample_size |
|
|
| class MyImageDataset(GeneratorBasedBuilder): |
| """A dataset of images with actuated_angle from metadata.json.""" |
| BUILDER_CONFIGS = [ |
| ImageSubsetConfig( |
| name="full", |
| sample_size=None, |
| description="All images (≈100 GB). Use with streaming=True." |
| ), |
| ImageSubsetConfig( |
| name="small", |
| sample_size=2, |
| description="Random subset of 10 000 images for quick iteration." |
| ), |
| ] |
| DEFAULT_CONFIG_NAME = "smgit all" |
|
|
| def _info(self): |
| return DatasetInfo( |
| description="Images with a 2-D actuated_angle from metadata.json", |
| features=Features({ |
| "image": Image(), |
| "actuated_angle": Sequence(Value("int32")), |
| }), |
| supervised_keys=None, |
| ) |
|
|
| def _split_generators(self, dl_manager: DownloadManager): |
| data_dir = dl_manager.manual_dir or os.path.abspath(os.path.dirname(__file__)) |
| images_dir = os.path.join(data_dir, "images") |
| meta_path = os.path.join(data_dir, "metadata.json") |
|
|
| |
| with open(meta_path, "r", encoding="utf-8") as f: |
| metadata = json.load(f) |
|
|
| |
| if self.config.sample_size: |
| all_fnames = list(metadata.keys()) |
| random.seed(42) |
| selected = set(random.sample(all_fnames, self.config.sample_size)) |
| else: |
| selected = set(metadata.keys()) |
|
|
| return [ |
| SplitGenerator( |
| name=Split.TRAIN, |
| gen_kwargs={ |
| "images_dir": images_dir, |
| "metadata": metadata, |
| "selected": selected, |
| }, |
| ), |
| ] |
|
|
| def _generate_examples(self, images_dir, metadata, selected): |
| """Yields examples of the form { "image": path, "actuated_angle": [int, int] }""" |
| for idx, fname in enumerate(selected): |
| if fname not in metadata: |
| continue |
| image_path = os.path.join(images_dir, fname) |
| if not os.path.exists(image_path): |
| continue |
| meta = metadata[fname] |
| |
| angles = [ int(meta.get("0", 0)), int(meta.get("1", 0)) ] |
| yield idx, { |
| "image": image_path, |
| "actuated_angle": angles, |
| } |
|
|