File size: 68,960 Bytes
8f94cdb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
#!/usr/bin/env python3
"""Render sampled ReInterHand 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".  H2O, dex-ycb, ARCTIC and RHD all ship sampled per-view pages for the second half;
this gives ReInterHand 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
  ``reinterhand_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 marks a bundled numeric field; media, the standalone
  ``*_valid.pt`` files beside it and the JSONL are read as the preserved files they are.
* the panels are the vocabulary of ReInterHand's **own** published v1.0 renderer
  (``shared-v1.0/script/render_reinterhand_full_random.py`` and its pages under
  ``doc/validation/full_random/``): native RGB, the MANO mesh in cyan for the left hand and
  orange for the right, and the free-standing non-binary foreground mask as grayscale
  intensity.  That vocabulary is used unchanged so a reviewer can read a v1.1 page against
  a v1.0 one -- including the one thing it is easy to get backwards, which is that this
  release's MANO colours are **not** RHD's red/blue.
* the v1.0 renderer required a MANO runtime (``smplx`` plus the ``MANO_*.pkl`` weights) and
  drew the geometry from it.  Those weights are not part of the shared release (CONTRACT
  5.2: 模型权重不作为共享数据附带上传), so the runtime is an **optional input** here: with
  ``--mano-runtime`` the MANO panel is drawn, without it the page names the missing runtime
  and draws the rest.  Either way the parameters are checked, because they are release
  content.
* what the v1.0 pages could not do is measure the **join between the bundled parameters and
  the preserved mask**, since there the two were separate files.  v1.1 is where they live
  one ``.pt`` apart, so this page projects the MANO geometry of *every* frame of the view
  -- not only the sampled ones -- and reports how much of it lands on the mask's foreground.
  The number is recorded, never asserted and never used to "fix" anything: a systematic
  offset would be a finding about the release, not a reason to change a page.

Per-frame validity is not uniform, and the pages have to survive that: over the two sample
sequences the exo views are valid on every frame while one sequence's ego view has only 5 of
181 frames valid per hand.  Sampling therefore always includes the first valid and the first
invalid frame of each series, and a hand whose slot is invalid is left undrawn with the
reason on the panel rather than drawn from parameters the release marks invalid.

Every page is one self-contained file (previews as base64 JPEG data URIs -- a lossy
*preview* of a lossless frame, which CONTRACT 6 does not forbid because the release's own
bytes are untouched; PNG was used for RHD's 320x320 frames, and at 667x1024 portrait it
would make the page set an order of magnitude larger).  Only the sampled RGB frames are
decoded; the mask is streamed once, end to end, for the whole-view scan.

Run -- the ordering matters, see the 收尾验收顺序 in script/reinterhand_v1_1/README.md:

    python shared-v1.1/script/reinterhand_v1_1/render.py \
        --mano-runtime ../../tmp/runtime-v1.0
"""

from __future__ import annotations

import argparse
import base64
import collections
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
#: reinterhand_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 numpy as np
import torch
from PIL import Image, ImageDraw

from reinterhand_common import (
    DATASET_ROOT,
    DEFAULT_MEDIA_DECLARATION,
    FRAMES_REF,
    RENDER_CELLS,
    MediaDeclaration,
    check_view,
    load,
    save,
)
from warehouse import BundleReader, Registry

import mano_review

DECODE_SCOPE = ("ffmpeg demux over the preserved MKV; the sampled RGB frames are decoded "
                "with select=, and the mask is streamed once from end to end for the "
                "whole-view scan.  Every frame's byte count is checked")
REPORT_SCOPE = ("v1.1 registry, keys, shapes, validity and timeline, plus the projection "
                "of the bundled MANO parameters onto the preserved mask; not a media pixel "
                "comparison of the released values themselves")
PROJECTION_SCOPE = ("bundled MANO parameters expanded to a camera-frame mesh and projected "
                    "through the view's own declared camera model (pinhole for exo, "
                    "opencv_fisheye4 for ego, both asserted by check_view before this runs), "
                    "then compared with the preserved mask's foreground.  The mask has no "
                    "per-hand identity, so this measures coverage of both hands together, "
                    "not a per-hand match")

#: The release's own review directory -- this script lives in
#: ``<release>/script/reinterhand_v1_1``.  It holds the sampled review the closing chain
#: renders (step 5): the pages, ``V1_1_VALIDATION.json`` and ``index.html``.  An explicit
#: ``--views`` run is not that review and may not write here (see the refusal in ``main``).
REVIEW_DIR = Path(__file__).resolve().parents[2] / "doc" / "validation"

#: ReInterHand's own published vocabulary, read off
#: ``shared-v1.0/script/preprocess_reinterhand.py`` (``draw_mano_meshes``) and the v1.0
#: review pages: 青色=左手, 橙色=右手.  RHD's red/blue is a different release's convention
#: and is deliberately not used.
HAND_COLORS = {"left": (0, 255, 255), "right": (255, 140, 0)}
#: the mask tint, likewise from ``draw_foreground_intensity``: magenta at 0.72 of the
#: intensity, capped so a saturated pixel does not hide the hand underneath
MASK_TINT = (255, 0, 200)
MASK_TINT_ALPHA = 0.72
MASK_TINT_CAP = 190
#: the preview box.  Exo frames are 667 wide by 1024 tall and ego ones 1024x1024, so the
#: box is portrait-shaped; a preview is scaled down and never up
PREVIEW_BOX = (460, 700)
PREVIEW_QUALITY = 88
#: the most sampled frames one page carries.  A hard limit, met exactly by
#: ``select_frames``: the ends, the validity boundary cases and the caller's extra frames are
#: never dropped, and the quarter points fill whatever is left
FRAMES_CAP = 6
#: the ``camera/frames.jsonl`` fields the captions print: a subset of the release's
#: ``FRAME_FIELDS``, chosen for what a reviewer needs to identify a frame
DISPLAY_FRAME_FIELDS = ("frame_index", "sample_id", "source_frame_id", "sync_id",
                        "timestamp_ns", "clock_domain")


# -- decoding ---------------------------------------------------------------


