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
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
"""CONTRACT 6.5: read one complete shard through the v1.1 reader, every component.

Acceptance item 5 asks for a check the byte-level ones cannot give.  ``verify.py``
compares a view's bytes against its own v1.0 source, which proves repackaging
preserved them, but it never decodes media and never crosses components -- a
release whose bundles are each individually byte-perfect and whose RGB, camera and
annotations no longer line up would pass it.  ``validate.py`` does cross
components, but per view and against the schema, not against the media.

So this opens the finished release the way a consumer would, through
``Registry.resolve`` and ``BundleReader``, and checks the joins:

  frames     the RGB's real frame count (ffprobe, demux only -- ``nb_frames`` is
             absent in Matroska) equals the metainfo ``num_frames``, the length of
             ``frames.jsonl`` and the ``T`` axis of every field the view declares.
             Depth, depth validity and the segment mask are counted the same way.
  camera     the directory the view lives in, its ``camera_id``, its ``camera``
             block and the intrinsic component's ``schema_id`` all name the same
             camera
  presence   a component declaring ``available: false`` leaves no file behind, and
             every declared one opens; a media component's standalone bool
             validity is a real file of the declared length (CONTRACT 4)
  frames.jsonl
             one row per frame, indices contiguous, ``sample_id`` unique, the
             split directory in ``sample_id`` equal to the declared ``split``, and
             ``source_locator.annotation_index`` equal to ``source_frame_id`` --
             the frame-level association the release claims
  visibility RHD's own join: ``xyz`` and ``uv`` are two components sharing one
             ``visibility`` leaf.  Reading it through each component's declared
             attribute and finding the same bytes is what "written once and
             referenced twice" (RAW_MAPPING.md) has to mean in the finished tree.

What it does not do: it never decodes pixels, compares an image to anything, or
forms an opinion about whether a mask looks right.  CONTRACT 6.5 keeps that --
human visual acceptance -- separate from this, and this tool is on the packaging
side of that line.
"""

from __future__ import annotations

import argparse
import json
import subprocess
import sys
from pathlib import Path

import torch

from rhd_common import RELEASE_ROOT, TMP_ROOT, load
from warehouse import BundleReader, Registry


def wildcard(segment: str) -> bool:
    return "<" in segment and ">" in segment


def registered_entry(registry, bundle_rel: str, keys: list) -> bool:
    """Is ``bundle_rel`` + ``keys`` an entry the registry declares?

    ``Registry.resolve`` answers the migrator's question -- given a *v1.0* ref,
    where did those bytes go.  A consumer asks the other direction: the v1.1
    metainfo names a bundle and a key path, and that pair has to be a registered
    entry.  Same templates, matched from the target side.
    """
    ref = Path(bundle_rel).parts
    for bundle in registry.bundles.values():
        template = Path(bundle["path"]).parts
        if len(ref) != len(template) or ref[-1] != template[-1]:
            continue
        if not all(wildcard(w) or w == g for w, g in zip(template[:-1], ref[:-1])):
            continue
        for name in bundle["entries"]:
            wanted = name.split("/")
            if len(wanted) == len(keys) and all(
                wildcard(w) or w == k for w, k in zip(wanted, keys)
            ):
                return True
    return False


def packet_count(path: Path) -> int:
    """Frames in an encoded video, by demux -- not by decoding."""
    out = subprocess.run(
        ["ffprobe", "-v", "error", "-select_streams", "v:0", "-count_packets",
         "-show_entries", "stream=nb_read_packets", "-of", "csv=p=0", str(path)],
        capture_output=True, text=True, check=True,
    ).stdout.strip()
    return int(out)


def view_dirs(root: Path, sequence: str) -> list[Path]:
    sequence_dir = root / "data" / sequence
    if not sequence_dir.is_dir():
        raise SystemExit(f"no such shard in the release: {sequence}")
    return sorted((p for p in sequence_dir.iterdir() if p.is_dir()),
                  key=lambda p: (len(p.name), p.name))


def all_sequences(root: Path) -> list[str]:
    return sorted(p.name for p in (root / "data").iterdir() if p.is_dir())


