XIAOHAOYANG's picture
Add files using upload-large-folder tool
fde9a21 verified
Raw History Blame Contribute Delete
9.6 kB
#!/usr/bin/env python3
"""Build the frozen manifest and public/private job files from case specs.
``metadata/case_specs.json`` is the human-reviewed source of truth. It stores
one prompt template and one edit specification per source image, plus two
pre-frozen ordinal targets. This builder expands those targets into A/B
variants, measures the actual model input, and writes deterministic metadata.
"""
from __future__ import annotations
import argparse
import hashlib
import json
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
from PIL import Image, ImageOps
DEFAULT_ROOT = Path(__file__).resolve().parents[1]
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--dataset-root", type=Path, default=DEFAULT_ROOT)
parser.add_argument("--specs", type=Path, default=None)
return parser.parse_args()
def read_json(path: Path) -> dict[str, Any]:
data = json.loads(path.read_text(encoding="utf-8"))
if not isinstance(data, dict):
raise ValueError(f"Expected JSON object: {path}")
return data
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def image_dimensions(path: Path) -> list[int]:
with Image.open(path) as raw:
displayed = ImageOps.exif_transpose(raw)
return [displayed.width, displayed.height]
def json_dump(path: Path, value: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(
json.dumps(value, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
def jsonl_dump(path: Path, rows: list[dict[str, Any]]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
text = "".join(json.dumps(row, ensure_ascii=False, separators=(",", ":")) + "\n" for row in rows)
path.write_text(text, encoding="utf-8")
def variant_for(
case_id: str,
prompt_template: str,
operation_id: str,
edit_spec: Any,
target: dict[str, Any],
pair: str,
instances: dict[str, dict[str, Any]],
) -> dict[str, Any]:
target_expression = str(target["target_expression"])
if prompt_template.count("{target_expression}") != 1:
raise ValueError(f"{case_id}: prompt_template must contain exactly one {{target_expression}}")
target_instance_id = str(target["target_instance_id"])
if target_instance_id not in instances:
raise KeyError(f"{case_id}/{pair}: unknown target instance {target_instance_id}")
prompt_full = prompt_template.replace("{target_expression}", target_expression)
sam2_prompt: dict[str, Any] = {
"bbox_xyxy_norm": instances[target_instance_id]["bbox_xyxy_norm"],
"positive_points_norm": target.get("positive_points_norm", []),
"negative_points_norm": target.get("negative_points_norm", []),
}
if "sam_candidate_index" in target:
sam2_prompt["sam_candidate_index"] = target["sam_candidate_index"]
return {
"pair": pair,
"prompt_full": prompt_full,
"target_expression": target_expression,
"target_instance_id": target_instance_id,
"operation_id": operation_id,
"edit_spec": edit_spec,
"sam2_prompt": sam2_prompt,
}
def main() -> None:
args = parse_args()
root = args.dataset_root.resolve()
specs_path = (args.specs or root / "metadata/case_specs.json").resolve()
specs = read_json(specs_path)
raw_cases = specs.get("cases")
if not isinstance(raw_cases, list) or not raw_cases:
raise ValueError("case_specs.json must contain a non-empty cases list")
manifest_cases: list[dict[str, Any]] = []
baseline_rows: list[dict[str, Any]] = []
private_rows: list[dict[str, Any]] = []
source_rows: list[dict[str, Any]] = []
for raw in raw_cases:
if not isinstance(raw, dict):
raise TypeError("Each case spec must be an object")
case_id = str(raw["case_id"])
image_rel = str(raw["image"])
image_path = (root / image_rel).resolve()
image_path.relative_to(root)
if not image_path.is_file():
raise FileNotFoundError(f"{case_id}: missing model input {image_path}")
instances_list = raw.get("instance_order")
if not isinstance(instances_list, list):
raise TypeError(f"{case_id}: instance_order must be a list")
instances = {str(item["instance_id"]): item for item in instances_list}
if len(instances) != len(instances_list):
raise ValueError(f"{case_id}: duplicate instance_id")
prompt_template = str(raw["prompt_template"])
operation_id = str(raw["operation_id"])
edit_spec = raw["edit_spec"]
targets = raw.get("targets")
if not isinstance(targets, dict) or set(targets) != {"A", "B"}:
raise ValueError(f"{case_id}: targets must contain exactly A and B")
variants = [
variant_for(case_id, prompt_template, operation_id, edit_spec, targets[pair], pair, instances)
for pair in ("A", "B")
]
dimensions = image_dimensions(image_path)
digest = sha256(image_path)
generated_keys = {
"prompt_template",
"targets",
"variants",
"image_dimensions",
"image_sha256",
"image_bytes",
}
case = {key: value for key, value in raw.items() if key not in generated_keys}
case.update(
{
"image_dimensions": dimensions,
"image_sha256": digest,
"image_bytes": image_path.stat().st_size,
"variants": variants,
}
)
manifest_cases.append(case)
for variant in variants:
baseline_rows.append(
{
"case_id": case_id,
"pair": variant["pair"],
"source_image": image_rel,
"prompt_full": variant["prompt_full"],
}
)
private_rows.append(
{
"case_id": case_id,
"pair": variant["pair"],
"source_image": image_rel,
"prompt_full": variant["prompt_full"],
"target_expression": variant["target_expression"],
"target_instance_id": variant["target_instance_id"],
"operation_id": operation_id,
"edit_spec": edit_spec,
"sam2_prompt": variant["sam2_prompt"],
}
)
source_rows.append(
{
"case_id": case_id,
"image": image_rel,
"image_dimensions": dimensions,
"image_sha256": digest,
"source": raw.get("source"),
"rights": raw.get("rights"),
"processing": raw.get("processing", "None; model input matches the downloaded source pixels."),
"release_guidance": raw.get("release_guidance"),
}
)
manifest_cases.sort(key=lambda item: str(item["case_id"]))
baseline_rows.sort(key=lambda item: (item["case_id"], item["pair"]))
private_rows.sort(key=lambda item: (item["case_id"], item["pair"]))
source_rows.sort(key=lambda item: item["case_id"])
manifest = {
"schema_version": "3.0",
"created_utc": datetime.now(timezone.utc).isoformat(),
"case_count": len(manifest_cases),
"job_count": len(baseline_rows),
"purpose": "Frozen high-quality ordinal-reference visualization dataset for cross-model image-editing comparison.",
"selection_policy": "Images, A/B targets, prompts, and SAM2 prompts are frozen before reviewing any editing-model output.",
"count_policy": {"preferred_min": 4, "preferred_max": 8, "hard_max": 10},
"layout_policy": "One or two visually legible horizontal rows; count from viewer left to right within the named row.",
"public_baseline_fields": ["source_image", "prompt_full"],
"evaluator_private_fields": ["target_expression", "target_instance_id", "instance_order", "sam2_prompt", "masks"],
"leakage_rule": "Do not send evaluator-private fields, boxes, masks, parsed locators, or target crops to ordinary editing baselines.",
"sam2": {
"checkpoint": "/workspace/models_weight/sam/sam2.1_hiera_large.pt",
"config": "configs/sam2.1/sam2.1_hiera_l.yaml",
"mask_semantics": "visible target-instance mask; this is not necessarily the smaller edited component",
},
"visual_audit": specs.get("visual_audit"),
"rights_note": specs.get("rights_note"),
"cases": manifest_cases,
}
metadata = root / "metadata"
json_dump(metadata / "manifest.json", manifest)
jsonl_dump(metadata / "baseline_jobs.jsonl", baseline_rows)
jsonl_dump(metadata / "prompt_pairs_private.jsonl", private_rows)
jsonl_dump(metadata / "source_inventory.jsonl", source_rows)
json_dump(
metadata / "build_summary.json",
{
"case_count": len(manifest_cases),
"job_count": len(baseline_rows),
"source_count": len(source_rows),
"specs": str(specs_path),
},
)
print(f"Built {len(manifest_cases)} cases / {len(baseline_rows)} A-B jobs")
if __name__ == "__main__":
main()