File size: 26,147 Bytes
10ed3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
"""Check complete FreiHAND v1.1 views using shared media, without raw or MANO.

All selected frames are decoded and checked; only the HTML display is sampled.
Output must be a new directory outside both input trees. Human review stays pending.
"""
import argparse
from contextlib import closing
from datetime import datetime, timezone
import hashlib
import html
import json
from pathlib import Path, PurePosixPath
import random
import shutil
import subprocess
import tempfile

import numpy as np
from PIL import Image, ImageDraw
import torch

try:
    from bundle_io import ViewReader
except ModuleNotFoundError as exc:
    # Development copy: script/updated. Packaged copy: script/.
    if exc.name != "bundle_io":
        raise
    import sys
    sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
    from bundle_io import ViewReader
from fetch_shared_subset import REPO, REVISION, PREFIX
from validate_freihand import check_source_manifest

SCHEMA_VERSION = "hand-warehouse/1.1"
RELEASE_ID = "shared-v1.1"
EDGES = [(0, b) for b in (1, 5, 9, 13, 17)] + [
    (b + j, b + j + 1) for b in (1, 5, 9, 13, 17) for j in range(3)]


def relative_path(value):
    if (not isinstance(value, str) or not value or "\\" in value or ":" in value or
            any(part in ("", ".", "..") for part in value.split("/"))):
        raise ValueError(f"Not a relative POSIX path: {value!r}")
    path = PurePosixPath(value)
    if path.is_absolute():
        raise ValueError(f"Not a relative POSIX path: {value!r}")
    return path


def safe_path(root, value):
    root = Path(root).resolve()
    path = (root / relative_path(value)).resolve()
    if not path.is_relative_to(root):
        raise ValueError(f"Reference escapes its input tree: {value}")
    return path


def file_hashes(path):
    size = path.stat().st_size
    sha = hashlib.sha256()
    git = hashlib.sha1(b"blob " + str(size).encode() + b"\0")
    with path.open("rb") as stream:
        for block in iter(lambda: stream.read(4 << 20), b""):
            sha.update(block)
            git.update(block)
    return {"size": size, "sha256": sha.hexdigest(), "git_blob_sha1": git.hexdigest()}


def source_entries(path):
    manifest = json.loads(Path(path).read_text())
    check_source_manifest(manifest)
    if (manifest.get("repo"), manifest.get("revision"), manifest.get("source_prefix")) != (
            REPO, REVISION, PREFIX.rstrip("/")):
        raise ValueError("Source manifest does not bind the expected fixed FreiHAND release")
    entries = {}
    for entry in manifest["files"]:
        name = str(relative_path(entry["relative_path"]))
        if entry.get("path") != PREFIX + name or name in entries:
            raise ValueError(f"Invalid or duplicate source-manifest entry: {name}")
        if entry.get("digest_algorithm") not in ("sha256", "git_blob_sha1"):
            raise ValueError(f"Unsupported source digest: {name}")
        entries[name] = entry
    return entries


def verify_source(path, name, entries):
    if name not in entries:
        raise ValueError(f"File is not in the fixed source manifest: {name}")
    entry, actual = entries[name], file_hashes(path)
    if actual["size"] != entry["size"] or actual[entry["digest_algorithm"]] != entry["digest"]:
        raise ValueError(f"Fixed-source digest mismatch: {name}")
    return {"relative_path": name, **actual}


def check_output(output, release, media_root):
    output = Path(output)
    if output.exists() or output.is_symlink():
        raise FileExistsError(f"Refusing to overwrite an existing output: {output}")
    output = output.resolve()
    for root in (Path(release).resolve(), Path(media_root).resolve()):
        if output.is_relative_to(root) or root.is_relative_to(output):
            raise ValueError("Review output must be a new directory outside both input trees")
    if "shared-v1.0" in output.parts:
        raise ValueError("v1.1 review output cannot be placed in a v1.0 release")
    return output


