File size: 65,440 Bytes
4139386
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
#!/usr/bin/env python3
"""Render sampled RHD shared-v1.1 views to self-contained HTML review pages.

CONTRACT 6.5 keeps "the repackaging preserved the bytes" apart from "a human looked
at it".  The published H2O and dex-ycb sets carry sampled per-view pages for the
second half, and ARCTIC's v1.1 release carries them too; this gives RHD the same
artifact, written against the v1.1 layout rather than ported from any of them:

* every value is read through the released reader -- ``Registry``/``BundleReader``
  plus ``rhd_common.check_view``, the calls ``validate.py`` and ``read_sequence.py``
  already make -- so a page shows what the release declares rather than a re-derived
  copy of it.  ``data_key`` in a component, the same split those two use, marks a
  bundled numeric field; media and JSONL are read as the preserved files they are.
* the v1.0 renderer (``v1_0_snapshot/script/render_full_random_review.py``) read
  ``annotation/keypoints/*.pt`` directly and required ``raw/RHD_v1-1.zip`` to
  re-check the pixels against the source.  Neither applies here: this reads the v1.1
  bundles, and the raw archive is not on this machine.  The panels below are that
  renderer's own vocabulary and panel set, re-pointed at the bundles.
* RHD uniquely publishes **both** the native 2D keypoints (``uv``) and the
  camera-frame 3D keypoints (``xyz``) with the same pinhole K, so unlike the other
  releases this page can run the published ``projection_qc``: it projects the saved
  xyz through the view's own intrinsic and compares the result with the saved uv.
  ARCTIC has no uv series and dex-ycb no xyz, so neither could.  The deviation is
  recorded per frame (median / max pixels, counts within 1 px and 3 px) and stated in
  the caption, never used to "fix" the published values.
* ``visibility`` is drawn as the release declares it: solid marker where the source
  says the joint is visible, hollow where it is not.  It is a bundled attribute of
  both keypoint components -- one shared leaf -- and the page reads it once.

Every page is one self-contained file (PNG previews as base64 data URIs, no script,
no external reference), and the sampled frames are the only pixels decoded.

Run -- the ordering matters, see the 收尾验收顺序 in README.md:
    python shared-v1.1/script/rhd_v1_1/render.py
"""

from __future__ import annotations

import argparse
import base64
import html
import io
import json
import multiprocessing
import os
import random
import subprocess
import sys
import time
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path

#: set before the sibling imports below, not inside main(): the first ``import
#: rhd_common`` is what would write a __pycache__ into the release tree, and it
#: happens while this module body runs.  The release must ship no bytecode cache, so
#: the switch has to be flipped before that line -- and inherited by the decoder
#: children, which re-import this module (os.environ, set in main, covers those)
sys.dont_write_bytecode = True

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

from rhd_common import BundleReader, check_view, load, save
from warehouse import Registry

PROJECTION_SCOPE = ("saved camera-frame xyz (metres) through the view's own pinhole "
                    "intrinsic, compared against the saved native uv; not a media pixel "
                    "comparison")
REPORT_SCOPE = ("v1.1 registry, keys, shapes, validity and timeline; not a media "
                "pixel comparison")
DECODE_SCOPE = ("ffmpeg select= demux filter over the preserved MKV; only the frames "
                "listed in selected_frames are decoded, each checked against its "
                "expected byte count")

#: Preview colours are RHD's own vocabulary rather than a new one.  The v1.0 review
#: renderer drew 左手 (255,90,70) and 右手 (30,180,255) and its pages state the same in
#: words -- 「颜色:红左手、蓝右手」 (doc/history-v1.0/validation/index.html, whose 24
#: sampled sheets ship with this release).  Those pages are in the tree, so a reviewer
#: may read the two side by side; reusing the vocabulary is what keeps that reading
#: correct.
HAND_COLORS = {"left": (255, 90, 70), "right": (30, 180, 255)}
#: The published ``source_index_map`` ([0,4,3,2,1, 8,7,6,5, 12,11,10,9, 16,15,14,13,
#: 20,19,18,17]) walks the native RHD layout one finger at a time -- five joints for the
#: thumb, four for each other finger -- so consecutive registered indices within each
#: group are that finger's chain.  The lines below trace those groups to make the pose
#: legible at 320x320, where 21 joints of a hand 50 px across otherwise merge into an
#: unreadable blob.  This is a reading of the published map for the reviewer's benefit:
#: the release itself declares joint *order*, not a skeleton, and the page does not claim
#: otherwise.
FINGER_CHAINS = ((0, 1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16),
                 (17, 18, 19, 20))
#: the segment mask's region ids, from the release's own mapping: 1 person, 2-17 left
#: hand, 18-33 right hand, background released as 65534
SEGMENT_RANGES = {"left": (2, 17), "right": (18, 33)}
SEGMENT_COLORS = {"left": np.array([255, 90, 70], np.uint8),
                  "right": np.array([30, 180, 255], np.uint8)}
#: RHD annotates **both** hands in every image and normally renders only one of them
#: inside the 320x320 frame; the source marks each joint with ``visibility``, which is
#: essentially "this joint lies inside the picture" plus occlusion (measured: on four
#: full views ``visibility`` agrees with "the published uv lies inside the frame" on
#: 97.0-97.9% of joints, and *every* disagreement is an in-frame joint marked
#: invisible -- a joint marked visible while lying outside the frame is 0-1 in 21,504).
#: So a page whose sampled frames sit near ``in_frame`` 0.5 is showing the dataset's
#: normal shape, not a defect, and the note below says so with the measured numbers.
#:
#: The other half of the same fact: the published ``uv`` is the *raw* projection, so a
#: joint can lie arbitrarily far outside the picture, and a hand close to the camera
#: plane has a published uv in the millions of pixels -- at z = 1e-4 m the projection of
#: a point half a metre off axis really is ~1e6 px.  Those are source values, not
#: errors, but they make an absolute pixel tolerance meaningless outside the frame: a
#: 6,246 px "deviation" on a coordinate of 15.24 million px is a 4e-4 relative one.
#: Hence the scan below splits the joints into the ones whose uv lies inside the frame
#: (checked in pixels) and the ones outside it (checked against their own magnitude),
#: and counts the joints that cannot be projected at all.
VISIBILITY_RULE = ("发布的 uv 是原始投影值,画外关节的坐标可以任意大;本页按发布的 uv 是否"
                   "落在画内分两组核验——画内点按像素偏差、画外点按相对自身量级的偏差,另"
                   "单列\"源标为可见却落在画外\"的点数(该方向才可能是标注与标定不一致)")
#: a sampled frame carrying any joint that the source marks visible while its published
#: uv lies outside the picture is called out by frame number in the header
VISIBLE_OUTSIDE_TOLERANCE = 0
#: depth at or below which the projection is not compared in pixels: below a millimetre
#: the published uv is itself in the 1e5 px range, where a pixel tolerance says nothing
#: about agreement.  Points under it are counted, not dropped.
PLANE_THRESHOLD_M = 1e-3
#: the tolerance the captions quote for the in-frame xyz-vs-uv agreement
UV_TOLERANCE_PX = 1.0
#: one frame_index -> one row of camera/frames.jsonl, the same ref validate.py reads
FRAMES_REF = "camera/frames.jsonl"


# -- helpers carried from the published v1.0 renderer -----------------------


