Download tools/validate_metadata.py from maxwellinked/time-lapse-artifacts: direct link, hf CLI and curl.
- Browser
- Download file 34.3 kB
-
https://huggingface.co/datasets/maxwellinked/time-lapse-artifacts/resolve/main/tools/validate_metadata.py
- Command line
-
hf download hf://datasets/maxwellinked/time-lapse-artifacts/tools/validate_metadata.py
-
curl -L -o validate_metadata.py https://huggingface.co/datasets/maxwellinked/time-lapse-artifacts/resolve/main/tools/validate_metadata.py
34.3 kB
| #!/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$") | |
| EARLIER_STANDARD_PROTOCOL = "standard-2025-07-13" | |
| PROSPECTIVE_FRAGMENT_PROTOCOL = "standard-2026-08-27" | |
| STANDARD_PROTOCOLS = { | |
| EARLIER_STANDARD_PROTOCOL, | |
| PROSPECTIVE_FRAGMENT_PROTOCOL, | |
| } | |
| RECOGNIZED_FILENAME_TOOL_TOKENS = frozenset( | |
| {"Pencil", "FountainPen", "BallpointPen", "Brush"} | |
| ) | |
| 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", | |
| "recording_mode", | |
| ] | |
| 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 load_fragment_protocol_membership( | |
| relationships_root: Path, | |
| errors: list[str], | |
| metadata_csv: Path | None = None, | |
| insertion_ids: set[str] | None = None, | |
| ) -> tuple[set[str], dict[str, list[str]], int]: | |
| """Load canonical-fragment membership from dated relationship sidecars.""" | |
| sidecars = sorted( | |
| relationships_root.glob("*/fragment_sequence_relationships.csv") | |
| ) | |
| if not sidecars: | |
| errors.append( | |
| f"no dated fragment relationship sidecars found under {relationships_root}" | |
| ) | |
| return set(), {}, 0 | |
| required_fields = { | |
| "fragment_set_label", | |
| "object_role", | |
| "record_id", | |
| } | |
| prospective_ids: set[str] = set() | |
| groups: dict[str, list[str]] = {} | |
| for sidecar in sidecars: | |
| try: | |
| fields, relationship_rows = load_csv(sidecar) | |
| except (OSError, ValueError) as exc: | |
| errors.append(f"{sidecar}: unable to load fragment relationships: {exc}") | |
| continue | |
| missing_fields = sorted(required_fields.difference(fields)) | |
| if missing_fields: | |
| errors.append( | |
| f"{sidecar}: missing protocol-boundary fields: {missing_fields}" | |
| ) | |
| continue | |
| for index, relationship in enumerate(relationship_rows, start=2): | |
| if relationship.get("object_role") != "canonical_fragment": | |
| continue | |
| record_id = relationship.get("record_id", "") | |
| label = relationship.get("fragment_set_label", "") | |
| row_label = f"{sidecar} row {index}" | |
| if not RECORD_ID_RE.fullmatch(record_id): | |
| errors.append(f"{row_label}: canonical fragment has invalid record_id") | |
| continue | |
| if not label: | |
| errors.append( | |
| f"{row_label}: canonical fragment has no fragment_set_label" | |
| ) | |
| continue | |
| if record_id in prospective_ids: | |
| errors.append( | |
| f"{row_label}: canonical record_id {record_id} occurs in " | |
| "multiple dated sidecars" | |
| ) | |
| continue | |
| prospective_ids.add(record_id) | |
| group_key = f"{sidecar.parent.name}/{label}" | |
| groups.setdefault(group_key, []).append(record_id) | |
| # The supplement repeats historical members for ordering, but contributes | |
| # only new IDs to protocol membership. Dated-packet duplicate rules above | |
| # remain intact. Never merge partially valid insertion data. | |
| from sequence_insertions import REGISTRY_PATH, validate_insertions | |
| repository_root = relationships_root.parent.parent | |
| if (repository_root / REGISTRY_PATH).exists(): | |
| report = validate_insertions( | |
| repository_root, metadata_csv or repository_root / "metadata.csv", | |
| bind_inventory=False, | |
| ) | |
| errors.extend(report["errors"]) | |
| for sequence in report["sequences"]: | |
| additions = sequence["additions"] | |
| if prospective_ids.intersection(additions): | |
| errors.append("insertion additions duplicate dated packet membership") | |
| continue | |
| predecessor_date = Path(sequence["predecessor"]["path"]).parent.name | |
| key = f"{predecessor_date}/{sequence['fragment_set_label']}" | |
| historical_ids = [m["record_id"] for m in sequence["members"] | |
| if m["record_id"] not in additions] | |
| if groups.get(key) != historical_ids: | |
| errors.append("insertion predecessor differs from dated membership") | |
| continue | |
| prospective_ids.update(additions) | |
| if insertion_ids is not None: | |
| insertion_ids.update(additions) | |
| groups[key] = [m["record_id"] for m in sequence["members"]] | |
| return prospective_ids, groups, len(sidecars) | |
| 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_filename_tool_tokens( | |
| row: dict[str, str], label: str, errors: list[str] | |
| ) -> None: | |
| """Require each declared tool to appear as its own literal filename token.""" | |
| filename_tokens = Path(row.get("file_name", "")).name.split(".") | |
| declared_tools = [ | |
| item.strip() for item in row.get("tool", "").split(";") if item.strip() | |
| ] | |
| for tool in declared_tools: | |
| if tool not in filename_tokens: | |
| errors.append( | |
| f"{label}: declared tool {tool!r} is not an exact " | |
| "case-sensitive dot-delimited filename token" | |
| ) | |
| def validate_recognized_filename_tool_coverage( | |
| row: dict[str, str], label: str, errors: list[str] | |
| ) -> None: | |
| """Require recognized filename tool tokens in the metadata tool set.""" | |
| filename_tokens = set(Path(row.get("file_name", "")).name.split(".")) | |
| declared_tools = { | |
| item.strip() | |
| for item in row.get("tool", "").split(";") | |
| if item.strip() | |
| } | |
| missing_tools = sorted( | |
| filename_tokens.intersection(RECOGNIZED_FILENAME_TOOL_TOKENS) | |
| - declared_tools | |
| ) | |
| for tool in missing_tools: | |
| errors.append( | |
| f"{label}: recognized filename tool {tool!r} is absent " | |
| "from tool metadata" | |
| ) | |
| 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, | |
| fragment_relationships_root: Path | None = 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] = [] | |
| prospective_fragment_ids: set[str] = set() | |
| prospective_fragment_groups: dict[str, list[str]] = {} | |
| fragment_sidecar_count = 0 | |
| registered_insertion_ids: set[str] = set() | |
| if fragment_relationships_root: | |
| ( | |
| prospective_fragment_ids, | |
| prospective_fragment_groups, | |
| fragment_sidecar_count, | |
| ) = load_fragment_protocol_membership( | |
| fragment_relationships_root, errors, metadata_csv, registered_insertion_ids | |
| ) | |
| 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("recording_mode") != "time_lapse": | |
| errors.append(f"{label}: recording_mode must be time_lapse") | |
| if row.get("is_canonical", "").lower() != "true": | |
| errors.append(f"{label}: is_canonical must be true") | |
| protocol = row.get("acquisition_protocol_version", "") | |
| if fragment_relationships_root: | |
| expected_protocol = ( | |
| PROSPECTIVE_FRAGMENT_PROTOCOL | |
| if row.get("record_id") in prospective_fragment_ids | |
| else EARLIER_STANDARD_PROTOCOL | |
| ) | |
| if protocol != expected_protocol: | |
| errors.append( | |
| f"{label}: acquisition protocol {protocol!r} does not match " | |
| f"sidecar-defined boundary {expected_protocol!r}" | |
| ) | |
| elif protocol not in STANDARD_PROTOCOLS: | |
| 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) | |
| validate_filename_tool_tokens(row, label, errors) | |
| validate_recognized_filename_tool_coverage(row, label, errors) | |
| if re.search(r"\.Rec\d+[a-zA-Z]+\.mp4$", row.get("file_name", "")): | |
| if row.get("record_id") not in registered_insertion_ids: | |
| errors.append(f"{label}: unregistered lettered Rec suffix") | |
| 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) | |
| if fragment_relationships_root: | |
| rows_by_id = { | |
| row.get("record_id", ""): row for row in rows if row.get("record_id") | |
| } | |
| missing_fragment_ids = sorted(prospective_fragment_ids.difference(rows_by_id)) | |
| if missing_fragment_ids: | |
| errors.append( | |
| f"{len(missing_fragment_ids)} sidecar-defined canonical fragments are absent " | |
| "from metadata.csv" | |
| ) | |
| for group_label, record_ids in prospective_fragment_groups.items(): | |
| group_rows = [ | |
| rows_by_id[record_id] | |
| for record_id in record_ids | |
| if record_id in rows_by_id | |
| ] | |
| timestamps = { | |
| (row.get("date", ""), row.get("time", "")) for row in group_rows | |
| } | |
| if len(group_rows) == len(record_ids) and len(timestamps) != 1: | |
| errors.append( | |
| f"{group_label}: prospective fragment members do not share one " | |
| "documented finish date and time" | |
| ) | |
| elif len(group_rows) == len(record_ids) and timestamps: | |
| finish_date, finish_time = next(iter(timestamps)) | |
| if not finish_date or not finish_time: | |
| errors.append( | |
| f"{group_label}: prospective fragment grouping must have a " | |
| "documented finish date and time" | |
| ) | |
| standard_30x40_non_board = sum( | |
| row.get("dimensions") == "30x40" | |
| and row.get("support") != "IllustrationBoard" | |
| for row in rows | |
| ) | |
| if standard_30x40_non_board: | |
| warnings.append( | |
| f"{standard_30x40_non_board} canonical 30x40 rows use support other " | |
| "than IllustrationBoard; an explicit curator-documented exception " | |
| "or correction is 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("recording_mode") != "time_lapse": | |
| errors.append(f"{label}: recording_mode must be time_lapse") | |
| 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_recognized_filename_tool_coverage(row, label, 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: | |
| row_verb = "row retains" if missing_material_rows == 1 else "rows retain" | |
| warnings.append( | |
| f"{missing_material_rows} pre-standard {row_verb} unknown material or support 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 "<missing>" for row in all_active_rows | |
| ) | |
| audio = Counter(row.get("has_audio", "") or "<missing>" for row in all_active_rows) | |
| if audio.get("True", 0) + audio.get("true", 0) > 0: | |
| warnings.append( | |
| "active indexed videos may 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), | |
| "protocol_version_counts": dict( | |
| sorted( | |
| Counter( | |
| row.get("acquisition_protocol_version", "") for row in rows | |
| ).items() | |
| ) | |
| ), | |
| "protocol_boundary": { | |
| "checked": fragment_relationships_root is not None, | |
| "fragment_relationship_sidecars": fragment_sidecar_count, | |
| "prospective_record_ids": len(prospective_fragment_ids), | |
| "earlier_standard_rows": len(rows) - len(prospective_fragment_ids), | |
| }, | |
| "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( | |
| "--fragment-relationships-root", | |
| type=Path, | |
| help=( | |
| "directory containing dated fragment_sequence_relationships.csv " | |
| "sidecars that define the Standard protocol-version boundary" | |
| ), | |
| ) | |
| 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, | |
| args.fragment_relationships_root, | |
| ) | |
| 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() | |