File size: 10,621 Bytes
156cbcc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
#!/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()