def read_media(registry, reader, view: Path, name: str, component: dict,
               record: dict, problem) -> None:
    """A preserved file (mkv or jsonl) and its standalone validity, if declared.

    A bundled leaf holds its own validity; a media component may not, so CONTRACT 4
    keeps that validity beside it -- a bool Tensor for RGB and the mask, a bool
    video for depth.  Either way the length has to match the declared frames.
    """
    ref = view / component["data_ref"]
    if not ref.is_file():
        problem(f"{name}: preserved file {component['data_ref']} is missing")
        return
    frames = None
    if ref.suffix == ".mkv":
        frames = packet_count(ref)
        declared = component["axes"].index("T")
        record["media"].append({"component": name, "ref": component["data_ref"],
                                "bytes": ref.stat().st_size, "frames": frames,
                                "declared_T_axis": declared})
        if frames != record["num_frames"]:
            problem(f"{name}: {frames} packets, metainfo declares "
                    f"{record['num_frames']}")
    else:
        record["media"].append({"component": name, "ref": component["data_ref"],
                                "bytes": ref.stat().st_size, "frames": None})

    valid_ref = component.get("valid_ref")
    if not valid_ref:
        record["media"][-1]["valid"] = None
        return
    valid_path = view / valid_ref
    if not valid_path.is_file():
        problem(f"{name}: declared validity {valid_ref} is missing")
        return
    if valid_ref.endswith(".pt"):
        #: CONTRACT 4: media validity stays a standalone bool Tensor.  It is not
        #: registered as a bundle, so the reader cannot address it by key
        payload = load_tensor(valid_path)
        length = payload.shape[0] if payload.ndim else 0
        record["media"][-1]["valid"] = {"ref": valid_ref, "kind": "pt",
                                        "dtype": str(payload.dtype),
                                        "shape": list(payload.shape)}
        if payload.dtype != torch.bool:
            problem(f"{name}: validity {valid_ref} is {payload.dtype}, not bool")
        if length != record["num_frames"]:
            problem(f"{name}: validity {valid_ref} holds {length} frames, "
                    f"metainfo declares {record['num_frames']}")
    else:
        frames = packet_count(valid_path)
        record["media"][-1]["valid"] = {"ref": valid_ref, "kind": "media",
                                        "frames": frames}
        if frames != record["num_frames"]:
            problem(f"{name}: validity {valid_ref} holds {frames} frames, "
                    f"metainfo declares {record['num_frames']}")


def load_tensor(path: Path) -> torch.Tensor:
    """A standalone ``.pt`` outside the registry, read the way the release stores it."""
    with path.open("rb") as stream:
        return torch.load(stream, map_location="cpu", weights_only=True)


def read_view(registry, reader, view: Path) -> dict:
    """Open every component of one view; return what the reader found."""
    meta = load(view / "metainfo.json")
    where = f"{view.parent.name}/{view.name}"
    record = {"view": where, "camera_id": meta.get("camera_id"),
              "view_type": meta.get("view_type"), "num_frames": meta.get("num_frames"),
              "fields": [], "media": [], "absent": [], "problems": []}
    problem = record["problems"].append

    #: the view's own directory name and its declared camera must agree; the whole
    #: release is laid out as <sequence>/<camera_id>/, so a mismatch would mean the
    #: calibration and the pixels come from different cameras
    if meta.get("camera_id") != view.name:
        problem(f"directory {view.name} but camera_id {meta.get('camera_id')!r}")

    for name, component in meta["components"].items():
        ref = component.get("data_ref")
        if not component.get("available", True):
            #: an omitted component must not leave a file claiming otherwise
            if ref and (view / ref).exists():
                problem(f"{name}: available=false but {ref} exists")
            record["absent"].append(name)
            continue
        if not ref:
            problem(f"{name}: available but declares no data_ref")
            continue
        #: a component carrying ``data_key`` is bundled numeric data; one with only
        #: ``data_ref`` is a preserved media/JSONL file (validate.py rebuilds on the
        #: same predicate).  The registry entry is matched from the target side.
        if "data_key" not in component:
            read_media(registry, reader, view, name, component, record, problem)
            continue
        leaves = [(name, component["data_ref"], component["data_key"],
                   component["valid_key"], list(component.get("axes") or []))]
        for attribute, spec in (component.get("attributes") or {}).items():
            leaves.append((f"{name}.{attribute}", spec["data_ref"], spec["data_key"],
                           spec["valid_key"], list(spec.get("axes") or [])))
        for owner, bundle, data_key, valid_key, axes in leaves:
            try:
                data = reader.get(view, bundle, data_key)
                valid = reader.get(view, bundle, valid_key)
            except (KeyError, TypeError, FileNotFoundError) as error:
                problem(f"{owner}: reader could not open {bundle}: {error}")
                continue
            if not isinstance(data, torch.Tensor) or valid.dtype != torch.bool:
                problem(f"{owner}: {bundle} does not hold (Tensor, bool Tensor)")
                continue
            frames = data.shape[axes.index("T")] if "T" in axes else None
            if frames is not None and frames != meta["num_frames"]:
                problem(f"{owner}: {frames} frames on its T axis, "
                        f"metainfo declares {meta['num_frames']}")
            if valid.shape != tuple(data.shape[: valid.ndim]):
                problem(f"{owner}: valid {list(valid.shape)} is not a prefix of "
                        f"data {list(data.shape)}")
            if not registered_entry(registry, bundle, data_key[:-1]):
                problem(f"{owner}: {bundle}:{'/'.join(data_key[:-1])} is not a "
                        f"registered bundle entry")
            record["fields"].append({
                "component": owner, "entry": f"{bundle}:{'/'.join(data_key)}",
                "dtype": str(data.dtype), "shape": list(data.shape),
                "T": frames, "valid_true": int(valid.sum()),
                "valid_false": int((~valid).sum()),
            })
    return record


