Datasets:
Download tools/validate_clock_evidence.py from maxwellinked/time-lapse-artifacts-derived: direct link, hf CLI and curl.
- Browser
- Download file 15.2 kB
-
https://huggingface.co/datasets/maxwellinked/time-lapse-artifacts-derived/resolve/main/tools/validate_clock_evidence.py
- Command line
-
hf download hf://datasets/maxwellinked/time-lapse-artifacts-derived/tools/validate_clock_evidence.py
-
curl -L -o validate_clock_evidence.py https://huggingface.co/datasets/maxwellinked/time-lapse-artifacts-derived/resolve/main/tools/validate_clock_evidence.py
15.2 kB
| #!/usr/bin/env python3 | |
| """Validate relocated Clock_Evidence/ packet, hydrated crops, and v2.0.0 / v1.0.0 joins. | |
| Checks: | |
| - Exact schema and claim-scope boundaries of Clock_Evidence/observations.json. | |
| - Byte-level fixity and RGB JPEG readability of all 11 Clock_Evidence/clock_crops/*.jpg | |
| against Clock_Evidence/RELOCATION_RECEIPT.json (rejecting Git LFS pointer stubs). | |
| - Exact 125-row partition in Clock_Evidence/record_joins.csv: | |
| 115 v2.0.0_canonical Standard rows + 10 v1.0.0_only_pre_standard historical rows. | |
| - PTS arithmetic and media duration bounds across all 333 observations (330 distinct positions). | |
| - Optional live cross-repo join against v2.0.0 canonical metadata.csv and SHA256SUMS (1,388 rows), | |
| ensuring all 115 v2.0.0_canonical rows join cleanly and none of the 10 v1.0.0-only rows | |
| collide with or break canonical joins. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import csv | |
| import hashlib | |
| import json | |
| import re | |
| from decimal import Decimal, InvalidOperation | |
| from fractions import Fraction | |
| from pathlib import Path, PurePosixPath | |
| from PIL import Image | |
| ROOT = Path(__file__).resolve().parents[1] | |
| POINTER_PREFIX = b"version https://git-lfs.github.com/spec/v1" | |
| RECORD_RE = re.compile(r"^tla-[0-9a-f]{16}$") | |
| WORK_RE = re.compile(r"^tlaw-[0-9a-f]{16}$") | |
| HASH_RE = re.compile(r"^[0-9a-f]{64}$") | |
| REV_RE = re.compile(r"^[0-9a-f]{40}$") | |
| def require(ok: bool, message: str) -> None: | |
| if not ok: | |
| raise ValueError(message) | |
| def safe_rel_posix(value: str) -> str: | |
| p = PurePosixPath(value) | |
| require( | |
| bool(value) | |
| and not p.is_absolute() | |
| and ".." not in p.parts | |
| and "\\" not in value | |
| and ":" not in value | |
| and p.as_posix() == value, | |
| f"Unsafe relative path: {value!r}", | |
| ) | |
| return value | |
| def sha256_file(path: Path) -> str: | |
| h = hashlib.sha256() | |
| with path.open("rb") as f: | |
| while chunk := f.read(4 * 1024 * 1024): | |
| h.update(chunk) | |
| return h.hexdigest() | |
| def parse_decimal(value: object, label: str) -> Decimal: | |
| try: | |
| d = Decimal(str(value)) | |
| except (InvalidOperation, ValueError) as exc: | |
| raise ValueError(f"Invalid decimal for {label}: {value!r}") from exc | |
| require(d.is_finite(), f"Nonfinite decimal for {label}") | |
| return d | |
| def read_csv_rows(path: Path) -> list[dict[str, str]]: | |
| with path.open("r", encoding="utf-8-sig", newline="") as f: | |
| reader = csv.DictReader(f) | |
| require( | |
| bool(reader.fieldnames) and len(reader.fieldnames) == len(set(reader.fieldnames)), | |
| f"Duplicate or missing CSV header in {path}", | |
| ) | |
| rows = list(reader) | |
| require( | |
| all(None not in r and all(v is not None for v in r.values()) for r in rows), | |
| f"Malformed CSV row width in {path}", | |
| ) | |
| return rows | |
| def read_sha256sums(path: Path) -> dict[str, str]: | |
| out: dict[str, str] = {} | |
| for line in path.read_text(encoding="utf-8").splitlines(): | |
| parts = line.split(" ", 1) | |
| require(len(parts) == 2, f"Malformed SHA256SUMS line in {path}") | |
| digest, rel = parts[0], safe_rel_posix(parts[1]) | |
| require(bool(HASH_RE.fullmatch(digest)) and rel not in out, f"Invalid/duplicate SHA256SUMS entry: {rel}") | |
| out[rel] = digest | |
| return out | |
| def validate_clock_evidence( | |
| derived_root: Path = ROOT, | |
| canonical_root: Path | None = None, | |
| ) -> dict[str, object]: | |
| derived_root = derived_root.resolve() | |
| ce_dir = derived_root / "Clock_Evidence" | |
| obs_path = ce_dir / "observations.json" | |
| joins_path = ce_dir / "record_joins.csv" | |
| receipt_path = ce_dir / "RELOCATION_RECEIPT.json" | |
| for p in (obs_path, joins_path, receipt_path): | |
| require(p.is_file(), f"Missing required Clock_Evidence file: {p}") | |
| receipt = json.loads(receipt_path.read_text(encoding="utf-8")) | |
| require(receipt.get("schema") == "clock-evidence-relocation-receipt/v1", "Invalid relocation receipt schema") | |
| require(bool(REV_RE.fullmatch(receipt.get("source_revision", ""))), "Invalid source_revision in receipt") | |
| if "target_canonical_source_revision" in receipt: | |
| require( | |
| bool(REV_RE.fullmatch(receipt.get("target_canonical_source_revision", ""))), | |
| "Invalid target_canonical_source_revision in receipt", | |
| ) | |
| obs_bytes = obs_path.read_bytes() | |
| require( | |
| len(obs_bytes) == receipt["observations_json"]["size_bytes"] | |
| and hashlib.sha256(obs_bytes).hexdigest() == receipt["observations_json"]["sha256"], | |
| "observations.json size/SHA-256 differs from RELOCATION_RECEIPT.json", | |
| ) | |
| joins_bytes = joins_path.read_bytes() | |
| require( | |
| len(joins_bytes) == receipt["record_joins_csv"]["size_bytes"] | |
| and hashlib.sha256(joins_bytes).hexdigest() == receipt["record_joins_csv"]["sha256"], | |
| "record_joins.csv size/SHA-256 differs from RELOCATION_RECEIPT.json", | |
| ) | |
| # Verify all 11 crops on disk (non-pointer, exact size/SHA-256, decodable RGB JPEG) | |
| declared_crops = receipt.get("clock_crops", []) | |
| require(len(declared_crops) == 11, f"Expected 11 declared clock crops, found {len(declared_crops)}") | |
| crop_paths_verified: set[str] = set() | |
| for item in declared_crops: | |
| rel = safe_rel_posix(item["path"]) | |
| require(rel.startswith("Clock_Evidence/clock_crops/") and rel.endswith(".jpg"), f"Unexpected crop path: {rel}") | |
| require(rel not in crop_paths_verified, f"Duplicate crop in receipt: {rel}") | |
| fp = derived_root / rel | |
| require(fp.is_file(), f"Missing crop file: {rel}") | |
| raw = fp.read_bytes() | |
| require(not raw.startswith(POINTER_PREFIX), f"Crop is an un-hydrated LFS pointer: {rel}") | |
| require(len(raw) == item["size_bytes"], f"Crop byte size mismatch: {rel}") | |
| require(hashlib.sha256(raw).hexdigest() == item["sha256"], f"Crop SHA-256 mismatch: {rel}") | |
| with Image.open(fp) as img: | |
| require(img.format == "JPEG" and img.mode == "RGB", f"Crop must be RGB JPEG: {rel}") | |
| img.load() | |
| crop_paths_verified.add(rel) | |
| actual_crop_files = { | |
| p.relative_to(derived_root).as_posix() for p in (ce_dir / "clock_crops").glob("*") if p.is_file() | |
| } | |
| require(actual_crop_files == crop_paths_verified, "Undeclared or missing files in Clock_Evidence/clock_crops/") | |
| packet = json.loads(obs_bytes.decode("utf-8")) | |
| require( | |
| packet.get("schema") == "displayed-clock-evidence/v1" | |
| and packet.get("claim_scope") == "file_specific_displayed_clock_evidence" | |
| and packet.get("externally_calibrated") is False | |
| and packet.get("archive_conversion_established") is False, | |
| "Unsupported Clock_Evidence packet scope", | |
| ) | |
| obs_records = {r["record_id"]: r for r in packet["records"]} | |
| require(len(obs_records) == len(packet["records"]) == 125, "Expected 125 unique records in observations.json") | |
| join_rows = read_csv_rows(joins_path) | |
| joins_by_id = {r["record_id"]: r for r in join_rows} | |
| require(len(joins_by_id) == len(join_rows) == 125, "Expected 125 unique rows in record_joins.csv") | |
| require(set(joins_by_id) == set(obs_records), "record_joins.csv record_id set differs from observations.json") | |
| total_observations = 0 | |
| distinct_positions = 0 | |
| referenced_public_crops: set[str] = set() | |
| v2_ids: set[str] = set() | |
| v1_only_ids: set[str] = set() | |
| for rid, entry in obs_records.items(): | |
| require(bool(RECORD_RE.fullmatch(rid)), f"Invalid record_id: {rid}") | |
| jrow = joins_by_id[rid] | |
| require( | |
| jrow["file_path"] == safe_rel_posix(entry["file_path"]) | |
| and jrow["sha256"] == entry["sha256"] | |
| and bool(HASH_RE.fullmatch(jrow["sha256"])) | |
| and bool(HASH_RE.fullmatch(jrow["hub_xet_hash"])) | |
| and int(jrow["size_bytes"]) == entry["size_bytes"] | |
| and bool(REV_RE.fullmatch(jrow["pinned_v1_source_revision"])), | |
| f"{rid}: join row identity mismatch against observations.json", | |
| ) | |
| duration = parse_decimal(jrow["duration_seconds"], f"{rid}.duration_seconds") | |
| require(duration > 0, f"{rid}: duration_seconds must be positive") | |
| status = jrow["v2_canonical_join_status"] | |
| if status == "v2.0.0_canonical": | |
| require( | |
| jrow["source_release_availability"] == "v1.0.0_and_v2.0.0" | |
| and jrow["collection_tier"] == "standard" | |
| and jrow["file_path"].startswith("Standard_Time_Lapses/") | |
| and bool(WORK_RE.fullmatch(jrow["work_id"])), | |
| f"{rid}: invalid v2.0.0_canonical row attributes", | |
| ) | |
| v2_ids.add(rid) | |
| elif status == "v1.0.0_only_pre_standard": | |
| require( | |
| jrow["source_release_availability"] == "v1.0.0_only" | |
| and jrow["collection_tier"] == "pre_standard" | |
| and jrow["file_path"].startswith("Pre_Standard_Time_Lapses/") | |
| and jrow["work_id"] == "", | |
| f"{rid}: invalid v1.0.0_only_pre_standard row attributes", | |
| ) | |
| v1_only_ids.add(rid) | |
| else: | |
| raise ValueError(f"{rid}: unexpected v2_canonical_join_status {status!r}") | |
| require(bool(entry["observations"]), f"{rid}: empty observations list") | |
| require(int(jrow["observation_count"]) == len(entry["observations"]), f"{rid}: observation_count mismatch") | |
| seen = set() | |
| pts_set = set() | |
| pub_crop_count = 0 | |
| for obs in entry["observations"]: | |
| seconds = parse_decimal(obs["video_pts_seconds"], f"{rid}.video_pts_seconds") | |
| require(Decimal(0) <= seconds <= duration + Decimal("0.001"), f"{rid}: PTS outside duration") | |
| if obs["position_basis"] == "integer_pts_and_time_base": | |
| require(type(obs["pts"]) is int, f"{rid}: pts must be int") | |
| tb = Fraction(obs["time_base"]) | |
| require(tb > 0, f"{rid}: time_base must be positive") | |
| exact = obs["pts"] * tb | |
| require( | |
| abs(seconds - Decimal(exact.numerator) / Decimal(exact.denominator)) <= Decimal("0.000001"), | |
| f"{rid}: integer PTS differs from video_pts_seconds", | |
| ) | |
| else: | |
| require( | |
| obs["position_basis"] == "observed_decoded_pts_seconds" | |
| and obs.get("pts") is None | |
| and obs.get("time_base") is None, | |
| f"{rid}: invalid observed_decoded_pts_seconds fields", | |
| ) | |
| require( | |
| isinstance(obs.get("display_literal"), str) and bool(obs["display_literal"].strip()), | |
| f"{rid}: blank display_literal", | |
| ) | |
| loc = obs.get("evidence_locator", "") | |
| require(isinstance(loc, str) and bool(loc), f"{rid}: missing evidence_locator") | |
| if loc.startswith("Clock_Evidence/clock_crops/"): | |
| require(loc in crop_paths_verified, f"{rid}: missing public crop {loc}") | |
| referenced_public_crops.add(loc) | |
| pub_crop_count += 1 | |
| key = (seconds, obs["display_kind"], obs["display_literal"]) | |
| require(key not in seen, f"{rid}: duplicate observation {key}") | |
| seen.add(key) | |
| pts_set.add(seconds) | |
| total_observations += 1 | |
| require(int(jrow["public_crop_count"]) == pub_crop_count, f"{rid}: public_crop_count mismatch") | |
| distinct_positions += len(pts_set) | |
| require(len(v2_ids) == 115, f"Expected 115 v2.0.0_canonical rows, got {len(v2_ids)}") | |
| require(len(v1_only_ids) == 10, f"Expected 10 v1.0.0_only_pre_standard rows, got {len(v1_only_ids)}") | |
| require(total_observations == 333, f"Expected 333 total observations, got {total_observations}") | |
| require(distinct_positions == 330, f"Expected 330 distinct positions, got {distinct_positions}") | |
| require(referenced_public_crops == crop_paths_verified, "Unreferenced crop in Clock_Evidence/clock_crops/") | |
| canonical_join_verified = False | |
| canonical_total_rows = None | |
| if canonical_root is not None: | |
| canonical_root = canonical_root.resolve() | |
| meta_rows = read_csv_rows(canonical_root / "metadata.csv") | |
| sums = read_sha256sums(canonical_root / "SHA256SUMS") | |
| meta_by_id = {r["record_id"]: r for r in meta_rows} | |
| require(len(meta_by_id) == len(meta_rows), "Duplicate record_id in canonical metadata.csv") | |
| canonical_total_rows = len(meta_rows) | |
| # Every v2.0.0_canonical row must join cleanly with matching path, size, Xet, work_id, duration, and SHA-256 | |
| for rid in sorted(v2_ids): | |
| require(rid in meta_by_id, f"{rid}: v2.0.0_canonical clock record missing from metadata.csv") | |
| mrow = meta_by_id[rid] | |
| jrow = joins_by_id[rid] | |
| require(mrow["file_name"] == jrow["file_path"], f"{rid}: file_name mismatch vs metadata.csv") | |
| require(mrow["work_id"] == jrow["work_id"], f"{rid}: work_id mismatch vs metadata.csv") | |
| require(mrow["hub_xet_hash"] == jrow["hub_xet_hash"], f"{rid}: hub_xet_hash mismatch vs metadata.csv") | |
| require(mrow["size_bytes"] == jrow["size_bytes"], f"{rid}: size_bytes mismatch vs metadata.csv") | |
| require(mrow["duration_seconds"] == jrow["duration_seconds"], f"{rid}: duration_seconds mismatch") | |
| require(sums.get(jrow["file_path"]) == jrow["sha256"], f"{rid}: SHA256SUMS mismatch") | |
| # None of the 10 v1.0.0-only Pre-Standard rows may appear in v2.0.0 canonical metadata.csv | |
| leaked = v1_only_ids & set(meta_by_id) | |
| require(not leaked, f"v1.0.0-only Pre-Standard rows unexpectedly present in v2.0.0 metadata: {sorted(leaked)}") | |
| canonical_join_verified = True | |
| return { | |
| "status": "passed", | |
| "clock_records": len(obs_records), | |
| "v2_canonical_records": len(v2_ids), | |
| "v1_only_pre_standard_records": len(v1_only_ids), | |
| "clock_observations": total_observations, | |
| "distinct_media_positions": distinct_positions, | |
| "verified_public_crops": len(crop_paths_verified), | |
| "canonical_join_verified": canonical_join_verified, | |
| "canonical_metadata_rows": canonical_total_rows, | |
| } | |
| def main() -> None: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--derived-root", type=Path, default=ROOT) | |
| parser.add_argument( | |
| "--canonical-root", | |
| type=Path, | |
| default=None, | |
| help="Optional path to time-lapse-artifacts checkout to verify v2.0.0 canonical joins.", | |
| ) | |
| args = parser.parse_args() | |
| canonical = args.canonical_root | |
| if canonical is None: | |
| sibling = args.derived_root.resolve().parent / "time-lapse-artifacts" | |
| if (sibling / "metadata.csv").is_file() and not (sibling / "Pre_Standard_Time_Lapses/metadata.csv").exists(): | |
| canonical = sibling | |
| try: | |
| report = validate_clock_evidence(args.derived_root, canonical) | |
| except (ValueError, KeyError, OSError) as exc: | |
| print(json.dumps({"status": "failed", "error": str(exc)}, indent=2)) | |
| raise SystemExit(1) | |
| print(json.dumps(report, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |