File size: 92,435 Bytes
81d9e86 | 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 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 | """ReInterHand hand-warehouse/1.0 preprocessing entry point.
The first implemented stage extracts one complete named sequence from the
already verified split archives. Raw archives are opened read-only and are
never joined, renamed, or modified. Later conversion and validation stages
consume this deterministic extraction manifest.
Example:
python preprocess_reinterhand.py extract-pilot \
--root /data2/shaoyunzhe/hand-datasets/ReInterHand
"""
from __future__ import annotations
import argparse
import codecs
import collections
import hashlib
import io
import json
import os
from pathlib import Path, PurePosixPath
import pickle
import shutil
import subprocess
import sys
import tarfile
from datetime import datetime, timezone
from types import SimpleNamespace
CAPTURE = "m--20221110--1033--TQH976--pilot--ProjectGoliathScript--Hands--two-hands"
SEGMENT = "DOU_finger_occlusions"
INTERWILD_SPLIT_REVISION = "7c01e4ad4909652056a68af93b4c16ceabbce8fe"
INTERWILD_TEST_CAPTURES = {
"m--20221215--0949--RNS217--pilot--ProjectGoliathScript--Hands--two-hands",
"m--20221216--0953--NKC880--pilot--ProjectGoliathScript--Hands--two-hands",
"m--20230317--1130--QZX685--pilot--ProjectGoliath--Hands--two-hands",
}
def official_split_metadata(capture: str) -> dict:
"""Return the capture-level split fixed by the official InterWild loader."""
return {
"split": "test" if capture in INTERWILD_TEST_CAPTURES else "train",
"split_scheme": "InterWild_official_capture_split",
"split_source_locator": {
"url": (
"https://github.com/facebookresearch/InterWild/blob/"
f"{INTERWILD_SPLIT_REVISION}/data/ReInterHand/ReInterHand.py"
),
"capture_id": capture,
},
}
def now() -> str:
return datetime.now(timezone.utc).isoformat()
def atomic_json(path: Path, value: object) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_name(path.name + ".tmp")
temporary.write_text(json.dumps(value, indent=2, sort_keys=True), encoding="utf-8")
os.replace(temporary, path)
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as stream:
for block in iter(lambda: stream.read(8 * 1024 * 1024), b""):
digest.update(block)
return digest.hexdigest()
def canonical_parts(folder: Path, prefix: str) -> list[Path]:
# Canonical archive parts end with exactly two lowercase letters. This
# intentionally excludes downloaded duplicate names such as .gzaa.1.
parts = sorted(
path
for path in folder.glob(prefix + "??")
if len(path.name) == len(prefix) + 2 and path.name[-2:].islower()
)
if not parts:
raise FileNotFoundError(f"No canonical parts for {folder / (prefix + '??')}")
return parts
def safe_output(base: Path, member_name: str) -> Path:
member = PurePosixPath(member_name)
if member.is_absolute() or ".." in member.parts:
raise RuntimeError(f"Unsafe archive member: {member_name}")
output = base.joinpath(*member.parts)
if not output.resolve().is_relative_to(base.resolve()):
raise RuntimeError(f"Archive member escapes extraction root: {member_name}")
return output
def wanted(group: str, member_name: str, frame_tokens: set[str]) -> bool:
path = PurePosixPath(member_name)
if not path.name:
return False
stem = path.stem
normalized = stem.rsplit("_", 1)[0] if group == "mano_fits" else stem
if normalized.isdigit():
normalized = str(int(normalized))
selected = normalized in frame_tokens
if group == "Ego_cameras":
return selected and path.suffix.lower() in {".png", ".json"} or path.name == "truncation_ratio.json"
if group == "Mugsy_cameras":
return selected and path.suffix.lower() == ".png"
if group == "mano_fits":
return selected and path.suffix.lower() in {".json", ".obj", ".ply"}
raise ValueError(group)
def extract_archive(
group: str,
parts: list[Path],
output_root: Path,
frame_tokens: set[str],
status_path: Path,
status: dict,
) -> list[dict]:
destination = output_root / group
destination.mkdir(parents=True, exist_ok=True)
process = subprocess.Popen(["cat", *map(str, parts)], stdout=subprocess.PIPE)
assert process.stdout is not None
records: list[dict] = []
scanned = 0
try:
with tarfile.open(fileobj=process.stdout, mode="r|gz") as archive:
for member in archive:
if not member.isfile():
continue
scanned += 1
if not wanted(group, member.name, frame_tokens):
continue
output = safe_output(destination, member.name)
output.parent.mkdir(parents=True, exist_ok=True)
source = archive.extractfile(member)
if source is None:
raise RuntimeError(f"Cannot read selected member: {member.name}")
with source, output.open("wb") as target:
shutil.copyfileobj(source, target, length=8 * 1024 * 1024)
if output.stat().st_size != member.size:
raise RuntimeError(f"Size mismatch after extraction: {member.name}")
records.append(
{
"group": group,
"member": member.name,
"bytes": member.size,
"sha256": sha256(output),
"output": output.relative_to(output_root).as_posix(),
}
)
status.update(updated_at=now(), active_group=group, members_scanned=scanned, selected_files=len(records))
atomic_json(status_path, status)
finally:
process.stdout.close()
return_code = process.wait()
if return_code != 0:
raise RuntimeError(f"cat failed for {group}: exit {return_code}")
status.update(updated_at=now(), active_group=group, members_scanned=scanned, selected_files=len(records))
atomic_json(status_path, status)
return records
def frame_ids(capture_root: Path, segment: str) -> list[int]:
rows = [line.split() for line in (capture_root / "frame_list.txt").read_text(encoding="utf-8").splitlines()]
result = [int(row[1]) for row in rows if len(row) >= 2 and row[0] == segment]
if not result or len(result) != len(set(result)) or result != sorted(result):
raise RuntimeError(f"Invalid or empty frame list for {segment}")
return result
def validate_extraction(output_root: Path, ids: list[int]) -> dict:
expected = {str(value) for value in ids}
images: dict[str, set[str]] = {}
for path in output_root.rglob("*.png"):
if "images" not in path.parts:
continue
stem = path.stem
if not stem.isdigit() or str(int(stem)) not in expected:
continue
relative = path.relative_to(output_root).parts
image_index = relative.index("images")
camera = "/".join(relative[: image_index + 1])
if len(relative) > image_index + 2:
camera += "/" + "/".join(relative[image_index + 1 : -1])
images.setdefault(camera, set()).add(str(int(stem)))
incomplete = {camera: sorted(expected - found, key=int) for camera, found in images.items() if found != expected}
mano = {"left": set(), "right": set()}
for path in (output_root / "mano_fits").rglob("*.json"):
for side in mano:
suffix = "_" + side
if path.stem.endswith(suffix) and path.stem[: -len(suffix)].isdigit():
mano[side].add(str(int(path.stem[: -len(suffix)])))
missing_mano = {side: sorted(expected - found, key=int) for side, found in mano.items() if found != expected}
if not images or incomplete or missing_mano:
raise RuntimeError(
"Pilot extraction coverage failed: "
+ json.dumps({"cameras": sorted(images), "incomplete": incomplete, "missing_mano": missing_mano})
)
return {
"camera_count": len(images),
"camera_frames": {camera: len(found) for camera, found in sorted(images.items())},
"mano_frames": {side: len(found) for side, found in mano.items()},
}
def extract_pilot(root: Path, capture: str, segment: str) -> None:
capture_root = root / "raw" / "data" / capture
ids = frame_ids(capture_root, segment)
state = root / "tmp" / "pilot-v1.0"
output = state / "extracted" / f"{capture}__{segment}"
status_path = state / "status.json"
status = {
"schema": "reinterhand-pilot-status/v1",
"phase": "extracting",
"capture": capture,
"segment": segment,
"frames": len(ids),
"started_at": now(),
"updated_at": now(),
}
atomic_json(status_path, status)
sources = {
"Ego_cameras": canonical_parts(capture_root / "Ego_cameras", "envmap_per_segment.tar.gz"),
"Mugsy_cameras": canonical_parts(capture_root / "Mugsy_cameras", "envmap_per_segment.tar.gz"),
"mano_fits": canonical_parts(capture_root / "mano_fits", "mano_fits.tar.gz"),
}
records: list[dict] = []
try:
for group, parts in sources.items():
records.extend(extract_archive(group, parts, output, {str(value) for value in ids}, status_path, status))
mugsy_camera = capture_root / "Mugsy_cameras" / "cam_params.json"
mugsy_target = output / "Mugsy_cameras" / "cam_params.json"
mugsy_target.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(mugsy_camera, mugsy_target)
records.append(
{
"group": "Mugsy_cameras",
"member": "cam_params.json",
"bytes": mugsy_target.stat().st_size,
"sha256": sha256(mugsy_target),
"output": mugsy_target.relative_to(output).as_posix(),
}
)
coverage = validate_extraction(output, ids)
manifest = {
"schema": "reinterhand-pilot-extraction/v1",
"capture": capture,
"segment": segment,
"source_frame_ids": ids,
"timestamp_policy": "unknown; preserve source_frame_id and sync_id, do not infer FPS",
"raw_read_only": True,
"source_archives": {
group: [{"path": path.relative_to(root).as_posix(), "bytes": path.stat().st_size} for path in parts]
for group, parts in sources.items()
},
"coverage": coverage,
"files": records,
"completed_at": now(),
}
atomic_json(state / "extraction-manifest.json", manifest)
status.update(phase="extracted", updated_at=now(), files=len(records), coverage=coverage)
atomic_json(status_path, status)
except Exception as exc:
status.update(phase="failed", updated_at=now(), error_type=type(exc).__name__, error=str(exc))
atomic_json(status_path, status)
raise
def extract_background_variant(root: Path, capture: str, segment: str, variant: str) -> None:
"""Add one released RGB/background variant to the same read-only pilot extraction."""
if variant not in {"envmap_per_frame", "envmap_per_segment"}:
raise ValueError(variant)
capture_root = root / "raw" / "data" / capture
ids = frame_ids(capture_root, segment)
state = root / "tmp" / "pilot-v1.0"
output = state / "extracted" / f"{capture}__{segment}"
status_path = state / "status.json"
status = json.loads(status_path.read_text(encoding="utf-8"))
status.update(phase="extracting_background_variant", variant=variant, updated_at=now())
atomic_json(status_path, status)
sources = {
"Ego_cameras": canonical_parts(capture_root / "Ego_cameras", variant + ".tar.gz"),
"Mugsy_cameras": canonical_parts(capture_root / "Mugsy_cameras", variant + ".tar.gz"),
}
records: list[dict] = []
for group, parts in sources.items():
records.extend(extract_archive(group, parts, output, {str(value) for value in ids}, status_path, status))
coverage = validate_extraction(output, ids)
manifest_path = state / "extraction-manifest.json"
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
manifest.setdefault("background_variants", {})[variant] = {
"source_archives": {
group: [{"path": path.relative_to(root).as_posix(), "bytes": path.stat().st_size} for path in parts]
for group, parts in sources.items()
},
"files": records,
"completed_at": now(),
}
manifest["coverage"] = coverage
atomic_json(manifest_path, manifest)
status.update(phase="background_variant_extracted", variant=variant, coverage=coverage,
selected_files=len(records), updated_at=now())
atomic_json(status_path, status)
def runtime_imports(runtime: Path):
sys.path.insert(0, str(runtime / "site"))
import cv2
import numpy as np
from PIL import Image
import smplx
import torch
return np, torch, cv2, Image, smplx
class StoredState:
def __setstate__(self, state):
self.__dict__.update(state)
def model_reader_class(np, torch):
class Restricted(pickle.Unpickler):
def find_class(self, module, name):
allowed = {
("numpy.core.multiarray", "_reconstruct"): np.core.multiarray._reconstruct,
("numpy._core.multiarray", "_reconstruct"): np.core.multiarray._reconstruct,
("numpy", "ndarray"): np.ndarray,
("numpy", "dtype"): np.dtype,
("numpy.core.numeric", "_frombuffer"): np.core.numeric._frombuffer,
("numpy._core.numeric", "_frombuffer"): np.core.numeric._frombuffer,
("_codecs", "encode"): codecs.encode,
("collections", "OrderedDict"): collections.OrderedDict,
("torch._utils", "_rebuild_tensor_v2"): torch._utils._rebuild_tensor_v2,
("torch.storage", "_load_from_bytes"): lambda value: torch.load(
io.BytesIO(value), map_location="cpu", weights_only=True
),
}
special = {
("chumpy.ch", "Ch"): StoredState,
("chumpy.reordering", "Select"): StoredState,
("scipy.sparse.csc", "csc_matrix"): StoredState,
("__builtin__", "set"): set,
}
if (module, name) in special:
return special[(module, name)]
if (module, name) not in allowed:
raise pickle.UnpicklingError(f"Unsupported model class: {module}.{name}")
return allowed[(module, name)]
return Restricted
def model_data(model_path: Path, np, torch) -> dict:
Reader = model_reader_class(np, torch)
with model_path.open("rb") as stream:
data = Reader(stream, encoding="latin1").load()
shapedirs = data["shapedirs"]
if isinstance(shapedirs, StoredState):
data["shapedirs"] = shapedirs.a.x.reshape(-1)[shapedirs.idxs].reshape(shapedirs.preferred_shape)
sparse = data["J_regressor"]
if isinstance(sparse, StoredState):
dense = np.zeros(sparse._shape)
for column in range(sparse._shape[1]):
begin, end = sparse.indptr[column : column + 2]
dense[sparse.indices[begin:end], column] = sparse.data[begin:end]
data["J_regressor"] = dense
if data["shapedirs"].shape != (778, 3, 10) or data["J_regressor"].shape != (16, 778):
raise RuntimeError("Unexpected MANO model dimensions")
return data
class ManoModel:
def __init__(self, side, model_dir, np, torch, smplx):
self.side = side
self.np = np
self.torch = torch
self.data = model_data(model_dir / f"MANO_{side.upper()}.pkl", np, torch)
self.layer = smplx.MANO(
model_path=str(model_dir),
data_struct=SimpleNamespace(**self.data),
is_rhand=side == "right",
use_pca=False,
flat_hand_mean=True,
)
def geometry(self, pose, betas, translation=None):
np, torch = self.np, self.torch
pose_tensor = torch.as_tensor(np.asarray(pose).copy(), dtype=torch.float32).reshape(-1, 48)
beta_tensor = torch.as_tensor(np.asarray(betas).copy(), dtype=torch.float32).reshape(-1, 10)
with torch.no_grad():
output = self.layer(
global_orient=pose_tensor[:, :3], hand_pose=pose_tensor[:, 3:], betas=beta_tensor
)
vertices = output.vertices.numpy()
joints = output.joints.numpy()[:, :16]
if translation is not None:
offset = np.asarray(translation).reshape(-1, 1, 3)
vertices = vertices + offset
joints = joints + offset
return vertices, joints
def read_ply_vertices(path: Path, np):
lines = path.read_text(encoding="ascii").splitlines()
if lines[0] != "ply" or lines[1] != "format ascii 1.0":
raise RuntimeError(f"Unsupported source mesh: {path}")
vertex_line = next(line for line in lines if line.startswith("element vertex "))
count = int(vertex_line.split()[-1])
begin = lines.index("end_header") + 1
return np.array([[float(value) for value in line.split()[:3]] for line in lines[begin : begin + count]]) / 1000
def camera_mano(model, pose, betas, translation, extrinsic, np, cv2):
root = np.einsum(
"v,tvc->tc",
model.data["J_regressor"][0],
model.data["v_template"][None] + np.einsum("vci,ti->tvc", model.data["shapedirs"], betas),
)
normalized_pose = pose.copy()
normalized_pose[:, :3] = np.stack(
[cv2.Rodrigues(E[:3, :3] @ cv2.Rodrigues(source[:3])[0])[0].ravel() for E, source in zip(extrinsic, pose)]
)
normalized_translation = (
np.einsum("tij,tj->ti", extrinsic[:, :3, :3], root + translation)
+ extrinsic[:, :3, 3]
- root
)
world_vertices, _ = model.geometry(pose, betas, translation)
camera_vertices, _ = model.geometry(normalized_pose, betas, normalized_translation)
expected = np.einsum("tij,tvj->tvi", extrinsic[:, :3, :3], world_vertices) + extrinsic[:, None, :3, 3]
error = float(np.linalg.norm(camera_vertices - expected, axis=-1).max())
if error >= 2e-5:
raise RuntimeError(f"MANO camera transform error: {error}")
return np.concatenate([normalized_pose, betas, normalized_translation], axis=-1), error, camera_vertices
def save_tensor(path: Path, value, torch, np) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
array = np.asarray(value)
temporary = path.with_name(path.name + ".tmp")
torch.save(torch.from_numpy(array.copy()), temporary)
os.replace(temporary, path)
restored = torch.load(path, map_location="cpu", weights_only=True).numpy()
if not np.array_equal(restored, array, equal_nan=True):
raise RuntimeError(f"Tensor round-trip mismatch: {path}")
def write_jsonl(path: Path, rows: list[dict]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_name(path.name + ".tmp")
with temporary.open("w", encoding="utf-8", newline="\n") as stream:
for row in rows:
stream.write(json.dumps(row, sort_keys=True) + "\n")
os.replace(temporary, path)
def encode_lossless_video(paths: list[Path], output: Path, size: tuple[int, int], Image, hashlib_module=hashlib):
width, height = size
output.parent.mkdir(parents=True, exist_ok=True)
temporary = output.with_name(output.stem + ".tmp" + output.suffix)
ffmpeg_threads = str(max(1, int(os.environ.get("REINTERHAND_FFMPEG_THREADS", "2"))))
command = [
"ffmpeg", "-v", "error", "-y", "-f", "rawvideo", "-pixel_format", "rgb24",
"-video_size", f"{width}x{height}", "-framerate", "1", "-i", "pipe:0",
"-an", "-c:v", "ffv1", "-level", "3", "-g", "1", "-threads", ffmpeg_threads, str(temporary),
]
process = subprocess.Popen(command, stdin=subprocess.PIPE)
hashes = []
assert process.stdin is not None
try:
for path in paths:
image = Image.open(path).convert("RGB")
if image.size != size:
raise RuntimeError(f"Image size changed in view: {path}")
payload = image.tobytes()
hashes.append(hashlib_module.sha256(payload).hexdigest())
process.stdin.write(payload)
finally:
process.stdin.close()
if process.wait() != 0:
raise RuntimeError(f"FFV1 encoder failed: {output}")
os.replace(temporary, output)
decoder = subprocess.Popen(
["ffmpeg", "-v", "error", "-threads", "1", "-i", str(output), "-f", "rawvideo", "-pix_fmt", "rgb24", "pipe:1"],
stdout=subprocess.PIPE,
)
assert decoder.stdout is not None
frame_bytes = width * height * 3
for expected in hashes:
payload = decoder.stdout.read(frame_bytes)
if len(payload) != frame_bytes or hashlib_module.sha256(payload).hexdigest() != expected:
raise RuntimeError(f"Full-frame RGB round-trip failed: {output}")
if decoder.stdout.read(1) or decoder.wait() != 0:
raise RuntimeError(f"Unexpected decoded frame count: {output}")
return hashes
def encode_mask_video(paths: list[Path], output: Path, size: tuple[int, int], Image, np):
width, height = size
output.parent.mkdir(parents=True, exist_ok=True)
temporary = output.with_name(output.stem + ".tmp" + output.suffix)
ffmpeg_threads = str(max(1, int(os.environ.get("REINTERHAND_FFMPEG_THREADS", "2"))))
process = subprocess.Popen(
[
"ffmpeg", "-v", "error", "-y", "-f", "rawvideo", "-pixel_format", "gray16le",
"-video_size", f"{width}x{height}", "-framerate", "1", "-i", "pipe:0",
"-an", "-c:v", "ffv1", "-level", "3", "-g", "1", "-threads", ffmpeg_threads, str(temporary),
],
stdin=subprocess.PIPE,
)
hashes = []
histogram = np.zeros(256, dtype=np.int64)
assert process.stdin is not None
try:
for path in paths:
source = np.asarray(Image.open(path))
if source.shape != (height, width) or source.dtype != np.uint8:
raise RuntimeError(f"Unexpected mask format: {path}")
histogram += np.bincount(source.ravel(), minlength=256)
payload = source.astype("<u2").tobytes()
hashes.append(hashlib.sha256(payload).hexdigest())
process.stdin.write(payload)
finally:
process.stdin.close()
if process.wait() != 0:
raise RuntimeError(f"Mask encoder failed: {output}")
os.replace(temporary, output)
decoder = subprocess.Popen(
["ffmpeg", "-v", "error", "-threads", "1", "-i", str(output), "-f", "rawvideo", "-pix_fmt", "gray16le", "pipe:1"],
stdout=subprocess.PIPE,
)
assert decoder.stdout is not None
frame_bytes = width * height * 2
for expected in hashes:
payload = decoder.stdout.read(frame_bytes)
if len(payload) != frame_bytes or hashlib.sha256(payload).hexdigest() != expected:
raise RuntimeError(f"Mask round-trip failed: {output}")
if decoder.stdout.read(1) or decoder.wait() != 0:
raise RuntimeError(f"Unexpected decoded mask count: {output}")
return histogram.tolist()
def component(data_ref, valid_ref, schema_id, axes, valid_axes, source_locator, method, **extra):
return {
"available": True,
"schema_id": schema_id,
"data_ref": data_ref,
"axes": axes,
"valid_ref": valid_ref,
"valid_axes": valid_axes,
"provenance": {"kind": "format_conversion", "method": method},
"source_locator": source_locator,
**extra,
}
def convert_pilot(root: Path, runtime: Path, capture: str, segment: str) -> None:
np, torch, cv2, Image, smplx = runtime_imports(runtime)
state = root / "tmp" / "pilot-v1.0"
status_path = state / "status.json"
extraction = json.loads((state / "extraction-manifest.json").read_text(encoding="utf-8"))
if extraction["capture"] != capture or extraction["segment"] != segment:
raise RuntimeError("Pilot extraction selection differs from conversion request")
ids = [int(value) for value in extraction["source_frame_ids"]]
T = len(ids)
source = state / "extracted" / f"{capture}__{segment}"
sequence_id = f"{capture}__{segment}"
release = root / "shared-v1.0"
status = json.loads(status_path.read_text(encoding="utf-8"))
status.update(phase="converting", updated_at=now(), views_completed=[])
atomic_json(status_path, status)
models = [
ManoModel("left", runtime / "models", np, torch, smplx),
ManoModel("right", runtime / "models", np, torch, smplx),
]
left_fix = bool(np.abs(models[0].data["shapedirs"][:, 0] - models[1].data["shapedirs"][:, 0]).sum() < 1)
if left_fix:
models[0].data["shapedirs"][:, 0] *= -1
with torch.no_grad():
models[0].layer.shapedirs[:, 0] *= -1
native = {}
source_meshes = {}
source_mesh_errors = []
for hand_index, side in enumerate(["left", "right"]):
rows = [json.loads((source / "mano_fits" / "params" / f"{frame}_{side}.json").read_text()) for frame in ids]
pose = np.stack([row["pose"] for row in rows]).astype(np.float64)
betas = np.stack([row["shape"] for row in rows]).astype(np.float64)
translation = np.stack([row["trans"] for row in rows]).astype(np.float64)
pose[:, 3:] += models[hand_index].data["hands_mean"]
predicted, _ = models[hand_index].geometry(pose, betas, translation)
meshes = np.stack(
[read_ply_vertices(source / "mano_fits" / "meshes" / f"{frame}_{side}.ply", np) for frame in ids]
)
error = np.linalg.norm(predicted - meshes, axis=-1)
if float(error.max()) >= 1e-4:
raise RuntimeError(f"Source MANO parameters do not reproduce source {side} meshes: {error.max()}")
source_mesh_errors.append({"side": side, "max_m": float(error.max()), "mean_m": float(error.mean())})
native[side] = (pose, betas, translation)
source_meshes[side] = meshes
mugsy_params = json.loads((source / "Mugsy_cameras" / "cam_params.json").read_text())
views = []
ego_images = source / "Ego_cameras" / "envmap_per_segment" / "images"
views.append(("ego_envmap_per_segment", "ego", ego_images, None))
mugsy_images = source / "Mugsy_cameras" / "envmap_per_segment" / "images"
for camera_dir in sorted(path for path in mugsy_images.iterdir() if path.is_dir()):
views.append((camera_dir.name, "exo", camera_dir, mugsy_params[camera_dir.name]))
review = {
"schema": "reinterhand-pilot-validation/v1",
"dataset": "ReInterHand",
"sequence_id": sequence_id,
"capture": capture,
"segment": segment,
"frames": T,
"source_frame_ids": ids,
"source_fps": None,
"timestamp_policy": "No trustworthy source timestamps or FPS in this release; preserve frame order, source_frame_id and cross-camera sync_id only.",
"source_mesh_parameter_checks": source_mesh_errors,
"left_shapedirs_fix": left_fix,
"views": [],
"human_review": "pending",
}
for camera_id, view_type, image_root, static_camera in views:
view = release / "data" / sequence_id / camera_id
image_paths = [image_root / f"{frame:06d}.png" for frame in ids]
first = Image.open(image_paths[0]).convert("RGB")
width, height = first.size
rgb_hashes = encode_lossless_video(image_paths, view / "observation" / "rgb.mkv", (width, height), Image)
if view_type == "ego":
camera_rows = [
json.loads(
(source / "Ego_cameras" / "envmap_per_segment" / "cam_params" / f"{frame:06d}.json").read_text()
)
for frame in ids
]
else:
camera_rows = [static_camera] * T
intrinsic = np.stack(
[
[[row["focal"][0], 0, row["princpt"][0]], [0, row["focal"][1], row["princpt"][1]], [0, 0, 1]]
for row in camera_rows
]
).astype(np.float32)
extrinsic = np.broadcast_to(np.eye(4, dtype=np.float32), (T, 4, 4)).copy()
extrinsic[:, :3, :3] = np.stack([row["R"] for row in camera_rows])
extrinsic[:, :3, 3] = np.stack([row["t"] for row in camera_rows]) / 1000
distortion = np.stack([row["D"] for row in camera_rows]).astype(np.float32) if view_type == "ego" else None
valid_frames = np.ones(T, dtype=bool)
save_tensor(view / "camera" / "intrinsic.pt", intrinsic, torch, np)
save_tensor(view / "camera" / "intrinsic_valid.pt", valid_frames, torch, np)
save_tensor(view / "camera" / "extrinsic.pt", extrinsic, torch, np)
save_tensor(view / "camera" / "extrinsic_valid.pt", valid_frames, torch, np)
if distortion is not None:
save_tensor(view / "camera" / "distortion.pt", distortion, torch, np)
save_tensor(view / "camera" / "distortion_valid.pt", valid_frames, torch, np)
motion = np.empty((T, 2, 61), dtype=np.float32)
camera_meshes = {}
transform_checks = []
for hand_index, side in enumerate(["left", "right"]):
pose, betas, translation = native[side]
converted, error, normalized_vertices = camera_mano(
models[hand_index], pose, betas, translation, extrinsic, np, cv2
)
motion[:, hand_index] = converted
camera_meshes[side] = normalized_vertices
transform_checks.append({"side": side, "max_vertex_error_m": error})
save_tensor(view / "annotation" / "mano" / "motion.pt", motion, torch, np)
save_tensor(view / "annotation" / "mano" / "motion_valid.pt", np.ones((T, 2), dtype=bool), torch, np)
components = {
"rgb": component(
"observation/rgb.mkv", "observation/rgb_valid.pt", "rgb/uint8/v1",
["T", "height", "width", "channel"], ["T"],
{"archive_prefix": f"raw/data/{capture}/{'Ego_cameras' if view_type == 'ego' else 'Mugsy_cameras'}/envmap_per_segment.tar.gz", "member_template": f"envmap_per_segment/images/{'' if view_type == 'ego' else camera_id + '/'}{{source_frame_id:06d}}.png"},
"Source PNG decoded to RGB and stored losslessly as FFV1; every frame decoded back and SHA256-compared",
storage={"profile": "mkv/ffv1_rgb24/v1", "codec": "ffv1", "pixel_format": "rgb24", "source_lossy": False},
storage_fps=1,
timebase_role="index_only",
),
"intrinsic": component(
"camera/intrinsic.pt", "camera/intrinsic_valid.pt",
"camera/opencv_fisheye4/v1" if view_type == "ego" else "camera/pinhole/v1",
["T", "row", "column"], ["T"],
{"archive_prefix": f"raw/data/{capture}/Ego_cameras/envmap_per_segment.tar.gz", "member_template": "envmap_per_segment/cam_params/{source_frame_id:06d}.json"} if view_type == "ego" else {"file": f"raw/data/{capture}/Mugsy_cameras/cam_params.json", "camera_id": camera_id},
"Source focal and principal point retained in a 3x3 matrix",
),
"extrinsic": component(
"camera/extrinsic.pt", "camera/extrinsic_valid.pt", "transform/se3/v1",
["T", "row", "column"], ["T"],
{"archive_prefix": f"raw/data/{capture}/Ego_cameras/envmap_per_segment.tar.gz", "member_template": "envmap_per_segment/cam_params/{source_frame_id:06d}.json"} if view_type == "ego" else {"file": f"raw/data/{capture}/Mugsy_cameras/cam_params.json", "camera_id": camera_id},
"Source R retained and source t converted from millimetres to metres",
unit="m", convention="T_camera_from_world",
),
"mano": component(
"annotation/mano/motion.pt", "annotation/mano/motion_valid.pt", "mano/axis_angle61/v1",
["T", "hand", "parameter"], ["T", "hand"],
{"archive_prefix": f"raw/data/{capture}/mano_fits/mano_fits.tar.gz", "member_template": "params/{source_frame_id}_{left|right}.json"},
"Native non-flat MANO mean expanded; root-corrected world-to-camera transform; verified against every source mesh and every transformed vertex",
unit="m", angle_unit="rad", coordinate_frame="camera",
model_profile={"version": "MANO-v1.2", "flat_hand_mean": True, "left_shapedirs_fix": left_fix},
valid_policy={"semantics": "usable_annotation", "formula": "source_parameters_present AND numerically_finite AND source_mesh_reproduction_pass", "no_qa_source_rule": "No independent manual QA field exists in this raw release; no QA was invented."},
),
}
save_tensor(view / "observation" / "rgb_valid.pt", valid_frames, torch, np)
if distortion is not None:
components["intrinsic"]["distortion_ref"] = "camera/distortion.pt"
components["distortion"] = component(
"camera/distortion.pt", "camera/distortion_valid.pt", "camera/fisheye4_distortion/v1",
["T", "parameter"], ["T"],
{"archive_prefix": f"raw/data/{capture}/Ego_cameras/envmap_per_segment.tar.gz", "member_template": "envmap_per_segment/cam_params/{source_frame_id:06d}.json"},
"Four native OpenCV fisheye coefficients retained",
parameter_names=["k1", "k2", "k3", "k4"],
)
mask_paths = [source / "Ego_cameras" / "envmap_per_segment" / "masks" / f"{frame:06d}.png" for frame in ids]
histogram = encode_mask_video(mask_paths, view / "annotation" / "segment" / "mask.mkv", (width, height), Image, np)
save_tensor(view / "annotation" / "segment" / "mask_valid.pt", valid_frames, torch, np)
components["segment"] = component(
"annotation/segment/mask.mkv", "annotation/segment/mask_valid.pt", "segment/foreground_intensity/v1",
["T", "height", "width"], ["T"],
{"archive_prefix": f"raw/data/{capture}/Ego_cameras/envmap_per_segment.tar.gz", "member_template": "envmap_per_segment/masks/{source_frame_id:06d}.png"},
"Every native uint8 foreground intensity retained losslessly in gray16 FFV1; no thresholding or invented hand identity",
value_range=[0, 255], normalization_scale=1 / 255,
foreground_category="hand", identity_semantics="left and right union; no per-hand instance identity",
)
else:
histogram = None
frames = [
{
"frame_index": index,
"source_frame_id": str(frame),
"timestamp_ns": None,
"clock_domain": None,
"sync_id": f"{capture}:{frame}",
"source_locator": {"capture": capture, "segment": segment, "source_frame_id": str(frame)},
}
for index, frame in enumerate(ids)
]
write_jsonl(view / "camera" / "frames.jsonl", frames)
metadata = {
"schema_version": "hand-warehouse/1.0",
"storage_revision": "lossless-video-2026-09-25",
"dataset_id": "ReInterHand",
"release_id": "shared-v1.0",
"sequence_id": sequence_id,
"camera_id": camera_id,
"sample_type": "video",
"num_frames": T,
"hand_slots": ["left", "right"],
"sampling": {"type": "dense", "source_fps": None, "frames_ref": "camera/frames.jsonl", "selection": "All released frames of the named action in official frame_list.txt", "time_semantics": "ordered source frame identifiers; no inferred timestamps"},
"camera": {"model": "opencv_fisheye4" if view_type == "ego" else "pinhole", "schema_id": "camera/opencv_fisheye4/v1" if view_type == "ego" else "camera/pinhole/v1", "image_size": [width, height]},
**official_split_metadata(capture),
"view_type": view_type,
"components": components,
"pilot": True,
"pilot_complete": True,
"pilot_human_review": "pending",
"full_output_human_review": "not_started",
"upload_authorized": False,
"omitted_components": {"depth": "No source depth selected by the unified contract", "contact": "No native contact labels in this raw release", "keypoints": "Intermediate source keypoint sets intentionally excluded by the contract; MANO parameters retained"},
}
atomic_json(view / "metainfo.json", metadata)
review["views"].append(
{
"camera_id": camera_id,
"view_type": view_type,
"frames": T,
"image_size": [width, height],
"rgb_full_frame_roundtrip": "passed",
"rgb_frame_sha256_count": len(rgb_hashes),
"mano_camera_transform_checks": transform_checks,
"foreground_histogram": histogram,
}
)
status["views_completed"].append(camera_id)
status.update(updated_at=now(), active_view=camera_id)
atomic_json(status_path, status)
validation = release / "doc" / "validation"
validation.mkdir(parents=True, exist_ok=True)
atomic_json(validation / "report.json", review)
rows = "\n".join(
f"<tr><td>{item['camera_id']}</td><td>{item['view_type']}</td><td>{item['frames']}</td><td>{item['image_size'][0]}脳{item['image_size'][1]}</td><td>passed</td></tr>"
for item in review["views"]
)
html = f"""<!doctype html><meta charset='utf-8'><title>ReInterHand pilot validation</title>
<style>body{{font-family:system-ui;max-width:1100px;margin:2rem auto;line-height:1.5}}table{{border-collapse:collapse}}td,th{{border:1px solid #bbb;padding:.4rem}}.pending{{color:#a60;font-weight:700}}</style>
<h1>ReInterHand complete-sequence pilot</h1>
<p class='pending'>Human review: pending</p>
<p>Capture: <code>{capture}</code><br>Action: <code>{segment}</code><br>Frames: {T}. Source FPS and timestamps are unknown; no timing was inferred. Cross-camera alignment uses the official frame identifiers recorded in <code>camera/frames.jsonl</code>.</p>
<p>All six actually available views were converted: one ego fisheye view and five exo Mugsy views. Every RGB frame completed a lossless FFV1 decode round-trip. Both hands' MANO parameters reproduced all source meshes within 0.1 mm and were root-corrected into each camera.</p>
<table><thead><tr><th>camera</th><th>view type</th><th>frames</th><th>size</th><th>automatic checks</th></tr></thead><tbody>{rows}</tbody></table>
<p>Machine-readable evidence: <a href='report.json'>report.json</a>. Visual all-frame overlay videos are generated by the next validation stage before human approval.</p>"""
(validation / "index.html").write_text(html, encoding="utf-8")
script_target = release / "script" / Path(__file__).name
script_target.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(Path(__file__), script_target)
status.update(phase="converted_pending_visual_report", updated_at=now(), active_view=None)
atomic_json(status_path, status)
def project_vertices(vertices, intrinsic, distortion, np, cv2):
visible = vertices[:, 2] > 1e-6
result = np.full((len(vertices), 2), np.nan, dtype=np.float64)
if distortion is None:
projected = vertices @ intrinsic.T
result[visible] = projected[visible, :2] / projected[visible, 2:3]
else:
points, _ = cv2.fisheye.projectPoints(
vertices.reshape(-1, 1, 3).astype(np.float64),
np.zeros(3), np.zeros(3), intrinsic.astype(np.float64), distortion.astype(np.float64),
)
result[visible] = points.reshape(-1, 2)[visible]
return result, visible
def draw_mano_meshes(image, points_by_side, faces, Image):
from PIL import ImageDraw
overlay = Image.new("RGBA", image.size, (0, 0, 0, 0))
draw = ImageDraw.Draw(overlay, "RGBA")
colors = {"left": (0, 255, 255), "right": (255, 140, 0)}
width, height = image.size
for side, points in points_by_side.items():
color = colors[side]
for face in faces:
polygon = [tuple(map(float, points[index])) for index in face]
if not all(float("-inf") < x < float("inf") and float("-inf") < y < float("inf") for x, y in polygon):
continue
xs, ys = zip(*polygon)
if max(xs) < 0 or min(xs) >= width or max(ys) < 0 or min(ys) >= height:
continue
draw.polygon(polygon, fill=(*color, 28))
draw.line(polygon + [polygon[0]], fill=(*color, 220), width=2)
return Image.alpha_composite(image.convert("RGBA"), overlay).convert("RGB")
def draw_foreground_intensity(image, mask_path, Image):
if mask_path is None or not mask_path.exists():
blank = Image.new("RGB", image.size, (25, 25, 25))
return label_panel(blank, "no native pixel mask for this exo view", Image)
mask = Image.open(mask_path).convert("L")
tint = Image.new("RGBA", image.size, (255, 0, 200, 0))
tint.putalpha(mask.point(lambda value: min(190, int(value * 0.72))))
return Image.alpha_composite(image.convert("RGBA"), tint).convert("RGB")
def label_panel(image, text, Image):
from PIL import ImageDraw
result = image.copy()
draw = ImageDraw.Draw(result)
draw.rectangle((0, 0, min(result.width, 360), 28), fill=(0, 0, 0))
draw.text((8, 6), text, fill=(255, 255, 255))
return result
def render_review_video(frames, output: Path, size: tuple[int, int], panels: int = 3):
width, height = size
output.parent.mkdir(parents=True, exist_ok=True)
temporary = output.with_name(output.stem + ".tmp" + output.suffix)
process = subprocess.Popen(
[
"ffmpeg", "-v", "error", "-y", "-f", "rawvideo", "-pixel_format", "rgb24",
"-video_size", f"{width * panels}x{height}", "-framerate", "12", "-i", "pipe:0",
"-an", "-vf", "pad=ceil(iw/2)*2:ceil(ih/2)*2", "-c:v", "libx264", "-crf", "18", "-preset", "medium", "-pix_fmt", "yuv420p", str(temporary),
],
stdin=subprocess.PIPE,
)
count = 0
assert process.stdin is not None
try:
for frame in frames:
if frame.size != (width * panels, height):
raise RuntimeError("Review frame dimensions changed")
process.stdin.write(frame.tobytes())
count += 1
finally:
process.stdin.close()
if process.wait() != 0 or count == 0:
raise RuntimeError(f"Review video encoder failed: {output}")
os.replace(temporary, output)
return count
def render_pilot(root: Path, runtime: Path, capture: str, segment: str) -> None:
np, torch, cv2, Image, smplx = runtime_imports(runtime)
state = root / "tmp" / "pilot-v1.0"
status_path = state / "status.json"
status = json.loads(status_path.read_text(encoding="utf-8"))
status.update(phase="rendering_visual_report", updated_at=now(), review_views_completed=[])
atomic_json(status_path, status)
extraction = json.loads((state / "extraction-manifest.json").read_text(encoding="utf-8"))
ids = [int(value) for value in extraction["source_frame_ids"]]
source = state / "extracted" / f"{capture}__{segment}"
sequence_id = f"{capture}__{segment}"
release = root / "shared-v1.0"
validation = release / "doc" / "validation"
report_path = validation / "report.json"
report = json.loads(report_path.read_text(encoding="utf-8"))
models = [
ManoModel("left", runtime / "models", np, torch, smplx),
ManoModel("right", runtime / "models", np, torch, smplx),
]
if report["left_shapedirs_fix"]:
models[0].data["shapedirs"][:, 0] *= -1
with torch.no_grad():
models[0].layer.shapedirs[:, 0] *= -1
source_meshes = {
side: np.stack(
[read_ply_vertices(source / "mano_fits" / "meshes" / f"{frame}_{side}.ply", np) for frame in ids]
)
for side in ["left", "right"]
}
view_lookup = {row["camera_id"]: row for row in report["views"]}
video_rows = []
for view in sorted((release / "data" / sequence_id).iterdir()):
metadata = json.loads((view / "metainfo.json").read_text(encoding="utf-8"))
camera_id = metadata["camera_id"]
view_type = metadata["view_type"]
width, height = metadata["camera"]["image_size"]
intrinsic = torch.load(view / "camera" / "intrinsic.pt", map_location="cpu", weights_only=True).numpy()
extrinsic = torch.load(view / "camera" / "extrinsic.pt", map_location="cpu", weights_only=True).numpy()
distortion = (
torch.load(view / "camera" / "distortion.pt", map_location="cpu", weights_only=True).numpy()
if (view / "camera" / "distortion.pt").exists()
else None
)
motion = torch.load(view / "annotation" / "mano" / "motion.pt", map_location="cpu", weights_only=True).numpy()
current_meshes = {}
for index, side in enumerate(["left", "right"]):
current_meshes[side], _ = models[index].geometry(
motion[:, index, :48], motion[:, index, 48:58], motion[:, index, 58:]
)
if view_type == "ego":
image_root = source / "Ego_cameras" / "envmap_per_segment" / "images"
else:
image_root = source / "Mugsy_cameras" / "envmap_per_segment" / "images" / camera_id
pixel_errors = []
def panels():
for frame_index, source_frame in enumerate(ids):
original = Image.open(image_root / f"{source_frame:06d}.png").convert("RGB")
source_points = {}
current_points = {}
for side in ["left", "right"]:
source_camera = (
source_meshes[side][frame_index] @ extrinsic[frame_index, :3, :3].T
+ extrinsic[frame_index, :3, 3]
)
src_uv, src_visible = project_vertices(
source_camera,
intrinsic[frame_index],
None if distortion is None else distortion[frame_index],
np,
cv2,
)
cur_uv, cur_visible = project_vertices(
current_meshes[side][frame_index],
intrinsic[frame_index],
None if distortion is None else distortion[frame_index],
np,
cv2,
)
good = src_visible & cur_visible & np.isfinite(src_uv).all(axis=1) & np.isfinite(cur_uv).all(axis=1)
if good.any():
pixel_errors.extend(np.linalg.norm(src_uv[good] - cur_uv[good], axis=1).tolist())
source_points[side] = src_uv[src_visible]
current_points[side] = cur_uv[cur_visible]
source_panel = draw_points(original, source_points, Image)
current_panel = draw_points(original, current_points, Image)
canvas = Image.new("RGB", (width * 3, height))
canvas.paste(label_panel(original, f"original | frame {source_frame}", Image), (0, 0))
canvas.paste(label_panel(source_panel, "source mesh projection", Image), (width, 0))
canvas.paste(label_panel(current_panel, "shared MANO projection", Image), (width * 2, 0))
yield canvas
relative_video = Path("media") / f"{camera_id}.mp4"
rendered = render_review_video(panels(), validation / relative_video, (width, height))
if rendered != len(ids) or not pixel_errors:
raise RuntimeError(f"Review coverage failed for {camera_id}")
row = view_lookup[camera_id]
row["visual_review_video"] = relative_video.as_posix()
row["visual_review_frames"] = rendered
row["source_vs_shared_projection_max_px"] = float(max(pixel_errors))
row["source_vs_shared_projection_mean_px"] = float(sum(pixel_errors) / len(pixel_errors))
video_rows.append(row)
status["review_views_completed"].append(camera_id)
status.update(updated_at=now(), active_view=camera_id)
atomic_json(status_path, status)
report["views"] = video_rows
report["automatic_status"] = "passed"
report["visual_scope"] = "all 58 frames of every one of the six actually available views"
report["completed_at"] = now()
atomic_json(report_path, report)
blocks = []
for item in video_rows:
blocks.append(
f"<section><h2>{item['camera_id']} 路 {item['view_type']}</h2>"
f"<video controls preload='metadata' width='100%' src='{item['visual_review_video']}'></video>"
f"<p>{item['frames']} frames; source/shared projection max {item['source_vs_shared_projection_max_px']:.4f}px; "
f"lossless RGB round-trip passed.</p></section>"
)
html = f"""<!doctype html><meta charset='utf-8'><title>ReInterHand pilot validation</title>
<style>body{{font-family:system-ui;max-width:1200px;margin:2rem auto;line-height:1.5}}section{{margin:2rem 0}}video{{background:#111}}.pending{{color:#a60;font-weight:700}}code{{overflow-wrap:anywhere}}</style>
<h1>ReInterHand complete-sequence pilot</h1>
<p class='pending'>Human review: pending</p>
<p>Capture: <code>{capture}</code><br>Action: <code>{segment}</code><br>Coverage: all {len(ids)} frames in every actually available camera (one ego, five exo). Source FPS and timestamps are unknown; no timing was inferred. Alignment uses official source frame identifiers.</p>
<p>Each video shows original RGB, source MANO mesh projection, and the shared camera-space MANO projection. Cyan is left; orange is right. RGB, camera arrays, MANO arrays, masks, frame mapping, source-mesh reproduction and projection equivalence passed automatic checks. This does not replace human visual review.</p>
{''.join(blocks)}
<p>Machine-readable evidence: <a href='report.json'>report.json</a>.</p>"""
(validation / "index.html").write_text(html, encoding="utf-8")
status.update(phase="pilot_ready_for_human_review", updated_at=now(), active_view=None)
atomic_json(status_path, status)
def render_expanded_review(root: Path, runtime: Path, capture: str, segment: str) -> None:
"""Render both official background policies with a large, explicit MANO panel."""
np, torch, cv2, Image, smplx = runtime_imports(runtime)
state = root / "tmp" / "pilot-v1.0"
status_path = state / "status.json"
status = json.loads(status_path.read_text(encoding="utf-8"))
status.update(phase="rendering_expanded_visual_report", updated_at=now(), review_streams_completed=[])
atomic_json(status_path, status)
extraction = json.loads((state / "extraction-manifest.json").read_text(encoding="utf-8"))
ids = [int(value) for value in extraction["source_frame_ids"]]
source = state / "extracted" / f"{capture}__{segment}"
sequence_id = f"{capture}__{segment}"
release = root / "shared-v1.0"
validation = release / "doc" / "validation"
report_path = validation / "report.json"
previous_report = json.loads(report_path.read_text(encoding="utf-8"))
physical_rows = {row["camera_id"]: row for row in previous_report["views"]}
physical_views = sorted((release / "data" / sequence_id).iterdir())
variants = ["envmap_per_frame", "envmap_per_segment"]
for variant in variants:
ego = source / "Ego_cameras" / variant / "images"
mugsy = source / "Mugsy_cameras" / variant / "images"
if not ego.is_dir() or not mugsy.is_dir():
raise RuntimeError(f"Missing extracted background variant: {variant}")
models = [
ManoModel("left", runtime / "models", np, torch, smplx),
ManoModel("right", runtime / "models", np, torch, smplx),
]
if previous_report["left_shapedirs_fix"]:
models[0].data["shapedirs"][:, 0] *= -1
with torch.no_grad():
models[0].layer.shapedirs[:, 0] *= -1
faces = np.asarray(models[0].data["f"], dtype=np.int64)
source_meshes = {
side: np.stack([read_ply_vertices(source / "mano_fits" / "meshes" / f"{frame}_{side}.ply", np) for frame in ids])
for side in ["left", "right"]
}
rows = []
for variant in variants:
for view in physical_views:
metadata = json.loads((view / "metainfo.json").read_text(encoding="utf-8"))
camera_id = metadata["camera_id"]
view_type = metadata["view_type"]
width, height = metadata["camera"]["image_size"]
intrinsic = torch.load(view / "camera" / "intrinsic.pt", map_location="cpu", weights_only=True).numpy()
extrinsic = torch.load(view / "camera" / "extrinsic.pt", map_location="cpu", weights_only=True).numpy()
distortion = (torch.load(view / "camera" / "distortion.pt", map_location="cpu", weights_only=True).numpy()
if (view / "camera" / "distortion.pt").exists() else None)
motion = torch.load(view / "annotation" / "mano" / "motion.pt", map_location="cpu", weights_only=True).numpy()
current_meshes = {}
for index, side in enumerate(["left", "right"]):
current_meshes[side], _ = models[index].geometry(
motion[:, index, :48], motion[:, index, 48:58], motion[:, index, 58:])
image_root = (source / "Ego_cameras" / variant / "images" if view_type == "ego"
else source / "Mugsy_cameras" / variant / "images" / camera_id)
mask_root = source / "Ego_cameras" / variant / "masks" if view_type == "ego" else None
pixel_errors = []
def mano_panels():
for frame_index, source_frame in enumerate(ids):
original = Image.open(image_root / f"{source_frame:06d}.png").convert("RGB")
current_points = {}
for side in ["left", "right"]:
source_camera = (source_meshes[side][frame_index] @ extrinsic[frame_index, :3, :3].T
+ extrinsic[frame_index, :3, 3])
src_uv, src_visible = project_vertices(source_camera, intrinsic[frame_index],
None if distortion is None else distortion[frame_index], np, cv2)
cur_uv, cur_visible = project_vertices(current_meshes[side][frame_index], intrinsic[frame_index],
None if distortion is None else distortion[frame_index], np, cv2)
good = src_visible & cur_visible & np.isfinite(src_uv).all(axis=1) & np.isfinite(cur_uv).all(axis=1)
if good.any():
pixel_errors.extend(np.linalg.norm(src_uv[good] - cur_uv[good], axis=1).tolist())
current_points[side] = cur_uv
overlay = draw_mano_meshes(original, current_points, faces, Image)
canvas = Image.new("RGB", (width * 2, height))
canvas.paste(label_panel(original, f"RGB | {variant} | frame {source_frame}", Image), (0, 0))
canvas.paste(label_panel(overlay, "shared MANO mesh | cyan left, orange right", Image), (width, 0))
yield canvas
stem = f"{variant}__{camera_id}"
mano_video = Path("media") / f"{stem}__mano.mp4"
rendered = render_review_video(mano_panels(), validation / mano_video, (width, height), panels=2)
mask_video = None
if mask_root is not None:
def mask_panels():
for source_frame in ids:
original = Image.open(image_root / f"{source_frame:06d}.png").convert("RGB")
mask = draw_foreground_intensity(original, mask_root / f"{source_frame:06d}.png", Image)
canvas = Image.new("RGB", (width * 2, height))
canvas.paste(label_panel(original, f"RGB | {variant} | frame {source_frame}", Image), (0, 0))
canvas.paste(label_panel(mask, "native foreground intensity (magenta)", Image), (width, 0))
yield canvas
mask_video = Path("media") / f"{stem}__mask.mp4"
render_review_video(mask_panels(), validation / mask_video, (width, height), panels=2)
if rendered != len(ids) or not pixel_errors:
raise RuntimeError(f"Expanded review coverage failed for {stem}")
base = dict(physical_rows[camera_id])
base.update(background_variant=variant, physical_camera_id=camera_id,
visual_review_video=mano_video.as_posix(), mask_review_video=None if mask_video is None else mask_video.as_posix(),
visual_review_frames=rendered,
source_vs_shared_projection_max_px=float(max(pixel_errors)),
source_vs_shared_projection_mean_px=float(sum(pixel_errors) / len(pixel_errors)))
rows.append(base)
status["review_streams_completed"].append(stem)
status.update(active_stream=stem, updated_at=now())
atomic_json(status_path, status)
report = dict(previous_report)
report["views"] = rows
report["physical_view_count"] = len(physical_views)
report["rendered_rgb_stream_count"] = len(rows)
report["background_variants"] = variants
report["modalities"] = {
"all_views": ["RGB", "camera intrinsics/extrinsics", "left/right MANO parameters", "source MANO OBJ/PLY meshes"],
"ego_only": ["fisheye distortion", "uint8 foreground-intensity mask", "truncation ratio"],
"not_present_in_this_release_scope": ["depth", "object pose/model", "contact labels"],
}
report["visual_scope"] = "all frames, six physical views, both official background variants; large MANO overlay for every stream"
report["completed_at"] = now()
atomic_json(report_path, report)
blocks = []
for item in rows:
mask_html = (f"<details><summary>ego foreground-intensity mask</summary><video controls preload='metadata' width='100%' src='{item['mask_review_video']}'></video></details>"
if item["mask_review_video"] else "<p>This exo stream has no native pixel mask.</p>")
blocks.append(
f"<section><h2>{item['physical_camera_id']} 路 {item['view_type']} 路 {item['background_variant']}</h2>"
f"<video controls preload='metadata' width='100%' src='{item['visual_review_video']}'></video>"
f"<p>All {item['frames']} frames. Right panel is the reconstructed shared MANO mesh: cyan left hand, orange right hand. "
f"Source/shared projection max {item['source_vs_shared_projection_max_px']:.4f}px.</p>{mask_html}</section>")
html = f"""<!doctype html><meta charset='utf-8'><title>ReInterHand expanded pilot validation</title>
<style>body{{font-family:system-ui;max-width:1900px;margin:2rem auto;line-height:1.5;padding:0 1rem}}section{{margin:2rem 0;padding:1rem;background:#f6f7f9}}video{{background:#111}}.pending{{color:#a60;font-weight:700}}code{{overflow-wrap:anywhere}}</style>
<h1>ReInterHand complete-sequence pilot 路 expanded coverage</h1><p class='pending'>Human review: pending</p>
<p>Capture: <code>{capture}</code><br>Action: <code>{segment}</code><br>Physical views: one ego plus five active Mugsy exo cameras. RGB streams: 12, because every physical view is shown under both official policies: <code>envmap_per_frame</code> (background changes each frame) and <code>envmap_per_segment</code> (one background per action segment).</p>
<p>Modalities: every view has RGB, camera calibration and left/right MANO; source MANO OBJ/PLY meshes independently reproduce the converted MANO. Ego additionally has fisheye distortion, native uint8 foreground-intensity masks and truncation ratios. This scope has no native depth, object pose/model or contact labels.</p>
<p>Each main video now uses two large panels. The right panel draws full MANO triangle meshes instead of sparse points. Ego mask videos are separately expandable so MANO remains large and readable. All 58 frames are rendered; source FPS/timestamps remain unknown and alignment uses official frame IDs.</p>
{''.join(blocks)}<p>Machine-readable evidence: <a href='report.json'>report.json</a>.</p>"""
(validation / "index.html").write_text(html, encoding="utf-8")
script_target = release / "script" / Path(__file__).name
script_target.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(Path(__file__), script_target)
status.update(phase="pilot_ready_for_human_review", active_stream=None,
expanded_review=True, updated_at=now())
atomic_json(status_path, status)
def convert_complete_pilot_v2(root: Path, runtime: Path, capture: str, segment: str) -> None:
"""Convert every released camera/background setting represented by one action."""
np, torch, cv2, Image, smplx = runtime_imports(runtime)
state = root / "tmp" / "pilot-v1.0"
status_path = state / "status.json"
source = state / "extracted" / f"{capture}__{segment}"
segment_ids = frame_ids(root / "raw" / "data" / capture, segment)
id_set = set(segment_ids)
models = [ManoModel("left", runtime / "models", np, torch, smplx), ManoModel("right", runtime / "models", np, torch, smplx)]
left_fix = bool(np.abs(models[0].data["shapedirs"][:, 0] - models[1].data["shapedirs"][:, 0]).sum() < 1)
if left_fix:
models[0].data["shapedirs"][:, 0] *= -1
with torch.no_grad(): models[0].layer.shapedirs[:, 0] *= -1
native, source_meshes, source_checks = {}, {}, []
for hand_index, side in enumerate(["left", "right"]):
rows = [json.loads((source / "mano_fits/params" / f"{frame}_{side}.json").read_text()) for frame in segment_ids]
pose = np.stack([row["pose"] for row in rows]).astype(np.float64)
betas = np.stack([row["shape"] for row in rows]).astype(np.float64)
translation = np.stack([row["trans"] for row in rows]).astype(np.float64)
pose[:, 3:] += models[hand_index].data["hands_mean"]
predicted, _ = models[hand_index].geometry(pose, betas, translation)
meshes = np.stack([read_ply_vertices(source / "mano_fits/meshes" / f"{frame}_{side}.ply", np) for frame in segment_ids])
error = np.linalg.norm(predicted - meshes, axis=-1)
if float(error.max()) >= 1e-4: raise RuntimeError(f"Source MANO mismatch: {side}")
native[side] = (pose, betas, translation)
source_meshes[side] = meshes
source_checks.append({"side": side, "max_m": float(error.max()), "mean_m": float(error.mean())})
id_to_index = {frame: index for index, frame in enumerate(segment_ids)}
mugsy_params = json.loads((source / "Mugsy_cameras/cam_params.json").read_text())
streams = []
for family, view_type in [("Ego_cameras", "ego"), ("Mugsy_cameras", "exo")]:
for variant in ["envmap_per_frame", "envmap_per_segment"]:
image_base = source / family / variant / "images"
camera_dirs = [("ego", image_base)] if family == "Ego_cameras" else [(p.name, p) for p in sorted(image_base.iterdir()) if p.is_dir()]
for camera_id, image_root in camera_dirs:
ids = sorted(int(p.stem) for p in image_root.glob("*.png") if p.stem.isdigit() and int(p.stem) in id_set)
if family == "Mugsy_cameras" and variant == "envmap_per_frame":
if not ids:
raise RuntimeError(f"Empty official 5 FPS image subset: {family}/{variant}/{camera_id}")
elif ids != segment_ids:
missing = sorted(id_set - set(ids))
raise RuntimeError(f"Camera-specific frame loss is forbidden: {family}/{variant}/{camera_id}; missing={missing[:20]}")
streams.append((family, view_type, variant, camera_id, image_root, ids))
# Official release definition: 1+1 ego streams, 20 Mugsy per-frame and 5 Mugsy per-segment.
counts = collections.Counter((family, variant) for family, _, variant, _, _, _ in streams)
expected = {("Ego_cameras", "envmap_per_frame"): 1, ("Ego_cameras", "envmap_per_segment"): 1,
("Mugsy_cameras", "envmap_per_frame"): 20, ("Mugsy_cameras", "envmap_per_segment"): 5}
if dict(counts) != expected: raise RuntimeError(f"Unexpected ReInterHand stream coverage: {dict(counts)}")
mugsy_per_frame_ids = [ids for family, _, variant, _, _, ids in streams if family == "Mugsy_cameras" and variant == "envmap_per_frame"]
if any(ids != mugsy_per_frame_ids[0] for ids in mugsy_per_frame_ids[1:]):
raise RuntimeError("Mugsy envmap_per_frame cameras do not share the same official 5 FPS frame subset")
report = {"schema":"reinterhand-pilot-validation/v2", "dataset":"ReInterHand", "capture":capture,
"segment":segment, "source_mesh_parameter_checks":source_checks, "left_shapedirs_fix":left_fix,
"official_settings":{"Mugsy_cameras/envmap_per_frame":{"cameras":20,"official_render_rate_fps":5,"split_kind":"frame_based","sample_type":"image","temporal_relationship":False},
"Mugsy_cameras/envmap_per_segment":{"cameras":5,"official_render_rate_fps":30,"split_kind":"video_based","sample_type":"video","temporal_relationship":True},
"Ego_cameras/envmap_per_frame":{"cameras":1,"official_render_rate_fps":30,"split_kind":"frame_based","sample_type":"image","temporal_relationship":False},
"Ego_cameras/envmap_per_segment":{"cameras":1,"official_render_rate_fps":30,"split_kind":"video_based","sample_type":"video","temporal_relationship":True}},
"views":[], "human_review":"pending"}
status = json.loads(status_path.read_text(encoding="utf-8")); status.update(phase="converting_complete_pilot_v2", streams_completed=[], updated_at=now()); atomic_json(status_path,status)
release = root / "shared-v1.0"
for family, view_type, variant, camera_id, image_root, ids in streams:
# Camera family belongs to the second-level view metadata. The first
# level identifies the parent capture, render setting and official
# source-frame span of the short sequence.
sequence_id = f"{capture}__{variant}__{segment_ids[0]}__{segment_ids[-1]}"
view = release / "data" / sequence_id / camera_id
positions = [id_to_index[frame] for frame in ids]; T=len(ids)
image_paths = [image_root / f"{frame:06d}.png" for frame in ids]
first=Image.open(image_paths[0]).convert("RGB"); width,height=first.size
rgb_hashes=encode_lossless_video(image_paths,view/"observation/rgb.mkv",(width,height),Image)
if view_type=="ego":
camera_rows=[json.loads((source/family/variant/"cam_params"/f"{frame:06d}.json").read_text()) for frame in ids]
else: camera_rows=[mugsy_params[camera_id]]*T
intrinsic=np.stack([[[r["focal"][0],0,r["princpt"][0]],[0,r["focal"][1],r["princpt"][1]],[0,0,1]] for r in camera_rows]).astype(np.float32)
extrinsic=np.broadcast_to(np.eye(4,dtype=np.float32),(T,4,4)).copy(); extrinsic[:,:3,:3]=np.stack([r["R"] for r in camera_rows]); extrinsic[:,:3,3]=np.stack([r["t"] for r in camera_rows])/1000
distortion=np.stack([r["D"] for r in camera_rows]).astype(np.float32) if view_type=="ego" else None
valid=np.ones(T,dtype=bool)
mano_valid=np.ones((T,2),dtype=bool); truncation=None
if view_type=="ego":
truncation_map=json.loads((source/family/variant/"truncation_ratio.json").read_text())
truncation=np.asarray([truncation_map[f"{frame:06d}"] for frame in ids],dtype=np.float32)
mano_valid[truncation < .2]=False
for name,value in [("intrinsic",intrinsic),("extrinsic",extrinsic)]:
save_tensor(view/"camera"/(name+".pt"),value,torch,np); save_tensor(view/"camera"/(name+"_valid.pt"),valid,torch,np)
if distortion is not None:
save_tensor(view/"camera/distortion.pt",distortion,torch,np); save_tensor(view/"camera/distortion_valid.pt",valid,torch,np)
motion=np.empty((T,2,61),dtype=np.float32); checks=[]
for hand_index,side in enumerate(["left","right"]):
pose,betas,translation=native[side]
converted,error,_=camera_mano(models[hand_index],pose[positions],betas[positions],translation[positions],extrinsic,np,cv2)
motion[:,hand_index]=converted; checks.append({"side":side,"max_vertex_error_m":error})
save_tensor(view/"annotation/mano/motion.pt",motion,torch,np); save_tensor(view/"annotation/mano/motion_valid.pt",mano_valid,torch,np)
mask_root=source/family/variant/"masks"/(camera_id if view_type=="exo" else "")
mask_paths=[mask_root/f"{frame:06d}.png" for frame in ids]
if not all(p.is_file() for p in mask_paths): raise RuntimeError(f"Missing native masks: {family}/{variant}/{camera_id}")
histogram=encode_mask_video(mask_paths,view/"annotation/segment/mask.mkv",(width,height),Image,np)
save_tensor(view/"annotation/segment/mask_valid.pt",valid,torch,np); save_tensor(view/"observation/rgb_valid.pt",valid,torch,np)
archive=f"raw/data/{capture}/{family}/{variant}.tar.gz"
image_member=f"{variant}/images/{'' if view_type=='ego' else camera_id+'/' }{{source_frame_id:06d}}.png"
mask_member=f"{variant}/masks/{'' if view_type=='ego' else camera_id+'/' }{{source_frame_id:06d}}.png"
camera_locator=({"archive_prefix":archive,"member_template":f"{variant}/cam_params/{{source_frame_id:06d}}.json"} if view_type=="ego" else {"file":f"raw/data/{capture}/Mugsy_cameras/cam_params.json","camera_id":camera_id})
components={
"rgb":component("observation/rgb.mkv","observation/rgb_valid.pt","rgb/uint8/v1",["T","height","width","channel"],["T"],{"archive_prefix":archive,"member_template":image_member},"Source PNG decoded to RGB and losslessly stored as FFV1",storage={"profile":"mkv/ffv1_rgb24/v1","codec":"ffv1","pixel_format":"rgb24","source_lossy":False},storage_fps=1,timebase_role="index_only"),
"intrinsic":component("camera/intrinsic.pt","camera/intrinsic_valid.pt","camera/opencv_fisheye4/v1" if view_type=="ego" else "camera/pinhole/v1",["T","row","column"],["T"],camera_locator,"Native focal and principal point retained"),
"extrinsic":component("camera/extrinsic.pt","camera/extrinsic_valid.pt","transform/se3/v1",["T","row","column"],["T"],camera_locator,"Native R retained; t converted mm to m",unit="m",convention="T_camera_from_world"),
"mano":component("annotation/mano/motion.pt","annotation/mano/motion_valid.pt","mano/axis_angle61/v1",["T","hand","parameter"],["T","hand"],{"archive_prefix":f"raw/data/{capture}/mano_fits/mano_fits.tar.gz","member_template":"params/{source_frame_id}_{left|right}.json"},"Native MANO mean expanded and root-corrected into camera coordinates",unit="m",angle_unit="rad",coordinate_frame="camera",model_profile={"version":"MANO-v1.2","flat_hand_mean":True,"left_shapedirs_fix":left_fix},valid_policy={"semantics":"usable_annotation","formula":"source present and finite; for ego, official truncation_ratio >= 0.2"}),
"segment":component("annotation/segment/mask.mkv","annotation/segment/mask_valid.pt","segment/foreground_intensity/v1",["T","height","width"],["T"],{"archive_prefix":archive,"member_template":mask_member},"Native uint8 non-binary foreground intensity retained losslessly",value_range=[0,255],normalization_scale=1/255,foreground_category="hand",identity_semantics="left and right union; no per-hand identity")}
if distortion is not None:
components["intrinsic"]["distortion_ref"]="camera/distortion.pt"; components["distortion"]=component("camera/distortion.pt","camera/distortion_valid.pt","camera/fisheye4_distortion/v1",["T","parameter"],["T"],camera_locator,"Native four-coefficient fisheye distortion retained",parameter_names=["k1","k2","k3","k4"])
independent = variant == "envmap_per_frame"
frames=[{"frame_index":i,"sample_id":f"{capture}:{family}:{variant}:{camera_id}:{frame}","source_frame_id":str(frame),"timestamp_ns":None,"clock_domain":None,"sync_id":f"{capture}:{frame}","source_locator":{"capture":capture,"segment":segment,"render_setting":f"{family}/{variant}","source_frame_id":str(frame)}} for i,frame in enumerate(ids)]
write_jsonl(view/"camera/frames.jsonl",frames)
official_render_rate_fps=5 if family=="Mugsy_cameras" and independent else 30
sample_type="image" if independent else "video"
sampling={"type":"independent" if independent else "dense","source_fps":None if independent else official_render_rate_fps,"frames_ref":"camera/frames.jsonl","selection":"All available frames for this official action/render setting","time_semantics":"independent rendered images; container index is not time" if independent else "official video frame order and documented source FPS; timestamps not inferred","temporal_relationship":not independent}
metadata={"schema_version":"hand-warehouse/1.0","storage_revision":"lossless-video-2026-09-25","dataset_id":"ReInterHand","release_id":"shared-v1.0","sequence_id":sequence_id,"sequence_id_role":"batch_identifier_only" if independent else "temporal_sequence","source_capture_id":capture,"source_segment_id":segment,"source_frame_span":[segment_ids[0],segment_ids[-1]],"camera_id":camera_id,"sample_type":sample_type,"num_frames":T,"hand_slots":["left","right"],"sampling":sampling,"camera":{"model":"opencv_fisheye4" if view_type=="ego" else "pinhole","schema_id":"camera/opencv_fisheye4/v1" if view_type=="ego" else "camera/pinhole/v1","image_size":[width,height]},**official_split_metadata(capture),"view_type":view_type,"source_rendering":{"camera_family":family,"background_policy":variant,"synthetic_background_variant":True,"official_split_kind":"frame_based" if independent else "video_based","official_render_rate_fps":official_render_rate_fps,"camera_randomized_per_image":bool(independent and view_type=="ego")},"components":components,"pilot":True,"pilot_complete":True,"pilot_human_review":"pending","full_output_human_review":"not_started","upload_authorized":False,"omitted_components":{"depth":"not present","contact":"not present","keypoints_xyz":"orig_fits keypoints are an auxiliary fitting source; MANO and source meshes are retained as the selected geometric supervision"}}
atomic_json(view/"metainfo.json",metadata)
report["views"].append({"sequence_id":sequence_id,"camera_id":camera_id,"view_type":view_type,"camera_family":family,"background_variant":variant,"sample_type":sample_type,"sampling_type":sampling["type"],"source_fps":sampling["source_fps"],"official_render_rate_fps":official_render_rate_fps,"temporal_relationship":not independent,"frames":T,"source_frame_ids":ids,"image_size":[width,height],"rgb_full_frame_roundtrip":"passed","rgb_frame_sha256_count":len(rgb_hashes),"mano_camera_transform_checks":checks,"mano_valid_frames":int(mano_valid[:,0].sum()),"official_truncation_excluded_frames":0 if truncation is None else int((truncation<.2).sum()),"foreground_histogram":histogram})
key=f"{family}/{variant}/{camera_id}"; status["streams_completed"].append(key); status.update(active_stream=key,updated_at=now()); atomic_json(status_path,status)
validation=release/"doc/validation"; validation.mkdir(parents=True,exist_ok=True); atomic_json(validation/"report.json",report)
shutil.copy2(Path(__file__),release/"script"/Path(__file__).name)
status.update(phase="complete_pilot_v2_converted_pending_render",active_stream=None,updated_at=now()); atomic_json(status_path,status)
def write_complete_pilot_v2_html(report: dict, validation: Path) -> None:
groups=[]
for setting,details in report["official_settings"].items():
rows=[r for r in report["views"] if f"{r['camera_family']}/{r['background_variant']}"==setting]
cards=[]
independent = details["sample_type"] == "image"
for row in rows:
amount = (f"{row['frames']} independent images 路 index-only review container"
if independent else f"{row['frames']} frames @ {row['source_fps']} FPS")
cards.append(f"<section><h3>{row['camera_id']} 路 {row['view_type']} 路 {amount}</h3><video controls preload='metadata' width='100%' src='{row['visual_review_video']}'></video><p>Full MANO mesh: cyan left, orange right. Source/shared projection max {row['source_vs_shared_projection_max_px']:.4f}px. MANO valid {row['mano_valid_frames']}/{row['frames']}; official truncation exclusions {row['official_truncation_excluded_frames']}.</p><details><summary>Native foreground mask</summary><video controls preload='metadata' width='100%' src='{row['mask_review_video']}'></video></details></section>")
semantics = (f"<strong>Frame-based independent-image split.</strong> These are not video frames: source FPS is null and adjacent container entries must not be treated as a continuous timeline. The official renderer sampled source motion at {details['official_render_rate_fps']} FPS. The MKV files below are lossless index-only packages for convenient review."
if independent else f"<strong>Video-based split.</strong> Temporal order is meaningful; official source rate {details['official_render_rate_fps']} FPS.")
groups.append(f"<h2>{setting}</h2><p>{details['cameras']} camera stream(s). {semantics}</p>{''.join(cards)}")
segment=report["segment"]
html=f"""<!doctype html><meta charset='utf-8'><title>ReInterHand complete pilot validation</title><style>body{{font-family:system-ui;max-width:1900px;margin:2rem auto;line-height:1.5;padding:0 1rem}}section{{margin:1.5rem 0;padding:1rem;background:#f5f7fa}}video{{background:#111}}.pending{{color:#a60;font-weight:700}}.warning{{padding:1rem;background:#fff1c7;border-left:5px solid #c77d00}}table{{border-collapse:collapse}}td,th{{border:1px solid #aaa;padding:.4rem}}</style><h1>ReInterHand pilot 路 all official settings</h1><p class='pending'>Human review: pending</p><p>Action <code>{segment}</code>. Coverage: 27 camera/setting streams: Mugsy frame-based 20 exo cameras, Mugsy video-based 5 exo cameras, Ego frame-based 1 view, and Ego video-based 1 view. These are rendering/background variants, not extra physical camera types.</p><p class='warning'><strong>Media semantics:</strong> both <code>envmap_per_frame</code> settings are independent image collections, not videos. Ego additionally randomizes camera position for every image. Their MKV files are only lossless batch containers and review players; playback order must not be used as motion, tracking, timing, velocity, or temporal supervision. Both <code>envmap_per_segment</code> settings are genuine video-based sequences.</p><p>Selected shared modalities: RGB, native non-binary foreground mask, camera intrinsics/extrinsics, ego fisheye distortion, and left/right MANO. Source MANO parameters reproduce the supplied PLY meshes before camera conversion. The raw release also contains <code>orig_fits</code> 3D keypoints used during fitting; they are disclosed but intentionally not duplicated because MANO is the selected standardized geometric supervision. No native depth, object pose/model or contact labels exist in this release scope.</p><p>Main review players use two large panels so MANO is readable. Mask players are separate expanders. Every available item is rendered. Source frame IDs remain explicit; timestamps are absent.</p>{''.join(groups)}<p><a href='report.json'>Machine-readable report</a></p>"""
(validation/"index.html").write_text(html,encoding="utf-8")
def fix_complete_pilot_v2_media_semantics(root: Path) -> None:
release=root/"shared-v1.0"; validation=release/"doc/validation"; report_path=validation/"report.json"
report=json.loads(report_path.read_text(encoding="utf-8"))
if report.get("schema")!="reinterhand-pilot-validation/v2": raise RuntimeError("Complete pilot v2 report required")
settings={
"Mugsy_cameras/envmap_per_frame":{"cameras":20,"official_render_rate_fps":5,"split_kind":"frame_based","sample_type":"image","temporal_relationship":False},
"Mugsy_cameras/envmap_per_segment":{"cameras":5,"official_render_rate_fps":30,"split_kind":"video_based","sample_type":"video","temporal_relationship":True},
"Ego_cameras/envmap_per_frame":{"cameras":1,"official_render_rate_fps":30,"split_kind":"frame_based","sample_type":"image","temporal_relationship":False},
"Ego_cameras/envmap_per_segment":{"cameras":1,"official_render_rate_fps":30,"split_kind":"video_based","sample_type":"video","temporal_relationship":True}}
report["official_settings"]=settings
for row in report["views"]:
key=f"{row['camera_family']}/{row['background_variant']}"; setting=settings[key]; independent=not setting["temporal_relationship"]
row.update(sample_type=setting["sample_type"],sampling_type="independent" if independent else "dense",source_fps=None if independent else setting["official_render_rate_fps"],official_render_rate_fps=setting["official_render_rate_fps"],temporal_relationship=not independent)
view=release/"data"/row["sequence_id"]/row["camera_id"]
metadata=json.loads((view/"metainfo.json").read_text(encoding="utf-8"))
metadata.update(sample_type=setting["sample_type"],sequence_id_role="batch_identifier_only" if independent else "temporal_sequence")
metadata["sampling"]={"type":"independent" if independent else "dense","source_fps":None if independent else setting["official_render_rate_fps"],"frames_ref":"camera/frames.jsonl","selection":"All available frames for this official action/render setting","time_semantics":"independent rendered images; container index is not time" if independent else "official video frame order and documented source FPS; timestamps not inferred","temporal_relationship":not independent}
metadata["source_rendering"].update(official_split_kind=setting["split_kind"],official_render_rate_fps=setting["official_render_rate_fps"],camera_randomized_per_image=bool(independent and row["view_type"]=="ego"))
atomic_json(view/"metainfo.json",metadata)
frames=[]
for frame in (view/"camera/frames.jsonl").read_text(encoding="utf-8").splitlines():
item=json.loads(frame); item["sample_id"]=f"{report['capture']}:{row['camera_family']}:{row['background_variant']}:{row['camera_id']}:{item['source_frame_id']}"; frames.append(item)
write_jsonl(view/"camera/frames.jsonl",frames)
report["media_semantics"]={"envmap_per_frame":"independent images; MKV is an index-only lossless batch container; no temporal continuity","envmap_per_segment":"video sequence with temporal order","corrected_at":now()}
atomic_json(report_path,report); write_complete_pilot_v2_html(report,validation); shutil.copy2(Path(__file__),release/"script"/Path(__file__).name)
status_path=root/"tmp/pilot-v1.0/status.json"; status=json.loads(status_path.read_text(encoding="utf-8")); status.update(phase="pilot_ready_for_human_review",media_semantics_corrected=True,updated_at=now()); atomic_json(status_path,status)
def render_complete_pilot_v2(root: Path, runtime: Path, capture: str, segment: str) -> None:
np, torch, cv2, Image, smplx = runtime_imports(runtime)
state=root/"tmp/pilot-v1.0"; status_path=state/"status.json"; source=state/"extracted"/f"{capture}__{segment}"
release=root/"shared-v1.0"; validation=release/"doc/validation"; report_path=validation/"report.json"; report=json.loads(report_path.read_text())
if report.get("schema")!="reinterhand-pilot-validation/v2": raise RuntimeError("Complete pilot v2 conversion report required")
models=[ManoModel("left",runtime/"models",np,torch,smplx),ManoModel("right",runtime/"models",np,torch,smplx)]
if report["left_shapedirs_fix"]:
models[0].data["shapedirs"][:,0]*=-1
with torch.no_grad(): models[0].layer.shapedirs[:,0]*=-1
faces=np.asarray(models[0].data["f"],dtype=np.int64)
all_ids=frame_ids(root/"raw/data"/capture,segment)
source_meshes={side:{frame:read_ply_vertices(source/"mano_fits/meshes"/f"{frame}_{side}.ply",np) for frame in all_ids} for side in ["left","right"]}
status=json.loads(status_path.read_text()); status.update(phase="rendering_complete_pilot_v2",review_streams_completed=[],updated_at=now()); atomic_json(status_path,status)
for row in report["views"]:
view=release/"data"/row["sequence_id"]/row["camera_id"]; ids=[int(x) for x in row["source_frame_ids"]]
family=row["camera_family"]; variant=row["background_variant"]; view_type=row["view_type"]
image_root=source/family/variant/"images"/(row["camera_id"] if view_type=="exo" else "")
mask_root=source/family/variant/"masks"/(row["camera_id"] if view_type=="exo" else "")
width,height=row["image_size"]
intrinsic=torch.load(view/"camera/intrinsic.pt",map_location="cpu",weights_only=True).numpy()
extrinsic=torch.load(view/"camera/extrinsic.pt",map_location="cpu",weights_only=True).numpy()
distortion=torch.load(view/"camera/distortion.pt",map_location="cpu",weights_only=True).numpy() if (view/"camera/distortion.pt").exists() else None
motion=torch.load(view/"annotation/mano/motion.pt",map_location="cpu",weights_only=True).numpy()
current={}
for index,side in enumerate(["left","right"]): current[side],_=models[index].geometry(motion[:,index,:48],motion[:,index,48:58],motion[:,index,58:])
pixel_errors=[]
def mano_panels():
for i,frame in enumerate(ids):
original=Image.open(image_root/f"{frame:06d}.png").convert("RGB"); points={}
for side in ["left","right"]:
source_camera=source_meshes[side][frame]@extrinsic[i,:3,:3].T+extrinsic[i,:3,3]
src_uv,src_visible=project_vertices(source_camera,intrinsic[i],None if distortion is None else distortion[i],np,cv2)
cur_uv,cur_visible=project_vertices(current[side][i],intrinsic[i],None if distortion is None else distortion[i],np,cv2)
good=src_visible&cur_visible&np.isfinite(src_uv).all(1)&np.isfinite(cur_uv).all(1)
if good.any(): pixel_errors.extend(np.linalg.norm(src_uv[good]-cur_uv[good],axis=1).tolist())
points[side]=cur_uv
overlay=draw_mano_meshes(original,points,faces,Image); canvas=Image.new("RGB",(width*2,height))
canvas.paste(label_panel(original,f"RGB | {variant} | source frame {frame}",Image),(0,0)); canvas.paste(label_panel(overlay,"shared MANO mesh | cyan left, orange right",Image),(width,0)); yield canvas
safe=f"{family[:-8].lower()}__{variant}__{row['camera_id']}"; mano_video=Path("media")/f"{safe}__mano.mp4"
rendered=render_review_video(mano_panels(),validation/mano_video,(width,height),panels=2)
def mask_panels():
for frame in ids:
original=Image.open(image_root/f"{frame:06d}.png").convert("RGB"); mask=draw_foreground_intensity(original,mask_root/f"{frame:06d}.png",Image); canvas=Image.new("RGB",(width*2,height)); canvas.paste(label_panel(original,f"RGB | {variant} | source frame {frame}",Image),(0,0)); canvas.paste(label_panel(mask,"native non-binary foreground mask",Image),(width,0)); yield canvas
mask_video=Path("media")/f"{safe}__mask.mp4"; mask_rendered=render_review_video(mask_panels(),validation/mask_video,(width,height),panels=2)
if rendered!=len(ids) or mask_rendered!=len(ids) or not pixel_errors: raise RuntimeError(f"Review failure: {safe}")
row.update(visual_review_video=mano_video.as_posix(),mask_review_video=mask_video.as_posix(),visual_review_frames=rendered,source_vs_shared_projection_max_px=float(max(pixel_errors)),source_vs_shared_projection_mean_px=float(sum(pixel_errors)/len(pixel_errors)))
status["review_streams_completed"].append(safe); status.update(active_stream=safe,updated_at=now()); atomic_json(status_path,status)
report["automatic_status"]="passed"; report["visual_scope"]="every available frame in all 27 streams across all four official settings"; report["completed_at"]=now(); atomic_json(report_path,report)
write_complete_pilot_v2_html(report,validation); shutil.copy2(Path(__file__),release/"script"/Path(__file__).name)
status.update(phase="pilot_ready_for_human_review",active_stream=None,expanded_review=True,updated_at=now()); atomic_json(status_path,status)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
subcommands = parser.add_subparsers(dest="command", required=True)
extract = subcommands.add_parser("extract-pilot")
extract.add_argument("--root", type=Path, required=True)
extract.add_argument("--capture", default=CAPTURE)
extract.add_argument("--segment", default=SEGMENT)
convert = subcommands.add_parser("convert-pilot")
convert.add_argument("--root", type=Path, required=True)
convert.add_argument("--runtime", type=Path, required=True)
convert.add_argument("--capture", default=CAPTURE)
convert.add_argument("--segment", default=SEGMENT)
render = subcommands.add_parser("render-pilot")
render.add_argument("--root", type=Path, required=True)
render.add_argument("--runtime", type=Path, required=True)
render.add_argument("--capture", default=CAPTURE)
render.add_argument("--segment", default=SEGMENT)
variant = subcommands.add_parser("extract-background-variant")
variant.add_argument("--root", type=Path, required=True)
variant.add_argument("--capture", default=CAPTURE)
variant.add_argument("--segment", default=SEGMENT)
variant.add_argument("--variant", choices=["envmap_per_frame", "envmap_per_segment"], required=True)
expanded = subcommands.add_parser("render-expanded-review")
expanded.add_argument("--root", type=Path, required=True)
expanded.add_argument("--runtime", type=Path, required=True)
expanded.add_argument("--capture", default=CAPTURE)
expanded.add_argument("--segment", default=SEGMENT)
complete = subcommands.add_parser("convert-complete-pilot-v2")
complete.add_argument("--root", type=Path, required=True)
complete.add_argument("--runtime", type=Path, required=True)
complete.add_argument("--capture", default=CAPTURE)
complete.add_argument("--segment", default=SEGMENT)
semantics = subcommands.add_parser("fix-pilot-v2-media-semantics")
semantics.add_argument("--root", type=Path, required=True)
return parser.parse_args()
def main() -> None:
args = parse_args()
if args.command == "extract-pilot":
extract_pilot(args.root.resolve(), args.capture, args.segment)
elif args.command == "convert-pilot":
convert_pilot(args.root.resolve(), args.runtime.resolve(), args.capture, args.segment)
elif args.command == "render-pilot":
render_pilot(args.root.resolve(), args.runtime.resolve(), args.capture, args.segment)
elif args.command == "extract-background-variant":
extract_background_variant(args.root.resolve(), args.capture, args.segment, args.variant)
elif args.command == "render-expanded-review":
render_complete_pilot_v2(args.root.resolve(), args.runtime.resolve(), args.capture, args.segment)
elif args.command == "convert-complete-pilot-v2":
convert_complete_pilot_v2(args.root.resolve(), args.runtime.resolve(), args.capture, args.segment)
elif args.command == "fix-pilot-v2-media-semantics":
fix_complete_pilot_v2_media_semantics(args.root.resolve())
if __name__ == "__main__":
main()
|