def _ffmpeg_threads() -> str:
    return os.environ.get("HAND_WAREHOUSE_FFMPEG_THREADS", "1")


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

    Same recipe as the published renderers (``HAND_WAREHOUSE_FFMPEG_THREADS``, one decoder
    thread by default), with ``select=`` so a 200-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 = _ffmpeg_threads()
    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 stream(path: Path, pix_fmt: str, dtype, width: int, height: int, channels: int):
    """Yield every frame of a preserved video in order, one at a time.

    The whole-view scan needs each mask frame once and nothing twice, so the decoder is read
    as a pipe rather than collected into one array: a 667x1024 gray16le frame is 1.4 MB, and
    all of a view's frames at once would be the largest thing this tool holds.
    """
    threads = _ffmpeg_threads()
    argv = ["ffmpeg", "-v", "error", "-nostdin", "-threads", threads, "-noautorotate",
            "-i", str(path), "-map", "0:v:0", "-vsync", "0", "-threads", threads,
            "-f", "rawvideo", "-pix_fmt", pix_fmt, "-"]
    frame_bytes = width * height * channels * np.dtype(dtype).itemsize
    process = subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    try:
        while True:
            block = process.stdout.read(frame_bytes)
            if not block:
                break
            if len(block) != frame_bytes:
                raise ValueError(f"{path}: short frame, {len(block)} of {frame_bytes} bytes")
            yield np.frombuffer(block, dtype=dtype).reshape(height, width, channels)
    finally:
        process.stdout.close()
        error = process.stderr.read().decode("utf-8", "replace").strip()
        process.stderr.close()
        if process.wait() != 0:
            raise ValueError(f"{path}: ffmpeg failed: {error}")


def probe(path: Path):
    """Demux-only facts about a media file: packet count, shape, codec."""
    out = subprocess.run(
        ["ffprobe", "-v", "error", "-select_streams", "v:0", "-count_packets",
         "-show_entries", "stream=width,height,codec_name,pix_fmt,nb_read_packets",
         "-of", "json", str(path)],
        capture_output=True, text=True, check=True).stdout
    facts = (json.loads(out).get("streams") or [{}])[0]
    return {"frames": int(facts["nb_read_packets"]), "width": facts.get("width"),
            "height": facts.get("height"), "codec": facts.get("codec_name"),
            "pix_fmt": facts.get("pix_fmt")}


# -- previews ---------------------------------------------------------------


def picture(image: Image.Image) -> str:
    """A preview as a JPEG data URI.  The released tensors and videos are never resized.

    The preview *is* lossy, and every page says so: a 667x1024 PNG of a real photograph is
    around 600 KB and a page carries four panels per sampled frame, so the page set would be
    an order of magnitude larger than the evidence it carries.  The decoded frame is full
    size until this last step, and every measurement on the page is taken before it.
    """
    preview = image.copy()
    preview.thumbnail(PREVIEW_BOX)
    output = io.BytesIO()
    preview.save(output, format="JPEG", quality=PREVIEW_QUALITY)
    return ('<img loading="lazy" src="data:image/jpeg;base64,'
            + base64.b64encode(output.getvalue()).decode() + '">')


def label_panel(image: Image.Image, text: str) -> Image.Image:
    """The v1.0 renderer's in-frame panel label, so the two page sets look alike."""
    result = image.copy()
    painter = ImageDraw.Draw(result)
    painter.rectangle((0, 0, min(result.width, 460), 26), fill=(0, 0, 0))
    painter.text((8, 6), text, fill=(255, 255, 255))
    return result


