File size: 8,712 Bytes
fde9a21 | 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 | #!/usr/bin/env python3
"""Normalize the three reviewed annotation fragments into 50 frozen cases."""
from __future__ import annotations
import json
from copy import deepcopy
from pathlib import Path
from typing import Any
ROOT = Path(__file__).resolve().parents[1]
STAGING = ROOT.parent / "dataset_staging"
BASE_PATH = STAGING / "base_case_specs_fragment.json"
STRICT_PATH = STAGING / "strict_replacements" / "preannotations.json"
MOTORCYCLE_PATH = STAGING / "motorcycle_rescue" / "selected" / "preannotations.json"
OUTPUT_PATH = ROOT / "metadata" / "case_specs.json"
def load_object(path: Path) -> dict[str, Any]:
value = json.loads(path.read_text(encoding="utf-8"))
if not isinstance(value, dict):
raise TypeError(f"Expected an object in {path}")
return value
def dump_object(path: Path, value: dict[str, 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 normalize_layout(layout: Any, instance_count: int) -> str:
if isinstance(layout, str) and layout.strip():
return layout.strip()
if not isinstance(layout, dict):
raise TypeError("layout must be a string or object")
note = layout.get("note")
if isinstance(note, str) and note.strip():
return note.strip()
row_count = int(layout.get("row_count", 1))
if row_count == 1:
return f"one horizontal row of {instance_count}, ordered from viewer left to right"
row_order = layout.get("row_order", [])
rows = " then ".join(str(row) for row in row_order)
return f"two horizontal rows ({rows}), each ordered from viewer left to right"
def processing_text(value: Any) -> str:
if isinstance(value, str) and value.strip():
return value.strip()
if not isinstance(value, dict):
raise TypeError("processing must be a string or object")
source_size = value.get("source_size_px")
final_size = value.get("final_size_px")
operation = value.get("operation", "unspecified")
parts: list[str] = []
if isinstance(source_size, list) and len(source_size) == 2:
parts.append(f"source {source_size[0]}x{source_size[1]}")
if isinstance(final_size, list) and len(final_size) == 2:
parts.append(f"final {final_size[0]}x{final_size[1]}")
parts.append(str(operation))
return "; ".join(parts)
def target_from_variant(variant: dict[str, Any]) -> tuple[str, dict[str, Any]]:
pair = str(variant.get("variant_id", variant.get("pair", "")))
target: dict[str, Any] = {
"target_instance_id": str(variant["target_instance_id"]),
"target_expression": str(variant["target_expression"]),
}
sam_prompt = variant.get("sam2_prompt")
if isinstance(sam_prompt, dict):
for key in ("positive_points_norm", "negative_points_norm", "sam_candidate_index"):
if key in sam_prompt:
target[key] = deepcopy(sam_prompt[key])
return pair, target
def normalize_strict_case(raw: dict[str, Any]) -> dict[str, Any]:
instances = deepcopy(raw["instances"])
instance_count = int(raw.get("instance_count", raw.get("layout", {}).get("instance_count", len(instances))))
variants = raw["variants"]
targets = dict(target_from_variant(variant) for variant in variants)
source_raw = deepcopy(raw["source"])
rights = {
"license": source_raw.pop("license"),
"license_url": source_raw.pop("license_url"),
"caveats": source_raw.pop("rights_caveat"),
}
if "license_evidence_url" in source_raw:
rights["license_evidence_url"] = source_raw.pop("license_evidence_url")
return {
"case_id": str(raw["case_id"]),
"category": str(raw["category"]),
"image": str(raw["image"]),
"instance_count": instance_count,
"layout": normalize_layout(raw["layout"], instance_count),
"subject_definition": str(raw["subject_definition"]),
"source": source_raw,
"rights": rights,
"processing": processing_text(raw["processing"]),
"release_guidance": rights["caveats"],
"instance_order": instances,
"operation_id": str(raw["operation_id"]),
"edit_spec": deepcopy(raw["edit_spec"]),
"prompt_template": str(raw["prompt_template"]),
"targets": targets,
"review_notes": deepcopy(raw.get("qa_flags", [])),
}
def normalize_motorcycle(raw: dict[str, Any]) -> dict[str, Any]:
source = deepcopy(raw["source"])
source["source_url"] = source.pop("source_page")
variants = raw["variants"]
targets = dict(target_from_variant(variant) for variant in variants)
rights = deepcopy(raw["rights"])
caveats = str(rights.pop("caveats"))
rights["caveats"] = caveats
return {
"case_id": str(raw["case_id"]),
"category": str(raw["category"]),
"image": str(raw["image"]),
"instance_count": int(raw["instance_count"]),
"layout": normalize_layout(raw["layout"], int(raw["instance_count"])),
"subject_definition": str(raw["subject_definition"]),
"source": source,
"rights": rights,
"processing": processing_text(raw["processing"]),
"release_guidance": str(raw.get("release_guidance", caveats)),
"instance_order": deepcopy(raw["instances"]),
"operation_id": str(raw["operation_id"]),
"edit_spec": deepcopy(raw["edit_spec"]),
"prompt_template": str(raw["prompt_template"]),
"targets": targets,
"review_notes": deepcopy(raw.get("qa_flags", [])),
}
def main() -> None:
base = load_object(BASE_PATH)
strict = load_object(STRICT_PATH)
motorcycle = load_object(MOTORCYCLE_PATH)
cases: list[dict[str, Any]] = [deepcopy(case) for case in base["cases"]]
cases.extend(normalize_strict_case(case) for case in strict["cases"])
cases.append(normalize_motorcycle(motorcycle))
cases.sort(key=lambda case: str(case["case_id"]))
case_ids = [str(case["case_id"]) for case in cases]
if len(cases) != 50 or len(set(case_ids)) != 50:
raise ValueError(f"Expected exactly 50 unique cases, got {len(cases)} cases / {len(set(case_ids))} IDs")
image_names = {path.name for path in (ROOT / "images").glob("*.jpg")}
spec_names = {Path(str(case["image"])).name for case in cases}
if image_names != spec_names:
raise ValueError(f"Image/spec mismatch: images-only={sorted(image_names - spec_names)}, specs-only={sorted(spec_names - image_names)}")
for case in cases:
if int(case["instance_count"]) != len(case["instance_order"]):
raise ValueError(f"{case['case_id']}: instance_count mismatch")
if set(case["targets"]) != {"A", "B"}:
raise ValueError(f"{case['case_id']}: targets must be exactly A/B")
for pair in ("A", "B"):
expected = str(case["prompt_template"]).replace(
"{target_expression}", str(case["targets"][pair]["target_expression"])
)
original_variants = next(
(raw_case.get("variants", []) for raw_case in strict["cases"] if raw_case["case_id"] == case["case_id"]),
[],
)
matching = next((variant for variant in original_variants if variant["variant_id"] == pair), None)
if matching is not None and matching.get("prompt_full") != expected:
raise ValueError(f"{case['case_id']}/{pair}: prompt_full does not match template")
output = {
"schema_version": "final-case-specs-v1",
"status": "frozen-before-model-output-review",
"coordinate_convention": "bbox_xyxy_norm = [left, top, right, bottom], normalized to the displayed model-input image after EXIF transpose.",
"prompt_pair_rule": "Within each case A and B share one exact prompt template and edit specification; only target_expression and target_instance_id differ.",
"visual_audit": {
"status": "main-agent visual audit required and recorded in the dataset documentation",
"scope": "Every final image, ordered instance overlay, prompt pair, and SAM2 target overlay",
"freeze_rule": "All images, targets, and prompts are frozen before inspecting editing-model outputs.",
},
"rights_note": "No external image can honestly be called zero-risk. Preserve per-case source, creator, license, processing, release guidance, and contextual caveats.",
"cases": cases,
}
dump_object(OUTPUT_PATH, output)
print(f"Wrote {OUTPUT_PATH}: {len(cases)} cases, {sum(len(case['instance_order']) for case in cases)} ordered instances")
if __name__ == "__main__":
main()
|