File size: 13,286 Bytes
9442718 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 | import json
import os
from typing import Any, Dict, List
import datasets
_CITATION = """\
@misc{photobench2026,
title={PhotoBench},
year={2026},
eprint={2603.01493},
archivePrefix={arXiv},
primaryClass={cs.CV}
}
"""
_DESCRIPTION = """\
PhotoBench is an image retrieval benchmark with two modes:
- samples: includes display images and query annotations for visualization.
- protected: includes machine-readable features (embeddings/captions/metadata/faceid)
without raw images for privacy-preserving evaluation.
"""
class PhotoBenchConfig(datasets.BuilderConfig):
def __init__(self, mode: str, **kwargs):
super().__init__(**kwargs)
self.mode = mode
class PhotoBench(datasets.GeneratorBasedBuilder):
VERSION = datasets.Version("1.0.0")
BUILDER_CONFIGS = [
PhotoBenchConfig(
name="samples",
version=VERSION,
mode="samples",
description="Display subset with raw images and query ground truth.",
),
PhotoBenchConfig(
name="protected",
version=VERSION,
mode="protected",
description="Privacy-preserving subset with embeddings/captions/metadata.",
),
]
DEFAULT_CONFIG_NAME = "samples"
def _info(self) -> datasets.DatasetInfo:
common_query_features = {
"album_id": datasets.Value("string"),
"query_id": datasets.Value("string"),
"query_cn": datasets.Value("string"),
"query_en": datasets.Value("string"),
"location": datasets.Value("string"),
"time": datasets.Value("string"),
"person": datasets.Value("string"),
"object": datasets.Value("string"),
"concept": datasets.Value("string"),
"genre": datasets.Value("string"),
"source": datasets.Value("string"),
}
if self.config.name == "samples":
features = datasets.Features(
{
**common_query_features,
"ground_truth": datasets.Sequence(datasets.Value("string")),
"ground_truth_count": datasets.Value("int32"),
"ground_truth_images": datasets.Sequence(datasets.Image()),
}
)
else:
features = datasets.Features(
{
**common_query_features,
"captions_cn_models": datasets.Sequence(
{
"model_name": datasets.Value("string"),
"metadata_path": datasets.Value("string"),
"filenames_count": datasets.Value("int32"),
}
),
"captions_en_models": datasets.Sequence(
{
"model_name": datasets.Value("string"),
"metadata_path": datasets.Value("string"),
"filenames_count": datasets.Value("int32"),
}
),
"embedding_models": datasets.Sequence(
{
"model_name": datasets.Value("string"),
"index_faiss_path": datasets.Value("string"),
"metadata_path": datasets.Value("string"),
"filenames_count": datasets.Value("int32"),
}
),
"geo_metadata_path": datasets.Value("string"),
"geo_metadata_count": datasets.Value("int32"),
"face_info_cn_path": datasets.Value("string"),
"face_info_en_path": datasets.Value("string"),
"face_id_images_dir": datasets.Value("string"),
}
)
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=features,
supervised_keys=None,
homepage="https://huggingface.co/datasets",
citation=_CITATION,
)
def _split_generators(self, dl_manager: datasets.DownloadManager):
data_root = self._resolve_data_root()
mode_dir = os.path.join(data_root, self.config.mode)
if not os.path.isdir(mode_dir):
raise FileNotFoundError(f"Expected directory not found: {mode_dir}")
album_dirs = [
os.path.join(mode_dir, d)
for d in sorted(os.listdir(mode_dir))
if os.path.isdir(os.path.join(mode_dir, d))
]
return [
datasets.SplitGenerator(
name=datasets.Split.TEST,
gen_kwargs={"album_dirs": album_dirs, "mode": self.config.mode},
)
]
def _resolve_data_root(self) -> str:
mode = self.config.mode
candidates = []
if self.config.data_dir:
candidates.append(os.path.abspath(self.config.data_dir))
# load_dataset("./photobench.py", ...) executes from cache, so prefer cwd.
candidates.append(os.path.abspath(os.getcwd()))
script_dir = os.path.abspath(os.path.dirname(__file__))
candidates.append(script_dir)
candidates.append(os.path.abspath(os.path.join(script_dir, "..")))
for root in candidates:
if os.path.isdir(os.path.join(root, mode)):
return root
raise FileNotFoundError(
f"Could not resolve data root containing '{mode}/'. "
"Run load_dataset from the project root or pass data_dir explicitly."
)
def _generate_examples(self, album_dirs: List[str], mode: str):
for album_dir in album_dirs:
album_id = os.path.basename(album_dir)
query_path = os.path.join(album_dir, "query.json")
if not os.path.isfile(query_path):
continue
with open(query_path, "r", encoding="utf-8") as f:
queries = json.load(f)
protected_summary = None
if mode == "protected":
protected_summary = self._build_protected_summary(album_dir)
for q_idx, row in enumerate(queries):
query = self._normalize_query_row(row, album_id=album_id, fallback_id=q_idx)
if mode == "samples":
image_dir = os.path.join(album_dir, "images")
image_items = []
for fname in query["ground_truth"]:
image_path = os.path.join(image_dir, fname)
if os.path.isfile(image_path):
image_items.append({"path": image_path})
example = {
**query,
"ground_truth_images": image_items,
}
else:
example = {
**query,
**protected_summary,
}
key = f"{mode}-{album_id}-{q_idx}"
yield key, example
@staticmethod
def _pick(row: Dict[str, Any], *keys: str, default: Any = None) -> Any:
for k in keys:
if k in row:
return row[k]
return default
def _normalize_query_row(self, row: Dict[str, Any], album_id: str, fallback_id: int) -> Dict[str, Any]:
query_id = self._pick(row, "query_id", "Query_id", "QueryID", default=str(fallback_id))
base = {
"album_id": str(self._pick(row, "album_id", "Album_id", default=album_id) or album_id),
"query_id": str(query_id),
"query_cn": self._to_nullable_str(self._pick(row, "query_cn", "Query", default=None)),
"query_en": self._to_nullable_str(self._pick(row, "query_en", default=None)),
"location": self._to_nullable_str(self._pick(row, "Location", default=None)),
"time": self._to_nullable_str(self._pick(row, "Time", default=None)),
"person": self._to_nullable_str(self._pick(row, "Person", default=None)),
"object": self._to_nullable_str(self._pick(row, "Object", default=None)),
"concept": self._to_nullable_str(self._pick(row, "Concept", default=None)),
"genre": self._to_nullable_str(self._pick(row, "Genre", default=None)),
"source": self._to_nullable_str(self._pick(row, "Source", "Source_type", default=None)),
}
if self.config.name == "samples":
ground_truth = self._pick(row, "ground_truth", "GroundTruth", default=[]) or []
if not isinstance(ground_truth, list):
ground_truth = [str(ground_truth)]
ground_truth_count = self._pick(row, "ground_truth_count", "GroundTruth_count", default=len(ground_truth))
try:
ground_truth_count = int(ground_truth_count)
except (TypeError, ValueError):
ground_truth_count = len(ground_truth)
base.update(
{
"ground_truth": [str(x) for x in ground_truth],
"ground_truth_count": ground_truth_count,
}
)
return base
@staticmethod
def _to_nullable_str(value: Any) -> Any:
if value is None:
return None
return str(value)
def _build_protected_summary(self, album_dir: str) -> Dict[str, Any]:
images_dir = os.path.join(album_dir, "images")
captions_dir = os.path.join(images_dir, "captions")
embeddings_dir = os.path.join(images_dir, "embeddings")
metadata_path = os.path.join(images_dir, "metadata", "metadata.json")
face_info_cn_path = os.path.join(images_dir, "faceid", "face_info_cn.json")
face_info_en_path = os.path.join(images_dir, "faceid", "face_info_en.json")
face_id_images_dir = os.path.join(images_dir, "faceid", "face_id_images")
captions_cn_models = self._read_caption_models(captions_dir, lang="cn")
captions_en_models = self._read_caption_models(captions_dir, lang="en")
embedding_models = self._read_embedding_models(embeddings_dir)
geo_metadata_count = 0
if os.path.isfile(metadata_path):
with open(metadata_path, "r", encoding="utf-8") as f:
meta = json.load(f)
if isinstance(meta, dict):
geo_metadata_count = len(meta)
return {
"captions_cn_models": captions_cn_models,
"captions_en_models": captions_en_models,
"embedding_models": embedding_models,
"geo_metadata_path": metadata_path,
"geo_metadata_count": geo_metadata_count,
"face_info_cn_path": face_info_cn_path,
"face_info_en_path": face_info_en_path,
"face_id_images_dir": face_id_images_dir,
}
def _read_caption_models(self, captions_dir: str, lang: str) -> List[Dict[str, Any]]:
lang_dir = os.path.join(captions_dir, lang)
if not os.path.isdir(lang_dir):
return []
entries = []
for model_name in sorted(os.listdir(lang_dir)):
model_dir = os.path.join(lang_dir, model_name)
if not os.path.isdir(model_dir):
continue
model_meta_path = os.path.join(model_dir, "metadata.json")
filenames_count = 0
if os.path.isfile(model_meta_path):
with open(model_meta_path, "r", encoding="utf-8") as f:
model_meta = json.load(f)
filenames = model_meta.get("filenames", []) if isinstance(model_meta, dict) else []
if isinstance(filenames, list):
filenames_count = len(filenames)
entries.append(
{
"model_name": model_name,
"metadata_path": model_meta_path,
"filenames_count": filenames_count,
}
)
return entries
def _read_embedding_models(self, embeddings_dir: str) -> List[Dict[str, Any]]:
if not os.path.isdir(embeddings_dir):
return []
entries = []
for model_name in sorted(os.listdir(embeddings_dir)):
model_dir = os.path.join(embeddings_dir, model_name)
if not os.path.isdir(model_dir):
continue
index_faiss_path = os.path.join(model_dir, "index.faiss")
model_meta_path = os.path.join(model_dir, "metadata.json")
filenames_count = 0
if os.path.isfile(model_meta_path):
with open(model_meta_path, "r", encoding="utf-8") as f:
model_meta = json.load(f)
filenames = model_meta.get("filenames", []) if isinstance(model_meta, dict) else []
if isinstance(filenames, list):
filenames_count = len(filenames)
entries.append(
{
"model_name": model_name,
"index_faiss_path": index_faiss_path,
"metadata_path": model_meta_path,
"filenames_count": filenames_count,
}
)
return entries
|