| from datasets import GeneratorBasedBuilder, DatasetInfo, SplitGenerator, DownloadManager |
| from typing import Any, Dict, List, Tuple |
| import os |
| import json |
|
|
| class ProcessedImageDataset(GeneratorBasedBuilder): |
| VERSION = "1.0.0" |
|
|
| def _info(self) -> DatasetInfo: |
| |
| return DatasetInfo( |
| |
| features=self._features(), |
| supervised_keys=("image", "text"), |
| ) |
|
|
| def _features(self): |
| |
| from datasets import Features, Image, Value |
| return Features({"image_file": Image(), "text": Value("string")}) |
|
|
| def _split_generators(self, dl_manager) -> List[SplitGenerator]: |
| |
| print(self.config.data_dir) |
| if self.config.data_dir is None: |
| raise ValueError(f'Data directory unspecified. Correct usage is: load_dataset(script_path, data_dir=data_dir_path)') |
| return [SplitGenerator(name="train", gen_kwargs={"data_dir": self.config.data_dir})] |
|
|
| def _generate_examples(self, data_dir): |
| |
| |
| metadata_file_path = os.path.join(data_dir, "metadata.jsonl") |
|
|
| |
| metadata = {} |
| with open(metadata_file_path, "r") as f: |
| for line in f: |
| item = json.loads(line) |
| metadata[item["file_name"]] = item |
|
|
| |
| for filename in os.listdir(data_dir): |
| if filename.endswith(".png") or filename.endswith(".jpg") or filename.endswith(".jpeg"): |
| if filename in metadata: |
| metadata_entry = metadata[filename] |
| yield filename, { |
| "image_file": os.path.join(data_dir, filename), |
| "text": metadata_entry["text"], |
| } |
|
|