Upload ImageRewardDB.py with huggingface_hub
Browse files- ImageRewardDB.py +222 -0
ImageRewardDB.py
ADDED
@@ -0,0 +1,222 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
|
2 |
+
#
|
3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
+
# you may not use this file except in compliance with the License.
|
5 |
+
# You may obtain a copy of the License at
|
6 |
+
#
|
7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
+
#
|
9 |
+
# Unless required by applicable law or agreed to in writing, software
|
10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
+
# See the License for the specific language governing permissions and
|
13 |
+
# limitations under the License.
|
14 |
+
# TODO: Address all TODOs and remove all explanatory comments
|
15 |
+
"""TODO: Add a description here."""
|
16 |
+
|
17 |
+
|
18 |
+
import pandas as pd
|
19 |
+
import json
|
20 |
+
import os
|
21 |
+
|
22 |
+
import datasets
|
23 |
+
from huggingface_hub import hf_hub_url
|
24 |
+
|
25 |
+
|
26 |
+
# TODO: Add BibTeX citation
|
27 |
+
# Find for instance the citation on arxiv or on the dataset repo/website
|
28 |
+
_CITATION = """\
|
29 |
+
@InProceedings{huggingface:dataset,
|
30 |
+
title = {A great new dataset},
|
31 |
+
author={huggingface, Inc.
|
32 |
+
},
|
33 |
+
year={2020}
|
34 |
+
}
|
35 |
+
"""
|
36 |
+
|
37 |
+
# TODO: Add description of the dataset here
|
38 |
+
# You can copy an official description
|
39 |
+
_DESCRIPTION = """\
|
40 |
+
This new dataset is designed to solve this great NLP task and is crafted with a lot of care.
|
41 |
+
"""
|
42 |
+
|
43 |
+
# TODO: Add a link to an official homepage for the dataset here
|
44 |
+
_HOMEPAGE = "https://huggingface.co/datasets/wuyuchen/ImageRewardDB"
|
45 |
+
_VERSION = datasets.Version("1.0.0")
|
46 |
+
|
47 |
+
# TODO: Add the licence for the dataset here if you can find it
|
48 |
+
_LICENSE = ""
|
49 |
+
|
50 |
+
# TODO: Add link to the official dataset URLs here
|
51 |
+
# The HuggingFace Datasets library doesn't host the datasets but only points to the original files.
|
52 |
+
# This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)
|
53 |
+
_REPO_ID = "wuyuchen/ImageRewardDB"
|
54 |
+
_URLS = {}
|
55 |
+
_PART_IDS = {
|
56 |
+
"train": 32,
|
57 |
+
"validation": 2,
|
58 |
+
"test": 2
|
59 |
+
}
|
60 |
+
|
61 |
+
for name in list(_PART_IDS.keys()):
|
62 |
+
_URLS[name] = {}
|
63 |
+
for i in range(1, _PART_IDS[name]+1):
|
64 |
+
_URLS[name][i] = hf_hub_url(
|
65 |
+
_REPO_ID,
|
66 |
+
filename=f"images/{name}/{name}_{id}.zip",
|
67 |
+
repo_type="dataset"
|
68 |
+
)
|
69 |
+
_URLS[name]["metadata"] = hf_hub_url(
|
70 |
+
_REPO_ID,
|
71 |
+
filename=f"metadata-{name}.parquet",
|
72 |
+
repo_type="dataset"
|
73 |
+
)
|
74 |
+
|
75 |
+
class ImageRewardDBConfig(datasets.BuilderConfig):
|
76 |
+
'''BuilderConfig for ImageRewardDB'''
|
77 |
+
|
78 |
+
def __init__(self, part_ids, **kwargs):
|
79 |
+
'''BuilderConfig for ImageRewardDB
|
80 |
+
Args:
|
81 |
+
part_ids([int]): A list of part_ids.
|
82 |
+
**kwargs: keyword arguments forwarded to super
|
83 |
+
'''
|
84 |
+
super(ImageRewardDBConfig, self).__init__(version=_VERSION, **kwargs)
|
85 |
+
self.part_ids = part_ids
|
86 |
+
|
87 |
+
# TODO: Name of the dataset usually matches the script name with CamelCase instead of snake_case
|
88 |
+
class ImageRewardDB(datasets.GeneratorBasedBuilder):
|
89 |
+
"""TODO: Short description of my dataset."""
|
90 |
+
|
91 |
+
# This is an example of a dataset with multiple configurations.
|
92 |
+
# If you don't want/need to define several sub-sets in your dataset,
|
93 |
+
# just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes.
|
94 |
+
|
95 |
+
# If you need to make complex sub-parts in the datasets with configurable options
|
96 |
+
# You can create your own builder configuration class to store attribute, inheriting from datasets.BuilderConfig
|
97 |
+
# BUILDER_CONFIG_CLASS = MyBuilderConfig
|
98 |
+
|
99 |
+
# You will be able to load one or the other configurations in the following list with
|
100 |
+
# data = datasets.load_dataset('my_dataset', 'first_domain')
|
101 |
+
# data = datasets.load_dataset('my_dataset', 'second_domain')
|
102 |
+
BUILDER_CONFIGS = []
|
103 |
+
|
104 |
+
for num_k in [1,2,4,8]:
|
105 |
+
part_ids = {
|
106 |
+
"train": 4*num_k,
|
107 |
+
"validation": 2,
|
108 |
+
"test": 2
|
109 |
+
}
|
110 |
+
BUILDER_CONFIGS.append(
|
111 |
+
ImageRewardDBConfig(name=f"{num_k}k", part_ids=part_ids, version=_VERSION, description=f"This is a {num_k}k-scale ImageRewardDB")
|
112 |
+
)
|
113 |
+
|
114 |
+
DEFAULT_CONFIG_NAME = "8k" # It's not mandatory to have a default configuration. Just use one if it make sense.
|
115 |
+
|
116 |
+
def _info(self):
|
117 |
+
# TODO: This method specifies the datasets.DatasetInfo object which contains informations and typings for the dataset
|
118 |
+
features = datasets.Features(
|
119 |
+
{
|
120 |
+
"image": datasets.Image(),
|
121 |
+
"prompt_id": datasets.Value("string"),
|
122 |
+
"prompt": datasets.Value("string"),
|
123 |
+
"classification": datasets.Value("string"),
|
124 |
+
"image_amount_in_total": datasets.Value("int8"),
|
125 |
+
"rank": datasets.Value("int8"),
|
126 |
+
"overall_rating": datasets.Value("int8"),
|
127 |
+
"image_text_alignment_rating": datasets.Value("int8"),
|
128 |
+
"fidelity_rating": datasets.Value("int8")
|
129 |
+
}
|
130 |
+
)
|
131 |
+
return datasets.DatasetInfo(
|
132 |
+
# This is the description that will appear on the datasets page.
|
133 |
+
description=_DESCRIPTION,
|
134 |
+
# This defines the different columns of the dataset and their types
|
135 |
+
features=features, # Here we define them above because they are different between the two configurations
|
136 |
+
# If there's a common (input, target) tuple from the features, uncomment supervised_keys line below and
|
137 |
+
# specify them. They'll be used if as_supervised=True in builder.as_dataset.
|
138 |
+
# supervised_keys=("sentence", "label"),
|
139 |
+
# Homepage of the dataset for documentation
|
140 |
+
homepage=_HOMEPAGE,
|
141 |
+
# License for the dataset if available
|
142 |
+
license=_LICENSE,
|
143 |
+
# Citation for the dataset
|
144 |
+
citation=_CITATION,
|
145 |
+
)
|
146 |
+
|
147 |
+
def _split_generators(self, dl_manager):
|
148 |
+
# TODO: This method is tasked with downloading/extracting the data and defining the splits depending on the configuration
|
149 |
+
# If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name
|
150 |
+
|
151 |
+
# dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLS
|
152 |
+
# 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.
|
153 |
+
# By default the archives will be extracted and a path to a cached folder where they are extracted is returned instead of the archive
|
154 |
+
data_dirs = {name: [] for name in list(_PART_IDS.keys())}
|
155 |
+
json_paths = {name: [] for name in list(_PART_IDS.keys())}
|
156 |
+
metadata_paths = {name: [] for name in list(_PART_IDS.keys())}
|
157 |
+
for key in list(self.config.part_ids.keys()):
|
158 |
+
for i in range(1, self.config.part_ids[key]+1):
|
159 |
+
data_dir = dl_manager.download_and_extract(_URLS[key][i])
|
160 |
+
data_dirs[key].append(data_dir)
|
161 |
+
json_paths[key].append(os.path.join(data_dir, f"{key}_{i}.json"))
|
162 |
+
metadata_paths[key] = dl_manager.download(_URLS[key]["metadata"])
|
163 |
+
return [
|
164 |
+
datasets.SplitGenerator(
|
165 |
+
name=datasets.Split.TRAIN,
|
166 |
+
# These kwargs will be passed to _generate_examples
|
167 |
+
gen_kwargs={
|
168 |
+
"split": "train",
|
169 |
+
"data_dirs": data_dirs["train"],
|
170 |
+
"json_paths": json_paths["train"],
|
171 |
+
"metadata_path": metadata_paths["train"]
|
172 |
+
},
|
173 |
+
),
|
174 |
+
datasets.SplitGenerator(
|
175 |
+
name=datasets.Split.VALIDATION,
|
176 |
+
# These kwargs will be passed to _generate_examples
|
177 |
+
gen_kwargs={
|
178 |
+
"split": "validation",
|
179 |
+
"data_dirs": data_dirs["validation"],
|
180 |
+
"json_paths": json_paths["validation"],
|
181 |
+
"metadata_path": metadata_paths["validation"]
|
182 |
+
},
|
183 |
+
),
|
184 |
+
datasets.SplitGenerator(
|
185 |
+
name=datasets.Split.TEST,
|
186 |
+
# These kwargs will be passed to _generate_examples
|
187 |
+
gen_kwargs={
|
188 |
+
"split": "test",
|
189 |
+
"data_dirs": data_dirs["test"],
|
190 |
+
"json_paths": json_paths["test"],
|
191 |
+
"metadata_path": metadata_paths["test"]
|
192 |
+
},
|
193 |
+
),
|
194 |
+
]
|
195 |
+
|
196 |
+
# method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
|
197 |
+
def _generate_examples(self, split, data_dirs, json_paths, metadata_path):
|
198 |
+
# TODO: This method handles input defined in _split_generators to yield (key, example) tuples from the dataset.
|
199 |
+
# The `key` is for legacy reasons (tfds) and is not important in itself, but must be unique for each example.
|
200 |
+
|
201 |
+
num_data_dirs = len(data_dirs)
|
202 |
+
assert num_data_dirs == len(json_paths)
|
203 |
+
|
204 |
+
#Iterate throug all extracted zip folders for images
|
205 |
+
for index, json_path in enumerate(json_paths):
|
206 |
+
json_data = json.load(open(json_path, "r", encoding="utf-8"))
|
207 |
+
for example in json_data:
|
208 |
+
image_path = os.path.join(data_dirs[index], str(example["image_path"]).split("/")[-1])
|
209 |
+
yield example["image_path"], {
|
210 |
+
"image": {
|
211 |
+
"path": image_path,
|
212 |
+
"bytes": open(image_path, "rb").read()
|
213 |
+
},
|
214 |
+
"prompt_id": example["prompt_id"],
|
215 |
+
"prompt": example["prompt"],
|
216 |
+
"classification": example["classification"],
|
217 |
+
"image_amount_in_total": example["image_amount_in_total"],
|
218 |
+
"rank": example["rank"],
|
219 |
+
"overall_rating": example["overall_rating"],
|
220 |
+
"image_text_alignment_rating": example["image_text_alignment_rating"],
|
221 |
+
"fidelity_rating": example["fidelity_rating"]
|
222 |
+
}
|