Datasets:
File size: 16,256 Bytes
fa41a2a 2dee2e9 fa41a2a 2767b5b fa41a2a 2dee2e9 fa41a2a 2dee2e9 fa41a2a 2dee2e9 2767b5b 2dee2e9 2767b5b 2dee2e9 fa41a2a beae8e5 2dee2e9 beae8e5 2dee2e9 2767b5b 2dee2e9 2767b5b 2dee2e9 fa41a2a 2767b5b fa41a2a beae8e5 2dee2e9 fa41a2a 2767b5b 2dee2e9 fa41a2a 2dee2e9 fa41a2a 2dee2e9 fa41a2a beae8e5 fa41a2a 2767b5b fa41a2a 2dee2e9 a2c1aaa fa41a2a 2dee2e9 fa41a2a 2dee2e9 fa41a2a 2767b5b 2dee2e9 fa41a2a 2dee2e9 beae8e5 2dee2e9 2767b5b 2dee2e9 fa41a2a 2dee2e9 fa41a2a 2dee2e9 fa41a2a 2dee2e9 fa41a2a 2dee2e9 fa41a2a 2dee2e9 fa41a2a 2dee2e9 fa41a2a | 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 | #!/usr/bin/env python3
"""Build the typed CASTAIGNE25 case table from case definitions and packages."""
import argparse
import hashlib
import io
import json
import tomllib
from pathlib import Path
from datetime import datetime, timezone
from datasets import Features, Image, List, Value
from PIL import Image as PILImage
import yaml
DATASET_VERSION = "0.3.0"
FEATURES = Features({
"original_image": Image(),
"broken_image": Image(),
"case_id": Value("string"),
"dataset_version": Value("string"),
"title": Value("string"),
"asset_id": Value("string"),
"source_revision": Value("string"),
"source_url": Value("string"),
"license": Value("string"),
"fault_count": Value("int64"),
"faults": List({"defect_id": Value("string"), "description": Value("string")}),
"failure_story": Value("string"),
"required_outcome": Value("string"),
"scope": Value("string"),
"agent_evidence": Value("string"),
"whole_package_path": Value("string"),
"whole_entrypoint": Value("string"),
"broken_package_path": Value("string"),
"broken_entrypoint": Value("string"),
"package_path": Value("string"),
"package_sha256": Value("string"),
"episode_paths": List(Value("string")),
"verification_scope": List(Value("string")),
})
def read_json(path):
return json.loads(path.read_text()) if path.is_file() else {}
def sha256(path):
digest = hashlib.sha256()
with path.open("rb") as stream:
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def preview_image(root, item, case_id, role, expected_asset_sha256, *, folder="previews"):
relative = f"{folder}/{case_id}-{role}.png"
if item.get("path") != relative:
raise ValueError(f"{case_id}: unexpected {role} preview path")
path = root / relative
if not path.is_file() or path.is_symlink():
raise ValueError(f"{case_id}: missing {role} preview")
blob = path.read_bytes()
if hashlib.sha256(blob).hexdigest() != item.get("sha256"):
raise ValueError(f"{case_id}: {role} preview image digest mismatch")
if item.get("asset_sha256") != expected_asset_sha256:
raise ValueError(f"{case_id}: {role} preview does not match the current asset")
with PILImage.open(io.BytesIO(blob)) as image:
if image.format != "PNG" or image.width < 1 or image.height < 1:
raise ValueError(f"{case_id}: invalid {role} PNG")
if folder == "gallery" and image.size != (1280, 1280):
raise ValueError(f"{case_id}: gallery images must be 1280 by 1280")
image.verify()
return {"bytes": blob, "path": relative}
def source_entry_sha256(root, case, verification):
entrypoint = verification["source_entrypoint"]
source = root / "work/originals" / case["case_id"] / case["source"]["asset_id"] / entrypoint
if source.is_file():
return sha256(source)
acquisition = read_json(root / "records" / case["case_id"] / "acquisition.json")
matches = [row["sha256"] for row in acquisition.get("files", []) if row["path"] == entrypoint]
if len(matches) != 1:
raise ValueError(f"{case['case_id']}: source entry digest is required")
return matches[0]
def validate_version(root, manifest):
project = tomllib.loads((root / "pyproject.toml").read_text())["project"]
if project["version"] != DATASET_VERSION or manifest.get("dataset_version") != DATASET_VERSION:
raise ValueError("The viewer requires dataset and software version 0.3.0")
if any(case.get("case_version") != DATASET_VERSION for case in manifest["cases"]):
raise ValueError("Every viewer case must belong to version 0.3.0")
def episode_paths(root, case, package_sha256):
index_path = case.get("artifacts", {}).get("episode_index", f"episodes/cases/{case['case_id']}.json")
index = read_json(root / index_path)
paths = index.get("episode_paths", [])
if not isinstance(paths, list) or not all(type(path) is str for path in paths):
raise ValueError(f"{case['case_id']}: episode_paths must be a native list of paths")
started = []
for path in paths:
target = (root / path).resolve()
if not path.startswith("episodes/") or not target.is_relative_to(root.resolve()) or not target.is_file():
raise ValueError(f"{case['case_id']}: episode manifest is missing or leaves the dataset")
episode = read_json(target)
if episode.get("case_id") != case["case_id"]:
raise ValueError(f"{case['case_id']}: episode case identity mismatch")
if (episode.get("dataset_version") != DATASET_VERSION
or episode.get("input", {}).get("package_sha256") != package_sha256):
continue
if episode.get("kind") == "repair_episode" and episode.get("state") in {
"running", "completed", "failed", "budget_exhausted", "interrupted", "uncertain"
}:
started.append(path)
return list(dict.fromkeys(started))
def build_rows(root, *, allow_missing_previews=False):
manifest = read_json(root / "cases/castaigne25.json")
validate_version(root, manifest)
cases = manifest["cases"]
ids = [case["case_id"] for case in cases]
if len(ids) != len(set(ids)):
raise ValueError("Case IDs must be unique")
# Presentation captures may change without changing pinned agent observations.
preview_folder = "gallery" if (root / "gallery/manifest.json").is_file() else "previews"
previews = read_json(root / preview_folder / "manifest.json").get("cases", [])
preview_ids = [item["case_id"] for item in previews]
missing = set(ids) - set(preview_ids)
allowed_missing = {f"R{i:02}" for i in range(21, 26)} if allow_missing_previews else set()
if (len(preview_ids) != len(set(preview_ids)) or set(preview_ids) - set(ids)
or not missing.issubset(allowed_missing)):
raise ValueError("Preview manifest must contain exactly one entry for every case")
for case_id in missing:
if any((root / f"previews/{case_id}-{role}.png").exists() for role in ("original", "broken")) or (root / f"work/preview-{case_id}.json").exists():
raise ValueError(f"{case_id}: existing preview evidence must be validated, never replaced with null")
by_id = {item["case_id"]: item for item in previews}
rows = []
for case in cases:
case_id = case["case_id"]
if not case_id.startswith("R") or not case_id[1:].isdigit():
raise ValueError(f"Invalid case ID: {case_id}")
record_dir = root / "records" / case_id
inventory = read_json(record_dir / "upstream-inventory.json")
verification = read_json(record_dir / "damage-verification.json")
archive = read_json(record_dir / "package-verification.json")
package = root / "packages" / f"{case_id}.tar.gz"
if verification.get("passed") is not True or verification.get("case_version") != DATASET_VERSION:
raise ValueError(f"{case_id}: passing authored fault checks are required")
checks = verification.get("verification_checks")
if not isinstance(checks, list) or not checks or not all(type(check) is str and check for check in checks):
raise ValueError(f"{case_id}: explicit verification_checks list is required")
if not archive.get("archive_verified") or archive.get("asset_sha256") != verification["asset_sha256"]:
raise ValueError(f"{case_id}: archive does not match the current damaged asset")
package_path, digest = archive["path"], archive["sha256"]
if package_path != f"packages/{case_id}.tar.gz":
raise ValueError(f"{case_id}: unexpected package path")
if package.is_file():
if sha256(package) != digest:
raise ValueError(f"{case_id}: local archive digest mismatch")
preview = by_id.get(case_id)
revision = inventory.get("revision") or case["source"].get("revision")
if verification.get("source_revision") != revision or (preview is not None and (
preview.get("source_revision") != revision or preview.get("asset_id") != case["source"]["asset_id"])):
raise ValueError(f"{case_id}: preview source identity mismatch")
faults = case["proposed_corruptions"]
if {fault["defect_id"] for fault in verification.get("defects", []) if fault.get("passed")} != {fault["defect_id"] for fault in faults}:
raise ValueError(f"{case_id}: verified faults do not match case definitions")
asset_id = case["source"]["asset_id"]
source_entrypoint = case["source"].get("root_entrypoint")
if source_entrypoint != verification["source_entrypoint"]:
raise ValueError(f"{case_id}: source entrypoint does not match the package records")
whole_package = f"assets/whole/{asset_id}"
broken_package = f"assets/broken/{asset_id}"
row = {
"original_image": preview_image(root, preview["original"], case_id, "original", source_entry_sha256(root, case, verification), folder=preview_folder) if preview else None,
"broken_image": preview_image(root, preview["broken"], case_id, "broken", verification["asset_sha256"], folder=preview_folder) if preview else None,
"case_id": case_id,
"dataset_version": DATASET_VERSION,
"title": case["title"],
"asset_id": case["source"]["asset_id"],
"source_revision": revision,
"source_url": f"https://huggingface.co/datasets/{inventory['repository']}/tree/{revision}/{asset_id}",
"license": case["source"]["declared_license"],
"fault_count": len(faults),
"faults": [{"defect_id": fault["defect_id"], "description": fault["description"]} for fault in faults],
"failure_story": case["failure_story"],
"required_outcome": case["acceptance"]["required_outcome"],
"scope": case["acceptance"]["scope"],
"agent_evidence": case["agent_evidence_plan"],
"whole_package_path": whole_package,
"whole_entrypoint": f"{whole_package}/{source_entrypoint}",
"broken_package_path": broken_package,
"broken_entrypoint": f"{broken_package}/asset.usdc",
"package_path": package_path,
"package_sha256": digest,
"episode_paths": episode_paths(root, case, digest),
"verification_scope": checks,
}
rows.append(row)
return rows
def jsonl_text(rows):
serializable = []
for row in rows:
item = dict(row)
for name in ("original_image", "broken_image"):
item[name] = {"path": row[name]["path"], "bytes": None} if row[name] is not None else None
serializable.append(item)
return "".join(json.dumps(row, ensure_ascii=False) + "\n" for row in serializable)
def check_parquet(path, rows):
import pyarrow.parquet as pq
table = pq.read_table(path)
if Features.from_arrow_schema(table.schema) != FEATURES or table.to_pylist() != rows:
raise ValueError("data/cases.parquet does not match the typed case records and previews")
# Decode from bytes after dropping paths, proving the table is self-contained.
for row in table.to_pylist():
for name in ("original_image", "broken_image"):
if row[name] is None:
continue
with PILImage.open(io.BytesIO(row[name]["bytes"])) as image:
image.load()
def check_card_schema(root):
card = yaml.safe_load((root / "README.md").read_text().split("---", 2)[1])
configs = [config for config in card["configs"] if config["config_name"] == "cases"]
if len(configs) != 1 or configs[0].get("data_files") != [{"split": "castaigne25", "path": "data/cases.parquet"}]:
raise ValueError("README cases config must select data/cases.parquet")
if Features._from_yaml_list(configs[0]["features"]) != FEATURES:
raise ValueError("README feature declarations do not match the native table schema")
def write_check_receipt(root, rows, allow_missing_previews):
import datasets
import pyarrow
files = ["data/cases.parquet", "data/cases.jsonl", "README.md", "cases/castaigne25.json",
"previews/manifest.json", "scripts/build_case_viewer.py"]
if (root / "gallery/manifest.json").is_file():
files.append("gallery/manifest.json")
for row in rows:
case_id = row["case_id"]
files.extend(f"records/{case_id}/{name}.json" for name in (
"damage-verification", "package-verification", "upstream-inventory"))
index = f"episodes/cases/{case_id}.json"
if (root / index).is_file():
files.append(index)
files.extend(row["episode_paths"])
files.extend(row[name]["path"] for name in ("original_image", "broken_image") if row[name] is not None)
present = sum(row[name] is not None for row in rows for name in ("original_image", "broken_image"))
receipt = {
"schema": "simrepairbench-case-viewer-check-v1",
"dataset_version": DATASET_VERSION,
"checked_at": datetime.now(timezone.utc).isoformat(),
"command": "scripts/build_case_viewer.py --check" + (" --allow-missing-previews" if allow_missing_previews else ""),
"allow_missing_previews": allow_missing_previews,
"counts": {"cases": len(rows), "faults": sum(row["fault_count"] for row in rows),
"images_present": present, "images_null": 2 * len(rows) - present,
"episode_paths": sum(len(row["episode_paths"]) for row in rows)},
"null_image_cases": [row["case_id"] for row in rows if row["original_image"] is None],
"assertions": {"parquet_matches_current_inputs": True, "embedded_images_decode": True,
"image_and_asset_hashes_match": True, "faults_are_native_list_of_records": True,
"fault_counts_match_lists": all(row["fault_count"] == len(row["faults"]) for row in rows),
"episode_paths_are_native_lists": True, "verification_scope_is_native_string_list": True,
"verification_scope_is_last_column": list(FEATURES)[-1] == "verification_scope",
"readme_features_match_parquet": True},
"native_features": FEATURES.to_dict(),
"runtime": {"datasets": datasets.__version__, "pyarrow": pyarrow.__version__},
"files": {path: sha256(root / path) for path in sorted(set(files))},
}
target = root / "work/case-viewer-check.json"
target.parent.mkdir(exist_ok=True)
target.write_text(json.dumps(receipt, ensure_ascii=False, indent=2) + "\n")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1])
parser.add_argument("--check", action="store_true", help="Check the table without rewriting it")
parser.add_argument("--allow-missing-previews", action="store_true",
help="Permit native null images only for absent R21–R25 previews")
args = parser.parse_args()
root = args.root.resolve()
check_card_schema(root)
rows = build_rows(root, allow_missing_previews=args.allow_missing_previews)
text = jsonl_text(rows)
output = root / "data/cases.jsonl"
parquet = root / "data/cases.parquet"
if args.check:
if not output.is_file() or output.read_text() != text:
parser.error("data/cases.jsonl does not match the case definitions and packages")
check_parquet(parquet, rows)
write_check_receipt(root, rows, args.allow_missing_previews)
else:
import pyarrow as pa
import pyarrow.parquet as pq
output.parent.mkdir(exist_ok=True)
# Preserve embedded image bytes even when the PNG also exists locally.
pq.write_table(pa.Table.from_pylist(rows, schema=FEATURES.arrow_schema), parquet)
check_parquet(parquet, rows)
output.write_text(text)
print(json.dumps({"cases": len(rows), "faults": sum(row["fault_count"] for row in rows)}))
if __name__ == "__main__":
main()
|