def mask_intensity_panel(mask: np.ndarray, shift: int) -> Image.Image:
    """The preserved mask's own values, shown as intensity rather than hidden in RGB.

    ``segment/foreground_intensity/v1`` is a *non-binary* foreground intensity in 0..255
    with no per-hand identity, so it is drawn as grayscale with a scale bar and its frame
    minimum and maximum.  The container is ``gray16le``: decoding it as 8-bit ``gray`` would
    make ffmpeg rescale 0..65535 down to 0..255 and collapse the native range to almost
    black, so the stored words are read verbatim.  ``shift`` is 0 for the declared range; a
    frame holding a value above 255 -- possible, since the container is wider than the
    declaration -- is drawn shifted down by 8 bits and the caption says so, never clamped
    silently, which would draw a wrong picture.
    """
    image = Image.fromarray((mask >> shift).astype(np.uint8), "L").convert("RGB")
    painter = ImageDraw.Draw(image)
    width, height = image.size
    bar_width = min(280, max(120, width // 2))
    x0, y0 = 12, max(40, height - 40)
    ramp = np.tile(np.arange(256, dtype=np.uint8), (14, 1))
    image.paste(Image.fromarray(ramp, "L").convert("RGB"), (x0, y0))
    painter.rectangle((x0 - 1, y0 - 1, x0 + bar_width, y0 + 14), outline=(255, 70, 70),
                      width=2)
    painter.text((x0, max(2, y0 - 16)), "intensity 0 -> 255" + (" (>>8)" if shift else ""),
                 fill=(255, 70, 70))
    painter.text((x0, min(height - 10, y0 + 17)),
                 f"stored min={int(mask.min())} max={int(mask.max())}", fill=(255, 70, 70))
    return image


def mask_overlay(image: np.ndarray, mask: np.ndarray, shift: int) -> Image.Image:
    """The v1.0 renderer's magenta foreground tint, so alignment can be judged by eye."""
    tint = Image.new("RGBA", (mask.shape[1], mask.shape[0]), (*MASK_TINT, 0))
    tint.putalpha(Image.fromarray((mask >> shift).astype(np.uint8), "L").point(
        lambda value: min(MASK_TINT_CAP, int(value * MASK_TINT_ALPHA))))
    return Image.alpha_composite(Image.fromarray(image).convert("RGBA"), tint).convert("RGB")


def mano_overlay(image: np.ndarray, pixels_by_side: dict, faces, width: int,
                 height: int) -> tuple:
    """The MANO mesh drawn the way the v1.0 pages drew it: translucent fill, solid edge.

    Returns the image and how many triangles each hand contributed, so a caption can say
    whether a hand was drawn at all rather than leaving an empty panel unexplained.  A side
    whose slot is invalid arrives as ``None`` and contributes nothing.
    """
    base = Image.fromarray(image).convert("RGBA")
    overlay = Image.new("RGBA", base.size, (0, 0, 0, 0))
    painter = ImageDraw.Draw(overlay, "RGBA")
    counts = {}
    for side in ("left", "right"):
        pixels = pixels_by_side.get(side)
        polygons = (list(mano_review.drawable_faces(faces, pixels, width, height, np))
                    if pixels is not None else [])
        counts[side] = None if pixels is None else len(polygons)
        colour = HAND_COLORS[side]
        for polygon in polygons:
            painter.polygon(polygon, fill=(*colour, 28))
            painter.line(polygon + [polygon[0]], fill=(*colour, 220), width=2)
    return Image.alpha_composite(base, overlay).convert("RGB"), counts


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


def numeric_records(meta: dict, reader, view: Path) -> dict:
    """One JSON-safe record per series the view carries, read through the released reader.

    Two shapes of series live here and the report has to keep them apart:

    * a **bundled** field (``data_key`` present) lives in a bundle file beside its ``valid``
      and is read with ``reader.field`` -- intrinsic, extrinsic, distortion, mano.  The
      migration owns these.
    * a **preserved** media component (``rgb``, ``segment``) keeps v1.0's layout: the payload
      is the MKV and the validity is a standalone ``*_valid.pt`` sibling, read with the same
      ``torch.load(..., weights_only=True)`` ``check_view`` uses.  The migration leaves both
      alone.

    ``check_view`` has already asserted every one of these; the records restate them for the
    report so the page and the checker cannot disagree.  The arrays themselves are not kept
    here -- they would make the record un-serialisable -- and ``validity_arrays`` reads the
    same series again for the per-frame panels.
    """
    records = {}
    for name, component in meta["components"].items():
        if not component.get("available", True):
            continue
        if "data_key" in component:
            data, valid = reader.field(view, component)
            records[name] = {
                "kind": "bundled", "file": component["data_ref"],
                "data_key": component["data_key"], "valid_key": component["valid_key"],
                "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),
            }
        elif component["data_ref"].endswith(".mkv"):
            valid = standalone_validity(view, component)
            records[name] = {
                "kind": "preserved_media", "file": component["data_ref"],
                "valid_file": component["valid_ref"],
                "shape": None, "dtype": None, "valid_shape": list(valid.shape),
                "valid_dtype": str(valid.dtype), "valid_true": int(valid.sum()),
                "valid_total": int(valid.numel()), "nan_count": None,
            }
        else:
            continue
        counts = valid_counts(valid if "data_key" not in component
                              else reader.field(view, component)[1])
        records[name]["valid_true_per_series"] = counts
    return records


def standalone_validity(view: Path, component: dict):
    """A preserved media component's standalone ``*_valid.pt``, exactly as check_view reads it."""
    return torch.load(view / component["valid_ref"], map_location="cpu", weights_only=True)


def valid_counts(valid) -> list:
    """``valid`` true-counts split along its last axis when that axis is a small series axis.

    ReInterHand's ``mano`` validity is ``[T, 2]`` -- one flag per hand -- and the pages report
    the two hands separately, which is why the split is worth carrying.  ``[T]`` series get a
    single count.  The threshold mirrors the release's own two ``hand_slots``.
    """
    if valid.dim() > 1 and valid.shape[-1] <= 4:
        return [int(valid[..., slot].sum()) for slot in range(valid.shape[-1])]
    return [int(valid.sum())]


def select_frames(n: int, valids, extra=(), cap: int = FRAMES_CAP) -> list:
    """Sampling driven by the release's own validity, so a page shows its boundary cases.

    Both ends, 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, and on these sample sequences it is the
    majority of one ego view's frames), and whatever the caller has already decided is worth
    seeing -- this renderer passes the frame whose MANO geometry the mask covers least, found
    by the whole-view scan.  Quarter points fill the rest, so a temporal view shows its span.

    Priority is strict, and the cap is therefore exact rather than a target: the ends and the
    boundary cases are claims about the release and are never dropped, ``extra`` is the
    caller's explicit choice, and only the quarter points are expendable.  A view whose
    validity is busy can legitimately fill the whole budget with boundary cases, in which
    case the page shows no quarter point at all -- which is the right trade, because the
    quarter point is the one pick that carries no information the caption does not.
    """
    keep = {0, n - 1} | {int(index) for index in extra}
    optional = {n // 4, n // 2, 3 * n // 4} - keep
    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):
                keep.add(int(present[0]))
    room = max(0, cap - len(keep))
    return sorted(keep | set(sorted(optional)[:room]))


def declared_cell(meta: dict) -> dict:
    """Which of the release's four render cells this view is in, and what follows from it.

    Taken from :data:`RENDER_CELLS` rather than re-derived, so the caption and the checkers
    cannot disagree about, say, whether the stored frames are a temporal sequence.  A view
    outside the four measured cells is reported as such rather than guessed about.
    """
    policy = meta["source_rendering"].get("background_policy")
    cell = RENDER_CELLS.get((meta["view_type"], policy))
    if cell is None:
        return {"view_type": meta["view_type"], "background_policy": policy, "known": False}
    return {"view_type": meta["view_type"], "background_policy": policy, "known": True,
            "temporal_relationship": cell["temporal_relationship"],
            "sample_type": cell["sample_type"], "sampling": cell["sampling"],
            "covers_span": cell["covers_span"],
            "modal_source_steps": list(cell["modal_steps"]),
            "source_fps": cell["source_fps"],
            "sequence_id_role": cell["sequence_id_role"]}


def frame_rows_of(view: Path) -> dict:
    """``camera/frames.jsonl`` as ``frame_index -> row``, the join the captions display."""
    rows = [json.loads(line) for line in
            (view / FRAMES_REF).read_text(encoding="utf-8").splitlines() if line.strip()]
    return {int(row["frame_index"]): {key: row.get(key) for key in DISPLAY_FRAME_FIELDS}
            for row in rows}


def project(index: int, geometry, intrinsic, distortion, width: int, height: int,
            cv2) -> dict:
    """One series' geometry at one frame, projected and classified against the picture.

    The single projection implementation, shared by the whole-view scan and the per-frame
    panels, so the number the header quotes and the polygon the panel draws cannot come from
    two different formulas.  Returns every point's pixel (NaN where the point is not in front
    of the camera), the in-front mask, which points are inside the picture, and those points
    as integer rows/columns for indexing the mask.

    ``distortion`` is the view's whole ``[T, 4]`` stack (or ``None`` for a pinhole view); this
    is where the frame's own row is selected, so no caller can pass the stack by mistake --
    OpenCV asserts on exactly four coefficients and would otherwise fail deep inside the
    fisheye call with an argument-shape message that says nothing about the frame index.
    """
    frame_distortion = None if distortion is None else distortion[index]
    pixels, front = mano_review.project_vertices(geometry[index], intrinsic[index],
                                                 frame_distortion, np, cv2)
    finite = front & np.isfinite(pixels).all(axis=-1)
    inside = (finite & (pixels[:, 0] >= 0) & (pixels[:, 0] < width)
              & (pixels[:, 1] >= 0) & (pixels[:, 1] < height))
    return {"pixels": pixels, "front": front, "inside": inside,
            "points": np.clip(pixels[inside], 0, None).astype(np.int64)}


def mano_mask_scan(meta: dict, mask_path: Path, mask_valid, mano_valid, geometry,
                   intrinsic, distortion, cv2) -> dict:
    """Project the MANO mesh of *every* frame and count how much lands on the foreground.

    This is the measurement the v1.0 pages could not make: there the parameters and the mask
    were separate files and nothing tied them together.  It is deliberately a *coverage* count
    and not an assertion -- the mask carries no per-hand identity, so it cannot say which hand
    a pixel belongs to, and a systematic offset would be a finding about the source rather than
    a reason to change the page.  Frames the release marks invalid for either series, and
    frames whose mask is entirely zero (a ratio with a zero denominator is not a number), are
    excluded from the ratios and counted separately.
    """
    n = meta["num_frames"]
    width, height = meta["camera"]["image_size"]
    per_side = {side: {"frames_used": 0, "joints_projected": 0, "joints_in_frame": 0,
                       "joints_on_foreground": 0, "vertices_in_frame": 0,
                       "vertices_on_foreground": 0, "frames_with_joints_in_frame": 0}
                for side in ("left", "right")}
    observed_min, observed_max = None, None
    frames_scanned = frames_mask_empty = valid_frames_skipped_empty = 0
    coverage, worst = [], None
    for index, frame in enumerate(stream(mask_path, "gray16le", np.uint16, width, height, 1)):
        if index >= n:
            break
        frames_scanned += 1
        mask = frame[..., 0]
        low, high = int(mask.min()), int(mask.max())
        observed_min = low if observed_min is None else min(observed_min, low)
        observed_max = high if observed_max is None else max(observed_max, high)
        if high == 0:
            frames_mask_empty += 1
            if bool(mask_valid[index]):
                valid_frames_skipped_empty += 1
            continue
        foreground = mask > 0
        total_in_frame = total_on = 0
        for slot, side in enumerate(("left", "right")):
            if not bool(mano_valid[index, slot]):
                continue
            data = per_side[side]
            data["frames_used"] += 1
            vertices = project(index, geometry[side][0], intrinsic, distortion, width,
                               height, cv2)
            rows = vertices["points"]
            on = int(foreground[rows[:, 1], rows[:, 0]].sum()) if len(rows) else 0
            data["vertices_in_frame"] += int(vertices["inside"].sum())
            data["vertices_on_foreground"] += on
            total_in_frame += int(vertices["inside"].sum())
            total_on += on
            joints = project(index, geometry[side][1], intrinsic, distortion, width,
                             height, cv2)
            data["joints_projected"] += int(joints["front"].sum())
            data["joints_in_frame"] += int(joints["inside"].sum())
            if joints["inside"].any():
                data["frames_with_joints_in_frame"] += 1
            joint_rows = joints["points"]
            data["joints_on_foreground"] += (int(foreground[joint_rows[:, 1],
                                                            joint_rows[:, 0]].sum())
                                             if len(joint_rows) else 0)
        #: a frame the release marks invalid is counted but kept out of the ratios, so a
        #: deliberately-flagged row cannot move the headline number
        if bool(mask_valid[index]) and total_in_frame:
            share = total_on / total_in_frame
            coverage.append(share)
            if worst is None or share < worst[1]:
                worst = (index, share)
    return {
        "frames_scanned": frames_scanned,
        "frames_the_mask_is_empty_on": frames_mask_empty,
        "valid_frames_excluded_because_the_mask_is_empty": valid_frames_skipped_empty,
        "observed_value_range": {"min": observed_min, "max": observed_max},
        "frames_used_for_coverage": len(coverage),
        "in_frame_vertices_median_on_foreground": (
            round(float(np.median(coverage)), 6) if coverage else None),
        "in_frame_vertices_min_on_foreground": (round(worst[1], 6) if worst else None),
        "least_covered_frame": (worst[0] if worst else None),
        "per_hand": per_side,
        "note": "the mask is a left+right union with no per-hand identity, so the per-hand "
                "counts describe the geometry each hand contributes, not a per-hand "
                "agreement; frames the release marks invalid, and frames whose mask is "
                "entirely zero, are excluded from the ratios and counted separately",
    }


_CV2 = None
_RUNTIME: dict = {}


def _cv2():
    """``cv2`` imported on demand: only the fisheye projection needs it."""
    global _CV2
    if _CV2 is None:
        import cv2
        _CV2 = cv2
    return _CV2


def mano_runtime(path):
    """One loaded MANO pair per process, however many views that process renders."""
    if "mano" not in _RUNTIME:
        _RUNTIME["mano"] = mano_review.ManoRuntime(Path(path), np, torch)
    return _RUNTIME["mano"]


# -- the page ---------------------------------------------------------------


def view_report(view: Path, meta: dict, records: dict, consumed: set, selected: list,
                media: list, scan, gaps) -> 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"],
        #: declared under source_rendering, and read_sequence.py asserts it against the
        #: release's own CAMERA_FAMILY_BY_VIEW_TYPE, so this is the released value, not a
        #: second derivation of it
        "camera_family": meta["source_rendering"].get("camera_family"),
        "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"]},
        "render_cell": declared_cell(meta),
        "series": records,
        "bundle_files": bundles,
        "media": media,
        "mano_on_mask": scan,
        "consumed_files": sorted(consumed),
        "declared_media_schema_gaps_counted_here": dict(gaps),
        "selected_frames": selected,
        "decode_scope": DECODE_SCOPE,
        "projection": {"model": meta["camera"]["model"], "scope": PROJECTION_SCOPE},
        "scope": REPORT_SCOPE,
    }


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

    return ('<p class="legend">配色沿用 ReInterHand v1.0 复核页自己的约定('
            "<code>draw_mano_meshes</code>:青左手、橙右手;前景用洋红叠加),便于与 "
            "<code>shared-v1.0/doc/validation/full_random/</code> 的页面并排读。"
            "<b>注意这不是 RHD 的红/蓝</b>——照抄 RHD 会让复核者把左右手读反:"
            + " · ".join([swatch(HAND_COLORS["left"], "左手(MANO 网格)"),
                          swatch(HAND_COLORS["right"], "右手(MANO 网格)"),
                          swatch(MASK_TINT, "前景强度叠加(洋红,α=0.72×强度)")])
            + "<br>mask 是 <code>segment/foreground_intensity/v1</code>:<b>非二值</b>前景"
              "强度 0–255、<b>左右手并集、无左右手身份</b>,所以它按灰度强度显示并带刻度"
              "条,而不是当成二值或按手着色。页面不画物体、不画接触、不画深度:这个 "
              "release 没有这三类内容。</p>")