def check_visibility(registry, reader, view: Path, meta: dict) -> list[str]:
    """RHD's own join: one ``visibility`` leaf, read through two components.

    v1.0 stored a single ``annotation/keypoints/visibility.pt`` referenced by both
    the xyz and the uv component; v1.1's registry fixes one entry for it, so the
    migration wrote the leaf once and both components point at it.  A reader that
    finds different bytes through the two declarations would mean the migration
    silently kept one and dropped the other -- the failure mode RAW_MAPPING.md says
    it refuses to paper over.
    """
    problems = []
    specs = [(name, (component.get("attributes") or {}).get("visibility"))
             for name, component in meta["components"].items()
             if isinstance(component, dict)]
    specs = [(name, spec) for name, spec in specs if spec]
    if len(specs) < 2:
        problems.append(f"expected two components declaring a visibility attribute, "
                        f"found {len(specs)}")
        return problems
    reference = None
    for name, spec in sorted(specs):
        try:
            data = reader.get(view, spec["data_ref"], spec["data_key"])
            valid = reader.get(view, spec["data_ref"], spec["valid_key"])
        except (KeyError, TypeError, FileNotFoundError) as error:
            problems.append(f"{name}.visibility: reader could not open "
                            f"{spec['data_ref']}: {error}")
            continue
        if reference is None:
            reference = (name, data, valid)
            continue
        if data.shape != reference[1].shape or data.dtype != reference[1].dtype:
            problems.append(f"{name}.visibility and {reference[0]}.visibility differ "
                            f"in shape/dtype")
        elif data.contiguous().numpy().tobytes() != reference[1].contiguous().numpy().tobytes():
            problems.append(f"{name}.visibility and {reference[0]}.visibility "
                            f"are different bytes")
        elif valid.contiguous().numpy().tobytes() != reference[2].contiguous().numpy().tobytes():
            problems.append(f"{name}.visibility and {reference[0]}.visibility have "
                            f"different validity bytes")
    return problems


#: RHD ships two official directories, <dataset>_published_v2/{training,evaluation},
#: and the release maps them onto the train/test splits (split_scheme
#: "RHD_official_training_evaluation").  A shard whose own frames name one
#: directory while its split label says the other would file one split's frames
#: under the other's label, so the three places that state it are read together.
SOURCE_DIRECTORY_SPLIT = {"training": "train", "evaluation": "test"}


def check_frames(view: Path, meta: dict) -> list[str]:
    """``frames.jsonl`` is what makes a sample_type=image shard a sequence."""
    problems = []
    path = view / (meta["sampling"].get("frames_ref") or "camera/frames.jsonl")
    if not path.is_file():
        return [f"frames table {path.name} is missing"]
    rows = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines()
            if line.strip()]
    if len(rows) != meta["num_frames"]:
        problems.append(f"frames.jsonl holds {len(rows)} rows, metainfo declares "
                        f"{meta['num_frames']}")
    seen = set()
    for index, row in enumerate(rows):
        if row.get("frame_index") != index:
            problems.append(f"frames.jsonl row {index} has frame_index "
                            f"{row.get('frame_index')!r}")
            break
        sample = row.get("sample_id")
        if sample in seen:
            problems.append(f"sample_id {sample!r} appears twice")
            break
        seen.add(sample)
        #: sample_id is "<dataset>/<source directory>/<id>"; both parts have to agree
        #: with what the metainfo declares about this shard
        parts = str(sample).split("/")
        if len(parts) == 3:
            if parts[0] != meta["dataset_id"]:
                problems.append(f"sample_id {sample!r} names dataset {parts[0]!r}")
                break
            if SOURCE_DIRECTORY_SPLIT.get(parts[1]) != meta.get("split"):
                problems.append(f"sample_id {sample!r} is filed under {parts[1]!r} "
                                f"but the shard split is {meta.get('split')!r}")
                break
        locator = row.get("source_locator") or {}
        if locator.get("annotation_index") != int(row.get("source_frame_id")):
            problems.append(f"frame {index}: annotation_index "
                            f"{locator.get('annotation_index')!r} != source_frame_id "
                            f"{row.get('source_frame_id')!r}")
            break
    return problems