def probe_video(path, storage, image_size):
    result = subprocess.run(["ffprobe", "-v", "error", "-show_streams", "-of", "json", str(path)],
                            check=True, capture_output=True, text=True)
    streams = [s for s in json.loads(result.stdout)["streams"] if s["codec_type"] == "video"]
    if len(streams) != 1:
        raise ValueError(f"Expected exactly one video stream: {path}")
    stream = streams[0]
    size = [stream["width"], stream["height"]]
    if size != list(image_size) or size != storage["encoded_size"]:
        raise ValueError(f"Video dimensions disagree with metainfo: {path}: {size}")
    if stream["codec_name"] != storage["codec"] or stream["pix_fmt"] != storage["pixel_format"]:
        raise ValueError(f"Video codec/native pixel format disagrees with metainfo: {path}")
    rotations = [s.get("rotation", 0) for s in stream.get("side_data_list", [])]
    rotations.append(stream.get("tags", {}).get("rotate", 0))
    if any(float(angle) % 360 for angle in rotations):
        raise ValueError(f"Unsupported video rotation: {path}")
    return {key: stream[key] for key in ("codec_name", "pix_fmt", "width", "height")}


def decode_frames(path, pixel_format, width, height, count):
    """Stream native gray data, then widen uint8 to uint16 without FFmpeg scaling."""
    if pixel_format not in ("rgb24", "gray", "gray16le"):
        raise ValueError(f"Unsupported decoded pixel format: {pixel_format}")
    dtype = np.dtype("<u2" if pixel_format == "gray16le" else "u1")
    shape = (height, width, 3) if pixel_format == "rgb24" else (height, width)
    frame_bytes = int(np.prod(shape)) * dtype.itemsize
    command = ["ffmpeg", "-nostdin", "-v", "error", "-threads", "1", "-filter_threads", "1",
               "-noautorotate", "-i", str(path), "-map", "0:v:0", "-an", "-sn", "-dn", "-vsync", "0",
               "-pix_fmt", pixel_format, "-f", "rawvideo", "-threads", "1", "pipe:1"]
    with tempfile.TemporaryFile() as errors:
        process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=errors)
        try:
            for index in range(count):
                data = process.stdout.read(frame_bytes)
                if len(data) != frame_bytes:
                    raise ValueError(f"Too few or truncated video frames: {path}, frame {index}/{count}")
                frame = np.frombuffer(data, dtype=dtype).reshape(shape)
                yield frame if pixel_format == "rgb24" else frame.astype(np.uint16)
            if process.stdout.read(1):
                raise ValueError(f"Too many video frames: {path}, expected {count}")
            if process.wait() != 0:
                errors.seek(0)
                raise RuntimeError(f"Video decoder failed: {errors.read().decode(errors='replace')}")
        finally:
            process.stdout.close()
            if process.poll() is None:
                process.terminate()
                try:
                    process.wait(timeout=2)
                except subprocess.TimeoutExpired:
                    process.kill()
                    process.wait()


def validate_mask(mask, component, record, frame_index, valid):
    if mask.dtype != np.uint16:
        raise ValueError("Mask must be losslessly promoted to uint16")
    schema = component["schema_id"]
    if schema == "segment/foreground_intensity/v1":
        if (int(mask.max()) > 255 or component.get("value_range") != [0, 255] or
                component.get("normalization_scale") != 1 / 255 or
                component.get("foreground_category") != "hand" or component.get("entity_id") != "hand_right"):
            raise ValueError(f"Invalid FreiHAND foreground-intensity semantics at frame {frame_index}")
        return {}
    if schema != "segment/uint16_labels/v1" or record is None or record.get("frame_index") != frame_index:
        raise ValueError(f"Missing or misaligned region mapping at frame {frame_index}")
    mapping = {}
    for label in record["labels"]:
        code = label["mask_value"]
        if type(code) is not int or not 1 <= code <= 65534 or code in mapping:
            raise ValueError(f"Invalid, duplicate or reserved mapped code at frame {frame_index}: {code}")
        if not all(key in label for key in ("category_id", "entity_id", "part_id")):
            raise ValueError(f"Incomplete region mapping at frame {frame_index}")
        category = label["category_id"]
        if (category not in ("hand", "background") or label["part_id"] is not None or
                label["entity_id"] != ("hand_right" if category == "hand" else None)):
            raise ValueError(f"Unverified FreiHAND region meaning at frame {frame_index}: {label}")
        mapping[code] = label
    unknown = set(map(int, np.unique(mask))) - {0, 65535} - mapping.keys()
    if unknown:
        raise ValueError(f"Unmapped mask codes at frame {frame_index}: {sorted(unknown)} (valid={valid})")
    return mapping