def scan_note(scan, mano_record) -> str:
    """The header's account of the MANO-on-mask scan, with its own measured numbers."""
    median = scan["in_frame_vertices_median_on_foreground"]
    sides = scan["per_hand"]
    return ('<p class="note"><b>全视图扫描</b>(不止抽样帧:本视图 '
            + str(scan["frames_scanned"]) + " 帧全部参与,mask 从头到尾流式解一遍):把每个"
            "有效帧的 MANO 网格按其自身参数展开、经该视图声明的相机模型投到像素上,再看它"
            "落在 mask 前景里的比例。取左右手都在画内的顶点合计,中位覆盖 "
            + (f"{median:g}" if median is not None else "—(无可用帧)")
            + ("(覆盖最低的一帧是 " + str(scan["least_covered_frame"]) + ","
               + f"{scan['in_frame_vertices_min_on_foreground']:g})"
               if scan["least_covered_frame"] is not None else "")
            + ";进入比值的帧 " + str(scan["frames_used_for_coverage"]) + "。逐手:"
            + "|".join(f"{side} 有效 {sides[side]['frames_used']} 帧、画内顶点 "
                        f"{sides[side]['vertices_in_frame']}、落在前景 "
                        f"{sides[side]['vertices_on_foreground']}、关节画内 "
                        f"{sides[side]['joints_in_frame']}"
                        for side in ("left", "right"))
            + "。mask 全零的帧 " + str(scan["frames_the_mask_is_empty_on"]) + " 个"
            + ("(其中 " + str(scan["valid_frames_excluded_because_the_mask_is_empty"])
               + " 个本身是有效帧,因分母为零而不进比值)"
               if scan["valid_frames_excluded_because_the_mask_is_empty"] else "")
            + "。实测值域 " + str(scan["observed_value_range"]["min"]) + "–"
            + str(scan["observed_value_range"]["max"]) + "(声明 "
            + str(scan.get("declared_value_range")) + ")。MANO 模型来自树外 runtime "
            + html.escape(str(mano_record["runtime"])) + "(smplx "
            + html.escape(str(mano_record.get("smplx"))) + ")。<b>这个数只被记录,不被断言、"
            "也不用来「修正」任何发布值</b>:mask 没有左右手身份,所以它衡量的是「参数展开"
            "出的几何是否落在前景上」这一件事,系统性偏移会是关于源的发现,而不是页面的"
            "缺陷。</p>")


