File size: 7,115 Bytes
44a7ed3 | 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 | #!/usr/bin/env python3
"""Build MVEB MS-Celeb-1M subset from train/test split JSON + identity metadata."""
from __future__ import annotations
import argparse
import json
import shutil
import sys
from pathlib import Path
from typing import Dict, List, Tuple
_SCRIPTS_ROOT = Path(__file__).resolve().parent.parent
if str(_SCRIPTS_ROOT) not in sys.path:
sys.path.insert(0, str(_SCRIPTS_ROOT))
from pack_media_parquet import pack_dataset_with_media, resolve_split_output_dir
QUERY_INSTRUCTION = "Represent the face with the following text."
QUERY_TEXT = "Retrieve all images with the same facial identity."
CANDIDATE_INSTRUCTION = "Represent the face with the following text."
CANDIDATE_TEXT = "Retrieve all images with the same facial identity."
def _load_path_to_instance_id(metadata_json: Path) -> Dict[str, str]:
with metadata_json.open("r", encoding="utf-8") as f:
annotations = json.load(f)
if not isinstance(annotations, dict):
raise ValueError(f"metadata must be a dict: {metadata_json}")
path_to_inst: Dict[str, str] = {}
for inst_id, image_names in annotations.items():
if not isinstance(image_names, list):
raise ValueError(f"metadata[{inst_id!r}] must be a list of image paths")
inst = str(inst_id)
for image_name in image_names:
rel = str(image_name).replace("\\", "/")
if rel in path_to_inst and path_to_inst[rel] != inst:
raise ValueError(
f"Image path {rel!r} maps to multiple instance ids: "
f"{path_to_inst[rel]!r} and {inst!r}"
)
path_to_inst[rel] = inst
return path_to_inst
def _make_annotations(
rel_paths: List[str],
path_to_inst: Dict[str, str],
) -> Tuple[List[dict], List[dict]]:
candidate_rows: List[dict] = []
inst_to_ids: Dict[str, List[str]] = {}
missing: List[str] = []
for idx, rel_path in enumerate(sorted(set(rel_paths))):
rel = rel_path.replace("\\", "/")
inst_id = path_to_inst.get(rel)
if inst_id is None:
missing.append(rel)
continue
candidate_rows.append(
{
"id": rel,
"instance_id": inst_id,
"image_path": rel,
"instruction": CANDIDATE_INSTRUCTION,
"text": CANDIDATE_TEXT,
}
)
inst_to_ids.setdefault(inst_id, []).append(rel)
if missing:
preview = ", ".join(missing[:5])
raise KeyError(
f"{len(missing)} split image(s) not found in metadata.json "
f"(e.g. {preview})"
)
query_rows: List[dict] = []
for row in candidate_rows:
target_ids = [x for x in inst_to_ids[row["instance_id"]] if x != row["id"]]
if not target_ids:
continue
query_rows.append(
{
"id": row["id"],
"instance_id": row["instance_id"],
"image_path": row["image_path"],
"instruction": QUERY_INSTRUCTION,
"text": QUERY_TEXT,
"target_ids": target_ids,
}
)
return query_rows, candidate_rows
def _process_one_split(
split_name: str,
rel_paths: List[str],
path_to_inst: Dict[str, str],
image_root: Path,
output_root: Path,
overwrite: bool,
media_rows_per_shard: int,
row_group_size: int,
num_workers: int,
) -> None:
out_dir = resolve_split_output_dir(output_root, split_name, "MS-Celeb-1M")
if overwrite and out_dir.exists():
shutil.rmtree(out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
query_rows, candidate_rows = _make_annotations(rel_paths, path_to_inst)
stats = pack_dataset_with_media(
query_annotations=query_rows,
candidate_annotations=candidate_rows,
image_dir=str(image_root),
output_dir=str(out_dir),
media_rows_per_shard=media_rows_per_shard,
row_group_size=row_group_size,
num_workers=num_workers,
dataset_name="MS-Celeb-1M",
data_split=split_name,
write_subset_readme=True,
show_progress=True,
)
print(
f"[{split_name}] done: media={stats['num_media']}, "
f"query={stats['num_query']}, candidate={stats['num_candidate']}, "
f"shards={stats['num_shards']} -> {out_dir}"
)
def main() -> None:
script_dir = Path(__file__).resolve().parent
root_dir = script_dir.parent.parent.parent
parser = argparse.ArgumentParser(description="Process MS1M split JSON to MVEB parquet format.")
parser.add_argument(
"--split-json",
type=Path,
default=script_dir / "train_test_split.json",
help="JSON containing train/test relative image paths.",
)
parser.add_argument(
"--metadata-json",
type=Path,
default=script_dir / "metadata.json",
help="Identity metadata: instance_id -> list of relative image paths.",
)
parser.add_argument(
"--image-root",
type=Path,
default=root_dir / "source" / "ms1m",
help="Root directory containing extracted shard folders 0000..0099.",
)
parser.add_argument(
"--output-root",
type=Path,
default=root_dir,
help="Output MVEB root directory (contains train/ and test/).",
)
parser.add_argument("--overwrite", action="store_true", help="Delete existing output split dir before writing.")
parser.add_argument("--media-rows-per-shard", type=int, default=5000)
parser.add_argument("--row-group-size", type=int, default=100)
parser.add_argument("--num-workers", type=int, default=1)
args = parser.parse_args()
if not args.split_json.exists():
raise FileNotFoundError(f"split json not found: {args.split_json}")
if not args.metadata_json.exists():
raise FileNotFoundError(f"metadata json not found: {args.metadata_json}")
if not args.image_root.exists():
raise FileNotFoundError(f"image root not found: {args.image_root}")
print(f"==> Load metadata: {args.metadata_json}")
path_to_inst = _load_path_to_instance_id(args.metadata_json)
print(f" images indexed: {len(path_to_inst)}")
with args.split_json.open("r", encoding="utf-8") as f:
split_data = json.load(f)
for key in ("train", "test"):
if key not in split_data or not isinstance(split_data[key], list):
raise ValueError(f"split json must contain key {key!r} with a list value")
_process_one_split(
"train",
split_data["train"],
path_to_inst,
args.image_root,
args.output_root,
args.overwrite,
args.media_rows_per_shard,
args.row_group_size,
args.num_workers,
)
_process_one_split(
"test",
split_data["test"],
path_to_inst,
args.image_root,
args.output_root,
args.overwrite,
args.media_rows_per_shard,
args.row_group_size,
args.num_workers,
)
if __name__ == "__main__":
main()
|