def mask_image(mask, component, mapping):
    if component["schema_id"] == "segment/foreground_intensity/v1":
        return Image.fromarray(mask.astype(np.uint8)).convert("RGB")
    colors = np.zeros((*mask.shape, 3), np.uint8)
    colors[mask == 0] = (110, 110, 110)
    colors[mask == 65535] = (255, 0, 255)
    for code, label in mapping.items():
        if label["category_id"] == "hand":
            # Native code colors do not assign unverified finger names.
            colors[mask == code] = (40 + code * 47 % 200, 40 + code * 83 % 200, 40 + code * 29 % 200)
    return Image.fromarray(colors)


def project_keypoints(intrinsic, xyz, point_valid, intrinsic_valid):
    uv = np.full((2, 21, 2), np.nan)
    usable = point_valid.copy() if intrinsic_valid else np.zeros_like(point_valid)
    if usable.any():
        projected = xyz[usable].astype(np.float64) @ intrinsic.astype(np.float64).T
        if not np.isfinite(projected).all() or (projected[:, 2] <= 0).any():
            raise ValueError("Valid keypoints cannot be projected with finite positive camera depth")
        uv[usable] = projected[:, :2] / projected[:, 2, None]
        if not np.isfinite(uv[usable]).all():
            raise ValueError("Non-finite keypoint projection")
    return uv, usable


def render_panel(rgb, mask, component, mapping, uv, usable, rgb_valid, mask_valid):
    width, height = rgb.shape[1], rgb.shape[0]
    projected = Image.fromarray(rgb.copy())
    draw = ImageDraw.Draw(projected)
    if rgb_valid:
        for hand in range(2):
            for a, b in EDGES:
                if usable[hand, a] and usable[hand, b]:
                    draw.line([tuple(uv[hand, a]), tuple(uv[hand, b])], fill=(255, 200, 0), width=1)
            for x, y in uv[hand, usable[hand]]:
                if 0 <= x < width and 0 <= y < height:
                    draw.ellipse((x - 2, y - 2, x + 2, y + 2), fill=(255, 30, 40))
    panel = Image.new("RGB", (width * 3, height + 30), "white")
    images = [Image.fromarray(rgb), mask_image(mask, component, mapping), projected]
    titles = [f"RGB (valid={rgb_valid})", f"Mask (valid={mask_valid})", "RGB + native XYZ"]
    for column, (image, title) in enumerate(zip(images, titles)):
        panel.paste(image, (column * width, 30))
        ImageDraw.Draw(panel).text((column * width + 3, 8), title, fill="black")
    return panel


def check_numeric(data, valid, shape, valid_shape, name):
    if (data.dtype != torch.float32 or tuple(data.shape) != shape or valid.dtype != torch.bool or
            tuple(valid.shape) != valid_shape or data.device.type != "cpu" or valid.device.type != "cpu"):
        raise ValueError(f"Wrong numeric dtype, shape or device: {name}")
    if not torch.isfinite(data[valid]).all() or not torch.isnan(data[~valid]).all():
        raise ValueError(f"Numeric data/valid disagreement: {name}")


def sample_indices(total, count, seed):
    if count <= 0:
        raise ValueError("--samples-per-view must be positive")
    count = min(total, count)
    selected = {0}
    if count > 1:
        selected.add(total - 1)
    selected.update(random.Random(seed).sample(sorted(set(range(total)) - selected), count - len(selected)))
    return sorted(selected)


def json_write(path, value):
    path.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n", encoding="utf-8")