def render_one(view: Path, destination: Path, root: Path, declaration_path,
               runtime_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"]
    declaration = MediaDeclaration.load(declaration_path)
    identity = {"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": n}

    #: media first: this working copy ships the numeric layer for all 6,750 views and the
    #: media of two sample sequences, so "not renderable" is the normal answer for most views
    #: and has to be a named outcome rather than a crash
    media_names = [name for name, component in components.items()
                   if str(component.get("data_ref", "")).endswith(".mkv")]
    states = {name: declaration.state(view, meta["sequence_id"],
                                      components[name]["data_ref"])
              for name in media_names}
    blocked = {name: state for name, state in states.items() if state != "present"}
    if blocked:
        return dict(identity, rendered=False, media_states=states,
                    reason="this copy of the tree does not ship the media for this sequence "
                           "(" + ", ".join(sorted(set(blocked.values())))
                           + "), so no frame can be decoded",
                    scope=REPORT_SCOPE)

    reader = BundleReader()
    gaps = collections.Counter()
    consumed = check_view(view, meta, registry, reader, media=declaration, gaps=gaps)
    records = numeric_records(meta, reader, view)

    bundled = {name: reader.field(view, component)
               for name, component in components.items()
               if component.get("available", True) and "data_key" in component}
    validity = {name: values[1].numpy() for name, values in bundled.items()}
    intrinsic = bundled["intrinsic"][0].numpy().astype(np.float64)
    motion = bundled["mano"][0].numpy().astype(np.float64)
    mano_valid = bundled["mano"][1].numpy().astype(bool)
    distortion = (bundled["distortion"][0].numpy().astype(np.float64)
                  if "distortion" in bundled else None)
    #: check_view has already asserted the split; re-asserting it here is what keeps a fisheye
    #: view from being projected with the pinhole formula by accident
    assert (distortion is None) == (meta["camera"]["model"] == "pinhole"), (
        meta["camera"]["model"], distortion is not None)
    rgb_valid = standalone_validity(view, components["rgb"]).numpy().astype(bool)
    mask_valid = standalone_validity(view, components["segment"]).numpy().astype(bool)
    validity["rgb"], validity["segment"] = rgb_valid, mask_valid

    media = []
    for name in media_names:
        reference = view / components[name]["data_ref"]
        entry = {"component": name, "ref": components[name]["data_ref"], "state": "present",
                 "bytes": reference.stat().st_size,
                 "valid_ref": components[name].get("valid_ref")}
        entry.update(probe(reference))
        media.append(entry)
    for entry in media:
        assert entry["frames"] == n, (entry, n)
        #: CONTRACT: camera.image_size is [W, H], and read_sequence.py checks it the same way
        assert [entry["width"], entry["height"]] == [width, height], (entry, [width, height])

    mano = mano_runtime(runtime_path) if runtime_path is not None else None
    geometry, scan = None, None
    if mano is not None:
        geometry = {side: mano.geometry(side, motion) for side in ("left", "right")}
        scan = mano_mask_scan(meta, view / components["segment"]["data_ref"], mask_valid,
                              mano_valid, geometry, intrinsic, distortion, _cv2())
        segment = components["segment"]
        scan["declared_value_range"] = segment.get("value_range")
        scan["declared_normalization_scale"] = segment.get("normalization_scale")
        scan["foreground_category"] = segment.get("foreground_category")
        scan["identity_semantics"] = segment.get("identity_semantics")

    rows = frame_rows_of(view)
    selected = select_frames(
        n, [mano_valid, rgb_valid, mask_valid],
        extra=([scan["least_covered_frame"]]
               if scan and scan["least_covered_frame"] is not None else []))
    rgb = decode(view / components["rgb"]["data_ref"], selected, "rgb24", np.uint8,
                 width, height, 3)
    #: every mask frame the page shows, in one decoder call rather than one per frame
    masks = {index: frame[..., 0] for index, frame in
             decode(view / components["segment"]["data_ref"], selected, "gray16le",
                    np.uint16, width, height, 1).items()}

    panels_by_frame, details_by_frame = {}, {}
    hands_not_drawn, hands_off_frame, mask_above_range = [], {}, []
    for index in selected:
        panels = []
        image = rgb[index]
        panels.append((f"原生 RGB(MKV 解出的第 {index} 帧,未重编码;预览为 JPEG 有损缩放)",
                       picture(label_panel(
                           Image.fromarray(image),
                           f"RGB | frame {index} | source "
                           f"{rows.get(index, {}).get('source_frame_id')}"))))

        #: ``pixels_by_side`` is the single source of truth for "was this hand drawn" -- a
        #: side whose slot is invalid carries None, and everything downstream (the overlay,
        #: the caption, the per-frame record) reads that rather than keeping its own tally
        #: that can disagree
        pixels_by_side, joints_by_side, drawn = {}, {}, {}
        for slot, side in enumerate(("left", "right")):
            if mano is None or not bool(mano_valid[index, slot]):
                pixels_by_side[side] = None
                joints_by_side[side] = None
                hands_not_drawn.append({
                    "frame_index": index, "side": side,
                    "why": "no MANO runtime" if mano is None
                           else "valid=false in the release"})
                continue
            vertices = project(index, geometry[side][0], intrinsic, distortion, width,
                               height, _cv2())
            pixels_by_side[side] = vertices["pixels"]
            joints = project(index, geometry[side][1], intrinsic, distortion, width,
                             height, _cv2())
            joints_by_side[side] = joints
            if not joints["inside"].any():
                hands_off_frame[side] = hands_off_frame.get(side, 0) + 1

        if mano is None:
            panels.append(("MANO 面板未绘制:未提供 <code>--mano-runtime</code>;MANO 权重按 "
                           "CONTRACT 5.2 不属于共享发布,参数仍记录在报告中", None))
        else:
            overlay, drawn = mano_overlay(image, pixels_by_side, mano.faces, width, height)
            caption = ("共享 MANO 网格(由 <code>mano/axis_angle61/v1</code> 参数展开的相机系"
                       "顶点,经本视图自己的 " + html.escape(meta["camera"]["model"])
                       + " 投到像素;青=左手、橙=右手;可绘三角形数 左 "
                       + str(drawn["left"]) + " / 右 " + str(drawn["right"]) + ")")
            for side in ("left", "right"):
                if pixels_by_side[side] is None:
                    caption += (f";{side} 本帧 valid=false,未绘制(参数存在但发布标记为无效,"
                                "不拿它当结果画)")
            caption += "。网格按 v1.0 口径渲染:平移已在相机系,未再乘外参"
            panels.append((caption, picture(overlay)))

        mask = masks[index]
        shift = 8 if int(mask.max()) > 255 else 0
        if shift:
            mask_above_range.append({"frame_index": index, "max": int(mask.max())})
        panels.append((f"原生非二值 mask 强度(gray16le 原值,未二值化;本帧存储值 "
                       f"min={int(mask.min())} max={int(mask.max())}"
                       + (",超出声明值域,面板按 &gt;&gt;8 缩放显示)" if shift else ")"),
                       picture(mask_intensity_panel(mask, shift))))
        panels.append(("mask 叠加在 RGB 上(洋红=前景强度 ×0.72,上限 190,便于目视对齐;"
                       "这不是分类结果)", picture(mask_overlay(image, mask, shift))))

        details = {
            "frame_index": index,
            "source": rows.get(index),
            "validity_at_this_frame": {
                #: a row of a ``[T, 2]`` series is two flags, not one, so the frame is
                #: "valid" if any of its series is -- and the flags themselves are kept
                name: ({"valid": bool(values[index].any()),
                        "per_series": [bool(flag) for flag in values[index]]}
                       if values.ndim > 1 and values.shape[-1] <= 4
                       else {"valid": bool(values[index])})
                for name, values in validity.items()},
            "mano": {side: {
                "valid": bool(mano_valid[index, slot]),
                "triangles_drawn": drawn.get(side),
                "joints_in_frame": (int(joints_by_side[side]["inside"].sum())
                                    if joints_by_side.get(side) else None),
                "joints_on_foreground": (
                    int((mask > 0)[joints_by_side[side]["points"][:, 1],
                                   joints_by_side[side]["points"][:, 0]].sum())
                    if joints_by_side.get(side) and len(joints_by_side[side]["points"])
                    else None)}
                for slot, side in enumerate(("left", "right"))},
            "mask": {"stored_min": int(mask.min()), "stored_max": int(mask.max()),
                     "panel_shift": shift, "nonzero_pixels": int((mask > 0).sum()),
                     "valid": bool(mask_valid[index])},
        }
        panels_by_frame[index] = panels
        details_by_frame[index] = details

    report = view_report(view, meta, records, consumed, selected, media, scan, gaps)
    report.update(identity)
    report["rendered"] = True
    report["mano_runtime"] = mano.record if mano is not None else None
    report["hands_not_drawn"] = hands_not_drawn
    report["hands_geometry_entirely_off_frame"] = hands_off_frame
    report["frames_with_a_mask_value_above_the_declared_range"] = mask_above_range

    title = f"{view.parent.name}_{view.name}"
    sections = []
    for index in selected:
        figures = []
        for caption, source in panels_by_frame.get(index) or []:
            figures.append("<figure>" + (source or "") + "<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>")

    cell = declared_cell(meta)
    temporal = ("真实时序视频序列:每帧之间的时间关系本身是发布内容(可作跟踪/时序监督)"
                if cell.get("temporal_relationship") else
                "独立图片集合:MKV 只是无损批容器,<b>播放顺序不是时间</b>,不得当作运动、"
                "跟踪、速度或时序监督使用")
    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:460px}"
           ".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:1000px}"
           ".legend{background:#eef3fa;border-left:3px solid #4a76a8;padding:.6rem;"
           "font-size:.9rem;max-width:1000px}.swatch{border:1px solid #b9c3d0}")
    header = ("<h1>" + html.escape(title) + "</h1>"
              "<p>直接读取 v1.1 bundle(<code>" + html.escape(meta["sequence_id"])
              + "</code> 的 <code>" + html.escape(meta["camera_id"]) + "</code> 视图,"
              + html.escape(meta["view_type"]) + " / "
              + html.escape(str(cell.get("background_policy"))) + ",split="
              + html.escape(meta["split"]) + ",共 " + str(n) + " 帧)。" + temporal
              + "。预览仅供人工复核,不是训练输入(CONTRACT §6.5);本次只解码抽样的 "
              + str(len(selected)) + " 帧 RGB,mask 则整段解过一遍。</p>")
    header += colour_legend()
    header += (scan_note(scan, mano.record) if scan is not None else
               '<p class="note">本次未提供 <code>--mano-runtime</code>,所以没有做 '
               'MANO→mask 的投影扫描,MANO 面板也未绘制。这不是数据缺失:MANO 权重按 '
               'CONTRACT 5.2 不属于共享发布,参数本身仍逐帧记录在上面的报告里。</p>')
    header += ('<p class="legend">MANO 参数 schema <code>'
               + html.escape(str(components["mano"].get("schema_id")))
               + "</code>:48 维 16 关节轴角 + 10 维 shape + 3 维全局平移(共 61),姿态"
                 "弧度、平移米、<b>已在当前相机系</b>(CONTRACT 5.2),所以本页不对平移再乘"
                 "外参。平移是「模型输出顶点所加的全局平移」,<b>不是某个腕关节坐标</b>,"
                 "所以页面画的是展开后的网格而不是一个点。左右手各占 <code>hand</code> 轴"
                 "一个槽位,valid 逐帧逐手,本视图的有效帧数见上。</p>")
    if hands_off_frame:
        header += ('<p class="note">抽样帧里有 ' + html.escape(str(hands_off_frame))
                   + " 次出现整只手都投到画外。ReInterHand 的 per_frame 单元每帧独立换背景、"
                     "相机也逐图随机,这属正常形态;此处只记录,不改判据。</p>")
    if scan and scan["frames_the_mask_is_empty_on"]:
        header += ('<p class="note">本视图有 ' + str(scan["frames_the_mask_is_empty_on"])
                   + " 帧 mask 前景全为 0。这些帧不进覆盖比值(分母为零的比例没有意义),"
                     "但若被抽样仍会显示,以便复核者自己看一眼。</p>")
    if mask_above_range:
        header += ('<p class="note">抽样帧中有 ' + str(len(mask_above_range))
                   + " 帧的 mask 存储值超过声明值域 [0,255](最高 "
                   + str(max(item["max"] for item in mask_above_range))
                   + ")。容器是 gray16le,所以这可以表示;面板按 &gt;&gt;8 缩放显示并在图注"
                     "标明,未做静默截断。全视图实测值域见上。</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>持久化复核结果(同 .report.json)</summary><pre>"
            + html.escape(json.dumps(
                {key: value for key, value in report.items() if not key.startswith("_")},
                ensure_ascii=False, indent=2))
            + "</pre></details></html>")

    destination.mkdir(parents=True, exist_ok=True)
    (destination / (title + ".html")).write_text(page, encoding="utf-8")
    save(destination / (title + ".report.json"),
         {key: value for key, value in report.items() if not key.startswith("_")})
    report["_page"] = title + ".html"
    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, declaration, runtime = task
    return render_one(Path(view), Path(destination), Path(root),
                      None if declaration is None else Path(declaration),
                      None if runtime is None else Path(runtime))