def decode(path: Path, indices, pix_fmt: str, dtype, width: int, height: int,
           channels: int):
    """Decode exactly the requested frames of a preserved video.

    Same recipe as the published renderer (``HAND_WAREHOUSE_FFMPEG_THREADS``, one
    decoder thread by default), with ``select=`` so a 512-frame stream is not read end
    to end for a handful of stills.  The byte count is checked rather than trusted: a
    short read would silently misalign every frame after it, and ``-vsync 0`` plus an
    explicit ``-frames:v`` is what makes ``select=`` yield exactly ``len(indices)``
    frames.
    """
    order = sorted(indices)
    select = "+".join(f"eq(n\\,{index})" for index in order)
    threads = os.environ.get("HAND_WAREHOUSE_FFMPEG_THREADS", "1")
    argv = ["ffmpeg", "-v", "error", "-nostdin", "-filter_threads", threads,
            "-threads", threads, "-noautorotate", "-i", str(path), "-map", "0:v:0",
            "-vf", f"select={select}", "-vsync", "0", "-frames:v", str(len(order)),
            "-threads", threads, "-f", "rawvideo", "-pix_fmt", pix_fmt, "-"]
    raw = subprocess.run(argv, capture_output=True, check=True).stdout
    #: rawvideo is bytes, so the count is elements times the itemsize -- a 16-bit
    #: mask yields two bytes per pixel, and getting that wrong would silently reshape
    #: the stream instead of failing
    expected = (len(order) * height * width * channels * np.dtype(dtype).itemsize)
    if len(raw) != expected:
        raise ValueError(f"{path}: decoded {len(raw)} bytes, expected {expected}")
    frames = np.frombuffer(raw, dtype=dtype).reshape(len(order), height, width, channels)
    return {index: frames[position].copy() for position, index in enumerate(order)}


def snapshot(path: Path, indices, width: int, height: int):
    """RGB frames of a preserved MKV, keyed by frame index."""
    return decode(path, indices, "rgb24", np.uint8, width, height, 3)


def picture(image: Image.Image) -> str:
    """A preview as a data URI.  Released tensors and videos are never resized."""
    image = image.copy()
    image.thumbnail((800, 450))
    output = io.BytesIO()
    image.save(output, format="PNG")
    return ('<img loading="lazy" src="data:image/png;base64,'
            + base64.b64encode(output.getvalue()).decode() + '">')


def depth_image(packed: np.ndarray, width: int) -> np.ndarray:
    """The float32 z depth of one frame, unpacked from its two uint16 half-words.

    The release stores the bit pattern of a float32 as two columns of uint16 (low half
    left, high half right, ``mkv/depth_float32_bits/v1``), exactly as ``RAW_MAPPING.md``
    describes and as the v1.0 renderer read it.  ``packed`` is the decoded row of
    2*width uint16 values.
    """
    low = packed[:, :width].astype(np.uint32)
    high = packed[:, width:].astype(np.uint32)
    return (low | (high << 16)).view(np.float32)