def check_view(release, media_root, view, entries, output, seed, samples_per_view):
    view_path = safe_path(release, view)
    reader = ViewReader(view_path)
    meta, components = reader.meta, reader.meta["components"]
    total = meta["num_frames"]
    if (meta.get("schema_version") != SCHEMA_VERSION or meta.get("release_id") != RELEASE_ID or
            meta.get("dataset_id") != "FreiHAND" or type(total) is not int or total <= 0 or
            meta.get("hand_slots") != ["left", "right"] or meta["camera"]["model"] != "pinhole"):
        raise ValueError(f"Unsupported view metadata: {view}")
    if view != f'data/{meta["sequence_id"]}/{meta["camera_id"]}':
        raise ValueError(f"View identity disagrees with its path: {view}")
    xyz_component = components["keypoints_xyz"]
    if (xyz_component.get("schema_id") != "keypoints/xyz/v1" or
            xyz_component.get("keypoint_schema") != "mano21/v1" or
            xyz_component.get("unit") != "m" or xyz_component.get("coordinate_frame") != "camera" or
            components["intrinsic"].get("schema_id") != "camera/pinhole/v1"):
        raise ValueError(f"Unsupported camera/keypoint semantics: {view}")
    for name in ("intrinsic", "keypoints_xyz", "rgb", "segment"):
        component = components[name]
        if component.get("available") is not True:
            raise ValueError(f"Required component is unavailable: {view}/{name}")
        for key in ("data_ref", "valid_ref"):
            safe_path(view_path, component[key])
    intrinsic, intrinsic_valid = reader.numeric("intrinsic")
    xyz, point_valid = reader.numeric("keypoints_xyz")
    check_numeric(intrinsic, intrinsic_valid, (total, 3, 3), (total,), "intrinsic")
    check_numeric(xyz, point_valid, (total, 2, 21, 3), (total, 2, 21), "keypoints_xyz")
    intrinsic, intrinsic_valid, xyz, point_valid = [x.numpy() for x in (intrinsic, intrinsic_valid, xyz, point_valid)]
    bound = []
    frames_ref = meta["sampling"]["frames_ref"]
    frames_path = safe_path(view_path, frames_ref)
    bound.append(verify_source(frames_path, view + "/" + frames_ref, entries))
    rows = [json.loads(line) for line in frames_path.read_text().splitlines()]
    if (len(rows) != total or any(row["frame_index"] != i for i, row in enumerate(rows)) or
            len({row["sample_id"] for row in rows}) != total):
        raise ValueError(f"Incomplete or misaligned frame table: {view}")
    media, validity, probes = {}, {}, {}
    for name in ("rgb", "segment"):
        component = components[name]
        if "data_key" in component or "valid_key" in component:
            raise ValueError("Media and standalone validity must not use bundle keys")
        valid_path = safe_path(view_path, component["valid_ref"])
        bound.append(verify_source(valid_path, view + "/" + component["valid_ref"], entries))
        valid = reader.validity(name)
        if valid.dtype != torch.bool or tuple(valid.shape) != (total,):
            raise ValueError(f"Invalid independent media validity: {view}/{name}")
        validity[name] = valid.numpy()
        name_in_tree = view + "/" + component["data_ref"]
        media[name] = safe_path(media_root, name_in_tree)
        bound.append(verify_source(media[name], name_in_tree, entries))
        probes[name] = probe_video(media[name], component["storage"], meta["camera"]["image_size"])
    segment = components["segment"]
    mask_pixel_format = segment["storage"]["pixel_format"]
    if mask_pixel_format not in ("gray", "gray16le") or segment["storage"]["codec"] != "ffv1":
        raise ValueError("Masks require native gray or gray16le FFV1")
    expected_schema = "segment/foreground_intensity/v1" if meta["split"] == "train" else "segment/uint16_labels/v1"
    if segment["schema_id"] != expected_schema or segment["storage"]["profile"] != "mkv/uint16_ffv1/v1":
        raise ValueError("Split and mask semantics do not match")
    mapping_rows = [None] * total
    if segment["schema_id"] == "segment/uint16_labels/v1":
        mapping_ref = segment["mapping_ref"]
        mapping_path = safe_path(view_path, mapping_ref)
        bound.append(verify_source(mapping_path, view + "/" + mapping_ref, entries))
        mapping_rows = [json.loads(line) for line in mapping_path.read_text().splitlines()]
        if len(mapping_rows) != total:
            raise ValueError(f"Region mapping frame count differs: {view}")
    selected = set(sample_indices(total, samples_per_view, seed))
    samples, values = [], set()
    rgb_hash, mask_hash = hashlib.sha256(), hashlib.sha256()
    width, height = meta["camera"]["image_size"]
    projected_points = out_of_image = 0
    snapshots = {name: (path.stat().st_size, path.stat().st_mtime_ns) for name, path in media.items()}
    with closing(decode_frames(media["rgb"], "rgb24", width, height, total)) as rgbs, closing(
            decode_frames(media["segment"], mask_pixel_format, width, height, total)) as masks:
        for index, (rgb, mask) in enumerate(zip(rgbs, masks, strict=True)):
            mask_valid = bool(validity["segment"][index])
            mapping = validate_mask(mask, segment, mapping_rows[index], index, mask_valid)
            values.update(map(int, np.unique(mask)))
            uv, usable = project_keypoints(intrinsic[index], xyz[index], point_valid[index], intrinsic_valid[index])
            projected_points += int(usable.sum())
            points = uv[usable]
            out_of_image += int(((points[:, 0] < 0) | (points[:, 0] >= width) |
                                 (points[:, 1] < 0) | (points[:, 1] >= height)).sum())
            rgb_bytes, mask_bytes = rgb.tobytes(), mask.astype("<u2", copy=False).tobytes()
            rgb_hash.update(rgb_bytes)
            mask_hash.update(mask_bytes)
            if index in selected:
                name = view.replace("/", "__") + f"__{index:06d}.png"
                render_panel(rgb, mask, segment, mapping, uv, usable, bool(validity["rgb"][index]), mask_valid).save(output / name)
                samples.append({"view": view, "sample_id": rows[index]["sample_id"], "frame_index": index,
                                "preview": name, "rgb_valid": bool(validity["rgb"][index]), "mask_valid": mask_valid,
                                "rgb_sha256": hashlib.sha256(rgb_bytes).hexdigest(),
                                "mask_uint16_sha256": hashlib.sha256(mask_bytes).hexdigest()})
    if any((path.stat().st_size, path.stat().st_mtime_ns) != snapshots[name] for name, path in media.items()):
        raise ValueError(f"Media changed during review: {view}")
    inputs = sorted({"metainfo.json", components["intrinsic"]["data_ref"], xyz_component["data_ref"]})
    return {"view": view, "frames_checked": total, "complete_view_checked": True,
            "pixel_formats": probes, "mask_schema": segment["schema_id"], "observed_mask_values": sorted(values),
            "valid_rgb_frames": int(validity["rgb"].sum()), "valid_mask_frames": int(validity["segment"].sum()),
            "projected_keypoints": projected_points, "projected_keypoints_outside_image": out_of_image,
            "rgb_all_frames_sha256": rgb_hash.hexdigest(), "mask_all_frames_uint16_sha256": mask_hash.hexdigest(),
            "fixed_source_files": bound, "bundle_inputs": [{"relative_path": view + "/" + p,
                **file_hashes(safe_path(view_path, p))} for p in inputs], "display_samples": samples}