def check_shard(meta: dict, frames_problems: list[str]) -> list[str]:
    """The shard-level claim: the split label, the locator and the frames agree."""
    problems = list(frames_problems)
    prefix = (meta.get("split_source_locator") or {}).get("member_prefix") or ""
    if not prefix:
        problems.append("split_source_locator names no member_prefix")
        return problems
    directory = prefix.rstrip("/").split("/")[-1]
    if SOURCE_DIRECTORY_SPLIT.get(directory) != meta.get("split"):
        problems.append(f"split {meta.get('split')!r} does not match the source "
                        f"directory {directory!r}")
    sequence = meta.get("sequence_id") or ""
    if sequence and not sequence.startswith(directory):
        #: shard ids carry their source directory, e.g. evaluation_00000512
        problems.append(f"sequence_id {sequence!r} does not start with "
                        f"{directory!r}")
    return problems


def sweep(root: Path, registry, reader, sequence: str, quiet: bool) -> dict:
    records, metas, shard_problems = [], {}, []
    for view in view_dirs(root, sequence):
        meta = load(view / "metainfo.json")
        record = read_view(registry, reader, view)
        #: the visibility join and the frame table are per-view checks, so their
        #: findings are recorded against the view that failed; split/sequence
        #: consistency is stated once for the shard
        record["problems"].extend(check_visibility(registry, reader, view, meta))
        record["problems"].extend(check_frames(view, meta))
        records.append(record)
        metas[view.name] = meta
    for name, meta in sorted(metas.items()):
        shard_problems.extend(check_shard(meta, []))

    per_view_problems = [(r["view"], p) for r in records for p in r["problems"]]

    if not quiet:
        print(f"{sequence}: {len(records)} view(s)")
        for record in records:
            print(f"  {record['view']:<28} {record['view_type']:<4} "
                  f"cam={record['camera_id']} frames={record['num_frames']} "
                  f"fields={len(record['fields'])} media={len(record['media'])} "
                  f"absent={len(record['absent'])}")
            for field in record["fields"]:
                print(f"      {field['component']:<26} {field['dtype']:<14} "
                      f"{str(field['shape']):<20} invalid={field['valid_false']}")
            for media in record["media"]:
                print(f"      {media['component']:<26} {media['ref']:<28} "
                      f"{media['bytes']} B  frames={media['frames']}")

    for view, problem in per_view_problems:
        print(f"FAIL {view}: {problem}", file=sys.stderr)
    for problem in shard_problems:
        print(f"FAIL {sequence}: {problem}", file=sys.stderr)

    return {
        "sequence": sequence,
        "views": records,
        "shard_problems": shard_problems,
        "view_problems": {record["view"]: record["problems"] for record in records},
        "accepted": not shard_problems and not per_view_problems,
        "scope": "repackaging equivalent by reading the release; not visual acceptance",
    }


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("sequence", nargs="?",
                        help="shard id, e.g. training_00000000 (omit with --all)")
    parser.add_argument("--all", action="store_true",
                        help="walk every shard in the release")
    parser.add_argument("--root", type=Path, default=RELEASE_ROOT)
    parser.add_argument("--schema", type=Path, default=RELEASE_ROOT / "doc" / "schema.json",
                        help="v1.1 schema.json (default <release>/doc/schema.json)")
    parser.add_argument("--report", type=Path,
                        help="write the full record here as JSON "
                             "(default: tmp/rhd-tools/read_sequence.json with --all)")
    parser.add_argument("--quiet", action="store_true")
    args = parser.parse_args(argv)

    if not args.sequence and not args.all:
        parser.error("name a shard, or pass --all to walk the release")
    registry = Registry.load(args.schema)
    reader = BundleReader()
    sequences = all_sequences(args.root) if args.all else [args.sequence]

    records = [sweep(args.root, registry, reader, sequence, args.quiet)
               for sequence in sequences]
    accepted = all(record["accepted"] for record in records)
    failed = [record["sequence"] for record in records if not record["accepted"]]

    report = {
        "release": "shared-v1.1",
        "shards": len(records),
        "shards_accepted": len(records) - len(failed),
        "failed": failed,
        "records": records if args.all else records[0],
        "accepted": accepted,
        "scope": "repackaging equivalent by reading the release; not visual acceptance",
    }
    target = args.report or (TMP_ROOT / "read_sequence.json" if args.all else None)
    if target:
        target.parent.mkdir(parents=True, exist_ok=True)
        target.write_text(json.dumps(report, ensure_ascii=False, indent=2),
                          encoding="utf-8")
        print(f"wrote {target}")
    if not args.quiet and args.all:
        print(f"{len(records) - len(failed)}/{len(records)} shard(s) accepted")
    print("ACCEPTANCE_PASS" if accepted else "ACCEPTANCE_FAIL")
    return 0 if accepted else 1


if __name__ == "__main__":
    sys.dont_write_bytecode = True
    raise SystemExit(main())