#!/usr/bin/env python3 """Validate active indexes and optional Viewer/repository snapshots.""" from __future__ import annotations import argparse import csv import json import math import re import statistics import sys from collections import Counter from datetime import date from pathlib import Path from urllib.parse import unquote, urlparse RECORD_ID_RE = re.compile(r"^tla-[0-9a-f]{16}$") HASH_RE = re.compile(r"^[0-9a-f]{64}$") DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$") TIME_RE = re.compile(r"^(?:[01]\d|2[0-3]):[0-5]\d$") DIMENSIONS_RE = re.compile(r"^\d+(?:\.\d+)?x\d+(?:\.\d+)?$") DIRECT_STANDARD_RE = re.compile(r"^Standard_Time_Lapses/[^/]+\.mp4$") DIRECT_PRE_STANDARD_RE = re.compile(r"^Pre_Standard_Time_Lapses/[^/]+\.mp4$") REQUIRED_FIELDS = [ "file_name", "record_id", "collection_tier", "is_canonical", "acquisition_protocol_version", "date", "time", "tool", "medium", "support", "dimensions", "duration_seconds", "width_px", "height_px", "orientation", "encoded_frame_rate", "video_codec", "pixel_format", "container", "has_audio", "hub_xet_hash", "original_filename", "provenance_status", "legacy_provenance_path", "legacy_related_references", "evidence_method", "provenance_reference_duration_delta_seconds", "size_bytes", "notes", ] PRE_STANDARD_REQUIRED_FIELDS = REQUIRED_FIELDS def viewer_path(row: dict[str, object]) -> str: video = row.get("video") if not isinstance(video, dict) or not isinstance(video.get("src"), str): return "" path = unquote(urlparse(video["src"]).path) marker = "/resolve/" if marker not in path: return "" after_revision = path.split(marker, 1)[1] parts = after_revision.split("/", 1) return parts[1] if len(parts) == 2 else "" def load_csv(path: Path) -> tuple[list[str], list[dict[str, str]]]: with path.open("r", encoding="utf-8-sig", newline="") as handle: reader = csv.DictReader(handle) if reader.fieldnames is None: raise ValueError("metadata file has no header") return list(reader.fieldnames), list(reader) def valid_calendar_date(value: str) -> bool: if not DATE_RE.fullmatch(value): return False try: date.fromisoformat(value) except ValueError: return False return True def validate_multi_value( row: dict[str, str], label: str, field: str, errors: list[str] ) -> None: value = row.get(field, "") if "|" in value: errors.append(f"{label}: {field} still uses a pipe separator") items = [item.strip() for item in value.split(";") if item.strip()] if value and len(items) != len(value.split(";")): errors.append(f"{label}: {field} contains an empty list item") if len(items) != len(set(items)): errors.append(f"{label}: {field} contains duplicate list values") def validate_positive_number( row: dict[str, str], label: str, field: str, errors: list[str], *, integer: bool = False, ) -> float | None: value = row.get(field, "") if not value: errors.append(f"{label}: technical field {field} is blank") return None try: parsed = float(value) except ValueError: errors.append(f"{label}: technical field {field} is not numeric") return None if not math.isfinite(parsed) or parsed <= 0: errors.append(f"{label}: technical field {field} must be positive") return None if integer and not parsed.is_integer(): errors.append(f"{label}: technical field {field} must be an integer") return None return parsed def validate_technical_row( row: dict[str, str], label: str, errors: list[str] ) -> None: duration = validate_positive_number(row, label, "duration_seconds", errors) width = validate_positive_number(row, label, "width_px", errors, integer=True) height = validate_positive_number(row, label, "height_px", errors, integer=True) frame_rate = validate_positive_number(row, label, "encoded_frame_rate", errors) size = validate_positive_number(row, label, "size_bytes", errors, integer=True) del duration, frame_rate, size for field in ("orientation", "video_codec", "pixel_format", "container"): if not row.get(field, ""): errors.append(f"{label}: technical field {field} is blank") if row.get("has_audio", "").lower() not in {"true", "false"}: errors.append(f"{label}: has_audio must be true or false") if not HASH_RE.fullmatch(row.get("hub_xet_hash", "")): errors.append(f"{label}: hub_xet_hash must be 64 lowercase hexadecimal characters") if width is not None and height is not None: expected_orientation = ( "portrait" if height > width else "landscape" if width > height else "square" ) if row.get("orientation") != expected_orientation: errors.append( f"{label}: orientation {row.get('orientation')!r} conflicts with " f"{int(width)}x{int(height)}" ) def validate( metadata_csv: Path, viewer_json: Path | None, pre_standard_metadata: Path | None, repo_files_json: Path | None, ) -> dict[str, object]: fields, rows = load_csv(metadata_csv) errors: list[str] = [] warnings: list[str] = [] pre_standard_rows: list[dict[str, str]] = [] repo_counts: dict[str, int] = {} repo_unindexed_standard: list[str] = [] repo_unindexed_pre_standard: list[str] = [] missing_fields = [field for field in REQUIRED_FIELDS if field not in fields] if missing_fields: errors.append(f"missing required columns: {missing_fields}") def duplicate_values(records: list[dict[str, str]], field: str) -> list[str]: values = [row.get(field, "") for row in records if row.get(field, "")] return sorted(value for value, count in Counter(values).items() if count > 1) for field in ("file_name", "record_id", "hub_xet_hash"): duplicates = duplicate_values(rows, field) if duplicates: errors.append(f"duplicate {field} values: {duplicates[:5]}") for index, row in enumerate(rows, start=2): label = row.get("file_name") or f"CSV row {index}" if not DIRECT_STANDARD_RE.fullmatch(row.get("file_name", "")): errors.append(f"{label}: canonical path must be a direct Standard_Time_Lapses MP4") if not RECORD_ID_RE.fullmatch(row.get("record_id", "")): errors.append(f"{label}: invalid record_id") if row.get("collection_tier") != "standard": errors.append(f"{label}: collection_tier must be standard") if row.get("is_canonical", "").lower() != "true": errors.append(f"{label}: is_canonical must be true") if row.get("acquisition_protocol_version") != "standard-2025-07-13": errors.append(f"{label}: unexpected acquisition protocol version") if not valid_calendar_date(row.get("date", "")): errors.append(f"{label}: invalid or missing finish date") if row.get("time") and not TIME_RE.fullmatch(row["time"]): errors.append(f"{label}: invalid finish time") if not DIMENSIONS_RE.fullmatch(row.get("dimensions", "")): errors.append(f"{label}: invalid dimensions") if not row.get("tool", ""): errors.append(f"{label}: canonical tool is blank") if not row.get("medium", ""): errors.append(f"{label}: canonical medium is blank") if not row.get("support", ""): errors.append(f"{label}: canonical support is blank") for field in ("tool", "medium"): validate_multi_value(row, label, field, errors) basename = Path(row.get("file_name", "")).name filename_parts = basename.split(".") expected_time = row.get("time", "").replace(":", "") or "UnknownTime" if len(filename_parts) < 2 or filename_parts[0] != row.get("date"): errors.append(f"{label}: filename date differs from metadata date") elif filename_parts[1] != expected_time: errors.append(f"{label}: filename time differs from metadata time") validate_technical_row(row, label, errors) standard_30x40_paper = sum( row.get("dimensions") == "30x40" and row.get("support") == "Paper" for row in rows ) if standard_30x40_paper: warnings.append( f"{standard_30x40_paper} canonical 30x40 rows use support=Paper while " "Archive_Specifications.md describes 30x40 Illustration Board; curator review required" ) if pre_standard_metadata: pre_fields, pre_standard_rows = load_csv(pre_standard_metadata) missing_pre_fields = [ field for field in PRE_STANDARD_REQUIRED_FIELDS if field not in pre_fields ] if missing_pre_fields: errors.append( f"pre-standard metadata is missing required columns: {missing_pre_fields}" ) for field in ("file_name", "record_id", "hub_xet_hash"): duplicates = duplicate_values(pre_standard_rows, field) if duplicates: errors.append(f"duplicate pre-standard {field} values: {duplicates[:5]}") all_rows = rows + pre_standard_rows for field in ("record_id", "hub_xet_hash"): duplicates = duplicate_values(all_rows, field) if duplicates: errors.append(f"duplicate cross-tier {field} values: {duplicates[:5]}") unknown_date_with_time = 0 for index, row in enumerate(pre_standard_rows, start=2): name = row.get("file_name", "") label = name or f"pre-standard CSV row {index}" if not name or "/" in name or "\\" in name or not name.endswith(".mp4"): errors.append( f"pre-standard CSV row {index}: file_name must be a direct MP4 basename" ) if not RECORD_ID_RE.fullmatch(row.get("record_id", "")): errors.append(f"{label}: invalid record_id") if row.get("collection_tier") != "pre_standard": errors.append(f"{label}: collection_tier must be pre_standard") if row.get("is_canonical", "").lower() != "false": errors.append(f"{label}: is_canonical must be false") if row.get("acquisition_protocol_version"): errors.append(f"{label}: pre-standard acquisition protocol must be blank") if row.get("date"): if not valid_calendar_date(row["date"]): errors.append(f"{label}: invalid finish date") elif row.get("time"): unknown_date_with_time += 1 if row.get("time") and not TIME_RE.fullmatch(row["time"]): errors.append(f"{label}: invalid finish time") if not DIMENSIONS_RE.fullmatch(row.get("dimensions", "")): errors.append(f"{label}: invalid dimensions") for field in ("tool", "medium"): validate_multi_value(row, label, field, errors) validate_technical_row(row, label, errors) if unknown_date_with_time: warnings.append( f"{unknown_date_with_time} pre-standard rows retain a time while the date is unknown; " "confirm that 00:00 means documented midnight rather than a placeholder" ) missing_material_rows = sum( not row.get("tool") or not row.get("medium") or not row.get("support") for row in pre_standard_rows ) if missing_material_rows: warnings.append( f"{missing_material_rows} pre-standard rows retain incomplete material fields" ) if repo_files_json: loaded_inventory = json.loads(repo_files_json.read_text(encoding="utf-8")) repo_items: dict[str, dict[str, object]] = {} if isinstance(loaded_inventory, list) and all( isinstance(path, str) for path in loaded_inventory ): loaded_paths = loaded_inventory elif isinstance(loaded_inventory, dict) and isinstance( loaded_inventory.get("siblings"), list ): loaded_paths = [] for item in loaded_inventory["siblings"]: if not isinstance(item, dict) or not isinstance(item.get("rfilename"), str): errors.append("Hub repository inventory contains an invalid sibling entry") continue path = item["rfilename"] loaded_paths.append(path) repo_items[path] = item else: loaded_paths = [] errors.append( "repository snapshot must be a JSON path list or a Hub API object with siblings" ) if loaded_paths: repo_paths = set(loaded_paths) standard_files = {path for path in repo_paths if DIRECT_STANDARD_RE.fullmatch(path)} pre_standard_files = { path for path in repo_paths if DIRECT_PRE_STANDARD_RE.fullmatch(path) } provenance_files = { path for path in repo_paths if path.startswith("Standard_Time_Lapses/Provenance/") and path.endswith(".mp4") } canonical_paths = {row.get("file_name", "") for row in rows} active_pre_paths = { f"Pre_Standard_Time_Lapses/{row.get('file_name', '')}" for row in pre_standard_rows if row.get("file_name") } missing_canonical_targets = sorted(canonical_paths.difference(repo_paths)) missing_pre_targets = sorted(active_pre_paths.difference(repo_paths)) repo_unindexed_standard = sorted(standard_files.difference(canonical_paths)) repo_unindexed_pre_standard = sorted( pre_standard_files.difference(active_pre_paths) ) if missing_canonical_targets: errors.append( f"{len(missing_canonical_targets)} canonical metadata paths have no repository file" ) if missing_pre_targets: errors.append( f"{len(missing_pre_targets)} active pre-standard metadata paths have no repository file" ) if repo_unindexed_pre_standard: errors.append( f"{len(repo_unindexed_pre_standard)} published pre-standard files are absent from the active index" ) if repo_unindexed_standard: warnings.append( f"{len(repo_unindexed_standard)} direct standard files are pending metadata ingestion" ) hash_mismatches: list[str] = [] size_mismatches: list[str] = [] missing_blob_metadata: list[str] = [] if repo_items: indexed_paths_and_rows = [ *((row.get("file_name", ""), row) for row in rows), *( (f"Pre_Standard_Time_Lapses/{row.get('file_name', '')}", row) for row in pre_standard_rows ), ] for path, row in indexed_paths_and_rows: item = repo_items.get(path, {}) lfs = item.get("lfs") if isinstance(item, dict) else None if not isinstance(lfs, dict): missing_blob_metadata.append(path) continue expected_hash = item.get("xetHash") expected_size = item.get("size") if expected_size is None: expected_size = lfs.get("size") if not isinstance(expected_hash, str) or expected_size is None: missing_blob_metadata.append(path) continue if row.get("hub_xet_hash", "").lower() != expected_hash.lower(): hash_mismatches.append(path) if row.get("size_bytes", "") != str(expected_size): size_mismatches.append(path) if missing_blob_metadata: errors.append( f"{len(missing_blob_metadata)} indexed files lack Hub LFS identity metadata" ) if hash_mismatches: errors.append( f"{len(hash_mismatches)} indexed hashes differ from the Hub inventory" ) if size_mismatches: errors.append( f"{len(size_mismatches)} indexed byte sizes differ from the Hub inventory" ) repo_counts = { "repository_files": len(repo_paths), "direct_standard_video_files": len(standard_files), "direct_pre_standard_video_files": len(pre_standard_files), "provenance_video_files": len(provenance_files), "missing_canonical_metadata_targets": len(missing_canonical_targets), "missing_pre_standard_metadata_targets": len(missing_pre_targets), "missing_hub_identity_metadata": len(missing_blob_metadata), "content_hash_mismatches": len(hash_mismatches), "size_mismatches": len(size_mismatches), } viewer_rows: list[dict[str, object]] = [] viewer_counts: dict[str, int] = {} if viewer_json: loaded = json.loads(viewer_json.read_text(encoding="utf-8")) if not isinstance(loaded, list): errors.append("Viewer snapshot must be a JSON list") else: viewer_rows = [row for row in loaded if isinstance(row, dict)] paths = [viewer_path(row) for row in viewer_rows] tiers = Counter(path.split("/", 1)[0] for path in paths if "/" in path) viewer_counts = dict(sorted(tiers.items())) canonical_viewer = { viewer_path(row): row for row in viewer_rows if viewer_path(row).startswith("Standard_Time_Lapses/") } metadata_paths = {row["file_name"] for row in rows} missing_from_viewer = sorted(metadata_paths.difference(canonical_viewer)) missing_from_metadata = sorted(set(canonical_viewer).difference(metadata_paths)) if missing_from_viewer: errors.append( f"{len(missing_from_viewer)} metadata paths are absent from the Viewer snapshot" ) if missing_from_metadata: errors.append( f"{len(missing_from_metadata)} canonical Viewer paths are absent from metadata.csv" ) by_path = {row["file_name"]: row for row in rows} for path, viewer_row in canonical_viewer.items(): metadata_row = by_path.get(path) if not metadata_row: continue for field in ( "date", "time", "support", "dimensions", "orientation", "video_codec", "pixel_format", "container", "hub_xet_hash", ): left = metadata_row.get(field, "") right_value = viewer_row.get(field) right = "" if right_value is None else str(right_value) if left != right: errors.append(f"{path}: {field} differs from Viewer snapshot") pre_standard_viewer_rows = [ row for row in viewer_rows if viewer_path(row).startswith("Pre_Standard_Time_Lapses/") ] pre_standard_without_technical = sum( row.get("duration_seconds") is None for row in pre_standard_viewer_rows ) if pre_standard_without_technical: warnings.append( f"{pre_standard_without_technical} pre-standard Viewer rows lack duration metadata" ) all_active_rows = rows + pre_standard_rows durations = [ float(row["duration_seconds"]) for row in all_active_rows if row.get("duration_seconds") ] sizes = [int(row["size_bytes"]) for row in all_active_rows if row.get("size_bytes")] orientations = Counter( row.get("orientation", "") or "" for row in all_active_rows ) audio = Counter(row.get("has_audio", "") or "" for row in all_active_rows) if audio.get("True", 0) + audio.get("true", 0) > 0: warnings.append("published masters commonly retain audio streams; rights/privacy review is still required") warnings.append( "encoded_frame_rate is playback rate, not original drawing-time sampling" ) return { "ok": not errors, "errors": errors, "warnings": warnings, "statistics": { "metadata_rows": len(rows), "metadata_columns": len(fields), "viewer_rows": len(viewer_rows), "viewer_collection_counts": viewer_counts, "pre_standard_metadata_rows": len(pre_standard_rows), "repository_inventory": repo_counts, "unindexed_direct_standard_files": repo_unindexed_standard, "unindexed_direct_pre_standard_files": repo_unindexed_pre_standard, "active_rows": len(all_active_rows), "unique_record_ids": len( {row.get("record_id", "") for row in all_active_rows if row.get("record_id")} ), "unique_nonempty_hashes": len( { row.get("hub_xet_hash", "") for row in all_active_rows if row.get("hub_xet_hash") } ), "unknown_finish_dates": sum(not row.get("date") for row in all_active_rows), "unknown_finish_times": sum(not row.get("time") for row in all_active_rows), "orientation_counts": dict(sorted(orientations.items())), "audio_counts": dict(sorted(audio.items())), "playback_hours": round(sum(durations) / 3600, 2), "median_playback_seconds": round(statistics.median(durations), 3), "indexed_size_tb_decimal": round(sum(sizes) / 1_000_000_000_000, 3), }, } def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("metadata_csv", type=Path) parser.add_argument("--viewer-json", type=Path) parser.add_argument("--pre-standard-metadata", type=Path) parser.add_argument( "--repo-files-json", "--repo-inventory-json", dest="repo_files_json", type=Path, ) parser.add_argument("--output", type=Path) args = parser.parse_args() report = validate( args.metadata_csv, args.viewer_json, args.pre_standard_metadata, args.repo_files_json, ) rendered = json.dumps(report, indent=2, sort_keys=True) if args.output: args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(rendered + "\n", encoding="utf-8") print(rendered) if not report["ok"]: sys.exit(1) if __name__ == "__main__": main()