PhotoBench-Protected / photobench.py
SorrowTea's picture
Upload folder using huggingface_hub
9442718 verified
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