File size: 8,993 Bytes
7a01b44 30fa729 7a01b44 30fa729 7a01b44 30fa729 7a01b44 30fa729 7a01b44 30fa729 7a01b44 30fa729 7a01b44 30fa729 7a01b44 30fa729 7a01b44 30fa729 7a01b44 30fa729 7a01b44 30fa729 7a01b44 30fa729 7a01b44 30fa729 7a01b44 30fa729 7a01b44 30fa729 7a01b44 30fa729 7a01b44 | 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 | #!/usr/bin/env python3
"""Build indexes and verify the physical Full-2554 benchmark package."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import re
from collections import Counter, defaultdict
from pathlib import Path
from typing import Any
VIEW_ROOT = Path(__file__).resolve().parent
# The local manifest tracks the physical episode paths and English metadata.
SOURCE_MANIFEST = VIEW_ROOT / "manifests/full2554.jsonl"
FAMILY_DIRS = {
"l2_passive": "passive_observation",
"l2_dynamic": "dynamic_tracking",
"l2_interaction": "interaction_experience",
"l3_owner_habit": "experience_generalization",
}
EXPECTED_COUNTS = {
"l2_passive": 1036,
"l2_dynamic": 1052,
"l2_interaction": 263,
"l3_owner_habit": 203,
}
HAN_RE = re.compile(
"[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\U00020000-\U000323af]"
)
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 read_jsonl(path: Path) -> list[dict[str, Any]]:
rows = []
with path.open("r", encoding="utf-8") as handle:
for line_number, line in enumerate(handle, 1):
if line.strip():
row = json.loads(line)
if not isinstance(row, dict):
raise ValueError(f"Non-object row at {path}:{line_number}")
rows.append(row)
return rows
def atomic_text(path: Path, content: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_suffix(path.suffix + ".tmp")
temporary.write_text(content, encoding="utf-8")
temporary.replace(path)
def write_json(path: Path, payload: Any) -> None:
atomic_text(path, json.dumps(payload, ensure_ascii=False, indent=2) + "\n")
def write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None:
atomic_text(
path,
"".join(json.dumps(row, ensure_ascii=False) + "\n" for row in rows),
)
def source_for(row: dict[str, Any]) -> tuple[str, str, Path]:
source = row.get("source") or {}
family = str(source.get("task_family") or "")
episode_id = str(source.get("episode_id") or "")
relative_path = str(source.get("episode_path") or "")
if family not in FAMILY_DIRS:
raise ValueError(f"Unknown task family: {family!r}")
if not episode_id or not relative_path:
raise ValueError(f"Incomplete source metadata for row {row.get('id')}")
episode_json = (
VIEW_ROOT / "episodes" / FAMILY_DIRS[family] / episode_id
/ Path(relative_path).name
)
return family, episode_id, episode_json
def validate_source(rows: list[dict[str, Any]], *, check_hashes: bool) -> None:
if len(rows) != sum(EXPECTED_COUNTS.values()):
raise ValueError(f"Expected 2,554 rows, found {len(rows):,}")
counts = Counter()
ids: set[str] = set()
episode_ids: set[str] = set()
for row in rows:
row_id = str(row.get("id") or "")
family, episode_id, episode_json = source_for(row)
if not row_id or row_id in ids:
raise ValueError(f"Duplicate or empty manifest ID: {row_id!r}")
if episode_id in episode_ids:
raise ValueError(f"Duplicate episode ID: {episode_id}")
if not episode_json.is_file():
raise FileNotFoundError(episode_json)
if episode_json.parent.is_symlink():
raise ValueError(f"Episode directory must be physical: {episode_json.parent}")
expected_hash = str((row.get("source") or {}).get("episode_sha256") or "")
if check_hashes and (not expected_hash or sha256(episode_json) != expected_hash):
raise ValueError(f"Episode hash mismatch: {episode_json}")
ids.add(row_id)
episode_ids.add(episode_id)
counts[family] += 1
if dict(counts) != EXPECTED_COUNTS:
raise ValueError(f"Family counts differ: {dict(counts)}")
def build_view(rows: list[dict[str, Any]]) -> None:
family_rows: dict[str, list[dict[str, Any]]] = defaultdict(list)
browse_lines = ["family\tepisode_id\tepisode_json\n"]
for row in rows:
family, episode_id, episode_json = source_for(row)
family_dir = FAMILY_DIRS[family]
local_json = Path("episodes") / family_dir / episode_id / episode_json.name
organized_row = dict(row)
organized_row["organized_view"] = {
"family_directory": family_dir,
"episode_directory": str(Path("episodes") / family_dir / episode_id),
"episode_json": str(local_json),
}
family_rows[family].append(organized_row)
browse_lines.append(f"{family_dir}\t{episode_id}\t{local_json}\n")
manifests_dir = VIEW_ROOT / "manifests"
manifests_dir.mkdir(parents=True, exist_ok=True)
for family, rows_for_family in family_rows.items():
write_jsonl(manifests_dir / f"{FAMILY_DIRS[family]}.jsonl", rows_for_family)
atomic_text(VIEW_ROOT / "browse.tsv", "".join(browse_lines))
metadata_path = VIEW_ROOT / "metadata.json"
existing_metadata = (
json.loads(metadata_path.read_text(encoding="utf-8"))
if metadata_path.is_file() else {}
)
write_json(
metadata_path,
{
**existing_metadata,
"schema": "embodied_memorizer_benchmark_full2554_organized_view_v1",
"organization": "physical_episode_directories",
"canonical_manifest": "manifests/full2554.jsonl",
"canonical_manifest_sha256": sha256(SOURCE_MANIFEST),
"episode_count": len(rows),
"family_counts": {
FAMILY_DIRS[family]: count
for family, count in EXPECTED_COUNTS.items()
},
"source_data_modified": existing_metadata.get("source_data_modified", False),
},
)
def verify_view(rows: list[dict[str, Any]]) -> dict[str, Any]:
counts = Counter()
failures = []
chinese_text_issues = []
symlinks = []
for directory, subdirectories, filenames in os.walk(VIEW_ROOT, followlinks=False):
for name in subdirectories + filenames:
path = Path(directory) / name
if path.is_symlink():
symlinks.append(str(path.relative_to(VIEW_ROOT)))
failures.extend(f"unexpected symlink: {path}" for path in symlinks)
for row in rows:
family, episode_id, episode_json = source_for(row)
episode_dir = VIEW_ROOT / "episodes" / FAMILY_DIRS[family] / episode_id
local_json = episode_dir / episode_json.name
if episode_dir.is_symlink() or not episode_dir.is_dir():
failures.append(f"not a physical episode directory: {episode_dir}")
continue
if not local_json.is_file():
failures.append(f"missing local JSON: {local_json}")
continue
expected_hash = str((row.get("source") or {}).get("episode_sha256") or "")
if sha256(local_json) != expected_hash:
failures.append(f"hash mismatch: {local_json}")
continue
# Decode escapes before checking, so ensure_ascii=True cannot hide
# Chinese text in nested keys or values.
payload = json.loads(local_json.read_text(encoding="utf-8"))
if HAN_RE.search(json.dumps(payload, ensure_ascii=False)):
chinese_text_issues.append(str(local_json.relative_to(VIEW_ROOT)))
failures.append(f"Chinese JSON text: {local_json}")
continue
counts[family] += 1
report = {
"schema": "embodied_memorizer_benchmark_full2554_view_verification_v1",
"status": "pass" if not failures and dict(counts) == EXPECTED_COUNTS else "fail",
"expected_episodes": sum(EXPECTED_COUNTS.values()),
"verified_episodes": sum(counts.values()),
"family_counts": {
FAMILY_DIRS[family]: counts[family] for family in FAMILY_DIRS
},
"source_manifest_sha256": sha256(SOURCE_MANIFEST),
"storage": "physical_episode_directories",
"symlink_count": len(symlinks),
"language": "en",
"chinese_text_issues": len(chinese_text_issues),
"issues": failures,
}
write_json(VIEW_ROOT / "verification_report.json", report)
if report["status"] != "pass":
raise RuntimeError(json.dumps(report, indent=2))
return report
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--verify-only",
action="store_true",
help="Verify the physical package without rebuilding indexes.",
)
args = parser.parse_args()
rows = read_jsonl(SOURCE_MANIFEST)
validate_source(rows, check_hashes=not args.verify_only)
if not args.verify_only:
build_view(rows)
print(json.dumps(verify_view(rows), indent=2))
return 0
if __name__ == "__main__":
raise SystemExit(main())
|