def write_html(output, report):
    cards = []
    for view in report["views"]:
        for sample in view["display_samples"]:
            cards.append(f'<section><h2>{html.escape(sample["sample_id"])}</h2>'
                         f'<p>{html.escape(sample["view"])} · frame {sample["frame_index"]}</p>'
                         f'<img src="{html.escape(sample["preview"])}" alt="RGB, mask, and XYZ projection"></section>')
    text = ('<!doctype html><html lang="zh-CN"><meta charset="utf-8">'
            '<title>FreiHAND v1.1 shared 视觉验收</title><style>'
            'body{font:16px system-ui;max-width:1100px;margin:32px auto;padding:0 16px;color:#18232f}'
            'section{margin:24px 0;padding:12px;background:#f3f5f7}img{max-width:100%;height:auto}</style>'
            '<h1>FreiHAND v1.1:完整分片检查与抽样展示</h1>'
            f'<p>自动检查:{report["frames_checked"]} 帧、{len(report["views"])} 个完整视图。'
            f'展示:{report["displayed_frames"]} 帧,包含首帧;每视图展示至少两帧时包含尾帧,'
            f'其余用固定种子 {report["seed"]} 抽样。'
            '抽样展示不等于人工看过完整分片,不能估计全量错误率。</p>'
            '<p><strong>人工验收:pending,尚待确认。</strong>本报告不宣称完整数据集可发布。</p>'
            '<p>每行依次是 RGB、独立 mask、RGB + 原生 XYZ 投影。训练 mask 为 0–255 灰度强度;'
            '评估 mask 用颜色区分原生区域码,不推断手指名称。评估黑色是明确映射的背景,'
            '灰色是未分配码 0,洋红是忽略码 65535。左右手投影遵循 valid,不用缺失标注补图。</p>'
            '<p>检查图片与标注对应、投影方向和尺度、分割边缘。数据只来自固定源 shared 媒体及新 bundle;'
            '未读取 raw,未调用 MANO 模型,也未在此报告中重做 raw 语义转换验收。</p>'
            '<p><a href="report.json">机器报告、完整检查范围和文件摘要</a></p>' + ''.join(cards) + '</html>')
    (output / "index.html").write_text(text, encoding="utf-8")


