time-lapse-artifacts / tools /validate_metadata.py
maxwellinked's picture
Prepare v0.2 metadata and documentation release (#2)
3967721
Raw
History Blame
14.9 kB
#!/usr/bin/env python3
"""Validate the v0.2 active indexes and optional Viewer/repository snapshots."""
from __future__ import annotations
import argparse
import csv
import json
import re
import statistics
import sys
from collections import Counter
from pathlib import Path
from urllib.parse import unquote, urlparse
RECORD_ID_RE = re.compile(r"^tla-[0-9a-f]{16}$")
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",
"size_bytes",
]
PRE_STANDARD_REQUIRED_FIELDS = [
"file_name",
"date",
"time",
"tool",
"medium",
"support",
"dimensions",
"original_filename",
]
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 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(field: str) -> list[str]:
values = [row.get(field, "") for row in rows 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(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 row.get("file_name", "").startswith("Standard_Time_Lapses/"):
errors.append(f"{label}: canonical path is outside Standard_Time_Lapses")
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-15":
errors.append(f"{label}: unexpected acquisition protocol version")
if not DATE_RE.fullmatch(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")
for field in ("tool", "medium"):
value = row.get(field, "")
if "|" in value:
errors.append(f"{label}: {field} still uses a pipe separator")
if value and any(not item.strip() for item in value.split(";")):
errors.append(f"{label}: {field} contains an empty list item")
for field in (
"duration_seconds",
"width_px",
"height_px",
"orientation",
"encoded_frame_rate",
"video_codec",
"pixel_format",
"container",
"has_audio",
"hub_xet_hash",
"size_bytes",
):
if not row.get(field, ""):
errors.append(f"{label}: canonical technical field {field} is blank")
try:
width = int(row.get("width_px", ""))
height = int(row.get("height_px", ""))
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 {width}x{height}"
)
except ValueError:
pass
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}"
)
pre_names = [row.get("file_name", "") for row in pre_standard_rows]
duplicate_pre_names = sorted(
value for value, count in Counter(pre_names).items() if value and count > 1
)
if duplicate_pre_names:
errors.append(
f"duplicate pre-standard file_name values: {duplicate_pre_names[:5]}"
)
for index, row in enumerate(pre_standard_rows, start=2):
name = row.get("file_name", "")
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 repo_files_json:
loaded_paths = json.loads(repo_files_json.read_text(encoding="utf-8"))
if not isinstance(loaded_paths, list) or not all(
isinstance(path, str) for path in loaded_paths
):
errors.append("repository snapshot must be a JSON list of paths")
else:
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"
)
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),
}
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"
)
durations = [float(row["duration_seconds"]) for row in rows if row.get("duration_seconds")]
sizes = [int(row["size_bytes"]) for row in rows if row.get("size_bytes")]
orientations = Counter(row.get("orientation", "") or "<missing>" for row in rows)
audio = Counter(row.get("has_audio", "") or "<missing>" for row in rows)
if audio.get("True", 0) + audio.get("true", 0) > 0:
warnings.append("canonical masters commonly retain audio; 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,
"unique_record_ids": len({row.get("record_id", "") for row in rows}),
"unique_nonempty_hashes": len(
{row.get("hub_xet_hash", "") for row in rows if row.get("hub_xet_hash")}
),
"unknown_finish_times": sum(not row.get("time") for row in 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", 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()