# -- planning ---------------------------------------------------------------


def shard_facts(root: Path, sequence: str) -> dict:
    """Split, frame count, view count and render policy of one sequence."""
    metas = [load(path) for path in
             sorted((root / "data" / sequence).glob("*/metainfo.json"))]
    if not metas:
        raise SystemExit(f"{sequence}: no views found")
    policies = {meta["source_rendering"].get("background_policy") for meta in metas}
    types = {meta["view_type"] for meta in metas}
    #: a complete sequence is exactly the two view types under one policy -- the same census
    #: ``validate.py`` and ``read_sequence.py`` use, so a half-pulled sequence cannot be
    #: rendered as if it were whole
    if len(policies) != 1 or types != {"exo", "ego"}:
        raise SystemExit(f"{sequence}: {sorted(types)} / {sorted(policies)} is not a complete "
                         f"sequence")
    return {"sequence": sequence, "split": metas[0]["split"], "views": len(metas),
            "num_frames": max(meta["num_frames"] for meta in metas),
            "view_types": sorted(types),
            "camera_ids": sorted(meta["camera_id"] for meta in metas),
            "policy": sorted(policies)[0]}


def shippable(root: Path, declaration: MediaDeclaration) -> dict:
    """Facts for the sequences whose declared media this copy of the tree actually ships."""
    facts = {}
    for path in sorted((root / "data").iterdir()):
        if path.is_dir() and declaration.ships(path.name):
            facts[path.name] = shard_facts(root, path.name)
    return facts


