Spatial457 / Spatial457.py
RyanWW's picture
Upload Spatial457.py with huggingface_hub
f03859b verified
import os
import json
import datasets
class Spatial457(datasets.GeneratorBasedBuilder):
BUILDER_CONFIGS = [
datasets.BuilderConfig(name="L1_single"),
datasets.BuilderConfig(name="L2_objects"),
datasets.BuilderConfig(name="L3_2d_spatial"),
datasets.BuilderConfig(name="L4_occ"),
datasets.BuilderConfig(name="L4_pose"),
datasets.BuilderConfig(name="L5_6d_spatial"),
datasets.BuilderConfig(name="L5_collision"),
]
def _info(self):
return datasets.DatasetInfo(
description="Spatial457: A multi-task spatial visual question answering dataset.",
features=datasets.Features({
"image": datasets.Image(), # 自动加载图片
"image_filename": datasets.Value("string"),
"question": datasets.Value("string"),
"answer": datasets.Value("string"), # 会自动处理 True / False / str
"question_index": datasets.Value("int32"),
"program": datasets.Sequence(
{
"type": datasets.Value("string"),
"inputs": datasets.Sequence(datasets.Value("int32")),
"_output": datasets.Value("string"),
"value_inputs": datasets.Sequence(datasets.Value("string")),
}
),
}),
supervised_keys=None,
)
def _split_generators(self, dl_manager):
base_url = "https://huggingface.co/datasets/RyanWW/Spatial457/resolve/main"
json_url = f"{base_url}/questions/{self.config.name}.json"
# 下载 json 文件
task_json = dl_manager.download(json_url)
# 读取 JSON 获取所有图片文件名
with open(task_json, "r", encoding="utf-8") as f:
all_data = json.load(f)["questions"]
# 构建所有图片的 URL
image_urls = {
q["image_filename"]: f"{base_url}/images/{q['image_filename']}"
for q in all_data
}
# 批量下载所有图片
downloaded_images = dl_manager.download(image_urls)
return [
datasets.SplitGenerator(
name=datasets.Split.VALIDATION,
gen_kwargs={"json_file": task_json, "downloaded_images": downloaded_images}
)
]
def _generate_examples(self, json_file, downloaded_images):
with open(json_file, "r", encoding="utf-8") as f:
all_data = json.load(f)["questions"]
for idx, q in enumerate(all_data):
img_filename = q["image_filename"]
img_path = downloaded_images[img_filename]
yield idx, {
"image": img_path,
"image_filename": img_filename,
"question": q["question"],
"answer": str(q["answer"]),
"question_index": q["question_index"],
"program": q["program"],
}