def run_review(release, media_root, source_manifest, output, views, seed=20261013, samples_per_view=12):
    release, media_root = Path(release).resolve(), Path(media_root).resolve()
    output = check_output(output, release, media_root)
    if not release.is_dir() or not media_root.is_dir():
        raise FileNotFoundError("Both --release and --media-root must exist")
    if not shutil.which("ffmpeg") or not shutil.which("ffprobe"):
        raise RuntimeError("FFmpeg and ffprobe are required")
    torch.set_num_threads(1)
    entries = source_entries(source_manifest)
    selected = [str(relative_path(view)) for view in views]
    if not selected or len(set(selected)) != len(selected):
        raise ValueError("Select one or more distinct complete views")
    source_views = {str(PurePosixPath(name).parent) for name in entries
                    if name.startswith("data/") and len(PurePosixPath(name).parts) == 4 and name.endswith("/metainfo.json")}
    for view in selected:
        if view not in source_views:
            raise ValueError(f"Selected view is absent from the fixed source manifest: {view}")
        siblings = {v for v in source_views if PurePosixPath(v).parent == PurePosixPath(view).parent}
        if not siblings.issubset(selected):
            raise ValueError(f"Select all cameras for a representative sequence: {sorted(siblings)}")
    report = {"schema_version": SCHEMA_VERSION, "release_id": RELEASE_ID,
              "status": "running", "human_review": "pending", "full_release_ready": False,
              "source_repo": REPO, "source_revision": REVISION,
              "source_manifest_sha256": file_hashes(Path(source_manifest))["sha256"],
              "script_sha256": file_hashes(Path(__file__))["sha256"],
              "started_utc": datetime.now(timezone.utc).isoformat(), "seed": seed,
              "scope": "All frames of selected complete shared views; sampled display; no raw or MANO rendering.",
              "ffmpeg_version": subprocess.check_output(["ffmpeg", "-version"], text=True).splitlines()[0],
              "selected_views": selected, "views": [], "frames_checked": 0, "displayed_frames": 0}
    output.mkdir(parents=True, exist_ok=False)
    json_write(output / "report.json", report)
    try:
        for view in selected:
            print(f"Checking complete view: {view}", flush=True)
            result = check_view(release, media_root, view, entries, output, seed, samples_per_view)
            report["views"].append(result)
            report["frames_checked"] += result["frames_checked"]
            report["displayed_frames"] += len(result["display_samples"])
            json_write(output / "report.json", report)
        report["status"] = "automated_checks_passed_human_review_pending"
        report["completed_utc"] = datetime.now(timezone.utc).isoformat()
        json_write(output / "report.json", report)
        write_html(output, report)
    except Exception as exc:
        report["status"] = "failed"
        report["error"] = f"{type(exc).__name__}: {exc}"
        json_write(output / "report.json", report)
        raise
    return report


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--release", type=Path, required=True)
    parser.add_argument("--media-root", type=Path, required=True,
                        help="External shared tree containing media at matching data/... paths")
    parser.add_argument("--source-manifest", type=Path, required=True)
    parser.add_argument("--output", type=Path, required=True,
                        help="New independent v1.1 evidence directory outside both input trees; never overwritten")
    parser.add_argument("--views", action="append", required=True,
                        help="Complete view relative to shared root, e.g. data/training_00118784/camera; repeatable")
    parser.add_argument("--seed", type=int, default=20261013)
    parser.add_argument("--samples-per-view", type=int, default=12)
    args = parser.parse_args()
    report = run_review(**vars(args))
    print(json.dumps({key: report[key] for key in ("status", "frames_checked", "displayed_frames", "human_review")},
                     ensure_ascii=False))
    print(args.output.resolve() / "index.html")


if __name__ == "__main__":
    main()