#!/usr/bin/env python3 """Build a deterministic engineering validation set from pinned source metadata.""" from __future__ import annotations import argparse import csv import hashlib from pathlib import Path from typing import Iterable SEED = "time-lapse-artifacts-derivative-validation-v1" DEFAULT_SIZE = 18 KNOWN_COMPLETENESS = { "tla-3f49a8917fe22676": { "source_master_status": "active_derivative", "visible_start_state": "mid_process", "visible_end_state": "completed_signed", "capture_extent": "starts_mid_process", "completeness_evidence": "creator-confirmed source note", }, "tla-9d7a3463d2902dcd": { "source_master_status": "active_derivative", "visible_start_state": "blank_or_unmarked", "visible_end_state": "unknown", "capture_extent": "unknown", "completeness_evidence": "creator-confirmed source note", }, "tla-c043b4f55b583c4e": { "source_master_status": "active_derivative", "visible_start_state": "preliminary_work_present", "visible_end_state": "active_work", "capture_extent": "starts_and_ends_mid_process", "completeness_evidence": "creator-confirmed source note", }, } OUTPUT_FIELDS = [ "record_id", "source_file_path", "collection_tier", "duration_seconds", "size_bytes", "video_codec", "orientation", "source_has_audio", "source_hub_xet_hash", "source_revision", "selection_reasons", "pilot_wave", "work_id", "work_id_status", "source_master_status", "visible_start_state", "visible_end_state", "capture_extent", "completeness_evidence", ] RELATIONSHIP_FIELDS = [ "record_id", "source_file_path", "filename_sequence_key", "filename_sequence_token", "work_id", "relationship_status", "sequence_status", "evidence_method", "notes", ] def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser() parser.add_argument("--standard-metadata", required=True, type=Path) parser.add_argument("--prestandard-metadata", required=True, type=Path) parser.add_argument("--source-revision", required=True) parser.add_argument("--output", required=True, type=Path) parser.add_argument("--relationship-output", required=True, type=Path) parser.add_argument("--size", type=int, default=DEFAULT_SIZE) return parser.parse_args() def stable_key(record_id: str) -> str: return hashlib.sha256(f"{SEED}:{record_id}".encode("utf-8")).hexdigest() def load_csv(path: Path, tier: str) -> list[dict[str, str]]: with path.open("r", encoding="utf-8-sig", newline="") as handle: rows = list(csv.DictReader(handle)) for row in rows: row["collection_tier"] = tier file_name = row["file_name"] if tier == "pre_standard" and not file_name.startswith( "Pre_Standard_Time_Lapses/" ): file_name = f"Pre_Standard_Time_Lapses/{file_name}" row["source_file_path"] = file_name row["_duration"] = float(row["duration_seconds"]) row["_size"] = int(row["size_bytes"]) return rows def add( selected: dict[str, set[str]], rows: Iterable[dict[str, str]], reason: str ) -> None: for row in rows: selected.setdefault(row["record_id"], set()).add(reason) def extremes( rows: list[dict[str, str]], key: str, count: int = 2 ) -> tuple[list[dict[str, str]], list[dict[str, str]]]: ordered = sorted(rows, key=lambda row: (row[key], stable_key(row["record_id"]))) return ordered[:count], list(reversed(ordered[-count:])) def median_record(rows: list[dict[str, str]], key: str) -> dict[str, str]: ordered = sorted(rows, key=lambda row: (row[key], stable_key(row["record_id"]))) return ordered[(len(ordered) - 1) // 2] def one_per_value( rows: list[dict[str, str]], field: str ) -> list[tuple[str, dict[str, str]]]: values = sorted({row[field] for row in rows}) chosen = [] for value in values: candidates = [row for row in rows if row[field] == value] # Categorical coverage should be inexpensive in the first pilot. Size # is therefore the primary key; the seeded hash is only a stable tie # breaker. A single small record may cover several rare conditions. chosen.append( ( value, min( candidates, key=lambda row: (row["_size"], stable_key(row["record_id"])), ), ) ) return chosen def filename_sequence_parts(source_path: str) -> tuple[str, str] | None: name = Path(source_path).name marker = ".Rec" if marker not in name or not name.endswith(".mp4"): return None prefix, suffix = name.rsplit(marker, 1) token = f"Rec{suffix[:-4]}" return prefix, token def choose(rows: list[dict[str, str]], target_size: int) -> dict[str, set[str]]: if target_size < 12: raise ValueError("validation set size must be at least 12") selected: dict[str, set[str]] = {} documented_shortened = [ row for row in rows if row["record_id"] in KNOWN_COMPLETENESS ] add(selected, documented_shortened, "documented_shortened_derivative") duration_low, duration_high = extremes(rows, "_duration") add(selected, duration_low, "duration_low_extreme") add(selected, duration_high, "duration_high_extreme") add(selected, [median_record(rows, "_duration")], "duration_median") size_low, size_high = extremes(rows, "_size") add(selected, size_low, "size_low_extreme") add(selected, size_high, "size_high_extreme") add(selected, [median_record(rows, "_size")], "size_median") for field, label in ( ("collection_tier", "tier"), ("video_codec", "codec"), ("orientation", "orientation"), ("has_audio", "audio_stream_presence"), ): for value, row in one_per_value(rows, field): add(selected, [row], f"{label}:{value}") sequence_rows = sorted( [row for row in rows if filename_sequence_parts(row["source_file_path"])], key=lambda row: (row["source_file_path"], stable_key(row["record_id"])), ) add(selected, sequence_rows[:2], "filename_multi_recording_case") if len(selected) > target_size: raise ValueError( f"required deterministic coverage selects {len(selected)} records, " f"which exceeds target size {target_size}" ) remaining = sorted( [row for row in rows if row["record_id"] not in selected], key=lambda row: stable_key(row["record_id"]), ) for row in remaining[: target_size - len(selected)]: add(selected, [row], "deterministic_fill") return selected def make_output_row( row: dict[str, str], reasons: set[str], source_revision: str ) -> dict[str, str]: completeness = KNOWN_COMPLETENESS.get(row["record_id"], {}) wave_one = ( "documented_shortened_derivative" in reasons or "duration_low_extreme" in reasons or row["video_codec"] != "h264" or row["orientation"] != "portrait" or row["has_audio"].lower() != "true" ) return { "record_id": row["record_id"], "source_file_path": row["source_file_path"], "collection_tier": row["collection_tier"], "duration_seconds": row["duration_seconds"], "size_bytes": row["size_bytes"], "video_codec": row["video_codec"], "orientation": row["orientation"], "source_has_audio": row["has_audio"].lower(), "source_hub_xet_hash": row["hub_xet_hash"], "source_revision": source_revision, "selection_reasons": ";".join(sorted(reasons)), "pilot_wave": "1" if wave_one else "2", "work_id": "", "work_id_status": "unassigned", "source_master_status": completeness.get("source_master_status", "unknown"), "visible_start_state": completeness.get("visible_start_state", "unknown"), "visible_end_state": completeness.get("visible_end_state", "unknown"), "capture_extent": completeness.get("capture_extent", "unknown"), "completeness_evidence": completeness.get("completeness_evidence", ""), } def write_csv(path: Path, fields: list[str], rows: list[dict[str, str]]) -> None: path.parent.mkdir(parents=True, exist_ok=True) with path.open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=fields, lineterminator="\n") writer.writeheader() writer.writerows(rows) def relationship_rows(rows: list[dict[str, str]]) -> list[dict[str, str]]: output = [] for row in sorted(rows, key=lambda item: item["source_file_path"]): parts = filename_sequence_parts(row["source_file_path"]) if not parts: continue key, token = parts output.append( { "record_id": row["record_id"], "source_file_path": row["source_file_path"], "filename_sequence_key": key, "filename_sequence_token": token, "work_id": "", "relationship_status": "unreviewed", "sequence_status": "unverified", "evidence_method": "", "notes": ( "Filename-level review candidate only; shared key and Rec token " "do not establish shared physical-work identity or sequence." ), } ) return output def main() -> None: args = parse_args() rows = load_csv(args.standard_metadata, "standard") + load_csv( args.prestandard_metadata, "pre_standard" ) ids = [row["record_id"] for row in rows] if len(ids) != len(set(ids)): raise ValueError("record_id values are not unique across source metadata") selected = choose(rows, args.size) by_id = {row["record_id"]: row for row in rows} output_rows = [ make_output_row(by_id[record_id], reasons, args.source_revision) for record_id, reasons in sorted(selected.items()) ] write_csv(args.output, OUTPUT_FIELDS, output_rows) write_csv( args.relationship_output, RELATIONSHIP_FIELDS, relationship_rows(rows), ) wave_one = sum(row["pilot_wave"] == "1" for row in output_rows) print( f"selected={len(output_rows)} wave1={wave_one} wave2={len(output_rows)-wave_one} " f"source_rows={len(rows)}" ) if __name__ == "__main__": main()