def select_frames(n: int, valids, media_valid, extra=()):
    """The published sampling policy, driven by the release's own validity.

    Quarter points plus both ends, plus the first frame each series is valid and the
    first it is not -- an invalid row is exactly what a reviewer wants to see once.
    ``extra`` carries frames the caller has already decided are worth seeing (this
    renderer passes the frame whose xyz-vs-uv deviation is largest in the whole view),
    so a page always shows the boundary case rather than only easy frames.  Truncated
    to twelve, and the last frame is always kept.
    """
    picks = {0, n // 4, n // 2, 3 * n // 4, n - 1} | {int(f) for f in extra}
    for valid in valids:
        if valid is None:
            continue
        flags = np.asarray(valid, dtype=bool).reshape(n, -1).any(axis=1)
        for present in (np.flatnonzero(flags), np.flatnonzero(~flags)):
            if len(present):
                picks.add(int(present[0]))
    if media_valid is not None:
        flags = np.asarray(media_valid, dtype=bool)
        for present in (np.flatnonzero(flags), np.flatnonzero(~flags)):
            if len(present):
                picks.add(int(present[0]))
    return sorted(set(sorted(picks)[:12]) | {n - 1})


def project(xyz, intrinsic, width: int, height: int):
    """Camera-frame xyz through the view's own pinhole intrinsic.

    ``uv = K @ xyz`` with the third component as the divisor -- the camera frame the
    release declares (``coordinate_frame: camera``), the pinhole model it declares
    (``camera.model: pinhole``, and no RHD view carries a distortion vector), and the
    same arithmetic the v1.0 renderer used.  Returns the pixel coordinates, a mask of
    points in front of the camera, and a mask of points inside the image.
    """
    image = xyz @ intrinsic.T
    with np.errstate(invalid="ignore", divide="ignore"):
        uv = image[..., :2] / image[..., 2:]
    front = np.isfinite(uv).all(axis=-1) & (image[..., 2] > 1e-6)
    inside = (front & (uv[..., 0] >= 0) & (uv[..., 0] < width)
              & (uv[..., 1] >= 0) & (uv[..., 1] < height))
    return uv, front, inside


def dot(painter: ImageDraw.ImageDraw, x: float, y: float, color, radius: int,
        filled: bool = True):
    """One joint: filled where the source marks it visible, hollow where it does not.

    Every marker carries a white ring, because the fill colour is drawn straight onto a
    hand whose pixels are a similar hue and a bare dot of this size disappears into it.
    """
    box = (x - radius, y - radius, x + radius, y + radius)
    if filled:
        painter.ellipse(box, fill=color, outline=(255, 255, 255), width=1)
    else:
        painter.ellipse(box, outline=color, width=2)


def draw_hand(painter: ImageDraw.ImageDraw, points, drawable, visible, color, radius):
    """One hand's joints on a panel: the finger chains, then the markers over them.

    ``points`` is the (21, 2) array to draw, ``drawable`` the joints that may be drawn
    at all (annotated, in front of the camera, inside the picture), and ``visible`` the
    source's per-joint flag.  Returns how many markers were drawn.
    """
    line_color = tuple(int(component * 0.55) for component in color)
    for chain in FINGER_CHAINS:
        run = [(float(points[joint, 0]), float(points[joint, 1]))
               for joint in chain if drawable[joint]]
        if len(run) > 1:
            painter.line(run, fill=line_color, width=max(1, radius // 2))
    drawn = 0
    for joint in range(len(points)):
        if not drawable[joint]:
            continue
        dot(painter, float(points[joint, 0]), float(points[joint, 1]), color, radius,
            filled=True if visible is None else bool(visible[joint]))
        drawn += 1
    return drawn


# -- per-view report --------------------------------------------------------


def numeric_records(view: Path, meta: dict, reader) -> dict:
    """One record per bundled numeric field, read through the released reader.

    ``check_view`` asserts these fields; this restates them for the report, so the two
    cannot disagree.  A bundled attribute (``visibility``) is recorded under the
    component that declares it, as ``validate.py`` and ``read_sequence.py`` name it;
    the registry fixes one entry, so both keypoint components report the same leaf.
    """
    records = {}
    for name, component in meta["components"].items():
        if not component.get("available", True) or "data_key" not in component:
            continue
        for owner, spec in [(name, component)] + [
                (f"{name}.{attribute}", attribute_spec)
                for attribute, attribute_spec in (component.get("attributes") or {}).items()]:
            data, valid = reader.field(view, spec)
            records[owner] = {
                "shape": list(data.shape), "dtype": str(data.dtype),
                "valid_true": int(valid.sum()), "valid_total": int(valid.numel()),
                "nan_count": (int(torch.isnan(data).sum())
                              if data.is_floating_point() else None),
            }
    return records


def view_report(view: Path, meta: dict, fields: dict, consumed: set, selected: list,
                projection: dict, media: list) -> dict:
    """The published report shape, composed from the released checker's evidence."""
    bundles = sorted({component["data_ref"] for component in meta["components"].values()
                      if "data_key" in component})
    return {
        "view": f"{view.parent.name}/{view.name}",
        "sequence_id": meta["sequence_id"],
        "camera_id": meta["camera_id"],
        "view_type": meta["view_type"],
        "split": meta["split"],
        "num_frames": meta["num_frames"],
        "camera": {"model": meta["camera"]["model"],
                   "schema_id": meta["camera"]["schema_id"],
                   "image_size": meta["camera"]["image_size"]},
        "numeric_components": fields,
        "bundle_files": len(bundles),
        "bundles": bundles,
        "media": media,
        "consumed_files": sorted(consumed),
        "selected_frames": selected,
        "decode_scope": DECODE_SCOPE,
        "projection": projection,
        "scope": REPORT_SCOPE,
    }


def colour_legend() -> str:
    """The colour vocabulary and what is deliberately not drawn, in one place."""
    def swatch(color, label: str) -> str:
        css = "rgb(" + ",".join(str(int(component)) for component in color) + ")"
        return ('<span class="swatch" style="background:' + css
                + '">&nbsp;&nbsp;&nbsp;</span> ' + html.escape(label))

    return ('<p class="legend">配色沿用 RHD v1.0 复核页自己的约定(「红左手、蓝右手」),'
            "便于与 <code>../history-v1.0/validation/</code> 里的 24 张抽查页并排读:"
            + " · ".join([swatch(HAND_COLORS["left"], "左手"),
                          swatch(HAND_COLORS["right"], "右手")])
            + "<br>手槽取自发布的 <code>hand_slots: [left, right]</code>,21 个关节保持"
              "发布的近端→远端顺序(<code>keypoint_schema: rhd21/v1</code>,"
              "原生 tip→palm 已按 <code>source_index_map</code> 重排)。RHD 的 21 点只"
              "统一其原生体系顺序,不宣称与 MANO 关节位置等价;release 里没有 MANO、"
              "没有物体、没有接触,这些面板也不画。</p>"
            '<p class="legend"><b>本页能做别人做不到的一件事</b>:RHD 同时发布了原生 2D '
            "关键点(<code>uv</code>)和相机系 3D 关键点(<code>xyz</code>)以及同一套"
            "针孔 <code>K</code>,所以第 4 个面板可以把 <code>xyz</code> 经该视图自己的 "
            "<code>K</code> 投到像素上,再与发布的 <code>uv</code> 逐点比对"
            "(H2O/dex-ycb/ARCTIC 都缺其中一条序列,做不了这项对照)。偏差记在每帧的"
            "<code>projection.frames</code> 里,面板标题上也会写出中位与最大偏离;"
            "<b>偏差只被记录,不用来「修正」发布值</b>。</p>")


# -- one view ---------------------------------------------------------------


def unmarked(reason: str) -> str:
    """Why a frame carries no geometry, stated rather than drawn as an empty panel."""
    return reason


def render_one(view: Path, destination: Path, root: Path) -> dict:
    registry = Registry.load(root / "doc/schema.json")
    meta = load(view / "metainfo.json")
    n = meta["num_frames"]
    width, height = meta["camera"]["image_size"]
    components = meta["components"]
    reader = BundleReader()
    #: the same structural check validate.py and read_sequence.py make; a page that
    #: skipped it could show a view the release's own reader rejects
    consumed = check_view(view, meta, registry, reader)
    fields = numeric_records(view, meta, reader)

    bundled = {name: reader.field(view, component)
               for name, component in components.items()
               if component.get("available", True) and "data_key" in component}
    intrinsic = bundled["intrinsic"]
    visibility = None
    attribute = (components["keypoints_xyz"].get("attributes") or {}).get("visibility")
    if attribute:
        visibility = reader.field(view, attribute)[0]

    rgb_valid = None
    if components["rgb"]["valid_ref"].endswith(".pt"):
        rgb_valid = torch.load(view / components["rgb"]["valid_ref"], map_location="cpu",
                               weights_only=True).numpy()

    #: The xyz-vs-uv agreement is pure tensor arithmetic, so it is taken over **every**
    #: frame of the view, not only the sampled ones -- a page that only checked its own
    #: five frames would say nothing about the other 507.  The same scan says which
    #: frame deviates most *inside the picture*, and that frame is forced into the
    #: sample below so a reviewer always sees the worst case next to the panels.
    uv_all = bundled["keypoints_uv"][0].numpy().astype(np.float64)
    xyz_all = bundled["keypoints_xyz"][0].numpy()
    intrinsic_all = intrinsic[0].numpy()
    projected_all = np.einsum("thjc,tdc->thjd", xyz_all, intrinsic_all)
    with np.errstate(invalid="ignore", divide="ignore"):
        pixels_all = projected_all[..., :2] / projected_all[..., 2:]
    depth_all = projected_all[..., 2]
    annotated_all = np.asarray(bundled["keypoints_xyz"][1].numpy(), dtype=bool)
    finite_all = np.isfinite(pixels_all).all(axis=-1)
    #: a point is projected only when the projection is finite and the depth is
    #: positive; a negative depth mirrors to a plausible-looking pixel otherwise
    behind_all = annotated_all & (depth_all <= 0)
    plate_all = annotated_all & (depth_all > 0) & (depth_all < PLANE_THRESHOLD_M) & finite_all
    comparable = (annotated_all & (depth_all >= PLANE_THRESHOLD_M) & finite_all
                  & np.isfinite(uv_all).all(axis=-1))
    deviation = np.linalg.norm(pixels_all - uv_all, axis=-1)
    #: in/out of the picture is decided from the published uv rather than from the
    #: projection, so the classification does not depend on the quantity being checked.
    #: The two agree to within the in-frame tolerance anyway (worst 0.161 px release-wide).
    in_frame = (comparable & (uv_all[..., 0] >= 0) & (uv_all[..., 0] < width)
                & (uv_all[..., 1] >= 0) & (uv_all[..., 1] < height))
    outside = comparable & ~in_frame
    #: the out-of-frame points flattened, each with the magnitude it is normalised by, so
    #: a reported ratio can always be read back as the absolute deviation it came from
    outside_dev = deviation[outside]
    outside_scale = np.abs(uv_all[outside]).max(axis=-1)
    outside_relative = outside_dev / np.maximum(outside_scale, 1.0)
    #: -1 marks a frame with nothing to compare inside the picture, so a frame that is
    #: entirely out of frame never wins the "worst frame" draw
    frame_max = np.where(in_frame, deviation, -1.0).reshape(n, -1).max(axis=1)
    seen_all = visibility.numpy() if visibility is not None else np.ones_like(comparable)
    worst = int(np.argmax(frame_max))

    #: every bundled field drives the sampling, in a fixed order so two runs of this
    #: script agree: a field whose validity starts later than the quarter points pulls
    #: its first valid frame in as well
    selected = select_frames(n,
                             [valid.numpy().reshape(n, -1).any(axis=1)
                              for _, (_, valid) in sorted(bundled.items())],
                             rgb_valid, extra=(worst,))
    frames = {row["frame_index"]: row for row in
              (json.loads(line) for line in
               (view / FRAMES_REF).read_text(encoding="utf-8").splitlines() if line.strip())}

    rgb = snapshot(view / components["rgb"]["data_ref"], selected, width, height)
    masks = decode(view / components["segment"]["data_ref"], selected, "gray16le",
                   np.uint16, width, height, 1)
    #: the depth video is the float32 bit pattern split into two 16-bit halves side by
    #: side, so its declared encoded width is twice the picture's
    packed = decode(view / components["depth"]["data_ref"], selected, "gray16le",
                    np.uint16, 2 * width, height, 1)
    depth_valid = decode(view / components["depth"]["valid_ref"], selected, "gray",
                         np.uint8, width, height, 1)

    radius = max(2, round(width * 0.008))
    in_frame_dev = deviation[in_frame]
    visible_outside_mask = annotated_all & seen_all & outside
    view_scan = {
        "frames_scanned": int(n),
        "points_scanned": int(annotated_all.sum()),
        #: the joints that cannot be compared in pixels at all, counted rather than
        #: dropped: at or behind the camera plane, and within a millimetre of it
        "behind_plane_points": int(behind_all.sum()),
        "near_plane_points": int(plate_all.sum()),
        "comparable_points": int(comparable.sum()),
        "in_frame_points": int(in_frame.sum()),
        "outside_frame_points": int(outside.sum()),
        #: a selection with nothing in it reports null rather than a number computed
        #: from no points at all
        "median_px": (round(float(np.median(in_frame_dev)), 4) if in_frame_dev.size else None),
        "in_frame_max_px": (round(float(in_frame_dev.max()), 4) if in_frame_dev.size else None),
        "frames_with_in_frame_points": int((frame_max >= 0).sum()),
        "frames_all_in_frame_points_within_1px": int(
            ((frame_max >= 0) & (frame_max <= UV_TOLERANCE_PX)).sum()),
        #: out-of-frame points are compared against their own magnitude: their published
        #: uv is the raw projection and can be millions of pixels wide.  Each extreme is
        #: reported together with the point that attained it, because the two extremes
        #: are different points and neither number means anything alone -- 14.6 px is
        #: 2e-4 of a 7.6e4 px coordinate, while the worst ratio of 2.2e-2 belongs to a
        #: point only 2.6 px from the origin whose absolute deviation is 0.057 px
        "outside_frame_within_1px": int((outside_dev <= UV_TOLERANCE_PX).sum()),
        "outside_frame_max_px": (round(float(outside_dev.max()), 4)
                                 if outside_dev.size else None),
        "outside_frame_max_px_uv_scale": (round(float(outside_scale[outside_dev.argmax()]), 4)
                                          if outside_dev.size else None),
        "outside_frame_max_relative": (float(f"{outside_relative.max():.3g}")
                                       if outside_dev.size else None),
        "outside_frame_max_relative_px": (round(float(outside_dev[outside_relative.argmax()]), 4)
                                          if outside_dev.size else None),
        "outside_frame_max_relative_uv_scale": (
            round(float(outside_scale[outside_relative.argmax()]), 4)
            if outside_dev.size else None),
        "worst_frame": worst,
        "worst_frame_in_frame_max_px": (round(float(frame_max[worst]), 4)
                                        if worst >= 0 and frame_max[worst] >= 0 else None),
        "visibility_true": int((annotated_all & seen_all).sum()),
        "visible_outside_frame": int(visible_outside_mask.sum()),
        "visible_outside_frame_max_px": (round(float(deviation[visible_outside_mask].max()), 4)
                                         if visible_outside_mask.any() else None),
        "visible_near_plane_points": int((annotated_all & seen_all & plate_all).sum()),
        "visible_behind_plane_points": int((annotated_all & seen_all & behind_all).sum()),
        "invisible_in_frame": int((annotated_all & ~seen_all & in_frame).sum()),
        "plane_threshold_m": PLANE_THRESHOLD_M,
    }
    projection = {
        "model": meta["camera"]["model"], "calibrated": True,
        "coordinate_frame": "camera", "scope": PROJECTION_SCOPE,
        "uv_tolerance_px": UV_TOLERANCE_PX, "visibility_rule": VISIBILITY_RULE,
        "view_scan": view_scan, "points": 0, "inside": 0, "off_image": 0,
        "uv_compared": 0, "uv_within_1px": 0, "uv_within_tolerance": 0, "frames": {},
        "note": "RHD publishes uv and xyz with one pinhole K, so this is the published "
                "projection_qc rather than a one-sided count: the saved xyz is projected "
                "through the view's own intrinsic and compared with the saved uv, split "
                "into the joints whose published uv lies inside the picture (pixel "
                "tolerance) and those outside it (relative to their own magnitude). "
                "view_scan covers every frame of the view; the per-frame entries below "
                "cover only the sampled frames whose pixels were decoded.",
    }
    panels_by_frame, details_by_frame = {}, {}
    visible_outside, not_annotated = [], []
    for index in selected:
        panels, skipped = [], []
        image = Image.fromarray(rgb[index])
        panels.append((f"原生 RGB(MKV 解出的第 {index} 帧,未重编码)", picture(image)))
        details = {
            "frame_index": index,
            "source": frames.get(index),
            "components": {name: {"shape": record["shape"], "dtype": record["dtype"],
                                  "valid_true": record["valid_true"],
                                  "valid_total": record["valid_total"],
                                  "nan_count": record["nan_count"]}
                           for name, record in fields.items()},
            "media_valid": {"rgb": None if rgb_valid is None else bool(rgb_valid[index]),
                            "depth_true_pixels": int((depth_valid[index] != 0).sum()),
                            "depth_pixels": int(depth_valid[index].size)},
        }

        # segmentation
        mask = masks[index][..., 0]
        coloured = np.zeros_like(rgb[index])
        counts = {}
        for hand, (low, high) in SEGMENT_RANGES.items():
            active = (mask >= low) & (mask <= high)
            counts[hand] = int(active.sum())
            coloured[active] = SEGMENT_COLORS[hand]
        active = coloured.any(-1)
        overlay = rgb[index].copy()
        overlay[active] = (0.5 * overlay[active] + 0.5 * coloured[active]).astype(np.uint8)
        panels.append((f"分割区域(左手红 {counts['left']} px / 右手蓝 {counts['right']} px,"
                       f"叠加在 RGB 上;区域号 {SEGMENT_RANGES['left'][0]}–"
                       f"{SEGMENT_RANGES['right'][1]},背景号 65534)",
                       picture(Image.fromarray(overlay))))

        # native uv, solid where the source says the joint is visible
        uv = bundled["keypoints_uv"][0][index].numpy()
        uv_valid = bundled["keypoints_uv"][1][index].numpy()
        seen = visibility[index].numpy() if visibility is not None else None
        if not uv_valid.any():
            reason = "该帧全部 valid 为假(源未标注,故不绘制)"
            panels.append(("原生 UV:" + reason, None))
            skipped.append(("原生 UV", reason))
        else:
            drawn = Image.fromarray(rgb[index].copy())
            painter = ImageDraw.Draw(drawn)
            shown = {}
            #: uv is (hand, joint, coordinate) -- the joint count is axis 1, not 2
            joints = uv.shape[1]
            for hand, slot in (("left", 0), ("right", 1)):
                in_frame = np.zeros(joints, bool)
                for joint in range(joints):
                    x, y = float(uv[slot, joint, 0]), float(uv[slot, joint, 1])
                    in_frame[joint] = (uv_valid[slot, joint] and 0 <= x < width
                                       and 0 <= y < height)
                shown[hand] = draw_hand(painter, uv[slot],
                                        uv_valid[slot] & in_frame,
                                        None if seen is None else seen[slot],
                                        HAND_COLORS[hand], radius)
            panels.append((f"原生 UV 关键点(发布的 2D 像素坐标;实心=源标为可见"
                           f"(基本等于落在画内)、空心=源标为不可见(画外或被遮挡);"
                           f"左手 {shown['left']} 点、右手 {shown['right']} 点在画内)",
                           picture(drawn)))

        # xyz projected with the view's own K, compared against the published uv
        xyz = bundled["keypoints_xyz"][0][index].numpy()
        xyz_valid = bundled["keypoints_xyz"][1][index].numpy()
        K = intrinsic[0][index].numpy()
        if not bool(intrinsic[1][index]):
            projection["frames"][index] = {"intrinsic_valid": False}
            panels.append(("XYZ 投影:该帧 intrinsic 的 valid 为假,不做投影", None))
            skipped.append(("XYZ 投影", "该帧 intrinsic 的 valid 为假"))
        elif not xyz_valid.any():
            projection["frames"][index] = {
                "annotated": False, "valid_points": 0, "behind_plane_points": 0,
                "near_plane_points": 0, "in_frame_points": 0, "outside_frame_points": 0,
                "visible_outside_frame": 0, "uv_compared": 0, "uv_median_px": None,
                "uv_max_px": None, "uv_within_1px": None, "uv_within_tolerance": None,
                "outside_uv_max_px": None, "outside_uv_max_relative": None}
            not_annotated.append(index)
            reason = "该帧全部 valid 为假(源未标注,数值非有限值,故不绘制也不投影)"
            panels.append(("XYZ 投影:" + reason, None))
            skipped.append(("XYZ 投影", reason))
        else:
            pixels, front, inside = project(xyz, K, width, height)
            #: the panels draw from the projection, so their mask is the projected one;
            #: the QC below splits the points the same way the whole-view scan does, by
            #: where the *published* uv lies
            drawable = front & xyz_valid & inside
            uv_row = uv_all[index]
            fin_row = np.isfinite(pixels).all(axis=-1)
            depth_row = depth_all[index]
            dev_row = deviation[index]
            behind_row = xyz_valid & (depth_row <= 0)
            plate_row = xyz_valid & (depth_row > 0) & (depth_row < PLANE_THRESHOLD_M) & fin_row
            cmp_row = (xyz_valid & (depth_row >= PLANE_THRESHOLD_M) & fin_row
                       & np.isfinite(uv_row).all(axis=-1))
            in_row = (cmp_row & (uv_row[..., 0] >= 0) & (uv_row[..., 0] < width)
                      & (uv_row[..., 1] >= 0) & (uv_row[..., 1] < height))
            out_row = cmp_row & ~in_row
            #: the direction that would mean annotation and calibration disagree: the
            #: source calls a joint visible and its own published uv lies outside
            outside_visible = int((seen & out_row).sum()) if seen is not None else 0
            entry = {"annotated": True,
                     "valid_points": int((xyz_valid & (depth_row > 0) & fin_row).sum()),
                     "behind_plane_points": int(behind_row.sum()),
                     "near_plane_points": int(plate_row.sum()),
                     "in_frame_points": int(in_row.sum()),
                     "outside_frame_points": int(out_row.sum()),
                     "visible_outside_frame": outside_visible,
                     "uv_compared": int(in_row.sum()), "uv_median_px": None,
                     "uv_max_px": None, "uv_within_1px": None, "uv_within_tolerance": None,
                     "outside_uv_max_px": None, "outside_uv_max_relative": None}
            if in_row.any():
                distance = dev_row[in_row]
                entry["uv_median_px"] = round(float(np.median(distance)), 4)
                entry["uv_max_px"] = round(float(distance.max()), 4)
                entry["uv_within_1px"] = int((distance <= 1.0).sum())
                entry["uv_within_tolerance"] = int((distance <= UV_TOLERANCE_PX).sum())
                projection["uv_compared"] += int(in_row.sum())
                projection["uv_within_1px"] += entry["uv_within_1px"]
                projection["uv_within_tolerance"] += entry["uv_within_tolerance"]
            if out_row.any():
                out_rel = dev_row[out_row] / np.maximum(
                    np.abs(uv_row[out_row]).max(axis=-1), 1.0)
                entry["outside_uv_max_px"] = round(float(dev_row[out_row].max()), 4)
                entry["outside_uv_max_relative"] = float(f"{out_rel.max():.3g}")
            projection["points"] += entry["valid_points"]
            projection["inside"] += int(drawable.sum())
            projection["off_image"] += entry["valid_points"] - int(drawable.sum())
            projection["frames"][index] = entry
            details["projection"] = entry
            if outside_visible > VISIBLE_OUTSIDE_TOLERANCE:
                visible_outside.append(index)
            if not drawable.any():
                panels.append((f"XYZ 投影:{entry['valid_points']} 个有效关键点全部落在画外", None))
                skipped.append(("XYZ 投影", f"{entry['valid_points']} 个有效点全部落在画外"))
            else:
                drawn = Image.fromarray(rgb[index].copy())
                painter = ImageDraw.Draw(drawn)
                shown = {}
                for hand, slot in (("left", 0), ("right", 1)):
                    #: in front of the camera and inside the picture, but whether the
                    #: marker is filled or hollow is the source's own visible flag -- the
                    #: same vocabulary as the UV panel, so the two can be read against
                    #: each other
                    shown[hand] = draw_hand(
                        painter, pixels[slot],
                        front[slot] & xyz_valid[slot] & inside[slot],
                        None if seen is None else seen[slot], HAND_COLORS[hand], radius)
                warning = (f"该帧有 {outside_visible} 个关节源标为可见、而发布的 uv 落在画外(多为 uv "
                           "恰好等于 320.0 或 0.0 的边界值,数值上仍与投影一致);"
                           if outside_visible > VISIBLE_OUTSIDE_TOLERANCE else "")
                agreement = ("" if entry["uv_median_px"] is None else
                             f";与发布 uv 逐点比对(画内 {entry['uv_compared']} 点):"
                             f"中位偏离 {entry['uv_median_px']} px、最大 "
                             f"{entry['uv_max_px']} px,≤1 px 的 {entry['uv_within_1px']} 点"
                             + (f";画外 {entry['outside_frame_points']} 点按自身量级的最大相对"
                                f"偏离 {entry['outside_uv_max_relative']}"
                                if entry["outside_uv_max_relative"] is not None else ""))
                panels.append((warning
                               + f"XYZ 投影(相机系米制经本视图自己的 K;左手 "
                                 f"{shown['left']} 点、右手 {shown['right']} 点在画内,实心="
                                 f"源标为可见)" + agreement, picture(drawn)))

        # depth
        depth = depth_image(packed[index][:, :, 0], width)
        lo, hi = np.percentile(depth, [2, 98])
        stretched = np.clip((depth - lo) / max(hi - lo, 1e-6), 0, 1)
        depth_panel = cv2.cvtColor(
            cv2.applyColorMap((stretched * 255).astype(np.uint8), cv2.COLORMAP_VIRIDIS),
            cv2.COLOR_BGR2RGB)
        panels.append((f"z 深度(float32 位串,逐图拉伸;显示范围 {lo:.3f}–{hi:.3f} m)",
                       picture(Image.fromarray(depth_panel))))
        details["media_valid"]["depth_all_true"] = bool((depth_valid[index] != 0).all())

        if skipped:
            details["not_drawn"] = [{"what": what, "why": why} for what, why in skipped]
        panels_by_frame[index] = panels
        details_by_frame[index] = details

    #: every listed stream is demuxed for exactly the selected frames -- decode() raises
    #: if a frame's byte count is off, so each count here is established, not assumed.
    #: The field previously read 0 for depth and segment, which contradicted the z-depth
    #: and segmentation panels that are drawn from those very decodes.
    media = [{"component": name, "ref": component["data_ref"],
              "frames_decoded": len(selected)}
             for name, component in components.items()
             if component.get("available", True) and "data_key" not in component]
    report = view_report(view, meta, fields, consumed, selected, projection, media)
    report["not_drawn"] = sorted({what for details in details_by_frame.values()
                                  for what, _ in details.get("not_drawn", [])})
    report["visible_outside_frame_frames"] = sorted(visible_outside)
    report["not_annotated_frames"] = sorted(not_annotated)

    title = f"{view.parent.name}_{view.name}"
    sections = []
    for index in selected:
        figures = []
        for caption, source in panels_by_frame.get(index) or []:
            if source is None:
                figures.append('<figure><p class="note">' + caption + "</p></figure>")
            else:
                figures.append("<figure>" + source + "<figcaption>" + caption
                               + "</figcaption></figure>")
        sections.append(
            f"<section><h2>帧 {index} / {n}</h2>"
            + '<div class="panels">' + "".join(figures) + "</div>"
            + "<details><summary>帧号、来源、全部数值组件与有效性</summary><pre>"
            + html.escape(json.dumps(details_by_frame[index], ensure_ascii=False, indent=2))
            + "</pre></details></section>")

    css = ("body{font:16px sans-serif;max-width:1500px;margin:auto;padding:1rem;"
           "background:#f5f7fa;color:#18232f;line-height:1.5}"
           "section,details{background:#fff;padding:1rem;margin:1rem 0;border-radius:8px}"
           "figure{margin:.5rem}figcaption{font-size:.85rem;max-width:800px}"
           ".panels{display:flex;flex-wrap:wrap}img{max-width:100%;border:1px solid #ddd}"
           "pre{white-space:pre-wrap;overflow:auto;font-size:12px}"
           ".note{background:#fff7e6;border-left:3px solid #e0a800;padding:.6rem;"
           "font-size:.9rem;max-width:800px}"
           ".legend{background:#eef3fa;border-left:3px solid #4a76a8;padding:.6rem;"
           "font-size:.9rem;max-width:800px}.swatch{border:1px solid #b9c3d0}")
    header = ("<h1>" + html.escape(title) + "</h1><p>直接读取 v1.1 bundle("
              + html.escape(meta["sequence_id"]) + " 的 " + html.escape(meta["view_type"])
              + " 视图,split=" + html.escape(meta["split"]) + ",共 " + str(n)
              + " 帧独立图像)。预览仅供人工复核,不是训练输入(CONTRACT §6.5);本次只解码"
                "抽样的 " + str(len(selected)) + " 帧,不是全部帧。本 release 另带 v1.0 的 24 "
                "张抽查页(doc/history-v1.0/validation/),两者并存,本页不替代它。</p>")
    header += colour_legend()
    header += ('<p class="note"><b>全视图数值扫描</b>(不止抽样帧,本视图 '
               + str(view_scan["frames_scanned"]) + " 帧全部参与):发布的 "
               "<code>xyz</code> 经本视图自己的 <code>K</code> 投影后与发布的 "
               "<code>uv</code> 逐点比对。<b>画内</b>(发布的 uv 落在 320×320 内)"
               + str(view_scan["in_frame_points"]) + " 个点:中位偏离 "
               + f"{view_scan['median_px']:g} px、最大 "
               + f"{view_scan['in_frame_max_px']:g} px;"
               + str(view_scan["frames_all_in_frame_points_within_1px"]) + "/"
               + str(view_scan["frames_with_in_frame_points"]) + " 帧的画内点全部在 "
               + f"{UV_TOLERANCE_PX:g} px 以内。"
               "<b>画外</b> " + str(view_scan["outside_frame_points"]) + " 个点:发布的 uv 是"
               "原始投影,可以任意大,像素阈值对它没有意义,故按相对自身量级核验——其中 "
               + str(view_scan["outside_frame_within_1px"]) + " 个点绝对偏差仍在 "
               + f"{UV_TOLERANCE_PX:g} px 以内。两个极值来自不同的点,故各自带上它自己的"
               "量级:绝对偏差最大 " + f"{view_scan['outside_frame_max_px']:g} px"
               "(该点坐标量级 " + f"{view_scan['outside_frame_max_px_uv_scale']:.3g}"
               " px,相对 " + f"{view_scan['outside_frame_max_px'] / view_scan['outside_frame_max_px_uv_scale']:.2g}"
               ");相对偏差最大 " + f"{view_scan['outside_frame_max_relative']:g}"
               "(该点绝对偏差仅 " + f"{view_scan['outside_frame_max_relative_px']:g}"
               " px、离原点 " + f"{view_scan['outside_frame_max_relative_uv_scale']:g}"
                 " px,比值大只因分母小)。"
               "另有 " + str(view_scan["behind_plane_points"]) + " 个关节深度 ≤0(在相机平面上"
               "或之后)、" + str(view_scan["near_plane_points"]) + " 个深度 &lt; "
               + f"{PLANE_THRESHOLD_M:g} m(其 uv 本身就在 1e5 px 量级),这两类不成对比较,"
                 "只计数。偏差最大的画内帧已强制进抽样,见下方。</p>")
    header += ('<p class="note">RHD 每张图标注<b>双手</b>,而通常只有一只手落在 320×320 '
               "画内(本视图 " + str(view_scan["in_frame_points"]) + "/"
               + str(view_scan["points_scanned"]) + " 个关节落在画内),源用 "
               "<code>visibility</code> 标出每个关节是否可见。实测该标量与"
               "「发布的 uv 是否落在画内」在绝大多点上一致,不一致的全部是"
               "「画内但被标为不可见」(本视图 " + str(view_scan["invisible_in_frame"])
               + " 个,多为被另一只手遮挡),而「标为可见却落在画外」只有 "
               + str(view_scan["visible_outside_frame"]) + " 个"
               + ("" if view_scan["visible_outside_frame_max_px"] is None else
                  "(其偏差 ≤ " + f"{view_scan['visible_outside_frame_max_px']:g} px,"
                  "即数值上完全一致,只是 uv 恰好落在边界上)")
               + "。" + html.escape(VISIBILITY_RULE)
               + "。可见与不可见只影响绘制时的实心/空心,不影响有效性判定:不可见关节仍然"
                 "有源给出的 xyz/uv,故仍参与上述比对。画外关节占多数是本数据集"
                 "「每图标注双手、通常只有一只在画内」的正常形态,不是标定缺陷。</p>")
    if visible_outside:
        header += ('<p class="note">抽样的 ' + str(len(selected)) + " 帧里有 "
                   + str(len(visible_outside)) + " 帧存在「源标为可见、但发布的 uv 落在画外」"
                     "的关节(帧 "
                   + "、".join(str(index) for index in visible_outside)
                   + ")。实测这些点多是 uv 恰好等于边界值(320.0 / 0.0),偏差仍在 0.1 px "
                     "内,即标注与标定并未冲突;列出帧号只是让复核者可以自己确认。逐帧数量与"
                     "最大偏差记在本视图报告的 projection.frames 里"
                     "(<code>visible_outside_frame</code>)。</p>")
    if not_annotated:
        header += ('<p class="note">抽样的 ' + str(len(selected)) + " 帧里有 "
                   + str(len(not_annotated)) + " 帧源未给出关键点(帧 "
                   + "、".join(str(index) for index in not_annotated)
                   + "):该帧全部 valid 为假,数值按发布的写法为非有限值,页面不绘制也不"
                     "投影。这是源未标注,不是投影失败。</p>")
    page = ('<!doctype html><html lang="zh"><meta charset="utf-8"><title>'
            + html.escape(title) + "</title><style>" + css + "</style>" + header
            + "".join(sections)
            + "<details><summary>全部组件元信息及原始来源</summary><pre>"
            + html.escape(json.dumps(meta, ensure_ascii=False, indent=2)) + "</pre></details>"
            + "<details><summary>持久化 QC 结果</summary><pre>"
            + html.escape(json.dumps(report, ensure_ascii=False, indent=2))
            + "</pre></details></html>")

    destination.mkdir(parents=True, exist_ok=True)
    (destination / (title + ".html")).write_text(page, encoding="utf-8")
    #: saved before _page is added: the file on disk is the report, and _page is a
    #: convenience index.html needs in memory
    save(destination / (title + ".report.json"), report)
    report["_page"] = title + ".html"
    print(destination / (title + ".html"), "selected_frames", selected, flush=True)
    return report


def render_task(task):
    for variable in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS",
                     "NUMEXPR_NUM_THREADS", "HAND_WAREHOUSE_FFMPEG_THREADS"):
        os.environ[variable] = "1"
    torch.set_num_threads(1)
    view, destination, root = map(Path, task)
    return render_one(view, destination, root)


# -- sampling ---------------------------------------------------------------


def shard_facts(root: Path, sequence: str) -> dict:
    """Split, frame count and source directory of one shard, from its own metadata."""
    views = sorted((root / "data" / sequence).glob("*/metainfo.json"))
    if len(views) != 1:
        raise SystemExit(f"{sequence}: expected exactly one camera, found {len(views)}")
    meta = load(views[0])
    return {"sequence": sequence, "split": meta["split"], "num_frames": meta["num_frames"],
            "member_prefix": meta["split_source_locator"]["member_prefix"],
            "camera": meta["camera_id"]}


def plan_views(facts: dict, seed: int, train_slots: int) -> list:
    """Stratified sample: the whole evaluation split, plus a seeded training draw.

    RHD's two splits are wildly unequal -- 81 training shards against 6 evaluation
    ones -- so an equal-allocation draw would either exhaust one stratum or drown the
    other.  The rule here is stated rather than balanced: **every** evaluation shard is
    rendered (all six, the whole official test split), and ``train_slots`` training
    shards are drawn uniformly with the seed.  The training split's partial tail shard
    is forced into the sample, because it is the one training shard whose frame count
    is not the shard size and therefore the boundary case a reviewer should see once.
    The draw is repeatable from the record in ``V1_1_VALIDATION.json``.
    """
    rng = random.Random(seed)
    evaluation = sorted(sequence for sequence, fact in facts.items() if fact["split"] == "test")
    training = sorted(sequence for sequence, fact in facts.items() if fact["split"] == "train")
    if not evaluation or not training:
        raise SystemExit("one of the two splits is empty")
    shard_size = max(fact["num_frames"] for fact in facts.values())
    #: the training shards that are not full: the tail of the 41,258-image split
    forced = sorted(sequence for sequence in training
                    if facts[sequence]["num_frames"] != shard_size)[:1]
    remaining = [sequence for sequence in training if sequence not in forced]
    if len(remaining) < train_slots - len(forced):
        raise SystemExit(f"the training split cannot fill {train_slots} slots")
    drawn = sorted(rng.sample(remaining, train_slots - len(forced)))
    return sorted(evaluation + forced + drawn)


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("--root", type=Path,
                        default=Path(__file__).resolve().parents[2],
                        help="the shared-v1.1 release root (default: this script's own)")
    parser.add_argument("--out", type=Path,
                        help="where the pages go (default <root>/doc/validation)")
    parser.add_argument("--seed", type=int, default=20261014)
    parser.add_argument("--reference-shards", type=int, default=12,
                        help="views to render; the whole evaluation split is always "
                             "included and the rest are training shards")
    parser.add_argument("--workers", type=int, default=4,
                        help="at most 8, one decoder thread each")
    parser.add_argument("--views", nargs="+",
                        help="render these views (sequence/camera) instead of sampling")
    args = parser.parse_args(argv)
    if not 1 <= args.workers <= 8:
        parser.error("at most 8 workers and one decoder thread each")

    root = args.root.resolve()
    destination = (args.out or root / "doc/validation").resolve()

    facts = {path.name: shard_facts(root, path.name)
             for path in sorted((root / "data").iterdir()) if path.is_dir()}
    if args.views:
        views = []
        for token in args.views:
            sequence, _, camera = token.partition("/")
            view = root / "data" / sequence / (camera or "camera")
            if not (view / "metainfo.json").is_file():
                parser.error(f"no such view: {token}")
            views.append(view)
        sequences = sorted({view.parent.name for view in views})
        sampling = {"kind": "explicit", "views": args.views,
                    "rule": "explicit view list; no sampling applied"}
    else:
        evaluation = [sequence for sequence, fact in facts.items() if fact["split"] == "test"]
        train_slots = args.reference_shards - len(evaluation)
        if train_slots < 0:
            parser.error(f"--reference-shards {args.reference_shards} is smaller than the "
                         f"{len(evaluation)} shards of the evaluation split")
        sequences = plan_views(facts, args.seed, train_slots)
        views = []
        for sequence in sequences:
            found = sorted((root / "data" / sequence).glob("*/metainfo.json"))
            if len(found) != 1:
                raise SystemExit(f"{sequence}: {len(found)} views enumerated")
            views.append(found[0].parent)
        shard_size = max(fact["num_frames"] for fact in facts.values())
        sampling = {
            "seed": args.seed,
            "rule": "the whole evaluation split (all of its shards) plus training shards "
                    "drawn uniformly inside the split with the seed, with the training "
                    "split's partial tail shard forced into the sample; one page per "
                    "shard (RHD has one camera per shard)",
            "evaluation_shards_rendered": len(evaluation),
            "training_slots": train_slots,
            "forced_training_shard": sorted(sequence for sequence, fact in facts.items()
                                            if fact["split"] == "train"
                                            and fact["num_frames"] != shard_size)[:1],
            "shard_size": shard_size,
            "selections": [{"sequence": sequence, "split": facts[sequence]["split"],
                            "num_frames": facts[sequence]["num_frames"],
                            "member_prefix": facts[sequence]["member_prefix"],
                            "camera": facts[sequence]["camera"]} for sequence in sequences],
            "pools": {split: sum(1 for fact in facts.values() if fact["split"] == split)
                      for split in ("train", "test")},
            "sequences_in_release": len(facts),
        }

    start = time.monotonic()
    #: no .pyc may land in the release tree, and a spawn child re-imports this module
    #: before any guard inside it runs -- so the switch has to be in the environment
    #: the children inherit, not only in this interpreter
    os.environ["PYTHONDONTWRITEBYTECODE"] = "1"
    with ProcessPoolExecutor(max_workers=args.workers,
                             mp_context=multiprocessing.get_context("spawn")) as pool:
        reports = list(pool.map(render_task,
                                [(str(view), str(destination), str(root)) for view in views]))

    compared = sum(entry["projection"]["uv_compared"] for entry in reports)
    within_1 = sum(entry["projection"]["uv_within_1px"] for entry in reports)
    within_tol = sum(entry["projection"]["uv_within_tolerance"] for entry in reports)
    scan = [entry["projection"]["view_scan"] for entry in reports]
    report = {
        "review_kind": "全量后抽样",
        "views": len(views),
        "sequences": len(sequences),
        "dataset_id": "RHD",
        "release_id": "shared-v1.1",
        "sampling": sampling,
        "wall_seconds": round(time.monotonic() - start, 3),
        "decode_scope": DECODE_SCOPE,
        "projection_qc": {
            #: the whole-view scan: every frame of every rendered view was projected and
            #: compared, so these numbers do not stop at the sampled frames
            "views_scanned": len(scan),
            "frames_scanned": sum(item["frames_scanned"] for item in scan),
            "points_scanned": sum(item["points_scanned"] for item in scan),
            #: counted, not dropped: joints at or behind the camera plane, and joints
            #: within a millimetre of it, have no meaningful pixel comparison
            "behind_plane_points": sum(item["behind_plane_points"] for item in scan),
            "near_plane_points": sum(item["near_plane_points"] for item in scan),
            "comparable_points": sum(item["comparable_points"] for item in scan),
            "in_frame_points": sum(item["in_frame_points"] for item in scan),
            "outside_frame_points": sum(item["outside_frame_points"] for item in scan),
            #: the worst median across views, so the headline is the pessimistic one
            "median_px": (max(item["median_px"] for item in scan) if scan else None),
            "in_frame_max_px": (max(item["in_frame_max_px"] for item in scan)
                                if scan else None),
            "frames_with_in_frame_points": sum(
                item["frames_with_in_frame_points"] for item in scan),
            "frames_all_in_frame_points_within_1px": sum(
                item["frames_all_in_frame_points_within_1px"] for item in scan),
            "outside_frame_within_1px": sum(
                item["outside_frame_within_1px"] for item in scan),
            "outside_frame_max_px": (max(item["outside_frame_max_px"] for item in scan)
                                     if scan else None),
            "outside_frame_max_relative": (max(item["outside_frame_max_relative"]
                                               for item in scan) if scan else None),
            "visible_outside_frame": sum(item["visible_outside_frame"] for item in scan),
            "invisible_in_frame": sum(item["invisible_in_frame"] for item in scan),
            "plane_threshold_m": PLANE_THRESHOLD_M,
            "tolerance_px": UV_TOLERANCE_PX,
            "sampled_frames": {"compared_points": compared, "within_1px": within_1,
                               "within_tolerance": within_tol},
            "visibility_rule": VISIBILITY_RULE,
            "scope": PROJECTION_SCOPE,
            "note": "saved xyz projected through each view's own K, compared with the "
                    "saved uv; RHD is the only release holding both series. The "
                    "whole-view scan covers every frame of every rendered view; "
                    "sampled_frames covers only the frames whose pixels were decoded. "
                    "Points at or within a millimetre of the camera plane are counted "
                    "separately rather than compared in pixels, and in-frame points are "
                    "separated from out-of-frame ones by where the published uv itself "
                    "lands, so a far out-of-frame joint cannot inflate the in-frame "
                    "maximum.",
        },
        "reports": reports,
        "scope": "post-full sampled shards, read directly from v1.1 bundles; evidence for "
                 "human acceptance, not training input; manual review pending",
    }
    save(destination / "V1_1_VALIDATION.json", report)

    page_names = sorted(path.name for path in destination.glob("*.html")
                        if path.name != "index.html")
    index_css = ("body{font:16px sans-serif;max-width:1100px;margin:auto;padding:1rem;"
                 "background:#f5f7fa;color:#18232f;line-height:1.5}"
                 ".legend{background:#eef3fa;border-left:3px solid #4a76a8;padding:.6rem;"
                 "font-size:.9rem;max-width:800px}.swatch{border:1px solid #b9c3d0}"
                 "table{border-collapse:collapse;width:100%}td,th{border:1px solid #ccd3de;"
                 "padding:4px 8px;text-align:left;font-size:.9rem}")
    rows = []
    for entry in sorted(reports, key=lambda item: (item["sequence_id"], item["camera_id"])):
        metrics = entry["projection"]["view_scan"]
        rows.append("<tr><td><a href=\"" + html.escape(entry["_page"], quote=True) + "\">"
                    + html.escape(entry["view"]) + "</a></td><td>"
                    + html.escape(entry["split"]) + "</td><td>" + str(entry["num_frames"])
                    + "</td><td>" + str(len(entry["selected_frames"])) + "</td><td>"
                    + str(metrics["in_frame_points"]) + " / "
                    + str(metrics["points_scanned"]) + "</td><td>"
                    + f"{metrics['median_px']:g} px</td><td>"
                    + f"{metrics['in_frame_max_px']:g} px</td><td>"
                    + str(metrics["frames_all_in_frame_points_within_1px"]) + " / "
                    + str(metrics["frames_with_in_frame_points"]) + "</td><td>"
                    + str(metrics["outside_frame_within_1px"]) + " / "
                    + str(metrics["outside_frame_points"]) + "</td><td>"
                    + str(metrics["visible_outside_frame"]) + "</td></tr>")
    index = ('<!doctype html><html lang="zh"><meta charset="utf-8">'
             "<title>RHD shared-v1.1 review</title><style>" + index_css + "</style>"
             "<h1>RHD shared-v1.1 全量后抽样人工复查</h1>"
             "<p>数值按字节一致(CONTRACT §6);媒体不重新编码,与 v1.0 共享 inode。"
             "抽样规则与种子见 V1_1_VALIDATION.json,本页所列视图即全部入选视图:"
             + str(len(views)) + " 个视图 / " + str(len(sequences)) + " 段(评估 split 全 "
             + str(sampling.get("evaluation_shards_rendered", 0)) + " 片 + 训练 split 抽 "
             + str(sampling.get("training_slots", 0)) + " 片)。全量读取器 sweep 的 87/87 "
             "结果见 <code>read_sequence_sweep.json</code>,逐字段字节验收见 "
             "<code>validate_report.json</code> 与发布树外的 "
             "<code>tmp/rhd-tools/acceptance.json</code>。</p>"
             + colour_legend()
             + "<p>每页只解码该视图抽样的帧;抽样帧之外的帧不在页面里。但 <b>xyz↔uv 投影比对"
               "扫的是每个入选视图的全部帧</b>(纯张量运算,不解码像素),全量结果见 "
               "V1_1_VALIDATION.json 的 <code>projection_qc</code>。表里的「画内」是"
               "发布的 uv 落在 320×320 内的关节数(RHD 每图标注双手,通常只有一只在画内,"
               "故画外关节占多数,属正常形态);「画内最坏点」只统计画内点的最大像素偏差。"
               "画外点的 uv 是原始投影、可以任意大,像素阈值对它没有意义,故按其自身量级"
               "核验,且两个极值各自带上它自己的坐标量级(见 V1_1_VALIDATION.json 的 "
               "<code>outside_frame_max_px_uv_scale</code> 与 "
               "<code>outside_frame_max_relative_uv_scale</code>)。深度 ≤0 或 &lt;1 mm 的"
               "关节不参与像素比较,只计数。v1.0 的 24 张抽查页"
               "见 <code>../history-v1.0/validation/</code>。</p>"
               "<table><tr><th>视图</th><th>split</th><th>帧数</th><th>本页抽样帧</th>"
               "<th>画内 / 全部关节</th><th>画内偏差中位</th><th>画内最坏点</th>"
               "<th>画内点全部≤1px 的帧</th><th>画外点绝对偏差≤1px</th>"
               "<th>标为可见却在画外</th></tr>"
             + "".join(rows) + "</table>"
               "<ul><li><a href=\"../CONTRACT.md\">CONTRACT.md</a></li>"
               "<li><a href=\"../RAW_MAPPING.md\">RAW_MAPPING.md</a></li>"
               "<li><a href=\"../REPORT.md\">REPORT.md</a></li>"
               "<li><a href=\"../FULL_MIGRATION_SUMMARY.json\">FULL_MIGRATION_SUMMARY.json</a></li>"
               "<li><a href=\"V1_1_VALIDATION.json\">V1_1_VALIDATION.json</a></li></ul><ul>"
             + "".join('<li><a href="' + html.escape(name, quote=True) + '">'
                       + html.escape(name) + "</a></li>" for name in page_names)
             + "</ul></html>")
    (destination / "index.html").write_text(index, encoding="utf-8")
    print("POST_FULL_HTML_DONE", len(views), "views", round(report["wall_seconds"], 2),
          "seconds", destination / "index.html", flush=True)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())