def plan_views(facts: dict, seed: int, per_policy: int) -> list:
    """Stratified sample over the sequences that ship media, one stratum per render policy.

    ``background_policy`` is the only sequence-wide render value -- the camera family and
    frame rate differ *between* a sequence's exo and ego views by design -- so a sequence,
    not a view, is the sampling unit, and the strata are the policies rather than the four
    (view type, policy) cells.  Inside a stratum the sequences are drawn uniformly with the
    seed, and every view of a drawn sequence is rendered, which is what the v1.0 pages did
    ("展示抽中序列的全部相机和全部帧").  With the media declaration this working copy
    carries, the pool is the two sample sequences, so the draw is the whole media read-through;
    on a published tree, where every sequence ships its media, the same rule spreads the sample
    over both policies.  A draw with no candidate at all is refused rather than silently
    returning nothing.
    """
    rng = random.Random(seed)
    strata = collections.defaultdict(list)
    for sequence, fact in facts.items():
        strata[fact["policy"]].append(sequence)
    drawn = []
    for policy in sorted(strata):
        pool = sorted(strata[policy])
        drawn.extend(pool if len(pool) <= per_policy
                     else sorted(rng.sample(pool, per_policy)))
    if not drawn:
        raise SystemExit("no sequence ships its media, so nothing can be rendered")
    return sorted(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=20261015)
    parser.add_argument("--per-policy", type=int, default=1,
                        help="sequences drawn per render policy; all their views are rendered")
    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")
    parser.add_argument("--media-declaration", type=Path, default=DEFAULT_MEDIA_DECLARATION,
                        help="which sequences' media this copy ships (default: the "
                             "tree-external declaration)")
    parser.add_argument("--mano-runtime", type=Path, default=None,
                        help="directory with models/MANO_{LEFT,RIGHT}.pkl and a site/ holding "
                             "smplx; without it the MANO panel is not drawn (default: "
                             "<dataset>/tmp/runtime-v1.0 when it exists)")
    parser.add_argument("--report", type=Path, help="write the whole-run report here too")
    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()
    #: "what does the sampled review look like?" is a question about the review the run
    #: rendered, and V1_1_VALIDATION.json names it -- views requested, the sampling rule,
    #: every page's report -- beside the page set and index.html.  An explicit ``--views``
    #: is a smoke test, not that review, so it may not land there.  Decided here, before
    #: anything is decoded, and asserted rather than commented: the refusing run leaves
    #: the release's own pages and both release-wide files untouched.
    assert not args.views or destination != REVIEW_DIR.resolve(), (
        f"--views renders a selection, but {destination} holds the release's own review: "
        "the pages, V1_1_VALIDATION.json and index.html that describe the sampled review "
        "of the whole release; drop --views to render that sampling, or point --out "
        "outside the release to look at one view")
    declaration = MediaDeclaration.load(args.media_declaration)
    runtime = args.mano_runtime
    if runtime is None:
        candidate = DATASET_ROOT / "tmp" / "runtime-v1.0"
        runtime = candidate if (candidate / "models").is_dir() else None
    if runtime is not None and not (Path(runtime) / "models").is_dir():
        parser.error(f"--mano-runtime {runtime} has no models/ directory")

    release_sequences = sorted(path.name for path in (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
            if not (view / "metainfo.json").is_file():
                parser.error(f"no such view: {token}")
            views.append(view)
        selected_sequences = sorted({view.parent.name for view in views})
        sampling = {"kind": "explicit", "views": args.views,
                    "rule": "explicit view list; no sampling applied"}
    else:
        facts = shippable(root, declaration)
        selected_sequences = plan_views(facts, args.seed, args.per_policy)
        views = []
        for sequence in selected_sequences:
            views.extend(sorted(path.parent for path in
                                (root / "data" / sequence).glob("*/metainfo.json")))
        sampling = {
            "seed": args.seed,
            "rule": "sequences drawn uniformly inside each render policy, with the seed, from "
                    "the ones whose media this copy ships; every view of a drawn sequence is "
                    "rendered",
            "per_policy": args.per_policy,
            "sequences_in_release": len(release_sequences),
            "sequences_shipping_media": len(facts),
            "selections": [{"sequence": sequence, **facts[sequence]}
                           for sequence in selected_sequences],
        }

    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:
        results = list(pool.map(render_task,
                                [(str(view), str(destination), str(root),
                                  str(args.media_declaration),
                                  None if runtime is None else str(runtime))
                                 for view in views]))

    rendered = [entry for entry in results if entry.get("rendered")]
    skipped = [entry for entry in results if not entry.get("rendered")]
    scanned = [entry["mano_on_mask"] for entry in rendered if entry["mano_on_mask"]]
    medians = [scan["in_frame_vertices_median_on_foreground"] for scan in scanned
               if scan["in_frame_vertices_median_on_foreground"] is not None]
    report = {
        "review_kind": "全量后抽样",
        "dataset_id": "ReInterHand",
        "release_id": "shared-v1.1",
        "views_requested": len(views),
        "views_rendered": len(rendered),
        "views_not_renderable": len(skipped),
        "sequences": len(selected_sequences),
        "sampling": sampling,
        "media_declaration": {
            "path": str(args.media_declaration), "origin": declaration.origin,
            "materialised": (sorted(declaration.materialised)
                             if isinstance(declaration.materialised, set)
                             else declaration.materialised)},
        "mano_runtime": (str(runtime) if runtime is not None else None),
        "wall_seconds": round(time.monotonic() - start, 3),
        "decode_scope": DECODE_SCOPE,
        "mano_on_mask": {
            "views_scanned": len(scanned),
            "frames_scanned": sum(scan["frames_scanned"] for scan in scanned),
            "frames_the_mask_is_empty_on": sum(scan["frames_the_mask_is_empty_on"]
                                               for scan in scanned),
            "frames_used_for_coverage": sum(scan["frames_used_for_coverage"]
                                            for scan in scanned),
            "observed_value_range": {
                "min": min((scan["observed_value_range"]["min"] for scan in scanned),
                           default=None),
                "max": max((scan["observed_value_range"]["max"] for scan in scanned),
                           default=None)},
            "declared_value_ranges": sorted({tuple(scan["declared_value_range"])
                                             for scan in scanned
                                             if scan.get("declared_value_range")
                                             is not None}),
            "in_frame_vertices_on_foreground": {
                "views": len(medians),
                "median_of_view_medians": (round(float(np.median(medians)), 6)
                                           if medians else None),
                "worst_view_median": min(medians) if medians else None,
                "best_view_median": max(medians) if medians else None},
            "per_hand": {side: {key: sum(scan["per_hand"][side][key] for scan in scanned)
                                for key in ("frames_used", "joints_projected",
                                            "joints_in_frame", "joints_on_foreground",
                                            "vertices_in_frame", "vertices_on_foreground",
                                            "frames_with_joints_in_frame")}
                         for side in ("left", "right")},
            "scope": PROJECTION_SCOPE},
        "reports": [{key: value for key, value in entry.items() if not key.startswith("_")}
                    for entry in results],
        "scope": "post-full sampled views, read directly from v1.1 bundles and decoded from "
                 "the preserved media; evidence for human acceptance, not training input; "
                 "manual review pending",
    }
    if args.report:
        save(args.report, report)
    save(destination / "V1_1_VALIDATION.json", report)

    index_css = ("body{font:16px sans-serif;max-width:1300px;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:1000px}.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:.85rem}"
                 ".note{background:#fff7e6;border-left:3px solid #e0a800;padding:.6rem;"
                 "font-size:.9rem;max-width:1000px}")
    rows = []
    for entry in sorted(rendered, key=lambda item: (item["sequence_id"], item["camera_id"])):
        scan = entry["mano_on_mask"]
        median = scan["in_frame_vertices_median_on_foreground"] if scan else None
        hands = (entry["series"].get("mano") or {}).get("valid_true_per_series")
        value_range = (f"{scan['observed_value_range']['min']}–"
                       f"{scan['observed_value_range']['max']}" if scan else "—")
        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>"
                    + html.escape(str(entry["render_cell"].get("background_policy")))
                    + "</td><td>" + html.escape(entry["view_type"]) + "</td><td>"
                    + str(entry["num_frames"]) + "</td><td>"
                    + str(len(entry["selected_frames"])) + "</td><td>"
                    + ("/".join(str(count) for count in hands) + f" / {entry['num_frames']}"
                       if hands else "—")
                    + "</td><td>"
                    + " / ".join(str(item["bytes"] // 1024) + " KiB"
                                 for item in entry["media"])
                    + "</td><td>" + (f"{median:g}" if median is not None else "—")
                    + "</td><td>" + value_range + "</td></tr>")
    skipped_rows = "".join(
        "<li>" + html.escape(entry["view"]) + " — " + html.escape(entry["reason"]) + "</li>"
        for entry in skipped)
    index = ('<!doctype html><html lang="zh"><meta charset="utf-8">'
             "<title>ReInterHand shared-v1.1 review</title><style>" + index_css + "</style>"
             "<h1>ReInterHand shared-v1.1 全量后抽样人工复查</h1>"
             "<p>数值按字节一致(CONTRACT §6);媒体不重新编码。抽样规则与种子见 "
             "V1_1_VALIDATION.json,本页所列视图即全部入选视图:" + str(len(rendered))
             + " 个视图 / " + str(len(selected_sequences)) + " 段序列。逐字段字节验收见 "
             "<code>verify.py</code>,全树结构校验见 <code>validate.py</code>,含媒体的完整"
             "读取见 <code>read_sequence.py</code>,证据留档在发布树外的 "
             "<code>tmp/reinterhand-tools/</code>。</p>" + colour_legend()
             + "<p>每页只解码该视图抽样的帧 RGB;<b>但 MANO↔mask 覆盖扫描跑的是每个入选"
               "视图的全部帧</b>(mask 整段流式解一遍),全量结果见 V1_1_VALIDATION.json 的 "
               "<code>mano_on_mask</code>。表里的覆盖中位是「左右手合计的画内顶点落在 mask "
               "前景里的比例」的中位;mask 无左右手身份,故不分手断言。「MANO 有效帧」列是"
               "左右手各自 valid=true 的帧数(分母为总帧数)——本发布里逐帧有效并非普遍成立,"
               "ego 视图尤其稀疏。</p>"
             + "<table><tr><th>视图</th><th>split</th><th>背景策略</th><th>类型</th>"
               "<th>帧数</th><th>本页抽样帧</th><th>MANO 有效帧 左/右</th>"
               "<th>媒体(rgb / mask)</th><th>前景覆盖中位</th><th>mask 实测值域</th></tr>"
             + "".join(rows) + "</table>"
             + ('<h2>未渲染的视图</h2><p>这些视图的媒体在本工作副本里按声明缺失,'
                "因此无法解码;这是预期,不是失败。</p><ul>" + skipped_rows + "</ul>"
                if skipped else "")
             + '<ul><li><a href="../CONTRACT.md">CONTRACT.md</a></li>'
               '<li><a href="../RAW_MAPPING.md">RAW_MAPPING.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 sorted(path.name for path in destination.glob("*.html")
                                      if path.name != "index.html"))
             + "</ul></html>")
    destination.mkdir(parents=True, exist_ok=True)
    (destination / "index.html").write_text(index, encoding="utf-8")
    print("RENDER_DONE", len(rendered), "rendered,", len(skipped), "not renderable,",
          round(report["wall_seconds"], 2), "seconds ->", destination / "index.html",
          flush=True)
    return 0


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