Stage H2O shared-v1.1 13457/13457
Browse files- H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/run-full.sh +26 -0
- H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/warehouse_v1_0.py +934 -0
- H2O/shared-v1.1/script/v1_0_snapshot/script/render_dexycb_validation.py +66 -0
- H2O/shared-v1.1/script/v1_0_snapshot/script/render_h2o_validation.py +97 -0
- H2O/shared-v1.1/script/v1_0_snapshot/script/render_hoi4d_source_review.py +108 -0
- H2O/shared-v1.1/script/v1_0_snapshot/script/render_hoi4d_validation.py +182 -0
- H2O/shared-v1.1/script/v1_0_snapshot/script/run-full.sh +14 -0
- H2O/shared-v1.1/script/v1_0_snapshot/script/warehouse_v1_0.py +1032 -0
H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/run-full.sh
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -u
|
| 3 |
+
base="$HOME/Datasets/uni-hoi-h2o-full-20260930-w4-c10-d10"
|
| 4 |
+
raw="$HOME/Datasets/Hand-Datasets-Raw/H2O"
|
| 5 |
+
cd "$HOME/Projects/uni-hoi-dataset" || exit 1
|
| 6 |
+
mkdir -p "$base/scratch"
|
| 7 |
+
export TMPDIR="$base/scratch" PYTHONUNBUFFERED=1
|
| 8 |
+
for n in 1 2 3 4; do test -s "$raw/raw/data/subject${n}_v1_1.tar.gz" || exit 2; done
|
| 9 |
+
test ! -e "$base/full.status" || exit 3
|
| 10 |
+
cg=$(awk -F: '$1=="0" {print $3}' /proc/self/cgroup)
|
| 11 |
+
if [[ -f "/sys/fs/cgroup$cg/cpu.max" ]]; then
|
| 12 |
+
read -r quota period < "/sys/fs/cgroup$cg/cpu.max"
|
| 13 |
+
else
|
| 14 |
+
quota=max
|
| 15 |
+
period=controller_disabled
|
| 16 |
+
fi
|
| 17 |
+
printf 'START=%s\nWORKERS=4 CODEC_THREADS=10 DECODE_THREADS=10 DEPTH_THREADS=4 SUBJECTS=1,2,3,4 CASA=false\nCPU_LIMIT=none\nCGROUP=%s\nCPU_MAX=%s %s\n' "$(date -Is)" "$cg" "$quota" "$period" > "$base/full.status"
|
| 18 |
+
if [[ "$quota" != max ]]; then
|
| 19 |
+
printf 'EXIT=4 ERROR=UNEXPECTED_CPU_QUOTA\n' >> "$base/full.status"
|
| 20 |
+
exit 4
|
| 21 |
+
fi
|
| 22 |
+
/usr/bin/time -v .venv/bin/python "$base/frozen-code/scripts/convert_h2o_v1.0.py" --root "$raw" --out "$base" --release-id shared-v1.0 --workers 4 --codec-threads 10 --decode-threads 10 --depth-threads 4 --mano-dir "$HOME/Projects/WiLoR/mano_data" > "$base/full.log" 2>&1
|
| 23 |
+
code=$?
|
| 24 |
+
printf 'EXIT=%s END=%s\n' "$code" "$(date -Is)" >> "$base/full.status"
|
| 25 |
+
if [[ -f "/sys/fs/cgroup$cg/cpu.stat" ]]; then cat "/sys/fs/cgroup$cg/cpu.stat" >> "$base/full.status"; fi
|
| 26 |
+
exit "$code"
|
H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/warehouse_v1_0.py
ADDED
|
@@ -0,0 +1,934 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared I/O for CONTRACT.md v1.0. No annotation synthesis."""
|
| 2 |
+
import argparse
|
| 3 |
+
from contextlib import contextmanager
|
| 4 |
+
from functools import lru_cache
|
| 5 |
+
import hashlib
|
| 6 |
+
import json
|
| 7 |
+
import math
|
| 8 |
+
import os
|
| 9 |
+
import shlex
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
import pickle
|
| 12 |
+
import random
|
| 13 |
+
import shutil
|
| 14 |
+
import subprocess
|
| 15 |
+
import tempfile
|
| 16 |
+
import time
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
from PIL import Image
|
| 20 |
+
import torch
|
| 21 |
+
|
| 22 |
+
SCHEMA_PATH = next(p for p in (Path(__file__).resolve().parents[1] / 'docs/schema.json',
|
| 23 |
+
Path(__file__).resolve().parents[1] / 'doc/schema.json') if p.is_file())
|
| 24 |
+
SCHEMA = json.loads(SCHEMA_PATH.read_text())
|
| 25 |
+
RAW_ROOT = Path.home() / 'Datasets/Hand-Datasets-Raw'
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def json_write(path, value):
|
| 29 |
+
path = Path(path)
|
| 30 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 31 |
+
path.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + '\n')
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def jsonl_write(path, rows):
|
| 35 |
+
path = Path(path)
|
| 36 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 37 |
+
with path.open('w') as out:
|
| 38 |
+
for row in rows:
|
| 39 |
+
out.write(json.dumps(row, ensure_ascii=False, allow_nan=False) + '\n')
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def sha256(path):
|
| 43 |
+
with Path(path).open('rb') as f:
|
| 44 |
+
return hashlib.file_digest(f, 'sha256').hexdigest()
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def locator(path, member=None, data=None, **extra):
|
| 48 |
+
result = {'file': str(Path(path).resolve())}
|
| 49 |
+
if member is not None:
|
| 50 |
+
result['member'] = member
|
| 51 |
+
if data is not None:
|
| 52 |
+
result['sha256'] = hashlib.sha256(data).hexdigest()
|
| 53 |
+
return result | extra
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def source(method='Copy source annotation; normalize storage only'):
|
| 57 |
+
return {'kind': 'format_conversion', 'method': method}
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def run(args, **kwargs):
|
| 61 |
+
return subprocess.run(args, check=True, stderr=subprocess.PIPE, **kwargs)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
@lru_cache(maxsize=1)
|
| 65 |
+
def ffversion():
|
| 66 |
+
return run(['ffmpeg', '-version'], stdout=subprocess.PIPE).stdout.decode().splitlines()[0]
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def probe(path):
|
| 70 |
+
return json.loads(run(['ffprobe', '-v', 'error', '-select_streams', 'v:0',
|
| 71 |
+
'-show_streams', '-of', 'json', str(path)],
|
| 72 |
+
stdout=subprocess.PIPE).stdout)['streams'][0]
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def decode_args(path, pixel_format):
|
| 76 |
+
threads = os.environ.get('HAND_WAREHOUSE_FFMPEG_THREADS', '1')
|
| 77 |
+
return ['ffmpeg', '-v', 'error', '-nostdin', '-filter_threads', threads, '-threads', threads, '-noautorotate',
|
| 78 |
+
'-i', str(path), '-map', '0:v:0', '-vsync', '0', '-threads', threads,
|
| 79 |
+
'-f', 'rawvideo', '-pix_fmt', pixel_format]
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def decoded_digest(path, pixel_format):
|
| 83 |
+
start = time.monotonic()
|
| 84 |
+
with tempfile.TemporaryFile() as err:
|
| 85 |
+
proc = subprocess.Popen(decode_args(path, pixel_format) + ['pipe:1'],
|
| 86 |
+
stdout=subprocess.PIPE, stderr=err)
|
| 87 |
+
digest, size = hashlib.sha256(), 0
|
| 88 |
+
with proc.stdout:
|
| 89 |
+
while chunk := proc.stdout.read(1024 * 1024):
|
| 90 |
+
digest.update(chunk)
|
| 91 |
+
size += len(chunk)
|
| 92 |
+
if proc.wait():
|
| 93 |
+
err.seek(0)
|
| 94 |
+
raise RuntimeError(err.read().decode(errors='replace'))
|
| 95 |
+
return digest.hexdigest(), size, time.monotonic() - start
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def video_frames(path, pixel_format, shape, dtype):
|
| 99 |
+
frame_bytes = int(np.prod(shape)) * np.dtype(dtype).itemsize
|
| 100 |
+
with tempfile.TemporaryFile() as err:
|
| 101 |
+
proc = subprocess.Popen(decode_args(path, pixel_format) + ['pipe:1'], stdout=subprocess.PIPE, stderr=err)
|
| 102 |
+
completed = False
|
| 103 |
+
try:
|
| 104 |
+
while True:
|
| 105 |
+
data = proc.stdout.read(frame_bytes)
|
| 106 |
+
if not data:
|
| 107 |
+
break
|
| 108 |
+
if len(data) != frame_bytes:
|
| 109 |
+
raise ValueError('truncated decoded video frame')
|
| 110 |
+
yield np.frombuffer(data, dtype=dtype).reshape(shape)
|
| 111 |
+
if proc.wait():
|
| 112 |
+
err.seek(0)
|
| 113 |
+
raise ValueError(err.read().decode(errors='replace'))
|
| 114 |
+
completed = True
|
| 115 |
+
finally:
|
| 116 |
+
proc.stdout.close()
|
| 117 |
+
if not completed and proc.poll() is None:
|
| 118 |
+
proc.terminate()
|
| 119 |
+
proc.wait()
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def storage(path, profile, parameters, source_lossy):
|
| 123 |
+
info = probe(path)
|
| 124 |
+
if info['codec_name'] == 'h264':
|
| 125 |
+
frames = json.loads(run(['ffprobe', '-v', 'error', '-threads', '1', '-select_streams', 'v:0',
|
| 126 |
+
'-show_entries', 'frame=key_frame', '-of', 'json', str(path)], stdout=subprocess.PIPE).stdout)['frames']
|
| 127 |
+
parameters = parameters | {'keyframe_indices': [i for i, f in enumerate(frames) if f['key_frame']]}
|
| 128 |
+
return {'profile': profile, 'codec': info['codec_name'],
|
| 129 |
+
'pixel_format': info['pix_fmt'], 'encoded_size': [info['width'], info['height']],
|
| 130 |
+
'decoder': {'name': 'ffmpeg', 'version': ffversion(), 'autorotate': False,
|
| 131 |
+
'color_space': info.get('color_space', 'unknown'),
|
| 132 |
+
'color_range': info.get('color_range', 'unknown'),
|
| 133 |
+
'color_primaries': info.get('color_primaries', 'unknown'),
|
| 134 |
+
'color_transfer': info.get('color_transfer', 'unknown')},
|
| 135 |
+
'encoder_parameters': {'version': ffversion()} | parameters,
|
| 136 |
+
'source_lossy': source_lossy, 'storage_fps': 30, 'timebase_role': 'index_only'}
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def encode_raw(raw, target, width, height, pixel_format, profile, codec='ffv1', extra=(), threads=1):
|
| 140 |
+
start = time.monotonic()
|
| 141 |
+
run(['ffmpeg', '-v', 'error', '-nostdin', '-filter_threads', '1', '-y', '-f', 'rawvideo',
|
| 142 |
+
'-pixel_format', pixel_format, '-video_size', f'{width}x{height}', '-framerate', '30',
|
| 143 |
+
'-i', str(raw), '-an', '-c:v', codec, '-threads', str(threads), *extra, str(target)])
|
| 144 |
+
digest, size, decode_seconds = decoded_digest(target, pixel_format)
|
| 145 |
+
if size != Path(raw).stat().st_size or digest != sha256(raw):
|
| 146 |
+
raise ValueError(f'lossless roundtrip failed: {target}')
|
| 147 |
+
config = storage(target, profile, {'name': codec, 'arguments': list(extra), 'threads': threads}, False)
|
| 148 |
+
return config, {'bytes': target.stat().st_size, 'encode_seconds': time.monotonic() - start - decode_seconds,
|
| 149 |
+
'decode_seconds': decode_seconds, 'decoded_sha256': digest, 'all_frames_exact': True}
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def measure_rgb_access(video, raw, width, height, count):
|
| 153 |
+
index = count // 2
|
| 154 |
+
start = time.monotonic()
|
| 155 |
+
data = run(decode_args(video, 'rgb24') +
|
| 156 |
+
['-vf', f'select=eq(n\\,{index})', '-frames:v', '1', 'pipe:1'],
|
| 157 |
+
stdout=subprocess.PIPE).stdout
|
| 158 |
+
with raw.open('rb') as inp:
|
| 159 |
+
inp.seek(index * width * height * 3)
|
| 160 |
+
if data != inp.read(width * height * 3):
|
| 161 |
+
raise ValueError('exact indexed RGB read failed')
|
| 162 |
+
return {'random_access_strategy': 'decode from first keyframe; select exact presentation index',
|
| 163 |
+
'random_frame_index': index, 'random_frame_read_seconds': time.monotonic() - start}
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def jpeg_sample_indices(sequence, camera, count):
|
| 167 |
+
seed = int.from_bytes(hashlib.sha256(f'{sequence}/{camera}/20260920'.encode()).digest()[:8], 'big')
|
| 168 |
+
indices = {0, count - 1, count // 4, count // 2, 3 * count // 4}
|
| 169 |
+
indices.update(random.Random(seed).sample([i for i in range(count) if i not in indices],
|
| 170 |
+
min(count, 16) - len(indices)))
|
| 171 |
+
return sorted(indices), seed
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def check_jpeg_copy(target, paths, hashes, size, sequence, camera, full):
|
| 175 |
+
packets = json.loads(run(['ffprobe', '-v', 'error', '-select_streams', 'v:0',
|
| 176 |
+
'-show_packets', '-show_data_hash', 'sha256', '-of', 'json', str(target)],
|
| 177 |
+
stdout=subprocess.PIPE).stdout)['packets']
|
| 178 |
+
if [p['data_hash'].split(':', 1)[1].lower() for p in packets] != hashes:
|
| 179 |
+
raise ValueError('JPEG packet hashes/order/count differ')
|
| 180 |
+
info = probe(target)
|
| 181 |
+
if [info['width'], info['height']] != list(size):
|
| 182 |
+
raise ValueError('JPEG container dimensions differ')
|
| 183 |
+
indices, seed = jpeg_sample_indices(sequence, camera, len(paths))
|
| 184 |
+
if full:
|
| 185 |
+
indices = list(range(len(paths)))
|
| 186 |
+
select = '+'.join(f'eq(n\\,{i})' for i in indices)
|
| 187 |
+
frame_bytes = size[0] * size[1] * 3
|
| 188 |
+
# Spool selected frames to disk, keeping RAM bounded for full-view audits.
|
| 189 |
+
with tempfile.TemporaryFile() as decoded:
|
| 190 |
+
run(decode_args(target, 'rgb24') + ([] if full else ['-vf', 'select=' + select]) + ['pipe:1'], stdout=decoded)
|
| 191 |
+
decoded.seek(0)
|
| 192 |
+
for i in indices:
|
| 193 |
+
expected = run(decode_args(paths[i], 'rgb24') + ['pipe:1'], stdout=subprocess.PIPE).stdout
|
| 194 |
+
if len(expected) != frame_bytes or decoded.read(frame_bytes) != expected:
|
| 195 |
+
raise ValueError(f'JPEG decoded pixels differ at frame {i}')
|
| 196 |
+
if decoded.read(1):
|
| 197 |
+
raise ValueError('JPEG selected pixel count differs')
|
| 198 |
+
return {'policy': 'jpeg-packets-all-rgb-sample16/v1', 'seed': seed,
|
| 199 |
+
'selected_frame_indices': indices, 'pixel_frames_checked': len(indices),
|
| 200 |
+
'packet_frames_checked': len(paths), 'jpeg_packets_exact': True,
|
| 201 |
+
'packet_count_order_dimensions_exact': True, 'sampled_pixels_exact': True,
|
| 202 |
+
'all_frames_exact': len(indices) == len(paths), 'full_view_audit': full}
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def rgb_video(paths, target, work, video=None, count=None, sequence="", camera="", full_jpeg=False,
|
| 206 |
+
ffv1_first=False, codec_threads=1):
|
| 207 |
+
"""JPEG packet proof plus deterministic pixels; re-encodings compare all pixels."""
|
| 208 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 209 |
+
raw = work / 'rgb.raw'
|
| 210 |
+
packets = []
|
| 211 |
+
has_missing = video is None and any(p is None for p in paths)
|
| 212 |
+
if has_missing:
|
| 213 |
+
present = next((p for p in paths if p is not None), None)
|
| 214 |
+
if present is None:
|
| 215 |
+
raise ValueError('no source RGB image to establish the pixel format/grid')
|
| 216 |
+
original = probe(present)
|
| 217 |
+
width, height = original['width'], original['height']
|
| 218 |
+
with raw.open('wb') as dest:
|
| 219 |
+
for path in paths:
|
| 220 |
+
if path is None:
|
| 221 |
+
dest.write(bytes(width * height * 3))
|
| 222 |
+
else:
|
| 223 |
+
with Image.open(path) as im:
|
| 224 |
+
if im.mode != 'RGB' or im.size != (width, height):
|
| 225 |
+
raise ValueError('source RGB grid/type changes within view')
|
| 226 |
+
run(decode_args(path, 'rgb24') + ['pipe:1'], stdout=dest)
|
| 227 |
+
lossy, count = 'unknown', len(paths)
|
| 228 |
+
input_args = None
|
| 229 |
+
elif video is None:
|
| 230 |
+
if not paths:
|
| 231 |
+
raise ValueError('RGB timeline must contain existing source images')
|
| 232 |
+
suffix = paths[0].suffix.lower()
|
| 233 |
+
if suffix not in ('.jpg', '.jpeg', '.png'):
|
| 234 |
+
raise ValueError('unsupported source RGB format')
|
| 235 |
+
images = work / 'rgb_source'
|
| 236 |
+
images.mkdir()
|
| 237 |
+
dimensions = None
|
| 238 |
+
for i, path in enumerate(paths):
|
| 239 |
+
with Image.open(path) as im:
|
| 240 |
+
if im.mode != 'RGB' or (dimensions is not None and dimensions != im.size):
|
| 241 |
+
raise ValueError('RGB must be homogeneous 8-bit RGB, with no silent color/size conversion')
|
| 242 |
+
dimensions = im.size
|
| 243 |
+
if im.format == 'PNG' and path.read_bytes()[24] != 8:
|
| 244 |
+
raise ValueError('high bit depth RGB needs a registered schema')
|
| 245 |
+
dest = images / f'{i:08d}{suffix}'
|
| 246 |
+
shutil.copyfile(path, dest)
|
| 247 |
+
packets.append(sha256(path))
|
| 248 |
+
width, height = dimensions
|
| 249 |
+
input_args = ['-framerate', '30', '-i', str(images / ('%08d' + suffix))]
|
| 250 |
+
count = len(paths)
|
| 251 |
+
original = probe(paths[0])
|
| 252 |
+
lossy = suffix in ('.jpg', '.jpeg')
|
| 253 |
+
else:
|
| 254 |
+
original = probe(video)
|
| 255 |
+
if int(original.get('bits_per_raw_sample') or 8) > 8 or any(
|
| 256 |
+
x in original.get('pix_fmt', '') for x in ('10', '12', '16', 'f32')):
|
| 257 |
+
raise ValueError('high bit depth RGB needs a registered schema')
|
| 258 |
+
width, height = original['width'], original['height']
|
| 259 |
+
input_args = ['-i', str(video)]
|
| 260 |
+
lossy = 'unknown'
|
| 261 |
+
limits = ['-frames:v', str(count)] if count else []
|
| 262 |
+
records = []
|
| 263 |
+
if video is None and not has_missing and suffix in ('.jpg', '.jpeg'):
|
| 264 |
+
start = time.monotonic()
|
| 265 |
+
try:
|
| 266 |
+
run(['ffmpeg', '-v', 'error', '-nostdin', '-y', *input_args, '-map', '0:v:0',
|
| 267 |
+
*limits, '-c:v', 'copy', '-an', str(target)])
|
| 268 |
+
encode_seconds = time.monotonic() - start
|
| 269 |
+
validation = check_jpeg_copy(target, paths, packets, (width, height), sequence, camera, full_jpeg)
|
| 270 |
+
cfg = storage(target, 'mkv/mjpeg_copy/v1', {'stream_copy': True}, lossy)
|
| 271 |
+
cfg['decoder']['source_color_metadata'] = {k: original.get(k, 'unknown') for k in
|
| 272 |
+
('color_space', 'color_range', 'color_primaries', 'color_transfer')}
|
| 273 |
+
records.append(validation | {'profile': cfg['profile'], 'bytes': target.stat().st_size,
|
| 274 |
+
'encode_seconds': encode_seconds, 'validation_seconds': time.monotonic() - start - encode_seconds})
|
| 275 |
+
return cfg, [width, height], records, count
|
| 276 |
+
except (subprocess.CalledProcessError, ValueError) as exc:
|
| 277 |
+
records.append({'profile': 'mkv/mjpeg_copy/v1', 'rejected': str(exc)})
|
| 278 |
+
target.unlink(missing_ok=True)
|
| 279 |
+
if not has_missing:
|
| 280 |
+
threads = os.environ.get('HAND_WAREHOUSE_FFMPEG_THREADS', '1')
|
| 281 |
+
run(['ffmpeg', '-v', 'error', '-nostdin', '-y', '-threads', threads, '-noautorotate',
|
| 282 |
+
*input_args, '-map', '0:v:0', *limits, '-vsync', '0', '-threads', threads,
|
| 283 |
+
'-f', 'rawvideo', '-pix_fmt', 'rgb24', str(raw)])
|
| 284 |
+
frame_bytes = width * height * 3
|
| 285 |
+
actual, remainder = divmod(raw.stat().st_size, frame_bytes)
|
| 286 |
+
if remainder or not actual or (count is not None and actual != count):
|
| 287 |
+
raise ValueError('source RGB frame count mismatch')
|
| 288 |
+
expected_hash = sha256(raw)
|
| 289 |
+
can_copy = video is not None
|
| 290 |
+
if can_copy:
|
| 291 |
+
start = time.monotonic()
|
| 292 |
+
try:
|
| 293 |
+
run(['ffmpeg', '-v', 'error', '-nostdin', '-y', *input_args, '-map', '0:v:0',
|
| 294 |
+
*limits, '-c:v', 'copy', '-an', str(target)])
|
| 295 |
+
digest, size, seconds = decoded_digest(target, 'rgb24')
|
| 296 |
+
if digest != expected_hash or size != raw.stat().st_size:
|
| 297 |
+
raise ValueError('stream-copy RGB bytes/order/count mismatch')
|
| 298 |
+
cfg = storage(target, 'mkv/source_copy/v1',
|
| 299 |
+
{'stream_copy': True}, lossy)
|
| 300 |
+
if video:
|
| 301 |
+
cfg['storage_fps'] = original.get('avg_frame_rate')
|
| 302 |
+
cfg['preserve_source_pts'] = True
|
| 303 |
+
records.append({'profile': cfg['profile'], 'all_frames_exact': True,
|
| 304 |
+
'decoded_sha256': digest,
|
| 305 |
+
'bytes': target.stat().st_size, 'decode_seconds': seconds,
|
| 306 |
+
'encode_seconds': time.monotonic() - start - seconds})
|
| 307 |
+
records[-1].update(measure_rgb_access(target, raw, width, height, actual))
|
| 308 |
+
return cfg, [width, height], records, actual
|
| 309 |
+
except (subprocess.CalledProcessError, ValueError) as exc:
|
| 310 |
+
records.append({'profile': 'stream_copy', 'rejected': str(exc)})
|
| 311 |
+
target.unlink(missing_ok=True)
|
| 312 |
+
candidates = []
|
| 313 |
+
for profile, codec, params in [
|
| 314 |
+
('mkv/ffv1_rgb/v1', 'ffv1', ['-level', '3', '-pix_fmt', 'bgr0']),
|
| 315 |
+
('mkv/h264_rgb_lossless/v1', 'libx264rgb', ['-crf', '0', '-preset', 'medium', '-g', '30'])]:
|
| 316 |
+
path = work / (codec + '.mkv')
|
| 317 |
+
try:
|
| 318 |
+
cfg, record = encode_raw(raw, path, width, height, 'rgb24', profile, codec, params,
|
| 319 |
+
codec_threads if codec == 'ffv1' else 1)
|
| 320 |
+
cfg['source_lossy'] = lossy
|
| 321 |
+
cfg['decoder']['source_color_metadata'] = {k: original.get(k, 'unknown') for k in
|
| 322 |
+
('color_space', 'color_range', 'color_primaries', 'color_transfer')}
|
| 323 |
+
record['profile'] = profile
|
| 324 |
+
record.update(measure_rgb_access(path, raw, width, height, actual))
|
| 325 |
+
records.append(record)
|
| 326 |
+
candidates.append((path.stat().st_size, path, cfg))
|
| 327 |
+
if ffv1_first and codec == 'ffv1':
|
| 328 |
+
break # Keep the H.264 fallback only if the preferred exact encoder fails.
|
| 329 |
+
except subprocess.CalledProcessError as exc:
|
| 330 |
+
records.append({'profile': profile, 'rejected': exc.stderr.decode(errors='replace')})
|
| 331 |
+
if not candidates:
|
| 332 |
+
raise ValueError('no supported lossless RGB encoder')
|
| 333 |
+
_, chosen, cfg = min(candidates, key=lambda x: x[0])
|
| 334 |
+
shutil.move(chosen, target)
|
| 335 |
+
return cfg, [width, height], records, actual
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def pack_depth(depth):
|
| 339 |
+
bits = np.ascontiguousarray(depth, dtype='<f4').view('<u4')
|
| 340 |
+
return np.concatenate([(bits & 65535).astype('<u2'), (bits >> 16).astype('<u2')], axis=-1)
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
def unpack_depth(encoded):
|
| 344 |
+
low, high = np.split(np.asarray(encoded, dtype='<u2'), 2, axis=-1)
|
| 345 |
+
return (low.astype('<u4') | (high.astype('<u4') << 16)).view('<f4')
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def check_transform(values):
|
| 349 |
+
a = np.asarray(values)
|
| 350 |
+
if not np.isfinite(a).all() or a.shape[-2:] != (4, 4):
|
| 351 |
+
raise ValueError('invalid transform shape/values')
|
| 352 |
+
if not np.allclose(a[..., 3, :], [0, 0, 0, 1], atol=1e-5):
|
| 353 |
+
raise ValueError('invalid homogeneous transform row')
|
| 354 |
+
r = a[..., :3, :3]
|
| 355 |
+
if not np.allclose(np.swapaxes(r, -1, -2) @ r, np.eye(3), atol=2e-3) or not np.allclose(
|
| 356 |
+
np.linalg.det(r), 1, atol=2e-3):
|
| 357 |
+
raise ValueError('nonrigid rotation')
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
class View:
|
| 361 |
+
def __init__(self, path, dataset, release, sequence, camera, frames, sampling='dense', split='unknown'):
|
| 362 |
+
self.path = Path(path)
|
| 363 |
+
self.path.mkdir(parents=True, exist_ok=True)
|
| 364 |
+
self.frames = frames
|
| 365 |
+
self.valid_rules = {}
|
| 366 |
+
self.full_jpeg = False
|
| 367 |
+
self.meta = dict(schema_version=SCHEMA['schema_version'], dataset_id=dataset,
|
| 368 |
+
release_id=release, sequence_id=sequence, camera_id=camera,
|
| 369 |
+
sample_type='video', num_frames=len(frames), hand_slots=['left', 'right'],
|
| 370 |
+
sampling={'type': sampling, 'source_fps': None, 'frames_ref': 'camera/frames.jsonl'},
|
| 371 |
+
camera={'model': 'unknown', 'schema_id': None, 'image_size': None},
|
| 372 |
+
components={}, split=split, view_type='unknown')
|
| 373 |
+
if split == 'unknown':
|
| 374 |
+
self.meta['split_reason'] = 'No verified official split mapping available for this sequence'
|
| 375 |
+
self.build = {'validation': [], 'unresolved': [], 'validity_revision': SCHEMA['validity_revision']}
|
| 376 |
+
|
| 377 |
+
def absent(self, key, reason, status='source_missing'):
|
| 378 |
+
self.meta['components'][key] = {'available': False, 'reason': reason, 'status': status}
|
| 379 |
+
if status != 'source_missing':
|
| 380 |
+
self.build['unresolved'].append({'component': key, 'status': status, 'reason': reason})
|
| 381 |
+
|
| 382 |
+
def component(self, key, schema, ref, axes, loc, **extra):
|
| 383 |
+
if schema not in SCHEMA['components']:
|
| 384 |
+
raise ValueError(f'unregistered schema: {schema}')
|
| 385 |
+
if ref.startswith('annotation/') and extra.get('valid_ref'):
|
| 386 |
+
rule = self.valid_rules.get(key, self.valid_rules.get(key.split('_')[0]))
|
| 387 |
+
if not rule:
|
| 388 |
+
raise ValueError(f'{key}: adapter must declare annotation validity rule')
|
| 389 |
+
extra.setdefault('valid_policy', dict(
|
| 390 |
+
revision=SCHEMA['validity_revision'], meaning=SCHEMA['annotation_validity']['meaning'],
|
| 391 |
+
source_rule=rule, source_locator=loc, scope=extra.get('valid_axes', axes),
|
| 392 |
+
numerical_checks='Schema shape, finite valid floats, SE(3) where applicable; malformed input aborts',
|
| 393 |
+
official_qa={'status': 'not_provided', 'reason': 'No separate applicable official QA in selected source inputs'},
|
| 394 |
+
local_excluded_frame_indices=[], local_exclusion_reasons={}, visibility_independent=True))
|
| 395 |
+
self.meta['components'][key] = dict(available=True, schema_id=schema, data_ref=ref,
|
| 396 |
+
axes=axes, provenance=source(), source_locator=loc) | extra
|
| 397 |
+
return self.meta['components'][key]
|
| 398 |
+
|
| 399 |
+
def tensor(self, key, schema, ref, array, valid, axes, loc, **extra):
|
| 400 |
+
array = np.asarray(array, dtype=np.float32)
|
| 401 |
+
valid = np.asarray(valid, dtype=bool)
|
| 402 |
+
valid_shape = SCHEMA['components'][schema].get('valid_shape')
|
| 403 |
+
if valid_shape and (len(valid_shape) != valid.ndim or any(isinstance(s, int) and valid.shape[i] != s for i, s in enumerate(valid_shape))):
|
| 404 |
+
raise ValueError(f'{key}: schema validity shape mismatch')
|
| 405 |
+
if array.shape[:valid.ndim] != valid.shape:
|
| 406 |
+
raise ValueError(f'{key}: validity axes mismatch')
|
| 407 |
+
if not np.isfinite(array[valid]).all():
|
| 408 |
+
raise ValueError(f'{key}: source annotation exists but is nonfinite')
|
| 409 |
+
array = array.copy()
|
| 410 |
+
array[~valid] = np.nan
|
| 411 |
+
if schema in ('transform/se3/v1', 'object/rigid/v1'):
|
| 412 |
+
check_transform(array[valid])
|
| 413 |
+
expected = SCHEMA['components'][schema].get('shape')
|
| 414 |
+
if expected and (len(expected) != array.ndim or any(
|
| 415 |
+
isinstance(n, int) and array.shape[i] != n for i, n in enumerate(expected))):
|
| 416 |
+
raise ValueError(f'{key}: schema shape mismatch {array.shape}')
|
| 417 |
+
dest = self.path / ref
|
| 418 |
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
| 419 |
+
torch.save(torch.from_numpy(array), dest)
|
| 420 |
+
valid_ref = str(Path(ref).with_name(Path(ref).stem + '_valid.pt'))
|
| 421 |
+
torch.save(torch.from_numpy(valid.copy()), self.path / valid_ref)
|
| 422 |
+
return self.component(key, schema, ref, axes, loc, valid_ref=valid_ref,
|
| 423 |
+
valid_axes=axes[:valid.ndim], **extra)
|
| 424 |
+
|
| 425 |
+
def rgb(self, paths, loc, video=None, count=None, ffv1_first=False, codec_threads=1):
|
| 426 |
+
with tempfile.TemporaryDirectory(prefix='rgb-', dir=self.path) as work:
|
| 427 |
+
cfg, size, records, n = rgb_video(paths, self.path / 'observation/rgb.mkv',
|
| 428 |
+
Path(work), video, count, self.meta['sequence_id'], self.meta['camera_id'],
|
| 429 |
+
self.full_jpeg, ffv1_first, codec_threads)
|
| 430 |
+
if n != len(self.frames):
|
| 431 |
+
raise ValueError('RGB differs from frames timeline')
|
| 432 |
+
torch.save(torch.ones(n, dtype=torch.bool, device='cpu') if video is not None else
|
| 433 |
+
torch.tensor([p is not None for p in paths], dtype=torch.bool, device='cpu'),
|
| 434 |
+
self.path / 'observation/rgb_valid.pt')
|
| 435 |
+
self.component('rgb', 'rgb/uint8/v1', 'observation/rgb.mkv', ['T', 'height', 'width', 'channel'],
|
| 436 |
+
loc, storage=cfg, valid_ref='observation/rgb_valid.pt', valid_axes=['T'],
|
| 437 |
+
provenance=source('Verified source packet copy or lossless fixed-decoder RGB encoding'))
|
| 438 |
+
self.meta['camera']['image_size'] = size
|
| 439 |
+
self.build['validation'].extend(records)
|
| 440 |
+
|
| 441 |
+
def raster(self, key, arrays, valid, loc, labels=None, codec_threads=1):
|
| 442 |
+
depth = key == 'depth'
|
| 443 |
+
ref = 'observation/depth.mkv' if depth else 'annotation/segment/mask.mkv'
|
| 444 |
+
dest = self.path / ref
|
| 445 |
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
| 446 |
+
width, height = self.meta['camera']['image_size']
|
| 447 |
+
count = 0
|
| 448 |
+
with tempfile.TemporaryDirectory(prefix='raster-', dir=self.path) as wd:
|
| 449 |
+
work = Path(wd)
|
| 450 |
+
with (work / 'data.raw').open('wb') as out, (work / 'valid.raw').open('wb') as vo:
|
| 451 |
+
for arr in arrays:
|
| 452 |
+
arr = np.asarray(arr)
|
| 453 |
+
if arr.shape != (height, width):
|
| 454 |
+
raise ValueError(f'{key}: raster not on RGB grid')
|
| 455 |
+
if depth:
|
| 456 |
+
arr = arr.astype('<f4')
|
| 457 |
+
good = np.isfinite(arr) & (arr > 0)
|
| 458 |
+
arr[~good] = np.nan
|
| 459 |
+
out.write(pack_depth(arr).tobytes())
|
| 460 |
+
vo.write(good.astype(np.uint8).tobytes())
|
| 461 |
+
else:
|
| 462 |
+
if not np.issubdtype(arr.dtype, np.integer) or arr.min() < 0 or arr.max() > 65535:
|
| 463 |
+
raise ValueError('invalid segmentation region codes')
|
| 464 |
+
out.write(arr.astype('<u2').tobytes())
|
| 465 |
+
count += 1
|
| 466 |
+
if count != len(self.frames):
|
| 467 |
+
raise ValueError(f'{key}: frame count mismatch')
|
| 468 |
+
cfg, record = encode_raw(work / 'data.raw', dest, width * (2 if depth else 1), height,
|
| 469 |
+
'gray16le', 'mkv/depth_float32_bits/v1' if depth else 'mkv/uint16_ffv1/v1',
|
| 470 |
+
threads=codec_threads)
|
| 471 |
+
self.build['validation'].append(record | {'component': key})
|
| 472 |
+
if depth:
|
| 473 |
+
vcfg, record = encode_raw(work / 'valid.raw', self.path / 'observation/depth_valid.mkv',
|
| 474 |
+
width, height, 'gray', 'mkv/bool_ffv1/v1', threads=codec_threads)
|
| 475 |
+
self.build['validation'].append(record | {'component': 'depth_valid'})
|
| 476 |
+
self.component(key, 'depth/z_float32/v1', ref, ['T', 'height', 'width'], loc,
|
| 477 |
+
storage=cfg, valid_storage=vcfg, valid_ref='observation/depth_valid.mkv',
|
| 478 |
+
valid_axes=['T', 'height', 'width'], unit='m', depth_type='z', depth_origin='measured', invalid_value='NaN')
|
| 479 |
+
else:
|
| 480 |
+
vref = 'annotation/segment/mask_valid.pt'
|
| 481 |
+
torch.save(torch.as_tensor(valid, dtype=torch.bool, device='cpu'), self.path / vref)
|
| 482 |
+
jsonl_write(self.path / 'annotation/segment/instances.jsonl', labels)
|
| 483 |
+
self.component(key, 'segment/uint16_labels/v1', ref, ['T', 'height', 'width'], loc,
|
| 484 |
+
storage=cfg, valid_ref=vref, valid_axes=['T'], segmentation_type='instance',
|
| 485 |
+
mapping_ref='annotation/segment/instances.jsonl', coverage={'kind': 'unknown'})
|
| 486 |
+
|
| 487 |
+
def camera(self, intrinsic, loc, extrinsic=None, extrinsic_loc=None):
|
| 488 |
+
n = len(self.frames)
|
| 489 |
+
if intrinsic is not None:
|
| 490 |
+
a = np.asarray(intrinsic)
|
| 491 |
+
a = np.broadcast_to(a, (n, 3, 3)) if a.shape == (3, 3) else a
|
| 492 |
+
if not np.allclose(a[..., 2, :], [0, 0, 1]) or np.any(a[..., 0, 0] <= 0) or np.any(a[..., 1, 1] <= 0):
|
| 493 |
+
raise ValueError('invalid pinhole intrinsic matrix')
|
| 494 |
+
self.tensor('intrinsic', 'camera/pinhole/v1', 'camera/intrinsic.pt', a,
|
| 495 |
+
np.ones(n, bool), ['T', 'row', 'column'], loc)
|
| 496 |
+
self.meta['camera'].update(model='pinhole', schema_id='camera/pinhole/v1')
|
| 497 |
+
if extrinsic is not None:
|
| 498 |
+
a = np.asarray(extrinsic)
|
| 499 |
+
a = np.broadcast_to(a, (n, 4, 4)) if a.shape == (4, 4) else a
|
| 500 |
+
self.tensor('extrinsic', 'transform/se3/v1', 'camera/extrinsic.pt', a,
|
| 501 |
+
np.ones(n, bool), ['T', 'row', 'column'], extrinsic_loc or loc,
|
| 502 |
+
convention='T_camera_from_world')
|
| 503 |
+
|
| 504 |
+
def object(self, oid, loc, scope='sequence', scope_id=None, **extra):
|
| 505 |
+
info = dict(object_id=oid, identity_scope=scope, scope_id=scope_id or self.meta['sequence_id'],
|
| 506 |
+
source_locator=loc, has_model=False) | extra
|
| 507 |
+
json_write(self.path / f'annotation/object/{oid}/metainfo.json', info)
|
| 508 |
+
return info
|
| 509 |
+
|
| 510 |
+
def relations(self, rows, valid, loc):
|
| 511 |
+
ref = 'annotation/contact/relations.jsonl'
|
| 512 |
+
jsonl_write(self.path / ref, rows)
|
| 513 |
+
vref = 'annotation/contact/relations_valid.pt'
|
| 514 |
+
torch.save(torch.as_tensor(valid, dtype=torch.bool, device='cpu'), self.path / vref)
|
| 515 |
+
self.component('relations', 'contact/relations/v1', ref, ['T'], loc, valid_ref=vref, valid_axes=['T'])
|
| 516 |
+
|
| 517 |
+
def finish(self):
|
| 518 |
+
check_view_type(self.meta)
|
| 519 |
+
for key, component in self.meta['components'].items():
|
| 520 |
+
if component.get('valid_policy'):
|
| 521 |
+
check_valid_policy(component, len(self.frames))
|
| 522 |
+
valid = torch.load(self.path / component['valid_ref'], weights_only=True)
|
| 523 |
+
self.build.setdefault('annotation_validity', {})[key] = {
|
| 524 |
+
'valid_policy': component['valid_policy'], 'valid_count': int(valid.sum()),
|
| 525 |
+
'invalid_count': valid.numel() - int(valid.sum())}
|
| 526 |
+
for i, frame in enumerate(self.frames):
|
| 527 |
+
frame.update(frame_index=i)
|
| 528 |
+
frame.setdefault('timestamp_ns', None)
|
| 529 |
+
frame.setdefault('clock_domain', None)
|
| 530 |
+
if 'source_locator' not in frame:
|
| 531 |
+
raise ValueError('frame source locator missing')
|
| 532 |
+
jsonl_write(self.path / 'camera/frames.jsonl', self.frames)
|
| 533 |
+
json_write(self.path / 'metainfo.json', self.meta)
|
| 534 |
+
return self.build
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
def check_mesh(path, asset_root):
|
| 538 |
+
path, asset_root = Path(path), Path(asset_root).resolve()
|
| 539 |
+
vertices, faces, largest_index = 0, 0, 0
|
| 540 |
+
materials = []
|
| 541 |
+
with path.open() as inp:
|
| 542 |
+
for line in inp:
|
| 543 |
+
fields = line.split()
|
| 544 |
+
if not fields or fields[0].startswith('#'):
|
| 545 |
+
continue
|
| 546 |
+
if fields[0] == 'v':
|
| 547 |
+
if len(fields) < 4 or not all(math.isfinite(float(v)) for v in fields[1:4]):
|
| 548 |
+
raise ValueError(f'invalid mesh vertex: {path}')
|
| 549 |
+
vertices += 1
|
| 550 |
+
elif fields[0] == 'f':
|
| 551 |
+
if len(fields) < 4:
|
| 552 |
+
raise ValueError('degenerate OBJ face')
|
| 553 |
+
for field in fields[1:]:
|
| 554 |
+
index = int(field.split('/')[0])
|
| 555 |
+
if index == 0 or index < -vertices:
|
| 556 |
+
raise ValueError('invalid OBJ vertex index')
|
| 557 |
+
largest_index = max(largest_index, index)
|
| 558 |
+
faces += 1
|
| 559 |
+
elif fields[0] == 'mtllib':
|
| 560 |
+
materials.extend(shlex.split(line)[1:])
|
| 561 |
+
if not vertices or not faces or largest_index > vertices:
|
| 562 |
+
raise ValueError('empty or invalid mesh')
|
| 563 |
+
def dependency(parent, name):
|
| 564 |
+
dep = (parent / name).resolve()
|
| 565 |
+
if not dep.is_relative_to(asset_root) or not dep.is_file():
|
| 566 |
+
raise ValueError(f'missing or escaping asset dependency: {name}')
|
| 567 |
+
return dep
|
| 568 |
+
dependencies = []
|
| 569 |
+
for name in materials:
|
| 570 |
+
mtl = dependency(path.parent, name)
|
| 571 |
+
dependencies.append(mtl)
|
| 572 |
+
for line in mtl.read_text().splitlines():
|
| 573 |
+
fields = shlex.split(line, comments=True)
|
| 574 |
+
if fields and (fields[0].startswith('map_') or fields[0] in ('bump', 'norm', 'disp', 'decal')):
|
| 575 |
+
dependencies.append(dependency(mtl.parent, fields[-1]))
|
| 576 |
+
return {'vertices': vertices, 'faces': faces, 'sha256': sha256(path),
|
| 577 |
+
'dependencies': {p.relative_to(asset_root).as_posix(): sha256(p) for p in dependencies}}
|
| 578 |
+
|
| 579 |
+
|
| 580 |
+
def mesh_asset(view, oid, directory, obj, loc):
|
| 581 |
+
dest = view.path / f'annotation/object/{oid}/assets'
|
| 582 |
+
shutil.copytree(directory, dest)
|
| 583 |
+
ref = (dest / Path(obj).relative_to(directory)).relative_to(view.path).as_posix()
|
| 584 |
+
mesh_check = check_mesh(dest / Path(obj).relative_to(directory), dest)
|
| 585 |
+
view.build['validation'].append({'component': f'mesh_{oid}', **mesh_check})
|
| 586 |
+
view.component(f'mesh_{oid}', 'mesh/obj/v1', ref, ['vertex'], loc, valid=True, unit='m')
|
| 587 |
+
p = view.path / f'annotation/object/{oid}/metainfo.json'
|
| 588 |
+
info = json.loads(p.read_text())
|
| 589 |
+
info.update(has_model=True, mesh_ref=ref)
|
| 590 |
+
json_write(p, info)
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
def safe_member(root, name):
|
| 594 |
+
path = (Path(root) / name).resolve()
|
| 595 |
+
if not path.is_relative_to(Path(root).resolve()):
|
| 596 |
+
raise ValueError(f'unsafe archive path: {name}')
|
| 597 |
+
return path
|
| 598 |
+
|
| 599 |
+
|
| 600 |
+
class ChumpyStub:
|
| 601 |
+
def __setstate__(self, state):
|
| 602 |
+
self.__dict__.update(state)
|
| 603 |
+
|
| 604 |
+
|
| 605 |
+
class ManoUnpickler(pickle.Unpickler):
|
| 606 |
+
def find_class(self, module, name):
|
| 607 |
+
if module.startswith('chumpy'):
|
| 608 |
+
return ChumpyStub
|
| 609 |
+
return super().find_class(module, name)
|
| 610 |
+
|
| 611 |
+
|
| 612 |
+
def mano_models(directory):
|
| 613 |
+
result = {}
|
| 614 |
+
if directory is None:
|
| 615 |
+
return result
|
| 616 |
+
for side in ('left', 'right'):
|
| 617 |
+
path = Path(directory).expanduser() / f'MANO_{side.upper()}.pkl'
|
| 618 |
+
if not path.exists():
|
| 619 |
+
continue
|
| 620 |
+
with path.open('rb') as f:
|
| 621 |
+
data = ManoUnpickler(f, encoding='latin1').load()
|
| 622 |
+
result[side] = {'components': np.asarray(data['hands_components']),
|
| 623 |
+
'mean': np.asarray(data['hands_mean']), 'sha256': sha256(path),
|
| 624 |
+
'file': path.name}
|
| 625 |
+
return result
|
| 626 |
+
|
| 627 |
+
|
| 628 |
+
def model_profile(models):
|
| 629 |
+
identity = json.dumps({side: d['sha256'] for side, d in sorted(models.items())}).encode()
|
| 630 |
+
return {'version': 'sha256:' + hashlib.sha256(identity).hexdigest(), 'flat_hand_mean': True,
|
| 631 |
+
'left_shapedirs_correction': 'not_applied',
|
| 632 |
+
'models': {side: {'file': d['file'], 'sha256': d['sha256']} for side, d in models.items()}}
|
| 633 |
+
|
| 634 |
+
|
| 635 |
+
def pca_to_axis_angle(coeffs, model):
|
| 636 |
+
coeffs = np.asarray(coeffs)
|
| 637 |
+
if coeffs.shape[-1:] != (45,) or not np.isfinite(coeffs).all():
|
| 638 |
+
raise ValueError('invalid MANO PCA coefficients')
|
| 639 |
+
return coeffs @ model['components'] + model['mean']
|
| 640 |
+
|
| 641 |
+
|
| 642 |
+
def parser(dataset, description):
|
| 643 |
+
p = argparse.ArgumentParser(description=description)
|
| 644 |
+
p.add_argument('--root', f'--{dataset.lower()}-root', dest='root', type=Path, default=RAW_ROOT / dataset)
|
| 645 |
+
p.add_argument('--out', type=Path, default=Path('converted'))
|
| 646 |
+
p.add_argument('--release-id', default='v1.0')
|
| 647 |
+
p.add_argument('--limit', type=int, help='Maximum sequences to convert')
|
| 648 |
+
p.add_argument('--max-frames', type=int, help='First N source frame indices per view (recorded as sampling)')
|
| 649 |
+
p.add_argument('--mano-dir', type=Path)
|
| 650 |
+
p.add_argument('--views', help='Comma-separated source camera IDs')
|
| 651 |
+
p.add_argument('--jpeg-full-check', action='store_true', help='Full decoded RGB check for selected JPEG pilot/final views')
|
| 652 |
+
return p
|
| 653 |
+
|
| 654 |
+
|
| 655 |
+
def roots(root):
|
| 656 |
+
root = Path(root).expanduser()
|
| 657 |
+
return [p for p in (root / 'raw/data', root / 'raw', root) if p.is_dir()]
|
| 658 |
+
|
| 659 |
+
|
| 660 |
+
def find_file(root, name):
|
| 661 |
+
return next((p / name for p in roots(root) if (p / name).exists()), None)
|
| 662 |
+
|
| 663 |
+
|
| 664 |
+
def release(args, dataset):
|
| 665 |
+
if not args.release_id or Path(args.release_id).name != args.release_id or args.release_id in ('.', '..'):
|
| 666 |
+
raise ValueError('release-id must be a single directory name')
|
| 667 |
+
if args.limit is not None and args.limit < 1 or args.max_frames is not None and args.max_frames < 1:
|
| 668 |
+
raise ValueError('limits must be positive')
|
| 669 |
+
out = args.out.expanduser().resolve() / dataset / args.release_id
|
| 670 |
+
raw = args.root.expanduser().resolve()
|
| 671 |
+
if out == raw or out.is_relative_to(raw):
|
| 672 |
+
raise ValueError('output must not modify the raw source tree')
|
| 673 |
+
(out / 'data').mkdir(parents=True, exist_ok=True)
|
| 674 |
+
(out / 'doc').mkdir(exist_ok=True)
|
| 675 |
+
(out / 'script').mkdir(exist_ok=True)
|
| 676 |
+
scripts = list(Path(__file__).resolve().parent.glob('*.py'))
|
| 677 |
+
existing = {p.name for p in (out / 'script').glob('*.py')}
|
| 678 |
+
if existing and existing != {p.name for p in scripts}:
|
| 679 |
+
raise ValueError('converter files changed; choose a new --release-id')
|
| 680 |
+
copies = [(SCHEMA_PATH.parent / name, out / 'doc' / name) for name in ('CONTRACT.md', 'schema.json')]
|
| 681 |
+
copies += [(path, out / 'script' / path.name) for path in scripts]
|
| 682 |
+
# Check every existing file before changing any published definition or script.
|
| 683 |
+
for src, dest in copies:
|
| 684 |
+
if dest.exists() and sha256(dest) != sha256(src):
|
| 685 |
+
raise ValueError('converter or contract changed within an existing release; choose a new --release-id')
|
| 686 |
+
for src, dest in copies:
|
| 687 |
+
if src.resolve() != dest.resolve():
|
| 688 |
+
shutil.copyfile(src, dest)
|
| 689 |
+
json_write(out / 'script/config.json', {k: str(v) if isinstance(v, Path) else v for k, v in vars(args).items()})
|
| 690 |
+
return out
|
| 691 |
+
|
| 692 |
+
|
| 693 |
+
@contextmanager
|
| 694 |
+
def sequence_dir(out, sequence):
|
| 695 |
+
if Path(sequence).name != sequence:
|
| 696 |
+
raise ValueError('sequence ID must be a single path component')
|
| 697 |
+
final = out / 'data' / sequence
|
| 698 |
+
with tempfile.TemporaryDirectory(prefix=sequence + '.tmp-', dir=out / 'data') as wd:
|
| 699 |
+
tmp = Path(wd)
|
| 700 |
+
yield tmp
|
| 701 |
+
if final.exists():
|
| 702 |
+
if any((final / child.name).exists() for child in tmp.iterdir()):
|
| 703 |
+
raise FileExistsError('view already published; use a new release-id to preserve it')
|
| 704 |
+
for child in list(tmp.iterdir()):
|
| 705 |
+
child.rename(final / child.name)
|
| 706 |
+
else:
|
| 707 |
+
tmp.rename(final)
|
| 708 |
+
|
| 709 |
+
|
| 710 |
+
def build_record(out, sequence, reports):
|
| 711 |
+
path = out / 'doc' / (sequence + '.build.json')
|
| 712 |
+
previous = json.loads(path.read_text()) if path.exists() else {}
|
| 713 |
+
config = json.loads((out / 'script/config.json').read_text())
|
| 714 |
+
for report in reports.values():
|
| 715 |
+
report['configuration'] = config
|
| 716 |
+
json_write(path, {'sequence_id': sequence, 'storage_revision': SCHEMA['storage_revision'],
|
| 717 |
+
'scripts': {p.name: sha256(p) for p in (out / 'script').glob('*.py')},
|
| 718 |
+
'runtime': {'torch': torch.__version__, 'ffmpeg': ffversion()},
|
| 719 |
+
'views': previous.get('views', {}) | reports})
|
| 720 |
+
|
| 721 |
+
|
| 722 |
+
def check_view_type(meta):
|
| 723 |
+
# The pinned ARCTIC contract makes view_type optional; adapters still supply known views.
|
| 724 |
+
if 'view_type' not in meta:
|
| 725 |
+
return
|
| 726 |
+
if meta['view_type'] not in ('ego', 'exo', 'unknown'):
|
| 727 |
+
raise ValueError('view_type must be ego/exo/unknown')
|
| 728 |
+
expected = {'dex-ycb': 'exo', 'EPIC-KITCHENS-VISOR': 'ego', 'HOI4D': 'ego'}.get(meta['dataset_id'])
|
| 729 |
+
if meta['dataset_id'] == 'H2O':
|
| 730 |
+
expected = 'ego' if meta['camera_id'] == 'cam4' else 'exo' if meta['camera_id'] in ('cam0', 'cam1', 'cam2', 'cam3') else 'unknown'
|
| 731 |
+
if expected and meta['view_type'] not in (expected, 'unknown'):
|
| 732 |
+
raise ValueError('view_type contradicts known source capture setup')
|
| 733 |
+
|
| 734 |
+
|
| 735 |
+
def check_valid_policy(component, count):
|
| 736 |
+
policy = component.get('valid_policy', {})
|
| 737 |
+
for field in ('revision', 'meaning', 'source_rule', 'source_locator', 'scope', 'numerical_checks',
|
| 738 |
+
'official_qa', 'local_excluded_frame_indices', 'local_exclusion_reasons', 'visibility_independent'):
|
| 739 |
+
if field not in policy:
|
| 740 |
+
raise ValueError(f'valid_policy missing {field}')
|
| 741 |
+
if policy['revision'] != SCHEMA['validity_revision'] or policy['meaning'] != SCHEMA['annotation_validity']['meaning']:
|
| 742 |
+
raise ValueError('outdated annotation validity semantics')
|
| 743 |
+
if not policy['source_rule'] or not policy['numerical_checks'] or policy['scope'] != component['valid_axes']:
|
| 744 |
+
raise ValueError('incomplete validity rule/scope')
|
| 745 |
+
if policy['official_qa'].get('status') != 'not_provided' or not policy['official_qa'].get('reason'):
|
| 746 |
+
raise ValueError('official QA requires a verified adapter; supervision acceptance paused')
|
| 747 |
+
excluded = policy['local_excluded_frame_indices']
|
| 748 |
+
if any(type(i) is not int or not 0 <= i < count for i in excluded):
|
| 749 |
+
raise ValueError('invalid local exclusion frame index')
|
| 750 |
+
if excluded:
|
| 751 |
+
raise ValueError('local exclusions require a reviewed rule/report; not supported by these adapters')
|
| 752 |
+
if policy['visibility_independent'] is not True:
|
| 753 |
+
raise ValueError('visibility must remain independent of validity')
|
| 754 |
+
|
| 755 |
+
|
| 756 |
+
def validate_view(path):
|
| 757 |
+
"""Validate the persisted contract, not a rendering of the source labels."""
|
| 758 |
+
path = Path(path)
|
| 759 |
+
meta = json.loads((path / 'metainfo.json').read_text())
|
| 760 |
+
n = meta['num_frames']
|
| 761 |
+
check_view_type(meta)
|
| 762 |
+
if meta['schema_version'] != SCHEMA['schema_version'] or meta['hand_slots'] != ['left', 'right'] or n < 1:
|
| 763 |
+
raise ValueError('invalid view header')
|
| 764 |
+
def resolve(ref):
|
| 765 |
+
if Path(ref).is_absolute() or '\\' in ref:
|
| 766 |
+
raise ValueError('component reference must be relative POSIX')
|
| 767 |
+
dest = safe_member(path, ref)
|
| 768 |
+
if not dest.is_file():
|
| 769 |
+
raise ValueError(f'referenced file missing: {ref}')
|
| 770 |
+
return dest
|
| 771 |
+
def tensor(ref):
|
| 772 |
+
def cpu_storage(storage, location):
|
| 773 |
+
if location != 'cpu':
|
| 774 |
+
raise ValueError('PT storage must be on CPU')
|
| 775 |
+
return storage
|
| 776 |
+
value = torch.load(resolve(ref), map_location=cpu_storage, weights_only=True)
|
| 777 |
+
if not isinstance(value, torch.Tensor) or value.device.type != 'cpu':
|
| 778 |
+
raise ValueError('PT must contain only a CPU Tensor')
|
| 779 |
+
return value.numpy()
|
| 780 |
+
frames = [json.loads(line) for line in resolve(meta['sampling']['frames_ref']).read_text().splitlines()]
|
| 781 |
+
if len(frames) != n or [f['frame_index'] for f in frames] != list(range(n)):
|
| 782 |
+
raise ValueError('frame index/count mismatch')
|
| 783 |
+
for f in frames:
|
| 784 |
+
if not all(k in f for k in ('source_frame_id', 'timestamp_ns', 'clock_domain', 'source_locator')):
|
| 785 |
+
raise ValueError('incomplete frame provenance')
|
| 786 |
+
entities = {'hand_left', 'hand_right'}
|
| 787 |
+
parts = {}
|
| 788 |
+
for p in (path / 'annotation/object').glob('*/metainfo.json'):
|
| 789 |
+
obj = json.loads(p.read_text())
|
| 790 |
+
if obj['object_id'] != p.parent.name or obj['identity_scope'] not in ('frame', 'subsequence', 'sequence'):
|
| 791 |
+
raise ValueError('invalid object identity')
|
| 792 |
+
entities.add(obj['object_id'])
|
| 793 |
+
if obj.get('mesh_ref'):
|
| 794 |
+
if not resolve(obj['mesh_ref']).is_relative_to(p.parent.resolve()):
|
| 795 |
+
raise ValueError('mesh must belong to its object')
|
| 796 |
+
if obj.get('articulation_ref'):
|
| 797 |
+
art = json.loads(resolve(obj['articulation_ref']).read_text())
|
| 798 |
+
part_ids = {part['part_id'] for part in art['parts']}
|
| 799 |
+
if len(part_ids) != len(art['parts']):
|
| 800 |
+
raise ValueError('duplicate part ID')
|
| 801 |
+
parents = {part['part_id']: part['parent_id'] for part in art['parts']}
|
| 802 |
+
for part_id in parents:
|
| 803 |
+
visited, cur = set(), part_id
|
| 804 |
+
while cur is not None:
|
| 805 |
+
if cur in visited or cur not in parents:
|
| 806 |
+
raise ValueError('invalid or cyclic part hierarchy')
|
| 807 |
+
visited.add(cur)
|
| 808 |
+
cur = parents[cur]
|
| 809 |
+
parts[obj['object_id']] = part_ids
|
| 810 |
+
video_stats = {}
|
| 811 |
+
for key, component in meta['components'].items():
|
| 812 |
+
if not component.get('available'):
|
| 813 |
+
if not component.get('reason'):
|
| 814 |
+
raise ValueError('unavailable component needs a reason')
|
| 815 |
+
continue
|
| 816 |
+
schema = SCHEMA['components'][component['schema_id']]
|
| 817 |
+
for required in ('axes', 'provenance', 'source_locator'):
|
| 818 |
+
if required not in component:
|
| 819 |
+
raise ValueError(f'{key}: {required} missing')
|
| 820 |
+
for required in schema.get('required_metadata', []):
|
| 821 |
+
if required not in component:
|
| 822 |
+
raise ValueError(f'{key}: {required} missing')
|
| 823 |
+
if component['provenance']['kind'] == 'derived':
|
| 824 |
+
raise ValueError('v1.0 must not synthesize annotations')
|
| 825 |
+
if component['data_ref'].startswith('annotation/') and schema.get('valid_shape'):
|
| 826 |
+
if not component.get('valid_ref') or not component.get('valid_axes'):
|
| 827 |
+
raise ValueError(f'{key}: annotation validity reference/axes missing')
|
| 828 |
+
check_valid_policy(component, n)
|
| 829 |
+
data_path = resolve(component['data_ref'])
|
| 830 |
+
valid = tensor(component['valid_ref']) if component.get('valid_ref', '').endswith('.pt') else None
|
| 831 |
+
valid_shape = schema.get('valid_shape')
|
| 832 |
+
if valid is not None and valid_shape and (len(valid_shape) != valid.ndim or any(
|
| 833 |
+
isinstance(s, int) and valid.shape[i] != s for i, s in enumerate(valid_shape))):
|
| 834 |
+
raise ValueError(f'{key}: validity schema shape mismatch')
|
| 835 |
+
if valid is not None and (valid.dtype != bool or valid.shape[0] != n):
|
| 836 |
+
raise ValueError(f'{key}: invalid validity tensor')
|
| 837 |
+
if component['schema_id'] == 'mesh/obj/v1':
|
| 838 |
+
objroot = next((parent for parent in data_path.parents if parent.parent.name == 'object'), None)
|
| 839 |
+
if objroot is None:
|
| 840 |
+
raise ValueError('mesh must be owned by an object')
|
| 841 |
+
check_mesh(data_path, objroot)
|
| 842 |
+
if data_path.suffix == '.pt':
|
| 843 |
+
arr = tensor(component['data_ref'])
|
| 844 |
+
if arr.dtype != np.float32 or arr.shape[0] != n:
|
| 845 |
+
raise ValueError(f'{key}: float dtype or timeline mismatch')
|
| 846 |
+
shape = schema.get('shape')
|
| 847 |
+
if shape and (len(shape) != arr.ndim or any(isinstance(s, int) and arr.shape[i] != s for i, s in enumerate(shape))):
|
| 848 |
+
raise ValueError(f'{key}: schema shape mismatch')
|
| 849 |
+
if valid is not None:
|
| 850 |
+
if arr.shape[:valid.ndim] != valid.shape or not np.isfinite(arr[valid]).all() or not np.isnan(arr[~valid]).all():
|
| 851 |
+
raise ValueError(f'{key}: invalid finite/NaN/validity values')
|
| 852 |
+
if component['schema_id'] in ('object/rigid/v1', 'transform/se3/v1'):
|
| 853 |
+
check_transform(arr[valid])
|
| 854 |
+
if data_path.suffix == '.mkv':
|
| 855 |
+
cfg = component['storage']
|
| 856 |
+
if cfg['profile'] not in SCHEMA['storage_profiles']:
|
| 857 |
+
raise ValueError('unregistered video profile')
|
| 858 |
+
for field in SCHEMA['video_metadata']['required']:
|
| 859 |
+
if field not in cfg:
|
| 860 |
+
raise ValueError('video storage declaration incomplete')
|
| 861 |
+
w, h = meta['camera']['image_size']
|
| 862 |
+
if cfg['encoded_size'] != [w * (2 if key == 'depth' else 1), h]:
|
| 863 |
+
raise ValueError('encoded raster differs from logical RGB grid')
|
| 864 |
+
actual = probe(data_path)
|
| 865 |
+
if (actual['codec_name'] != cfg['codec'] or actual['pix_fmt'] != cfg['pixel_format'] or
|
| 866 |
+
[actual['width'], actual['height']] != cfg['encoded_size']):
|
| 867 |
+
raise ValueError('video storage metadata differs from file')
|
| 868 |
+
if key == 'rgb':
|
| 869 |
+
fmt, bpp = 'rgb24', 3
|
| 870 |
+
else:
|
| 871 |
+
fmt, bpp = 'gray16le', 2
|
| 872 |
+
digest, size, _ = decoded_digest(data_path, fmt)
|
| 873 |
+
w, h = cfg['encoded_size']
|
| 874 |
+
if size != n * w * h * bpp:
|
| 875 |
+
raise ValueError('raster timeline mismatch')
|
| 876 |
+
video_stats[key] = {'decoded_sha256': digest, 'frames': n}
|
| 877 |
+
if key == 'depth':
|
| 878 |
+
validity = component['valid_storage']
|
| 879 |
+
vp = resolve(component['valid_ref'])
|
| 880 |
+
actual_valid = probe(vp)
|
| 881 |
+
if (validity['profile'] != 'mkv/bool_ffv1/v1' or actual_valid['codec_name'] != 'ffv1'
|
| 882 |
+
or actual_valid['pix_fmt'] != 'gray' or [actual_valid['width'], actual_valid['height']] != [w // 2, h]):
|
| 883 |
+
raise ValueError('invalid depth validity video')
|
| 884 |
+
count = 0
|
| 885 |
+
for encoded, mask in zip(video_frames(data_path, 'gray16le', (h, w), '<u2'),
|
| 886 |
+
video_frames(vp, 'gray', (h, w // 2), np.uint8), strict=True):
|
| 887 |
+
if not np.isin(mask, [0, 1]).all():
|
| 888 |
+
raise ValueError('depth valid pixels must be 0 or 1')
|
| 889 |
+
depth, good = unpack_depth(encoded), mask.astype(bool)
|
| 890 |
+
if not (np.isfinite(depth[good]) & (depth[good] > 0)).all() or not np.isnan(depth[~good]).all():
|
| 891 |
+
raise ValueError('invalid depth/validity semantics')
|
| 892 |
+
count += 1
|
| 893 |
+
if count != n:
|
| 894 |
+
raise ValueError('depth validity timeline mismatch')
|
| 895 |
+
if component['schema_id'].startswith('segment/') and component.get('mapping_ref'):
|
| 896 |
+
rows = [json.loads(line) for line in resolve(component['mapping_ref']).read_text().splitlines()]
|
| 897 |
+
if len(rows) != n or [row['frame_index'] for row in rows] != list(range(n)):
|
| 898 |
+
raise ValueError('segmentation mapping timeline mismatch')
|
| 899 |
+
for row in rows:
|
| 900 |
+
labels = row['labels']
|
| 901 |
+
if len({a['mask_value'] for a in labels}) != len(labels):
|
| 902 |
+
raise ValueError('duplicate region mapping')
|
| 903 |
+
for label in labels:
|
| 904 |
+
if label['entity_id'] is not None and label['entity_id'] not in entities:
|
| 905 |
+
raise ValueError('unresolved segmentation entity')
|
| 906 |
+
if label['part_id'] is not None and label['part_id'] not in parts.get(label['entity_id'], set()):
|
| 907 |
+
raise ValueError('unresolved segmentation part')
|
| 908 |
+
if component['schema_id'] == 'segment/uint16_labels/v1':
|
| 909 |
+
width, height = meta['camera']['image_size']
|
| 910 |
+
for i, mask in enumerate(video_frames(data_path, 'gray16le', (height, width), '<u2')):
|
| 911 |
+
codes = set(np.unique(mask).tolist()) - {0, 65535}
|
| 912 |
+
mapped = {label['mask_value'] for label in rows[i]['labels']} - {0, 65535}
|
| 913 |
+
if codes != mapped or not valid[i] and codes:
|
| 914 |
+
raise ValueError('mask values differ from declared instances/validity')
|
| 915 |
+
if component['schema_id'] == 'segment/instance_polygons/v1':
|
| 916 |
+
polygons = [json.loads(line) for line in data_path.read_text().splitlines()]
|
| 917 |
+
if len(polygons) != n:
|
| 918 |
+
raise ValueError('polygon timeline mismatch')
|
| 919 |
+
for i, row in enumerate(polygons):
|
| 920 |
+
if row['frame_index'] != i or {x['mask_value'] for x in row['instances']} != {x['mask_value'] for x in rows[i]['labels']}:
|
| 921 |
+
raise ValueError('polygon/mapping mismatch')
|
| 922 |
+
if component['schema_id'] == 'contact/relations/v1':
|
| 923 |
+
rows = [json.loads(line) for line in data_path.read_text().splitlines()]
|
| 924 |
+
if len(rows) != n:
|
| 925 |
+
raise ValueError('relation timeline mismatch')
|
| 926 |
+
for i, row in enumerate(rows):
|
| 927 |
+
if row['frame_index'] != i or not valid[i] and row['relations']:
|
| 928 |
+
raise ValueError('relation validity mismatch')
|
| 929 |
+
for relation in row['relations']:
|
| 930 |
+
if relation['subject_id'] not in entities or relation['status'] not in ('positive', 'negative', 'unknown', 'target_unannotated'):
|
| 931 |
+
raise ValueError('invalid relation')
|
| 932 |
+
if relation['status'] == 'positive' and relation['object_id'] not in entities:
|
| 933 |
+
raise ValueError('unresolved positive contact')
|
| 934 |
+
return {'view': str(path), 'num_frames': n, 'videos': video_stats, 'validated': True}
|
H2O/shared-v1.1/script/v1_0_snapshot/script/render_dexycb_validation.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Audit a finished Dex-YCB release and render persisted modalities for manual review."""
|
| 3 |
+
from collections import Counter
|
| 4 |
+
import hashlib
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import sys
|
| 8 |
+
|
| 9 |
+
from render_hoi4d_validation import render
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def inspect(root):
|
| 13 |
+
data, doc, scripts = root / 'data', root / 'doc', root / 'script'
|
| 14 |
+
sequences = sorted(p for p in data.iterdir() if p.is_dir())
|
| 15 |
+
assert len(sequences) == 1000, f'expected 1000 sequences, got {len(sequences)}'
|
| 16 |
+
assert len(list(doc.glob('*.build.json'))) == 1000
|
| 17 |
+
assert not list(data.glob('*.tmp-*')), 'unfinished temporary sequences'
|
| 18 |
+
config = json.loads((scripts / 'config.json').read_text())
|
| 19 |
+
assert all(config.get(k) is None for k in ('limit', 'max_frames', 'subjects', 'views'))
|
| 20 |
+
hashes = {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in scripts.glob('*.py')}
|
| 21 |
+
subjects, splits, availability = Counter(), Counter(), Counter()
|
| 22 |
+
selected = []
|
| 23 |
+
for seq in sequences:
|
| 24 |
+
views = sorted(p for p in seq.iterdir() if p.is_dir())
|
| 25 |
+
assert len(views) == 8, (seq, len(views))
|
| 26 |
+
build = json.loads((doc / (seq.name + '.build.json')).read_text())
|
| 27 |
+
assert set(build['views']) == {p.name for p in views}, seq
|
| 28 |
+
assert all(hashes.get(k) == v for k, v in build['scripts'].items()), seq
|
| 29 |
+
subject = seq.name.split('_')[0]
|
| 30 |
+
subjects[subject] += 1
|
| 31 |
+
if subjects[subject] == 1:
|
| 32 |
+
selected.append(views[0])
|
| 33 |
+
if subject.endswith('subject-09'):
|
| 34 |
+
selected.append(views[-1]) # one more camera, different camera
|
| 35 |
+
if seq.name == '20201015-subject-09_20201015_150838':
|
| 36 |
+
selected.append(views[0]) # source-labelled left-hand sequence
|
| 37 |
+
for view in views:
|
| 38 |
+
meta = json.loads((view / 'metainfo.json').read_text())
|
| 39 |
+
assert meta['sequence_id'] == seq.name and meta['camera_id'] == view.name, view
|
| 40 |
+
assert meta['dataset_id'] == 'dex-ycb' and meta['release_id'] == 'shared-v1.0', view
|
| 41 |
+
assert meta['num_frames'] > 0 and meta.get('view_type') == 'exo', view
|
| 42 |
+
assert (view / 'camera/frames.jsonl').is_file(), view
|
| 43 |
+
assert meta['components']['rgb']['available'], view
|
| 44 |
+
splits[meta['split']] += 1
|
| 45 |
+
for key, part in meta['components'].items():
|
| 46 |
+
if part.get('available'):
|
| 47 |
+
availability[key] += 1
|
| 48 |
+
for ref in ('data_ref', 'valid_ref'):
|
| 49 |
+
if part.get(ref):
|
| 50 |
+
assert (view / part[ref]).is_file(), (view, key, ref)
|
| 51 |
+
assert len(subjects) == 10 and set(subjects.values()) == {100}, subjects
|
| 52 |
+
assert availability['depth'] == availability['rgb'] == 8000, availability
|
| 53 |
+
report = dict(sequences=len(sequences), views=sum(splits.values()), subjects=dict(subjects),
|
| 54 |
+
splits=dict(splits), available_views=dict(availability), config=config,
|
| 55 |
+
published_script_sha256=hashes, sampled_views=[str(v.relative_to(root)) for v in selected],
|
| 56 |
+
scope='Structure and file refs checked for all views; persisted QC and HTML only for sampled views. No manual visual approval yet.')
|
| 57 |
+
destination = doc / 'validation'
|
| 58 |
+
destination.mkdir(exist_ok=True)
|
| 59 |
+
(destination / 'STRUCTURAL_AUDIT.json').write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n')
|
| 60 |
+
for view in selected:
|
| 61 |
+
render(view, destination)
|
| 62 |
+
return report
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
if __name__ == '__main__':
|
| 66 |
+
print(json.dumps(inspect(Path(sys.argv[1]).expanduser().resolve()), ensure_ascii=False), flush=True)
|
H2O/shared-v1.1/script/v1_0_snapshot/script/render_h2o_validation.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Render stored H2O RGB-D, native camera-space hands/objects, and OBJ assets for review."""
|
| 3 |
+
import argparse
|
| 4 |
+
import html
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
from PIL import Image, ImageDraw
|
| 10 |
+
import torch
|
| 11 |
+
|
| 12 |
+
from render_hoi4d_validation import mesh_preview, picture, snapshot
|
| 13 |
+
from warehouse_v1_0 import unpack_depth, validate_view
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def load(view, item, n):
|
| 17 |
+
if not item.get('available') or not item.get('data_ref', '').endswith('.pt'):
|
| 18 |
+
return None, None
|
| 19 |
+
values = torch.load(view / item['data_ref'], map_location='cpu', weights_only=True).numpy()
|
| 20 |
+
valid = torch.load(view / item['valid_ref'], map_location='cpu', weights_only=True).numpy() if item.get('valid_ref') else None
|
| 21 |
+
return (values, valid) if values.ndim and values.shape[0] == n else (None, None)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def render(view, destination):
|
| 25 |
+
meta = json.loads((view / 'metainfo.json').read_text())
|
| 26 |
+
if meta['dataset_id'] != 'H2O':
|
| 27 |
+
raise ValueError('H2O view required')
|
| 28 |
+
n = meta['num_frames']
|
| 29 |
+
height, width = reversed(meta['camera']['image_size'])
|
| 30 |
+
parts = meta['components']
|
| 31 |
+
frames = [json.loads(line) for line in (view / 'camera/frames.jsonl').read_text().splitlines()]
|
| 32 |
+
assert len(frames) == n
|
| 33 |
+
selected = {0, n // 4, n // 2, 3 * n // 4, n - 1}
|
| 34 |
+
numeric = {}
|
| 35 |
+
for name, item in parts.items():
|
| 36 |
+
if item.get('data_ref', '').endswith('.pt') and item.get('available'):
|
| 37 |
+
values, valid = load(view, item, n)
|
| 38 |
+
if values is not None:
|
| 39 |
+
numeric[name] = (values, valid)
|
| 40 |
+
if valid is not None:
|
| 41 |
+
indices = np.flatnonzero(valid.reshape(n, -1).any(axis=1))
|
| 42 |
+
if len(indices):
|
| 43 |
+
selected.add(int(indices[0]))
|
| 44 |
+
selected = set(sorted(selected)[:12]) | {n - 1}
|
| 45 |
+
rgb = snapshot(view / parts['rgb']['data_ref'], 'rgb24', (height, width, 3), np.uint8, selected)
|
| 46 |
+
depth = snapshot(view / parts['depth']['data_ref'], 'gray16le', (height, 2 * width), '<u2', selected) if parts.get('depth', {}).get('available') else {}
|
| 47 |
+
intrinsic = numeric.get('intrinsic', (None, None))[0]
|
| 48 |
+
pages = []
|
| 49 |
+
for i in sorted(selected):
|
| 50 |
+
photo = Image.fromarray(rgb[i])
|
| 51 |
+
legend = []
|
| 52 |
+
if intrinsic is not None:
|
| 53 |
+
draw = ImageDraw.Draw(photo)
|
| 54 |
+
for name, (points, valid) in numeric.items():
|
| 55 |
+
if name != 'keypoints_xyz' and not name.startswith('points_'):
|
| 56 |
+
continue
|
| 57 |
+
color = '#00e6ff' if name == 'keypoints_xyz' else '#ff48a4'
|
| 58 |
+
for slot, row in enumerate(points[i] if points.ndim == 4 else [points[i]]):
|
| 59 |
+
mask = valid[i, slot] if points.ndim == 4 else valid[i]
|
| 60 |
+
for xyz, good in zip(row, mask, strict=True):
|
| 61 |
+
if good and np.isfinite(xyz).all() and xyz[2] > 0:
|
| 62 |
+
u, v = intrinsic[i, 0, 0] * xyz[0] / xyz[2] + intrinsic[i, 0, 2], intrinsic[i, 1, 1] * xyz[1] / xyz[2] + intrinsic[i, 1, 2]
|
| 63 |
+
if 0 <= u < width and 0 <= v < height:
|
| 64 |
+
draw.ellipse((u-4, v-4, u+4, v+4), fill=color)
|
| 65 |
+
legend.append(name + ' ' + color)
|
| 66 |
+
panels = ['<figure>' + picture(photo) + '<figcaption>RGB + 原生 3D 关键点投影(仅预览:' + html.escape(', '.join(legend) or '当前帧无可投影点') + ')</figcaption></figure>']
|
| 67 |
+
if i in depth:
|
| 68 |
+
z = unpack_depth(depth[i])
|
| 69 |
+
luminance = (np.clip(np.nan_to_num(z, nan=0), 0, 3) * 85).astype(np.uint8)
|
| 70 |
+
panels.append('<figure>' + picture(Image.fromarray(luminance)) + '<figcaption>深度 Z,黑=无效,白≥3 m;不改源深度</figcaption></figure>')
|
| 71 |
+
details = {'frame': frames[i]}
|
| 72 |
+
for name, (values, valid) in numeric.items():
|
| 73 |
+
details[name] = {'value': values[i].tolist(), 'valid': None if valid is None else valid[i].tolist()}
|
| 74 |
+
pages.append('<section><h2>帧 ' + str(i) + ' / ' + str(n) + '</h2><div class="panels">' + ''.join(panels) + '</div><details><summary>原帧号、全部数值标注及有效性</summary><pre>' + html.escape(json.dumps(details, ensure_ascii=False, indent=2)) + '</pre></details></section>')
|
| 75 |
+
assets = []
|
| 76 |
+
for name, item in parts.items():
|
| 77 |
+
if item.get('available') and item.get('data_ref', '').lower().endswith('.obj'):
|
| 78 |
+
assets.append('<figure><h3>' + html.escape(name) + '</h3>' + mesh_preview(view / item['data_ref']) + '<figcaption>源 OBJ 静态预览,不代表物体姿态投影</figcaption></figure>')
|
| 79 |
+
report = validate_view(view)
|
| 80 |
+
destination.mkdir(parents=True, exist_ok=True)
|
| 81 |
+
title = view.parent.name + '_' + view.name
|
| 82 |
+
style = 'body{font:16px sans-serif;max-width:1500px;margin:auto;padding:1rem;background:#f5f7fa;color:#18232f}section,details{background:white;padding:1rem;margin:1rem 0;border-radius:8px}.panels{display:flex;flex-wrap:wrap}img{max-width:100%}pre{white-space:pre-wrap;overflow:auto;font-size:12px}'
|
| 83 |
+
page = '<!doctype html><html lang="zh"><meta charset="utf-8"><title>' + html.escape(title) + '</title><style>' + style + '</style><h1>' + html.escape(title) + '</h1><p>预览只作人工核查;仅显示真实存在的标注,不合成分割。</p>' + ''.join(pages) + '<h2>源网格</h2><div class="panels">' + ''.join(assets) + '</div><details><summary>全部组件元数据</summary><pre>' + html.escape(json.dumps(meta, ensure_ascii=False, indent=2)) + '</pre></details><details><summary>持久化 QC</summary><pre>' + html.escape(json.dumps(report, ensure_ascii=False, indent=2)) + '</pre></details></html>'
|
| 84 |
+
(destination / (title + '.html')).write_text(page)
|
| 85 |
+
(destination / (title + '.report.json')).write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n')
|
| 86 |
+
links = sorted(p.name for p in destination.glob('*.html') if p.name != 'index.html')
|
| 87 |
+
(destination / 'index.html').write_text('<!doctype html><html lang="zh"><meta charset="utf-8"><h1>H2O 试点预览</h1><ul>' + ''.join('<li><a href="' + html.escape(x, quote=True) + '">' + html.escape(x) + '</a></li>' for x in links) + '</ul></html>')
|
| 88 |
+
return destination / (title + '.html')
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
if __name__ == '__main__':
|
| 92 |
+
p = argparse.ArgumentParser()
|
| 93 |
+
p.add_argument('views', nargs='+', type=Path)
|
| 94 |
+
p.add_argument('--out', type=Path, required=True)
|
| 95 |
+
args = p.parse_args()
|
| 96 |
+
for view in args.views:
|
| 97 |
+
print(render(view, args.out), flush=True)
|
H2O/shared-v1.1/script/v1_0_snapshot/script/render_hoi4d_source_review.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Evidence-only HTML: native HOI4D pose boxes over persisted RGB and native masks."""
|
| 3 |
+
import argparse
|
| 4 |
+
import html
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import shutil
|
| 8 |
+
import zipfile
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
from PIL import Image, ImageDraw
|
| 12 |
+
|
| 13 |
+
from render_hoi4d_validation import picture, snapshot
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def source_parts(view):
|
| 17 |
+
rows = []
|
| 18 |
+
for source in view.glob('annotation/object/*/assets/result.json'):
|
| 19 |
+
def visit(node):
|
| 20 |
+
if isinstance(node, list):
|
| 21 |
+
for child in node:
|
| 22 |
+
visit(child)
|
| 23 |
+
return
|
| 24 |
+
if node.get('objs'):
|
| 25 |
+
rows.append({'source_part_id': node['id'], 'source_part_name': node['name'],
|
| 26 |
+
'source_meshes': node['objs'], 'source_locator': str(source.relative_to(view))})
|
| 27 |
+
for child in node.get('children', []):
|
| 28 |
+
visit(child)
|
| 29 |
+
visit(json.loads(source.read_text()))
|
| 30 |
+
return rows
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def render(view, z, output):
|
| 34 |
+
output.mkdir(parents=True, exist_ok=True)
|
| 35 |
+
meta = json.loads((view / 'metainfo.json').read_text())
|
| 36 |
+
seq = meta['sampling']['selection']['source_sequence']
|
| 37 |
+
w, h = meta['camera']['image_size']
|
| 38 |
+
chosen = sorted({0, meta['num_frames'] // 2, meta['num_frames'] - 1})
|
| 39 |
+
frames = [json.loads(line) for line in (view / 'camera/frames.jsonl').read_text().splitlines()]
|
| 40 |
+
rgb = snapshot(view / meta['components']['rgb']['data_ref'], 'rgb24', (h, w, 3), np.uint8, chosen)
|
| 41 |
+
segment = meta['components'].get('segment', {})
|
| 42 |
+
masks = (snapshot(view / segment['data_ref'], 'gray16le', (h, w), '<u2', chosen)
|
| 43 |
+
if segment.get('available') else {})
|
| 44 |
+
rows = [json.loads(line) for line in (view / 'annotation/segment/instances.jsonl').read_text().splitlines()]
|
| 45 |
+
source = f'HOI4D_annotations/{seq}/objpose/'
|
| 46 |
+
pose_files = {int(Path(name).stem): name for name in z.namelist()
|
| 47 |
+
if name.startswith(source) and name.endswith('.json')}
|
| 48 |
+
panels = []
|
| 49 |
+
for index in chosen:
|
| 50 |
+
native_id = frames[index]['source_frame_id']
|
| 51 |
+
arr = rgb[index].copy()
|
| 52 |
+
mask = masks.get(index)
|
| 53 |
+
if mask is not None:
|
| 54 |
+
tint = np.zeros_like(arr)
|
| 55 |
+
for code in np.unique(mask):
|
| 56 |
+
if code not in (0, 65535):
|
| 57 |
+
tint[mask == code] = ((int(code) * 89) % 240 + 15,
|
| 58 |
+
(int(code) * 61) % 240 + 15, (int(code) * 131) % 240 + 15)
|
| 59 |
+
affected = (mask != 0) & (mask != 65535)
|
| 60 |
+
arr[affected] = ((arr[affected].astype(np.uint16) * 3 + tint[affected]) // 4).astype(np.uint8)
|
| 61 |
+
image = Image.fromarray(arr)
|
| 62 |
+
draw = ImageDraw.Draw(image)
|
| 63 |
+
native = json.loads(z.read(pose_files[native_id])) if native_id in pose_files else {}
|
| 64 |
+
for source_index, record in enumerate(native.get('dataList', native.get('objects', []))):
|
| 65 |
+
box = record.get('2dBox', {}).get('camera1') or []
|
| 66 |
+
if len(box) == 2 and all(len(point) == 2 for point in box):
|
| 67 |
+
x0, y0 = box[0]
|
| 68 |
+
x1, y1 = box[1]
|
| 69 |
+
draw.rectangle((x0, y0, x1, y1), outline='#ffff00', width=4)
|
| 70 |
+
draw.text((x0, max(0, y0 - 16)), f"source[{source_index}] id={record.get('id')} {record.get('label')}", fill='#ffff00', stroke_width=2, stroke_fill='#000000')
|
| 71 |
+
mask_row = rows[index]['labels'] if segment.get('available') else []
|
| 72 |
+
note = {'source_frame_id': native_id, 'native_pose_records': [
|
| 73 |
+
{k: r.get(k) for k in ('id', 'label', '2dBox')} for r in native.get('dataList', native.get('objects', []))],
|
| 74 |
+
'native_mask_codes': mask_row}
|
| 75 |
+
panels.append('<section><h2>' + html.escape(seq) + f' / frame {native_id}</h2>' + picture(image)
|
| 76 |
+
+ '<p>仅验收:伪彩=原生分割码,黄框=上游 2dBox;颜色和框不写回 shared,空间重叠不能代替身份依据。</p>'
|
| 77 |
+
+ '<details><summary>上游原记录与编码对照</summary><pre>'
|
| 78 |
+
+ html.escape(json.dumps(note, ensure_ascii=False, indent=2)) + '</pre></details></section>')
|
| 79 |
+
parts = source_parts(view)
|
| 80 |
+
name = view.parent.name + '_' + view.name + '.html'
|
| 81 |
+
page = '<!doctype html><html lang="zh"><meta charset="utf-8"><title>HOI4D source correspondence review</title><style>body{font:16px sans-serif;max-width:1100px;margin:auto;background:#f6f7fa}section{background:white;padding:1em;margin:1em}img{max-width:100%}pre{white-space:pre-wrap;overflow:auto}</style><h1>源姿态/原生分割/RGB 的证据图(非真值修改)</h1>'
|
| 82 |
+
page += ''.join(panels) + '<details><summary>CAD result.json 原生部件→OBJ;不等同逐帧姿态对应</summary><pre>'
|
| 83 |
+
page += html.escape(json.dumps(parts, ensure_ascii=False, indent=2)) + '</pre></details></html>'
|
| 84 |
+
(output / name).write_text(page)
|
| 85 |
+
print(name, 'native_part_links',len(parts),flush=True)
|
| 86 |
+
return name
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def main(argv=None):
|
| 90 |
+
p = argparse.ArgumentParser(description=__doc__)
|
| 91 |
+
p.add_argument('--raw-root', type=Path, required=True)
|
| 92 |
+
p.add_argument('--release', type=Path, required=True)
|
| 93 |
+
p.add_argument('--out', type=Path, required=True)
|
| 94 |
+
args = p.parse_args(argv)
|
| 95 |
+
args.out.mkdir(parents=True, exist_ok=True)
|
| 96 |
+
with zipfile.ZipFile(args.raw_root / 'HOI4D_annotations.zip') as z:
|
| 97 |
+
names = []
|
| 98 |
+
for view in sorted((args.release / 'data').glob('*/ego')):
|
| 99 |
+
if any('/C' + category + '/' in json.loads((view / 'metainfo.json').read_text())['sampling']['selection']['source_sequence']
|
| 100 |
+
for category in ('2', '3', '14', '17')):
|
| 101 |
+
names.append(render(view, z, args.out))
|
| 102 |
+
links = ''.join(f'<li><a href="{html.escape(name, quote=True)}">{html.escape(name)}</a></li>' for name in names)
|
| 103 |
+
(args.out / 'index.html').write_text('<!doctype html><html lang="zh"><meta charset="utf-8"><h1>源依据对照(非物体几何验收通过)</h1><ul>' + links + '</ul></html>')
|
| 104 |
+
shutil.copyfile(Path(__file__), args.out / 'renderer.py')
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
if __name__ == '__main__':
|
| 108 |
+
main()
|
H2O/shared-v1.1/script/v1_0_snapshot/script/render_hoi4d_validation.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Standalone, offline HTML review of every persisted component in selected views."""
|
| 3 |
+
import argparse
|
| 4 |
+
import base64
|
| 5 |
+
import html
|
| 6 |
+
import io
|
| 7 |
+
import json
|
| 8 |
+
import random
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
from PIL import Image, ImageDraw
|
| 13 |
+
import torch
|
| 14 |
+
|
| 15 |
+
from warehouse_v1_0 import video_frames, unpack_depth, validate_view
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def snapshot(video, fmt, shape, dtype, indices):
|
| 19 |
+
return {i: frame.copy() for i, frame in enumerate(video_frames(video, fmt, shape, dtype)) if i in indices}
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def picture(image):
|
| 23 |
+
image.thumbnail((800, 450)) # Previews only; released tensors and videos are not resized.
|
| 24 |
+
output = io.BytesIO()
|
| 25 |
+
image.save(output, format='PNG')
|
| 26 |
+
return '<img loading="lazy" src="data:image/png;base64,' + base64.b64encode(output.getvalue()).decode() + '">'
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def preview_color(value, dataset_id):
|
| 30 |
+
# Dex-YCB reserves 255 for the native hand mask. The old mod-240 palette
|
| 31 |
+
# gave it the same color as YCB object 15; keep data codes untouched.
|
| 32 |
+
if dataset_id == 'dex-ycb' and value == 255:
|
| 33 |
+
return (255, 32, 64)
|
| 34 |
+
return tuple((value * factor) % 240 + 15 for factor in (89, 61, 131))
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def mesh_preview(path):
|
| 38 |
+
"""Project the whole source asset; bound drawing cost without favoring early faces."""
|
| 39 |
+
vertices, faces, referenced = [], [], set()
|
| 40 |
+
rng = random.Random(0)
|
| 41 |
+
face_count = 0
|
| 42 |
+
with path.open(errors='replace') as stream:
|
| 43 |
+
for line in stream:
|
| 44 |
+
if line.startswith('v '):
|
| 45 |
+
vertices.append([float(v) for v in line.split()[1:4]])
|
| 46 |
+
elif line.startswith('f '):
|
| 47 |
+
face = []
|
| 48 |
+
for token in line.split()[1:]:
|
| 49 |
+
index = int(token.split('/')[0])
|
| 50 |
+
face.append(index - 1 if index > 0 else len(vertices) + index)
|
| 51 |
+
if len(face) < 3:
|
| 52 |
+
continue
|
| 53 |
+
referenced.update(face)
|
| 54 |
+
face_count += 1
|
| 55 |
+
# ponytail: bounded static preview; use a full OBJ viewer if 5000 faces miss fine detail.
|
| 56 |
+
if len(faces) < 5000:
|
| 57 |
+
faces.append(face)
|
| 58 |
+
else:
|
| 59 |
+
pick = rng.randrange(face_count)
|
| 60 |
+
if pick < len(faces):
|
| 61 |
+
faces[pick] = face
|
| 62 |
+
if not vertices or not faces:
|
| 63 |
+
return 'OBJ 未提供可绘制的顶点/面'
|
| 64 |
+
if min(referenced) < 0 or max(referenced) >= len(vertices):
|
| 65 |
+
raise ValueError(f'invalid OBJ face index: {path}')
|
| 66 |
+
xyz = np.asarray(vertices, dtype=np.float64)
|
| 67 |
+
if not np.isfinite(xyz).all():
|
| 68 |
+
raise ValueError(f'nonfinite OBJ vertex: {path}')
|
| 69 |
+
# Fixed orthonormal isometric basis: geometry only, not an inferred camera pose.
|
| 70 |
+
projected = np.column_stack(((xyz[:, 0] - xyz[:, 2]) / np.sqrt(2),
|
| 71 |
+
(xyz[:, 0] + xyz[:, 2] - 2 * xyz[:, 1]) / np.sqrt(6)))
|
| 72 |
+
used = projected[np.fromiter(referenced, dtype=np.int64)]
|
| 73 |
+
lo, hi = used.min(axis=0), used.max(axis=0)
|
| 74 |
+
extent = (hi - lo).max()
|
| 75 |
+
if extent <= 0:
|
| 76 |
+
return 'OBJ 所有面投影到同一点'
|
| 77 |
+
projected = (projected - (lo + hi) / 2) * (380 / extent) + 215
|
| 78 |
+
image = Image.new('RGB', (430, 430), 'white')
|
| 79 |
+
draw = ImageDraw.Draw(image)
|
| 80 |
+
for face in faces:
|
| 81 |
+
polygon = [tuple(projected[i]) for i in face]
|
| 82 |
+
draw.line(polygon + [polygon[0]], fill='#205caa', width=1)
|
| 83 |
+
return picture(image)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def render(view, destination):
|
| 87 |
+
meta = json.loads((view / 'metainfo.json').read_text())
|
| 88 |
+
n = meta['num_frames']
|
| 89 |
+
width, height = meta['camera']['image_size']
|
| 90 |
+
components = meta['components']
|
| 91 |
+
frames = [json.loads(line) for line in (view / 'camera/frames.jsonl').read_text().splitlines()]
|
| 92 |
+
assert len(frames) == n
|
| 93 |
+
selected = {0, n // 4, n // 2, 3 * n // 4, n - 1}
|
| 94 |
+
for item in components.values():
|
| 95 |
+
ref = item.get('valid_ref', '')
|
| 96 |
+
if ref.endswith('.pt'):
|
| 97 |
+
valid = torch.load(view / ref, map_location='cpu', weights_only=True).numpy()
|
| 98 |
+
if valid.shape[0] == n:
|
| 99 |
+
matching = np.flatnonzero(valid.reshape(n, -1).any(axis=1))
|
| 100 |
+
if len(matching):
|
| 101 |
+
selected.add(int(matching[0]))
|
| 102 |
+
selected = set(sorted(selected)[:12]) | {n - 1}
|
| 103 |
+
rgb = snapshot(view / components['rgb']['data_ref'], 'rgb24', (height, width, 3), np.uint8, selected)
|
| 104 |
+
depth = (snapshot(view / components['depth']['data_ref'], 'gray16le', (height, 2 * width), '<u2', selected)
|
| 105 |
+
if components.get('depth', {}).get('available') else {})
|
| 106 |
+
masks = (snapshot(view / components['segment']['data_ref'], 'gray16le', (height, width), '<u2', selected)
|
| 107 |
+
if components.get('segment', {}).get('available') else {})
|
| 108 |
+
labels = {}
|
| 109 |
+
mapping = view / 'annotation/segment/instances.jsonl'
|
| 110 |
+
if mapping.exists():
|
| 111 |
+
labels = {row['frame_index']: row['labels'] for row in map(json.loads, mapping.read_text().splitlines()) if row['frame_index'] in selected}
|
| 112 |
+
uv = components.get('keypoints_uv', {})
|
| 113 |
+
uv_points = torch.load(view / uv['data_ref'], map_location='cpu', weights_only=True).numpy() if uv.get('available') else None
|
| 114 |
+
uv_valid = torch.load(view / uv['valid_ref'], map_location='cpu', weights_only=True).numpy() if uv.get('available') else None
|
| 115 |
+
sections = []
|
| 116 |
+
for i in sorted(selected):
|
| 117 |
+
image = Image.fromarray(rgb[i])
|
| 118 |
+
if uv_points is not None:
|
| 119 |
+
draw = ImageDraw.Draw(image)
|
| 120 |
+
for slot, color in enumerate(('#00ffff', '#ff9922')):
|
| 121 |
+
for (x, y), valid in zip(uv_points[i, slot], uv_valid[i, slot], strict=True):
|
| 122 |
+
if valid and np.isfinite([x, y]).all():
|
| 123 |
+
draw.ellipse((x - 3, y - 3, x + 3, y + 3), fill=color)
|
| 124 |
+
panels = ['<figure>' + picture(image) + '<figcaption>RGB + 原生 2D 手关键点(若有)</figcaption></figure>']
|
| 125 |
+
if i in depth:
|
| 126 |
+
z = unpack_depth(depth[i])
|
| 127 |
+
luminance = (np.clip(np.nan_to_num(z, nan=0), 0, 3) * 85).astype(np.uint8)
|
| 128 |
+
panels.append('<figure>' + picture(Image.fromarray(luminance)) + '<figcaption>深度 Z(黑=无效,白≥3 m;仅预览)</figcaption></figure>')
|
| 129 |
+
if i in masks:
|
| 130 |
+
mask = masks[i]
|
| 131 |
+
colors = np.zeros((*mask.shape, 3), dtype=np.uint8)
|
| 132 |
+
for value in np.unique(mask):
|
| 133 |
+
if value not in (0, 65535):
|
| 134 |
+
colors[mask == value] = preview_color(int(value), meta['dataset_id'])
|
| 135 |
+
legend = ';'.join(f'{int(value)}=' + ('手' if value == 255 and meta['dataset_id'] == 'dex-ycb' else '物体' if meta['dataset_id'] == 'dex-ycb' else '区域') + f' #{bytes(preview_color(int(value), meta["dataset_id"])).hex()}' for value in np.unique(mask) if value not in (0, 65535))
|
| 136 |
+
panels.append('<figure>' + picture(Image.fromarray(colors)) + '<figcaption>原生分割整数编码的伪彩色预览(' + html.escape(legend) + ')</figcaption></figure>')
|
| 137 |
+
active = (mask != 0) & (mask != 65535)
|
| 138 |
+
overlay = rgb[i].copy()
|
| 139 |
+
overlay[active] = ((overlay[active].astype(np.uint16) + colors[active]) // 2).astype(np.uint8)
|
| 140 |
+
panels.append('<figure>' + picture(Image.fromarray(overlay)) + '<figcaption>原生分割叠加 RGB(仅预览)</figcaption></figure>')
|
| 141 |
+
details = {'frame': frames[i], 'segment_labels': labels.get(i, [])}
|
| 142 |
+
for name, component in components.items():
|
| 143 |
+
ref = component.get('data_ref', '')
|
| 144 |
+
if component.get('available') and ref.endswith('.pt'):
|
| 145 |
+
values = torch.load(view / ref, map_location='cpu', weights_only=True)
|
| 146 |
+
if values.ndim and values.shape[0] == n:
|
| 147 |
+
details[name] = {'value': values[i].tolist()}
|
| 148 |
+
if component.get('valid_ref', '').endswith('.pt'):
|
| 149 |
+
valid = torch.load(view / component['valid_ref'], map_location='cpu', weights_only=True)
|
| 150 |
+
details[name]['valid'] = valid[i].tolist()
|
| 151 |
+
sections.append('<section><h2>帧 ' + str(i) + ' / ' + str(n) + '</h2><div class="panels">' + ''.join(panels)
|
| 152 |
+
+ '</div><details><summary>帧号、来源、全部数值组件与有效性</summary><pre>'
|
| 153 |
+
+ html.escape(json.dumps(details, ensure_ascii=False, indent=2)) + '</pre></details></section>')
|
| 154 |
+
assets = []
|
| 155 |
+
for name, component in components.items():
|
| 156 |
+
if component.get('available') and component['data_ref'].lower().endswith('.obj'):
|
| 157 |
+
ref = component['data_ref']
|
| 158 |
+
assets.append('<figure><h3>' + html.escape(name) + '</h3>' + mesh_preview(view / ref)
|
| 159 |
+
+ '<figcaption>仅展示网格原生形状;未验证尺度/位姿对应。</figcaption></figure>')
|
| 160 |
+
result = validate_view(view)
|
| 161 |
+
destination.mkdir(parents=True, exist_ok=True)
|
| 162 |
+
title = view.parent.name + '_' + view.name
|
| 163 |
+
css = 'body{font:16px sans-serif;max-width:1500px;margin:auto;padding:1rem;background:#f5f7fa;color:#18232f}section,details{background:#fff;padding:1rem;margin:1rem 0;border-radius:8px}figure{margin:.5rem}figcaption{font-size:.85rem}.panels{display:flex;flex-wrap:wrap}img{max-width:100%;border:1px solid #ddd}pre{white-space:pre-wrap;overflow:auto;font-size:12px}'
|
| 164 |
+
page = '<!doctype html><html lang="zh"><meta charset="utf-8"><title>' + html.escape(title) + '</title><style>' + css + '</style><h1>' + html.escape(title) + '</h1><p>预览图仅供人工审核,不是训练输入;未提供的模态在 metainfo 中保留原因。</p>' + ''.join(sections) + '<h2>原始物体模型(独立预览)</h2><div class="panels">' + ''.join(assets) + '</div><details><summary>全部组件元信息及原始来源</summary><pre>' + html.escape(json.dumps(meta, ensure_ascii=False, indent=2)) + '</pre></details><details><summary>持久化 QC 结果</summary><pre>' + html.escape(json.dumps(result, ensure_ascii=False, indent=2)) + '</pre></details></html>'
|
| 165 |
+
(destination / (title + '.html')).write_text(page)
|
| 166 |
+
(destination / (title + '.report.json')).write_text(json.dumps(result, ensure_ascii=False, indent=2))
|
| 167 |
+
links = sorted(p.name for p in destination.glob('*.html') if p.name != 'index.html')
|
| 168 |
+
(destination / 'index.html').write_text('<!doctype html><html lang="zh"><meta charset="utf-8"><title>' + html.escape(meta['dataset_id']) + ' review</title><h1>' + html.escape(meta['dataset_id']) + ' 抽样人工审核</h1><p>选择视图;所有预览均来自已保存的 shared 数据。</p><ul>' + ''.join('<li><a href="' + html.escape(x, quote=True) + '">' + html.escape(x) + '</a></li>' for x in links) + '</ul></html>')
|
| 169 |
+
print(destination / (title + '.html'), 'selected_frames', sorted(selected), flush=True)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def main():
|
| 173 |
+
p = argparse.ArgumentParser(description=__doc__)
|
| 174 |
+
p.add_argument('views', nargs='+', type=Path)
|
| 175 |
+
p.add_argument('--out', type=Path)
|
| 176 |
+
args = p.parse_args()
|
| 177 |
+
for view in args.views:
|
| 178 |
+
render(view, args.out or view.parents[2] / 'doc/validation')
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
if __name__ == '__main__':
|
| 182 |
+
main()
|
H2O/shared-v1.1/script/v1_0_snapshot/script/run-full.sh
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -u
|
| 3 |
+
base="$HOME/Datasets/uni-hoi-h2o-full-20260930-process16-pipe"
|
| 4 |
+
raw="$HOME/Datasets/Hand-Datasets-Raw/H2O"
|
| 5 |
+
ram=/dev/shm/xuzhefeng-h2o-full-process16-20260930
|
| 6 |
+
cd "$HOME/Projects/uni-hoi-dataset" || exit 1
|
| 7 |
+
mkdir -p "$base/scratch" "$ram"
|
| 8 |
+
export TMPDIR="$base/scratch" PYTHONUNBUFFERED=1
|
| 9 |
+
test ! -e "$base/full.status" || exit 2
|
| 10 |
+
printf 'START=%s\nARCHIVE_WORKERS=4 VIEW_WORKERS=16 VIEW_BACKEND=processes\nCODEC_THREADS=10 DECODE_THREADS=10 DEPTH_THREADS=4 FFV1_SLICES=16\nCAMERA_PIPELINE=true STREAM_MEDIA=true PNG_RAM_GIB=32\nCPU_TARGET_PERCENT=80 CPU_LIMIT=none\n' "$(date -Is)" > "$base/full.status"
|
| 11 |
+
/usr/bin/time -v .venv/bin/python "$base/frozen-code/scripts/convert_h2o_v1.0.py" --root "$raw" --out "$base" --release-id shared-v1.0 --workers 4 --view-workers 16 --view-backend processes --camera-pipeline --stream-media --codec-threads 10 --decode-threads 10 --depth-threads 4 --ffv1-slices 16 --ram-stage-dir "$ram" --ram-stage-gib 32 --mano-dir "$HOME/Projects/WiLoR/mano_data" > "$base/full.log" 2>&1
|
| 12 |
+
code=$?
|
| 13 |
+
printf 'EXIT=%s END=%s\n' "$code" "$(date -Is)" >> "$base/full.status"
|
| 14 |
+
exit "$code"
|
H2O/shared-v1.1/script/v1_0_snapshot/script/warehouse_v1_0.py
ADDED
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared I/O for CONTRACT.md v1.0. No annotation synthesis."""
|
| 2 |
+
import argparse
|
| 3 |
+
from contextlib import contextmanager
|
| 4 |
+
from functools import lru_cache
|
| 5 |
+
import hashlib
|
| 6 |
+
import json
|
| 7 |
+
import math
|
| 8 |
+
import os
|
| 9 |
+
import shlex
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
import pickle
|
| 12 |
+
import random
|
| 13 |
+
import shutil
|
| 14 |
+
import subprocess
|
| 15 |
+
import tempfile
|
| 16 |
+
import time
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
from PIL import Image
|
| 20 |
+
import torch
|
| 21 |
+
|
| 22 |
+
SCHEMA_PATH = next(p for p in (Path(__file__).resolve().parents[1] / 'docs/schema.json',
|
| 23 |
+
Path(__file__).resolve().parents[1] / 'doc/schema.json') if p.is_file())
|
| 24 |
+
SCHEMA = json.loads(SCHEMA_PATH.read_text())
|
| 25 |
+
RAW_ROOT = Path.home() / 'Datasets/Hand-Datasets-Raw'
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def json_write(path, value):
|
| 29 |
+
path = Path(path)
|
| 30 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 31 |
+
path.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + '\n')
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def jsonl_write(path, rows):
|
| 35 |
+
path = Path(path)
|
| 36 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 37 |
+
with path.open('w') as out:
|
| 38 |
+
for row in rows:
|
| 39 |
+
out.write(json.dumps(row, ensure_ascii=False, allow_nan=False) + '\n')
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def sha256(path):
|
| 43 |
+
with Path(path).open('rb') as f:
|
| 44 |
+
return hashlib.file_digest(f, 'sha256').hexdigest()
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def locator(path, member=None, data=None, **extra):
|
| 48 |
+
result = {'file': str(Path(path).resolve())}
|
| 49 |
+
if member is not None:
|
| 50 |
+
result['member'] = member
|
| 51 |
+
if data is not None:
|
| 52 |
+
result['sha256'] = hashlib.sha256(data).hexdigest()
|
| 53 |
+
return result | extra
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def source(method='Copy source annotation; normalize storage only'):
|
| 57 |
+
return {'kind': 'format_conversion', 'method': method}
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def run(args, **kwargs):
|
| 61 |
+
return subprocess.run(args, check=True, stderr=subprocess.PIPE, **kwargs)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
@lru_cache(maxsize=1)
|
| 65 |
+
def ffversion():
|
| 66 |
+
return run(['ffmpeg', '-version'], stdout=subprocess.PIPE).stdout.decode().splitlines()[0]
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def probe(path):
|
| 70 |
+
return json.loads(run(['ffprobe', '-v', 'error', '-select_streams', 'v:0',
|
| 71 |
+
'-show_streams', '-of', 'json', str(path)],
|
| 72 |
+
stdout=subprocess.PIPE).stdout)['streams'][0]
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def decode_args(path, pixel_format):
|
| 76 |
+
threads = os.environ.get('HAND_WAREHOUSE_FFMPEG_THREADS', '1')
|
| 77 |
+
return ['ffmpeg', '-v', 'error', '-nostdin', '-filter_threads', threads, '-threads', threads, '-noautorotate',
|
| 78 |
+
'-i', str(path), '-map', '0:v:0', '-vsync', '0', '-threads', threads,
|
| 79 |
+
'-f', 'rawvideo', '-pix_fmt', pixel_format]
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def decoded_digest(path, pixel_format):
|
| 83 |
+
start = time.monotonic()
|
| 84 |
+
with tempfile.TemporaryFile() as err:
|
| 85 |
+
proc = subprocess.Popen(decode_args(path, pixel_format) + ['pipe:1'],
|
| 86 |
+
stdout=subprocess.PIPE, stderr=err)
|
| 87 |
+
digest, size = hashlib.sha256(), 0
|
| 88 |
+
with proc.stdout:
|
| 89 |
+
while chunk := proc.stdout.read(1024 * 1024):
|
| 90 |
+
digest.update(chunk)
|
| 91 |
+
size += len(chunk)
|
| 92 |
+
if proc.wait():
|
| 93 |
+
err.seek(0)
|
| 94 |
+
raise RuntimeError(err.read().decode(errors='replace'))
|
| 95 |
+
return digest.hexdigest(), size, time.monotonic() - start
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def video_frames(path, pixel_format, shape, dtype):
|
| 99 |
+
frame_bytes = int(np.prod(shape)) * np.dtype(dtype).itemsize
|
| 100 |
+
with tempfile.TemporaryFile() as err:
|
| 101 |
+
proc = subprocess.Popen(decode_args(path, pixel_format) + ['pipe:1'], stdout=subprocess.PIPE, stderr=err)
|
| 102 |
+
completed = False
|
| 103 |
+
try:
|
| 104 |
+
while True:
|
| 105 |
+
data = proc.stdout.read(frame_bytes)
|
| 106 |
+
if not data:
|
| 107 |
+
break
|
| 108 |
+
if len(data) != frame_bytes:
|
| 109 |
+
raise ValueError('truncated decoded video frame')
|
| 110 |
+
yield np.frombuffer(data, dtype=dtype).reshape(shape)
|
| 111 |
+
if proc.wait():
|
| 112 |
+
err.seek(0)
|
| 113 |
+
raise ValueError(err.read().decode(errors='replace'))
|
| 114 |
+
completed = True
|
| 115 |
+
finally:
|
| 116 |
+
proc.stdout.close()
|
| 117 |
+
if not completed and proc.poll() is None:
|
| 118 |
+
proc.terminate()
|
| 119 |
+
proc.wait()
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def storage(path, profile, parameters, source_lossy):
|
| 123 |
+
info = probe(path)
|
| 124 |
+
if info['codec_name'] == 'h264':
|
| 125 |
+
frames = json.loads(run(['ffprobe', '-v', 'error', '-threads', '1', '-select_streams', 'v:0',
|
| 126 |
+
'-show_entries', 'frame=key_frame', '-of', 'json', str(path)], stdout=subprocess.PIPE).stdout)['frames']
|
| 127 |
+
parameters = parameters | {'keyframe_indices': [i for i, f in enumerate(frames) if f['key_frame']]}
|
| 128 |
+
return {'profile': profile, 'codec': info['codec_name'],
|
| 129 |
+
'pixel_format': info['pix_fmt'], 'encoded_size': [info['width'], info['height']],
|
| 130 |
+
'decoder': {'name': 'ffmpeg', 'version': ffversion(), 'autorotate': False,
|
| 131 |
+
'color_space': info.get('color_space', 'unknown'),
|
| 132 |
+
'color_range': info.get('color_range', 'unknown'),
|
| 133 |
+
'color_primaries': info.get('color_primaries', 'unknown'),
|
| 134 |
+
'color_transfer': info.get('color_transfer', 'unknown')},
|
| 135 |
+
'encoder_parameters': {'version': ffversion()} | parameters,
|
| 136 |
+
'source_lossy': source_lossy, 'storage_fps': 30, 'timebase_role': 'index_only'}
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def encode_raw(raw, target, width, height, pixel_format, profile, codec='ffv1', extra=(), threads=1):
|
| 140 |
+
start = time.monotonic()
|
| 141 |
+
slices = os.environ.get('HAND_WAREHOUSE_FFV1_SLICES')
|
| 142 |
+
if codec == 'ffv1' and slices:
|
| 143 |
+
if slices != '16':
|
| 144 |
+
raise ValueError('only the verified FFV1 16-slice profile is enabled')
|
| 145 |
+
extra = (*extra, '-level', '3', '-slices', slices)
|
| 146 |
+
command = ['ffmpeg', '-v', 'error', '-nostdin', '-filter_threads',
|
| 147 |
+
os.environ.get('HAND_WAREHOUSE_FFMPEG_THREADS', '1'), '-y', '-f', 'rawvideo',
|
| 148 |
+
'-pixel_format', pixel_format, '-video_size', f'{width}x{height}', '-framerate', '30',
|
| 149 |
+
'-i', str(raw) if isinstance(raw, Path) else 'pipe:0', '-an', '-c:v', codec,
|
| 150 |
+
'-threads', str(threads), *extra, str(target)]
|
| 151 |
+
if isinstance(raw, Path):
|
| 152 |
+
run(command)
|
| 153 |
+
expected_size, expected_hash = raw.stat().st_size, sha256(raw)
|
| 154 |
+
else:
|
| 155 |
+
with tempfile.TemporaryFile() as err:
|
| 156 |
+
proc = subprocess.Popen(command, stdin=subprocess.PIPE, stderr=err)
|
| 157 |
+
expected_size, checksum = 0, hashlib.sha256()
|
| 158 |
+
try:
|
| 159 |
+
for frame in raw:
|
| 160 |
+
proc.stdin.write(frame)
|
| 161 |
+
checksum.update(frame)
|
| 162 |
+
expected_size += len(frame)
|
| 163 |
+
proc.stdin.close()
|
| 164 |
+
if proc.wait():
|
| 165 |
+
err.seek(0)
|
| 166 |
+
raise RuntimeError(err.read().decode(errors='replace'))
|
| 167 |
+
except BaseException:
|
| 168 |
+
if proc.poll() is None:
|
| 169 |
+
proc.kill()
|
| 170 |
+
proc.stdin.close()
|
| 171 |
+
proc.wait()
|
| 172 |
+
raise
|
| 173 |
+
expected_hash = checksum.hexdigest()
|
| 174 |
+
digest, size, decode_seconds = decoded_digest(target, pixel_format)
|
| 175 |
+
if size != expected_size or digest != expected_hash:
|
| 176 |
+
raise ValueError(f'lossless roundtrip failed: {target}')
|
| 177 |
+
parameters = {'name': codec, 'arguments': list(extra)}
|
| 178 |
+
if threads != 1:
|
| 179 |
+
parameters['threads'] = threads
|
| 180 |
+
config = storage(target, profile, parameters, False)
|
| 181 |
+
return config, {'bytes': target.stat().st_size, 'encode_seconds': time.monotonic() - start - decode_seconds,
|
| 182 |
+
'decode_seconds': decode_seconds, 'decoded_sha256': digest, 'all_frames_exact': True}
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def measure_rgb_access(video, raw, width, height, count, source_video=None, source_image=None):
|
| 186 |
+
index = count // 2
|
| 187 |
+
start = time.monotonic()
|
| 188 |
+
data = run(decode_args(video, 'rgb24') +
|
| 189 |
+
['-vf', f'select=eq(n\\,{index})', '-frames:v', '1', 'pipe:1'],
|
| 190 |
+
stdout=subprocess.PIPE).stdout
|
| 191 |
+
if raw is None:
|
| 192 |
+
if source_image is not None:
|
| 193 |
+
expected = run(decode_args(source_image, 'rgb24') + ['-frames:v', '1', 'pipe:1'],
|
| 194 |
+
stdout=subprocess.PIPE).stdout
|
| 195 |
+
elif source_video is not None:
|
| 196 |
+
expected = run(decode_args(source_video, 'rgb24') +
|
| 197 |
+
['-vf', f'select=eq(n\\,{index})', '-frames:v', '1', 'pipe:1'],
|
| 198 |
+
stdout=subprocess.PIPE).stdout
|
| 199 |
+
else:
|
| 200 |
+
raise ValueError('source video/image required for streaming RGB access check')
|
| 201 |
+
else:
|
| 202 |
+
with raw.open('rb') as inp:
|
| 203 |
+
inp.seek(index * width * height * 3)
|
| 204 |
+
expected = inp.read(width * height * 3)
|
| 205 |
+
if len(expected) != width * height * 3 or data != expected:
|
| 206 |
+
raise ValueError('exact indexed RGB read failed')
|
| 207 |
+
return {'random_access_strategy': 'decode from first keyframe; select exact presentation index',
|
| 208 |
+
'random_frame_index': index, 'random_frame_read_seconds': time.monotonic() - start}
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def jpeg_sample_indices(sequence, camera, count):
|
| 212 |
+
seed = int.from_bytes(hashlib.sha256(f'{sequence}/{camera}/20260920'.encode()).digest()[:8], 'big')
|
| 213 |
+
indices = {0, count - 1, count // 4, count // 2, 3 * count // 4}
|
| 214 |
+
indices.update(random.Random(seed).sample([i for i in range(count) if i not in indices],
|
| 215 |
+
min(count, 16) - len(indices)))
|
| 216 |
+
return sorted(indices), seed
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def check_jpeg_copy(target, paths, hashes, size, sequence, camera, full):
|
| 220 |
+
packets = json.loads(run(['ffprobe', '-v', 'error', '-select_streams', 'v:0',
|
| 221 |
+
'-show_packets', '-show_data_hash', 'sha256', '-of', 'json', str(target)],
|
| 222 |
+
stdout=subprocess.PIPE).stdout)['packets']
|
| 223 |
+
if [p['data_hash'].split(':', 1)[1].lower() for p in packets] != hashes:
|
| 224 |
+
raise ValueError('JPEG packet hashes/order/count differ')
|
| 225 |
+
info = probe(target)
|
| 226 |
+
if [info['width'], info['height']] != list(size):
|
| 227 |
+
raise ValueError('JPEG container dimensions differ')
|
| 228 |
+
indices, seed = jpeg_sample_indices(sequence, camera, len(paths))
|
| 229 |
+
if full:
|
| 230 |
+
indices = list(range(len(paths)))
|
| 231 |
+
select = '+'.join(f'eq(n\\,{i})' for i in indices)
|
| 232 |
+
frame_bytes = size[0] * size[1] * 3
|
| 233 |
+
# Spool selected frames to disk, keeping RAM bounded for full-view audits.
|
| 234 |
+
with tempfile.TemporaryFile() as decoded:
|
| 235 |
+
run(decode_args(target, 'rgb24') + ([] if full else ['-vf', 'select=' + select]) + ['pipe:1'], stdout=decoded)
|
| 236 |
+
decoded.seek(0)
|
| 237 |
+
for i in indices:
|
| 238 |
+
expected = run(decode_args(paths[i], 'rgb24') + ['pipe:1'], stdout=subprocess.PIPE).stdout
|
| 239 |
+
if len(expected) != frame_bytes or decoded.read(frame_bytes) != expected:
|
| 240 |
+
raise ValueError(f'JPEG decoded pixels differ at frame {i}')
|
| 241 |
+
if decoded.read(1):
|
| 242 |
+
raise ValueError('JPEG selected pixel count differs')
|
| 243 |
+
return {'policy': 'jpeg-packets-all-rgb-sample16/v1', 'seed': seed,
|
| 244 |
+
'selected_frame_indices': indices, 'pixel_frames_checked': len(indices),
|
| 245 |
+
'packet_frames_checked': len(paths), 'jpeg_packets_exact': True,
|
| 246 |
+
'packet_count_order_dimensions_exact': True, 'sampled_pixels_exact': True,
|
| 247 |
+
'all_frames_exact': len(indices) == len(paths), 'full_view_audit': full}
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def rgb_video(paths, target, work, video=None, count=None, sequence="", camera="", full_jpeg=False,
|
| 251 |
+
ffv1_first=False, codec_threads=1, stream_source=False):
|
| 252 |
+
"""JPEG packet proof plus deterministic pixels; re-encodings compare all pixels."""
|
| 253 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 254 |
+
raw = work / 'rgb.raw'
|
| 255 |
+
packets = []
|
| 256 |
+
has_missing = video is None and any(p is None for p in paths)
|
| 257 |
+
if has_missing:
|
| 258 |
+
present = next((p for p in paths if p is not None), None)
|
| 259 |
+
if present is None:
|
| 260 |
+
raise ValueError('no source RGB image to establish the pixel format/grid')
|
| 261 |
+
original = probe(present)
|
| 262 |
+
width, height = original['width'], original['height']
|
| 263 |
+
with raw.open('wb') as dest:
|
| 264 |
+
for path in paths:
|
| 265 |
+
if path is None:
|
| 266 |
+
dest.write(bytes(width * height * 3))
|
| 267 |
+
else:
|
| 268 |
+
with Image.open(path) as im:
|
| 269 |
+
if im.mode != 'RGB' or im.size != (width, height):
|
| 270 |
+
raise ValueError('source RGB grid/type changes within view')
|
| 271 |
+
run(decode_args(path, 'rgb24') + ['pipe:1'], stdout=dest)
|
| 272 |
+
lossy, count = 'unknown', len(paths)
|
| 273 |
+
input_args = None
|
| 274 |
+
elif video is None:
|
| 275 |
+
if not paths:
|
| 276 |
+
raise ValueError('RGB timeline must contain existing source images')
|
| 277 |
+
suffix = paths[0].suffix.lower()
|
| 278 |
+
if suffix not in ('.jpg', '.jpeg', '.png'):
|
| 279 |
+
raise ValueError('unsupported source RGB format')
|
| 280 |
+
images = work / 'rgb_source'
|
| 281 |
+
images.mkdir()
|
| 282 |
+
dimensions = None
|
| 283 |
+
for i, path in enumerate(paths):
|
| 284 |
+
with Image.open(path) as im:
|
| 285 |
+
if im.mode != 'RGB' or (dimensions is not None and dimensions != im.size):
|
| 286 |
+
raise ValueError('RGB must be homogeneous 8-bit RGB, with no silent color/size conversion')
|
| 287 |
+
dimensions = im.size
|
| 288 |
+
if im.format == 'PNG':
|
| 289 |
+
with path.open('rb') as header:
|
| 290 |
+
if header.read(25)[24] != 8:
|
| 291 |
+
raise ValueError('high bit depth RGB needs a registered schema')
|
| 292 |
+
dest = images / f'{i:08d}{suffix}'
|
| 293 |
+
if stream_source and suffix == '.png':
|
| 294 |
+
try:
|
| 295 |
+
os.link(path, dest) # Immutable staging input; avoid a second PNG copy.
|
| 296 |
+
except OSError:
|
| 297 |
+
# Temporary alias only: RAM/disk staging may be on different filesystems.
|
| 298 |
+
os.symlink(path.resolve(), dest)
|
| 299 |
+
else:
|
| 300 |
+
shutil.copyfile(path, dest)
|
| 301 |
+
if suffix in ('.jpg', '.jpeg'):
|
| 302 |
+
packets.append(sha256(path))
|
| 303 |
+
width, height = dimensions
|
| 304 |
+
input_args = ['-framerate', '30', '-i', str(images / ('%08d' + suffix))]
|
| 305 |
+
count = len(paths)
|
| 306 |
+
original = probe(paths[0])
|
| 307 |
+
lossy = suffix in ('.jpg', '.jpeg')
|
| 308 |
+
else:
|
| 309 |
+
original = probe(video)
|
| 310 |
+
if int(original.get('bits_per_raw_sample') or 8) > 8 or any(
|
| 311 |
+
x in original.get('pix_fmt', '') for x in ('10', '12', '16', 'f32')):
|
| 312 |
+
raise ValueError('high bit depth RGB needs a registered schema')
|
| 313 |
+
width, height = original['width'], original['height']
|
| 314 |
+
input_args = ['-i', str(video)]
|
| 315 |
+
lossy = 'unknown'
|
| 316 |
+
limits = ['-frames:v', str(count)] if count else []
|
| 317 |
+
records = []
|
| 318 |
+
if video is None and not has_missing and suffix in ('.jpg', '.jpeg'):
|
| 319 |
+
start = time.monotonic()
|
| 320 |
+
try:
|
| 321 |
+
run(['ffmpeg', '-v', 'error', '-nostdin', '-y', *input_args, '-map', '0:v:0',
|
| 322 |
+
*limits, '-c:v', 'copy', '-an', str(target)])
|
| 323 |
+
encode_seconds = time.monotonic() - start
|
| 324 |
+
validation = check_jpeg_copy(target, paths, packets, (width, height), sequence, camera, full_jpeg)
|
| 325 |
+
cfg = storage(target, 'mkv/mjpeg_copy/v1', {'stream_copy': True}, lossy)
|
| 326 |
+
cfg['decoder']['source_color_metadata'] = {k: original.get(k, 'unknown') for k in
|
| 327 |
+
('color_space', 'color_range', 'color_primaries', 'color_transfer')}
|
| 328 |
+
records.append(validation | {'profile': cfg['profile'], 'bytes': target.stat().st_size,
|
| 329 |
+
'encode_seconds': encode_seconds, 'validation_seconds': time.monotonic() - start - encode_seconds})
|
| 330 |
+
return cfg, [width, height], records, count
|
| 331 |
+
except (subprocess.CalledProcessError, ValueError) as exc:
|
| 332 |
+
records.append({'profile': 'mkv/mjpeg_copy/v1', 'rejected': str(exc)})
|
| 333 |
+
target.unlink(missing_ok=True)
|
| 334 |
+
stream_images = stream_source and video is None and not has_missing and suffix == '.png'
|
| 335 |
+
if stream_images:
|
| 336 |
+
source_size, expected_hash = count * width * height * 3, None
|
| 337 |
+
elif stream_source and video is not None:
|
| 338 |
+
expected_hash, source_size, source_seconds = decoded_digest(video, 'rgb24', count)
|
| 339 |
+
else:
|
| 340 |
+
if not has_missing:
|
| 341 |
+
threads = os.environ.get('HAND_WAREHOUSE_FFMPEG_THREADS', '1')
|
| 342 |
+
run(['ffmpeg', '-v', 'error', '-nostdin', '-y', '-threads', threads, '-noautorotate',
|
| 343 |
+
*input_args, '-map', '0:v:0', *limits, '-vsync', '0', '-threads', threads,
|
| 344 |
+
'-f', 'rawvideo', '-pix_fmt', 'rgb24', str(raw)])
|
| 345 |
+
source_size, expected_hash = raw.stat().st_size, sha256(raw)
|
| 346 |
+
frame_bytes = width * height * 3
|
| 347 |
+
actual, remainder = divmod(source_size, frame_bytes)
|
| 348 |
+
if remainder or not actual or (count is not None and actual != count):
|
| 349 |
+
raise ValueError('source RGB frame count mismatch')
|
| 350 |
+
can_copy = video is not None
|
| 351 |
+
if can_copy:
|
| 352 |
+
start = time.monotonic()
|
| 353 |
+
try:
|
| 354 |
+
run(['ffmpeg', '-v', 'error', '-nostdin', '-y', *input_args, '-map', '0:v:0',
|
| 355 |
+
*limits, '-c:v', 'copy', '-an', str(target)])
|
| 356 |
+
digest, size, seconds = decoded_digest(target, 'rgb24')
|
| 357 |
+
if digest != expected_hash or size != source_size:
|
| 358 |
+
raise ValueError('stream-copy RGB bytes/order/count mismatch')
|
| 359 |
+
cfg = storage(target, 'mkv/source_copy/v1',
|
| 360 |
+
{'stream_copy': True}, lossy)
|
| 361 |
+
if video:
|
| 362 |
+
cfg['storage_fps'] = original.get('avg_frame_rate')
|
| 363 |
+
cfg['preserve_source_pts'] = True
|
| 364 |
+
records.append({'profile': cfg['profile'], 'all_frames_exact': True,
|
| 365 |
+
'decoded_sha256': digest,
|
| 366 |
+
'bytes': target.stat().st_size, 'decode_seconds': seconds,
|
| 367 |
+
'encode_seconds': time.monotonic() - start - seconds})
|
| 368 |
+
records[-1].update(measure_rgb_access(target, None if stream_source else raw, width, height, actual, video))
|
| 369 |
+
if stream_source:
|
| 370 |
+
records[-1]['source_decode_seconds'] = source_seconds
|
| 371 |
+
return cfg, [width, height], records, actual
|
| 372 |
+
except (subprocess.CalledProcessError, ValueError) as exc:
|
| 373 |
+
records.append({'profile': 'stream_copy', 'rejected': str(exc)})
|
| 374 |
+
target.unlink(missing_ok=True)
|
| 375 |
+
if stream_source and video is not None:
|
| 376 |
+
# Exact fallback only: stream-copy normally avoids creating the source RGB spool.
|
| 377 |
+
run(decode_args(video, 'rgb24') + limits + [str(raw)])
|
| 378 |
+
if raw.stat().st_size != source_size or sha256(raw) != expected_hash:
|
| 379 |
+
raise ValueError('streaming source RGB differs from fallback decode')
|
| 380 |
+
candidates = []
|
| 381 |
+
for profile, codec, params in [
|
| 382 |
+
('mkv/ffv1_rgb/v1', 'ffv1', ['-level', '3', '-pix_fmt', 'bgr0']),
|
| 383 |
+
('mkv/h264_rgb_lossless/v1', 'libx264rgb', ['-crf', '0', '-preset', 'medium', '-g', '30'])]:
|
| 384 |
+
path = work / (codec + '.mkv')
|
| 385 |
+
try:
|
| 386 |
+
streamed = stream_images
|
| 387 |
+
def source_frames():
|
| 388 |
+
source_path = video if video is not None else images / ('%08d' + suffix)
|
| 389 |
+
frames = video_frames(source_path, 'rgb24', (height, width, 3), np.uint8)
|
| 390 |
+
try:
|
| 391 |
+
for _ in range(actual):
|
| 392 |
+
try:
|
| 393 |
+
frame = next(frames)
|
| 394 |
+
except StopIteration:
|
| 395 |
+
raise ValueError('source RGB frame count mismatch') from None
|
| 396 |
+
yield frame.tobytes()
|
| 397 |
+
finally:
|
| 398 |
+
frames.close()
|
| 399 |
+
cfg, record = encode_raw(source_frames() if streamed else raw, path, width, height,
|
| 400 |
+
'rgb24', profile, codec, params, codec_threads)
|
| 401 |
+
if expected_hash is not None and record['decoded_sha256'] != expected_hash:
|
| 402 |
+
raise ValueError('source RGB digest/order differs from encoded output')
|
| 403 |
+
cfg['source_lossy'] = lossy
|
| 404 |
+
cfg['decoder']['source_color_metadata'] = {k: original.get(k, 'unknown') for k in
|
| 405 |
+
('color_space', 'color_range', 'color_primaries', 'color_transfer')}
|
| 406 |
+
record['profile'] = profile
|
| 407 |
+
record.update(measure_rgb_access(path, None if streamed else raw, width, height, actual,
|
| 408 |
+
source_video=video, source_image=paths[actual // 2] if stream_images else None))
|
| 409 |
+
records.append(record)
|
| 410 |
+
candidates.append((path.stat().st_size, path, cfg))
|
| 411 |
+
if ffv1_first and codec == 'ffv1':
|
| 412 |
+
break # Keep the H.264 fallback only if the preferred exact encoder fails.
|
| 413 |
+
except subprocess.CalledProcessError as exc:
|
| 414 |
+
records.append({'profile': profile, 'rejected': exc.stderr.decode(errors='replace')})
|
| 415 |
+
if not candidates:
|
| 416 |
+
raise ValueError('no supported lossless RGB encoder')
|
| 417 |
+
_, chosen, cfg = min(candidates, key=lambda x: x[0])
|
| 418 |
+
shutil.move(chosen, target)
|
| 419 |
+
return cfg, [width, height], records, actual
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
def pack_depth(depth):
|
| 423 |
+
bits = np.ascontiguousarray(depth, dtype='<f4').view('<u4')
|
| 424 |
+
return np.concatenate([(bits & 65535).astype('<u2'), (bits >> 16).astype('<u2')], axis=-1)
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
def unpack_depth(encoded):
|
| 428 |
+
low, high = np.split(np.asarray(encoded, dtype='<u2'), 2, axis=-1)
|
| 429 |
+
return (low.astype('<u4') | (high.astype('<u4') << 16)).view('<f4')
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
def check_transform(values):
|
| 433 |
+
a = np.asarray(values)
|
| 434 |
+
if not np.isfinite(a).all() or a.shape[-2:] != (4, 4):
|
| 435 |
+
raise ValueError('invalid transform shape/values')
|
| 436 |
+
if not np.allclose(a[..., 3, :], [0, 0, 0, 1], atol=1e-5):
|
| 437 |
+
raise ValueError('invalid homogeneous transform row')
|
| 438 |
+
r = a[..., :3, :3]
|
| 439 |
+
if not np.allclose(np.swapaxes(r, -1, -2) @ r, np.eye(3), atol=2e-3) or not np.allclose(
|
| 440 |
+
np.linalg.det(r), 1, atol=2e-3):
|
| 441 |
+
raise ValueError('nonrigid rotation')
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
class View:
|
| 445 |
+
def __init__(self, path, dataset, release, sequence, camera, frames, sampling='dense', split='unknown'):
|
| 446 |
+
self.path = Path(path)
|
| 447 |
+
self.path.mkdir(parents=True, exist_ok=True)
|
| 448 |
+
self.frames = frames
|
| 449 |
+
self.valid_rules = {}
|
| 450 |
+
self.full_jpeg = False
|
| 451 |
+
self.meta = dict(schema_version=SCHEMA['schema_version'], dataset_id=dataset,
|
| 452 |
+
release_id=release, sequence_id=sequence, camera_id=camera,
|
| 453 |
+
sample_type='video', num_frames=len(frames), hand_slots=['left', 'right'],
|
| 454 |
+
sampling={'type': sampling, 'source_fps': None, 'frames_ref': 'camera/frames.jsonl'},
|
| 455 |
+
camera={'model': 'unknown', 'schema_id': None, 'image_size': None},
|
| 456 |
+
components={}, split=split, view_type='unknown')
|
| 457 |
+
if split == 'unknown':
|
| 458 |
+
self.meta['split_reason'] = 'No verified official split mapping available for this sequence'
|
| 459 |
+
self.build = {'validation': [], 'unresolved': [], 'validity_revision': SCHEMA['validity_revision']}
|
| 460 |
+
|
| 461 |
+
def absent(self, key, reason, status='source_missing'):
|
| 462 |
+
self.meta['components'][key] = {'available': False, 'reason': reason, 'status': status}
|
| 463 |
+
if status != 'source_missing':
|
| 464 |
+
self.build['unresolved'].append({'component': key, 'status': status, 'reason': reason})
|
| 465 |
+
|
| 466 |
+
def component(self, key, schema, ref, axes, loc, **extra):
|
| 467 |
+
if schema not in SCHEMA['components']:
|
| 468 |
+
raise ValueError(f'unregistered schema: {schema}')
|
| 469 |
+
if ref.startswith('annotation/') and extra.get('valid_ref'):
|
| 470 |
+
rule = self.valid_rules.get(key, self.valid_rules.get(key.split('_')[0]))
|
| 471 |
+
if not rule:
|
| 472 |
+
raise ValueError(f'{key}: adapter must declare annotation validity rule')
|
| 473 |
+
extra.setdefault('valid_policy', dict(
|
| 474 |
+
revision=SCHEMA['validity_revision'], meaning=SCHEMA['annotation_validity']['meaning'],
|
| 475 |
+
source_rule=rule, source_locator=loc, scope=extra.get('valid_axes', axes),
|
| 476 |
+
numerical_checks='Schema shape, finite valid floats, SE(3) where applicable; malformed input aborts',
|
| 477 |
+
official_qa={'status': 'not_provided', 'reason': 'No separate applicable official QA in selected source inputs'},
|
| 478 |
+
local_excluded_frame_indices=[], local_exclusion_reasons={}, visibility_independent=True))
|
| 479 |
+
self.meta['components'][key] = dict(available=True, schema_id=schema, data_ref=ref,
|
| 480 |
+
axes=axes, provenance=source(), source_locator=loc) | extra
|
| 481 |
+
return self.meta['components'][key]
|
| 482 |
+
|
| 483 |
+
def tensor(self, key, schema, ref, array, valid, axes, loc, **extra):
|
| 484 |
+
array = np.asarray(array, dtype=np.float32)
|
| 485 |
+
valid = np.asarray(valid, dtype=bool)
|
| 486 |
+
valid_shape = SCHEMA['components'][schema].get('valid_shape')
|
| 487 |
+
if valid_shape and (len(valid_shape) != valid.ndim or any(isinstance(s, int) and valid.shape[i] != s for i, s in enumerate(valid_shape))):
|
| 488 |
+
raise ValueError(f'{key}: schema validity shape mismatch')
|
| 489 |
+
if array.shape[:valid.ndim] != valid.shape:
|
| 490 |
+
raise ValueError(f'{key}: validity axes mismatch')
|
| 491 |
+
if not np.isfinite(array[valid]).all():
|
| 492 |
+
raise ValueError(f'{key}: source annotation exists but is nonfinite')
|
| 493 |
+
array = array.copy()
|
| 494 |
+
array[~valid] = np.nan
|
| 495 |
+
if schema in ('transform/se3/v1', 'object/rigid/v1'):
|
| 496 |
+
check_transform(array[valid])
|
| 497 |
+
expected = SCHEMA['components'][schema].get('shape')
|
| 498 |
+
if expected and (len(expected) != array.ndim or any(
|
| 499 |
+
isinstance(n, int) and array.shape[i] != n for i, n in enumerate(expected))):
|
| 500 |
+
raise ValueError(f'{key}: schema shape mismatch {array.shape}')
|
| 501 |
+
dest = self.path / ref
|
| 502 |
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
| 503 |
+
torch.save(torch.from_numpy(array), dest)
|
| 504 |
+
valid_ref = str(Path(ref).with_name(Path(ref).stem + '_valid.pt'))
|
| 505 |
+
torch.save(torch.from_numpy(valid.copy()), self.path / valid_ref)
|
| 506 |
+
return self.component(key, schema, ref, axes, loc, valid_ref=valid_ref,
|
| 507 |
+
valid_axes=axes[:valid.ndim], **extra)
|
| 508 |
+
|
| 509 |
+
def rgb(self, paths, loc, video=None, count=None, ffv1_first=False, codec_threads=1,
|
| 510 |
+
stream_source=False):
|
| 511 |
+
media_dir = os.environ.get('HAND_WAREHOUSE_MEDIA_TMPDIR') if stream_source and (video is not None or all(p is not None for p in paths)) else None
|
| 512 |
+
with tempfile.TemporaryDirectory(prefix='rgb-', dir=media_dir or self.path) as work:
|
| 513 |
+
cfg, size, records, n = rgb_video(paths, self.path / 'observation/rgb.mkv',
|
| 514 |
+
Path(work), video, count, self.meta['sequence_id'], self.meta['camera_id'],
|
| 515 |
+
self.full_jpeg, ffv1_first, codec_threads, stream_source)
|
| 516 |
+
if n != len(self.frames):
|
| 517 |
+
raise ValueError('RGB differs from frames timeline')
|
| 518 |
+
torch.save(torch.ones(n, dtype=torch.bool, device='cpu') if video is not None else
|
| 519 |
+
torch.tensor([p is not None for p in paths], dtype=torch.bool, device='cpu'),
|
| 520 |
+
self.path / 'observation/rgb_valid.pt')
|
| 521 |
+
self.component('rgb', 'rgb/uint8/v1', 'observation/rgb.mkv', ['T', 'height', 'width', 'channel'],
|
| 522 |
+
loc, storage=cfg, valid_ref='observation/rgb_valid.pt', valid_axes=['T'],
|
| 523 |
+
provenance=source('Verified source packet copy or lossless fixed-decoder RGB encoding'))
|
| 524 |
+
self.meta['camera']['image_size'] = size
|
| 525 |
+
self.build['validation'].extend(records)
|
| 526 |
+
|
| 527 |
+
def raster(self, key, arrays, valid, loc, labels=None, codec_threads=1, stream=False):
|
| 528 |
+
depth = key == 'depth'
|
| 529 |
+
ref = 'observation/depth.mkv' if depth else 'annotation/segment/mask.mkv'
|
| 530 |
+
dest = self.path / ref
|
| 531 |
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
| 532 |
+
width, height = self.meta['camera']['image_size']
|
| 533 |
+
count = 0
|
| 534 |
+
media_dir = os.environ.get('HAND_WAREHOUSE_MEDIA_TMPDIR') if stream and len(self.frames) * width * height <= 2 * 1024**3 else None
|
| 535 |
+
with tempfile.TemporaryDirectory(prefix='raster-', dir=media_dir or self.path) as wd:
|
| 536 |
+
work = Path(wd)
|
| 537 |
+
with (work / 'valid.raw').open('wb') as vo:
|
| 538 |
+
def frames():
|
| 539 |
+
nonlocal count
|
| 540 |
+
for arr in arrays:
|
| 541 |
+
arr = np.asarray(arr)
|
| 542 |
+
if arr.shape != (height, width):
|
| 543 |
+
raise ValueError(f'{key}: raster not on RGB grid')
|
| 544 |
+
if depth:
|
| 545 |
+
arr = arr.astype('<f4')
|
| 546 |
+
good = np.isfinite(arr) & (arr > 0)
|
| 547 |
+
arr[~good] = np.nan
|
| 548 |
+
vo.write(good.astype(np.uint8).tobytes())
|
| 549 |
+
payload = pack_depth(arr).tobytes()
|
| 550 |
+
else:
|
| 551 |
+
if not np.issubdtype(arr.dtype, np.integer) or arr.min() < 0 or arr.max() > 65535:
|
| 552 |
+
raise ValueError('invalid segmentation region codes')
|
| 553 |
+
payload = arr.astype('<u2').tobytes()
|
| 554 |
+
count += 1
|
| 555 |
+
yield payload
|
| 556 |
+
if count != len(self.frames):
|
| 557 |
+
raise ValueError(f'{key}: frame count mismatch')
|
| 558 |
+
|
| 559 |
+
if stream:
|
| 560 |
+
source = frames()
|
| 561 |
+
else:
|
| 562 |
+
source = work / 'data.raw'
|
| 563 |
+
with source.open('wb') as out:
|
| 564 |
+
for payload in frames():
|
| 565 |
+
out.write(payload)
|
| 566 |
+
cfg, record = encode_raw(source, dest, width * (2 if depth else 1), height,
|
| 567 |
+
'gray16le', 'mkv/depth_float32_bits/v1' if depth else 'mkv/uint16_ffv1/v1',
|
| 568 |
+
threads=codec_threads)
|
| 569 |
+
self.build['validation'].append(record | {'component': key})
|
| 570 |
+
if depth:
|
| 571 |
+
vcfg, record = encode_raw(work / 'valid.raw', self.path / 'observation/depth_valid.mkv',
|
| 572 |
+
width, height, 'gray', 'mkv/bool_ffv1/v1', threads=codec_threads)
|
| 573 |
+
self.build['validation'].append(record | {'component': 'depth_valid'})
|
| 574 |
+
self.component(key, 'depth/z_float32/v1', ref, ['T', 'height', 'width'], loc,
|
| 575 |
+
storage=cfg, valid_storage=vcfg, valid_ref='observation/depth_valid.mkv',
|
| 576 |
+
valid_axes=['T', 'height', 'width'], unit='m', depth_type='z', depth_origin='measured', invalid_value='NaN')
|
| 577 |
+
else:
|
| 578 |
+
vref = 'annotation/segment/mask_valid.pt'
|
| 579 |
+
torch.save(torch.as_tensor(valid, dtype=torch.bool, device='cpu'), self.path / vref)
|
| 580 |
+
jsonl_write(self.path / 'annotation/segment/instances.jsonl', labels)
|
| 581 |
+
self.component(key, 'segment/uint16_labels/v1', ref, ['T', 'height', 'width'], loc,
|
| 582 |
+
storage=cfg, valid_ref=vref, valid_axes=['T'], segmentation_type='instance',
|
| 583 |
+
mapping_ref='annotation/segment/instances.jsonl', coverage={'kind': 'unknown'})
|
| 584 |
+
|
| 585 |
+
def camera(self, intrinsic, loc, extrinsic=None, extrinsic_loc=None):
|
| 586 |
+
n = len(self.frames)
|
| 587 |
+
if intrinsic is not None:
|
| 588 |
+
a = np.asarray(intrinsic)
|
| 589 |
+
a = np.broadcast_to(a, (n, 3, 3)) if a.shape == (3, 3) else a
|
| 590 |
+
if not np.allclose(a[..., 2, :], [0, 0, 1]) or np.any(a[..., 0, 0] <= 0) or np.any(a[..., 1, 1] <= 0):
|
| 591 |
+
raise ValueError('invalid pinhole intrinsic matrix')
|
| 592 |
+
self.tensor('intrinsic', 'camera/pinhole/v1', 'camera/intrinsic.pt', a,
|
| 593 |
+
np.ones(n, bool), ['T', 'row', 'column'], loc)
|
| 594 |
+
self.meta['camera'].update(model='pinhole', schema_id='camera/pinhole/v1')
|
| 595 |
+
if extrinsic is not None:
|
| 596 |
+
a = np.asarray(extrinsic)
|
| 597 |
+
a = np.broadcast_to(a, (n, 4, 4)) if a.shape == (4, 4) else a
|
| 598 |
+
self.tensor('extrinsic', 'transform/se3/v1', 'camera/extrinsic.pt', a,
|
| 599 |
+
np.ones(n, bool), ['T', 'row', 'column'], extrinsic_loc or loc,
|
| 600 |
+
convention='T_camera_from_world')
|
| 601 |
+
|
| 602 |
+
def object(self, oid, loc, scope='sequence', scope_id=None, **extra):
|
| 603 |
+
info = dict(object_id=oid, identity_scope=scope, scope_id=scope_id or self.meta['sequence_id'],
|
| 604 |
+
source_locator=loc, has_model=False) | extra
|
| 605 |
+
json_write(self.path / f'annotation/object/{oid}/metainfo.json', info)
|
| 606 |
+
return info
|
| 607 |
+
|
| 608 |
+
def relations(self, rows, valid, loc):
|
| 609 |
+
ref = 'annotation/contact/relations.jsonl'
|
| 610 |
+
jsonl_write(self.path / ref, rows)
|
| 611 |
+
vref = 'annotation/contact/relations_valid.pt'
|
| 612 |
+
torch.save(torch.as_tensor(valid, dtype=torch.bool, device='cpu'), self.path / vref)
|
| 613 |
+
self.component('relations', 'contact/relations/v1', ref, ['T'], loc, valid_ref=vref, valid_axes=['T'])
|
| 614 |
+
|
| 615 |
+
def finish(self):
|
| 616 |
+
check_view_type(self.meta)
|
| 617 |
+
for key, component in self.meta['components'].items():
|
| 618 |
+
if component.get('valid_policy'):
|
| 619 |
+
check_valid_policy(component, len(self.frames))
|
| 620 |
+
valid = torch.load(self.path / component['valid_ref'], weights_only=True)
|
| 621 |
+
self.build.setdefault('annotation_validity', {})[key] = {
|
| 622 |
+
'valid_policy': component['valid_policy'], 'valid_count': int(valid.sum()),
|
| 623 |
+
'invalid_count': valid.numel() - int(valid.sum())}
|
| 624 |
+
for i, frame in enumerate(self.frames):
|
| 625 |
+
frame.update(frame_index=i)
|
| 626 |
+
frame.setdefault('timestamp_ns', None)
|
| 627 |
+
frame.setdefault('clock_domain', None)
|
| 628 |
+
if 'source_locator' not in frame:
|
| 629 |
+
raise ValueError('frame source locator missing')
|
| 630 |
+
jsonl_write(self.path / 'camera/frames.jsonl', self.frames)
|
| 631 |
+
json_write(self.path / 'metainfo.json', self.meta)
|
| 632 |
+
return self.build
|
| 633 |
+
|
| 634 |
+
|
| 635 |
+
def check_mesh(path, asset_root):
|
| 636 |
+
path, asset_root = Path(path), Path(asset_root).resolve()
|
| 637 |
+
vertices, faces, largest_index = 0, 0, 0
|
| 638 |
+
materials = []
|
| 639 |
+
with path.open() as inp:
|
| 640 |
+
for line in inp:
|
| 641 |
+
fields = line.split()
|
| 642 |
+
if not fields or fields[0].startswith('#'):
|
| 643 |
+
continue
|
| 644 |
+
if fields[0] == 'v':
|
| 645 |
+
if len(fields) < 4 or not all(math.isfinite(float(v)) for v in fields[1:4]):
|
| 646 |
+
raise ValueError(f'invalid mesh vertex: {path}')
|
| 647 |
+
vertices += 1
|
| 648 |
+
elif fields[0] == 'f':
|
| 649 |
+
if len(fields) < 4:
|
| 650 |
+
raise ValueError('degenerate OBJ face')
|
| 651 |
+
for field in fields[1:]:
|
| 652 |
+
index = int(field.split('/')[0])
|
| 653 |
+
if index == 0 or index < -vertices:
|
| 654 |
+
raise ValueError('invalid OBJ vertex index')
|
| 655 |
+
largest_index = max(largest_index, index)
|
| 656 |
+
faces += 1
|
| 657 |
+
elif fields[0] == 'mtllib':
|
| 658 |
+
materials.extend(shlex.split(line)[1:])
|
| 659 |
+
if not vertices or not faces or largest_index > vertices:
|
| 660 |
+
raise ValueError('empty or invalid mesh')
|
| 661 |
+
def dependency(parent, name):
|
| 662 |
+
dep = (parent / name).resolve()
|
| 663 |
+
if not dep.is_relative_to(asset_root) or not dep.is_file():
|
| 664 |
+
raise ValueError(f'missing or escaping asset dependency: {name}')
|
| 665 |
+
return dep
|
| 666 |
+
dependencies = []
|
| 667 |
+
for name in materials:
|
| 668 |
+
mtl = dependency(path.parent, name)
|
| 669 |
+
dependencies.append(mtl)
|
| 670 |
+
for line in mtl.read_text().splitlines():
|
| 671 |
+
fields = shlex.split(line, comments=True)
|
| 672 |
+
if fields and (fields[0].startswith('map_') or fields[0] in ('bump', 'norm', 'disp', 'decal')):
|
| 673 |
+
dependencies.append(dependency(mtl.parent, fields[-1]))
|
| 674 |
+
return {'vertices': vertices, 'faces': faces, 'sha256': sha256(path),
|
| 675 |
+
'dependencies': {p.relative_to(asset_root).as_posix(): sha256(p) for p in dependencies}}
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
def mesh_asset(view, oid, directory, obj, loc):
|
| 679 |
+
dest = view.path / f'annotation/object/{oid}/assets'
|
| 680 |
+
shutil.copytree(directory, dest)
|
| 681 |
+
ref = (dest / Path(obj).relative_to(directory)).relative_to(view.path).as_posix()
|
| 682 |
+
mesh_check = check_mesh(dest / Path(obj).relative_to(directory), dest)
|
| 683 |
+
view.build['validation'].append({'component': f'mesh_{oid}', **mesh_check})
|
| 684 |
+
view.component(f'mesh_{oid}', 'mesh/obj/v1', ref, ['vertex'], loc, valid=True, unit='m')
|
| 685 |
+
p = view.path / f'annotation/object/{oid}/metainfo.json'
|
| 686 |
+
info = json.loads(p.read_text())
|
| 687 |
+
info.update(has_model=True, mesh_ref=ref)
|
| 688 |
+
json_write(p, info)
|
| 689 |
+
|
| 690 |
+
|
| 691 |
+
def safe_member(root, name):
|
| 692 |
+
path = (Path(root) / name).resolve()
|
| 693 |
+
if not path.is_relative_to(Path(root).resolve()):
|
| 694 |
+
raise ValueError(f'unsafe archive path: {name}')
|
| 695 |
+
return path
|
| 696 |
+
|
| 697 |
+
|
| 698 |
+
class ChumpyStub:
|
| 699 |
+
def __setstate__(self, state):
|
| 700 |
+
self.__dict__.update(state)
|
| 701 |
+
|
| 702 |
+
|
| 703 |
+
class ManoUnpickler(pickle.Unpickler):
|
| 704 |
+
def find_class(self, module, name):
|
| 705 |
+
if module.startswith('chumpy'):
|
| 706 |
+
return ChumpyStub
|
| 707 |
+
return super().find_class(module, name)
|
| 708 |
+
|
| 709 |
+
|
| 710 |
+
def mano_models(directory):
|
| 711 |
+
result = {}
|
| 712 |
+
if directory is None:
|
| 713 |
+
return result
|
| 714 |
+
for side in ('left', 'right'):
|
| 715 |
+
path = Path(directory).expanduser() / f'MANO_{side.upper()}.pkl'
|
| 716 |
+
if not path.exists():
|
| 717 |
+
continue
|
| 718 |
+
with path.open('rb') as f:
|
| 719 |
+
data = ManoUnpickler(f, encoding='latin1').load()
|
| 720 |
+
result[side] = {'components': np.asarray(data['hands_components']),
|
| 721 |
+
'mean': np.asarray(data['hands_mean']), 'sha256': sha256(path),
|
| 722 |
+
'file': path.name}
|
| 723 |
+
return result
|
| 724 |
+
|
| 725 |
+
|
| 726 |
+
def model_profile(models):
|
| 727 |
+
identity = json.dumps({side: d['sha256'] for side, d in sorted(models.items())}).encode()
|
| 728 |
+
return {'version': 'sha256:' + hashlib.sha256(identity).hexdigest(), 'flat_hand_mean': True,
|
| 729 |
+
'left_shapedirs_correction': 'not_applied',
|
| 730 |
+
'models': {side: {'file': d['file'], 'sha256': d['sha256']} for side, d in models.items()}}
|
| 731 |
+
|
| 732 |
+
|
| 733 |
+
def pca_to_axis_angle(coeffs, model):
|
| 734 |
+
coeffs = np.asarray(coeffs)
|
| 735 |
+
if coeffs.shape[-1:] != (45,) or not np.isfinite(coeffs).all():
|
| 736 |
+
raise ValueError('invalid MANO PCA coefficients')
|
| 737 |
+
return coeffs @ model['components'] + model['mean']
|
| 738 |
+
|
| 739 |
+
|
| 740 |
+
def parser(dataset, description):
|
| 741 |
+
p = argparse.ArgumentParser(description=description)
|
| 742 |
+
p.add_argument('--root', f'--{dataset.lower()}-root', dest='root', type=Path, default=RAW_ROOT / dataset)
|
| 743 |
+
p.add_argument('--out', type=Path, default=Path('converted'))
|
| 744 |
+
p.add_argument('--release-id', default='v1.0')
|
| 745 |
+
p.add_argument('--limit', type=int, help='Maximum sequences to convert')
|
| 746 |
+
p.add_argument('--max-frames', type=int, help='First N source frame indices per view (recorded as sampling)')
|
| 747 |
+
p.add_argument('--mano-dir', type=Path)
|
| 748 |
+
p.add_argument('--views', help='Comma-separated source camera IDs')
|
| 749 |
+
p.add_argument('--jpeg-full-check', action='store_true', help='Full decoded RGB check for selected JPEG pilot/final views')
|
| 750 |
+
return p
|
| 751 |
+
|
| 752 |
+
|
| 753 |
+
def roots(root):
|
| 754 |
+
root = Path(root).expanduser()
|
| 755 |
+
return [p for p in (root / 'raw/data', root / 'raw', root) if p.is_dir()]
|
| 756 |
+
|
| 757 |
+
|
| 758 |
+
def find_file(root, name):
|
| 759 |
+
return next((p / name for p in roots(root) if (p / name).exists()), None)
|
| 760 |
+
|
| 761 |
+
|
| 762 |
+
def release(args, dataset):
|
| 763 |
+
if not args.release_id or Path(args.release_id).name != args.release_id or args.release_id in ('.', '..'):
|
| 764 |
+
raise ValueError('release-id must be a single directory name')
|
| 765 |
+
if args.limit is not None and args.limit < 1 or args.max_frames is not None and args.max_frames < 1:
|
| 766 |
+
raise ValueError('limits must be positive')
|
| 767 |
+
out = args.out.expanduser().resolve() / dataset / args.release_id
|
| 768 |
+
raw = args.root.expanduser().resolve()
|
| 769 |
+
if out == raw or out.is_relative_to(raw):
|
| 770 |
+
raise ValueError('output must not modify the raw source tree')
|
| 771 |
+
(out / 'data').mkdir(parents=True, exist_ok=True)
|
| 772 |
+
(out / 'doc').mkdir(exist_ok=True)
|
| 773 |
+
(out / 'script').mkdir(exist_ok=True)
|
| 774 |
+
scripts = list(Path(__file__).resolve().parent.glob('*.py'))
|
| 775 |
+
existing = {p.name for p in (out / 'script').glob('*.py')}
|
| 776 |
+
if existing and existing != {p.name for p in scripts}:
|
| 777 |
+
raise ValueError('converter files changed; choose a new --release-id')
|
| 778 |
+
copies = [(SCHEMA_PATH.parent / name, out / 'doc' / name) for name in ('CONTRACT.md', 'schema.json')]
|
| 779 |
+
copies += [(path, out / 'script' / path.name) for path in scripts]
|
| 780 |
+
# Check every existing file before changing any published definition or script.
|
| 781 |
+
for src, dest in copies:
|
| 782 |
+
if dest.exists() and sha256(dest) != sha256(src):
|
| 783 |
+
raise ValueError('converter or contract changed within an existing release; choose a new --release-id')
|
| 784 |
+
for src, dest in copies:
|
| 785 |
+
if src.resolve() != dest.resolve():
|
| 786 |
+
shutil.copyfile(src, dest)
|
| 787 |
+
json_write(out / 'script/config.json', {k: str(v) if isinstance(v, Path) else v for k, v in vars(args).items()})
|
| 788 |
+
return out
|
| 789 |
+
|
| 790 |
+
|
| 791 |
+
@contextmanager
|
| 792 |
+
def sequence_dir(out, sequence):
|
| 793 |
+
if Path(sequence).name != sequence:
|
| 794 |
+
raise ValueError('sequence ID must be a single path component')
|
| 795 |
+
final = out / 'data' / sequence
|
| 796 |
+
with tempfile.TemporaryDirectory(prefix=sequence + '.tmp-', dir=out / 'data') as wd:
|
| 797 |
+
tmp = Path(wd)
|
| 798 |
+
yield tmp
|
| 799 |
+
if final.exists():
|
| 800 |
+
if any((final / child.name).exists() for child in tmp.iterdir()):
|
| 801 |
+
raise FileExistsError('view already published; use a new release-id to preserve it')
|
| 802 |
+
for child in list(tmp.iterdir()):
|
| 803 |
+
child.rename(final / child.name)
|
| 804 |
+
else:
|
| 805 |
+
tmp.rename(final)
|
| 806 |
+
|
| 807 |
+
|
| 808 |
+
def build_record(out, sequence, reports):
|
| 809 |
+
path = out / 'doc' / (sequence + '.build.json')
|
| 810 |
+
previous = json.loads(path.read_text()) if path.exists() else {}
|
| 811 |
+
config = json.loads((out / 'script/config.json').read_text())
|
| 812 |
+
for report in reports.values():
|
| 813 |
+
report['configuration'] = config
|
| 814 |
+
json_write(path, {'sequence_id': sequence, 'storage_revision': SCHEMA['storage_revision'],
|
| 815 |
+
'scripts': {p.name: sha256(p) for p in (out / 'script').glob('*.py')},
|
| 816 |
+
'runtime': {'torch': torch.__version__, 'ffmpeg': ffversion()},
|
| 817 |
+
'views': previous.get('views', {}) | reports})
|
| 818 |
+
|
| 819 |
+
|
| 820 |
+
def check_view_type(meta):
|
| 821 |
+
# The pinned ARCTIC contract makes view_type optional; adapters still supply known views.
|
| 822 |
+
if 'view_type' not in meta:
|
| 823 |
+
return
|
| 824 |
+
if meta['view_type'] not in ('ego', 'exo', 'unknown'):
|
| 825 |
+
raise ValueError('view_type must be ego/exo/unknown')
|
| 826 |
+
expected = {'dex-ycb': 'exo', 'EPIC-KITCHENS-VISOR': 'ego', 'HOI4D': 'ego'}.get(meta['dataset_id'])
|
| 827 |
+
if meta['dataset_id'] == 'H2O':
|
| 828 |
+
expected = 'ego' if meta['camera_id'] == 'cam4' else 'exo' if meta['camera_id'] in ('cam0', 'cam1', 'cam2', 'cam3') else 'unknown'
|
| 829 |
+
if expected and meta['view_type'] not in (expected, 'unknown'):
|
| 830 |
+
raise ValueError('view_type contradicts known source capture setup')
|
| 831 |
+
|
| 832 |
+
|
| 833 |
+
def check_valid_policy(component, count):
|
| 834 |
+
policy = component.get('valid_policy', {})
|
| 835 |
+
for field in ('revision', 'meaning', 'source_rule', 'source_locator', 'scope', 'numerical_checks',
|
| 836 |
+
'official_qa', 'local_excluded_frame_indices', 'local_exclusion_reasons', 'visibility_independent'):
|
| 837 |
+
if field not in policy:
|
| 838 |
+
raise ValueError(f'valid_policy missing {field}')
|
| 839 |
+
if policy['revision'] != SCHEMA['validity_revision'] or policy['meaning'] != SCHEMA['annotation_validity']['meaning']:
|
| 840 |
+
raise ValueError('outdated annotation validity semantics')
|
| 841 |
+
if not policy['source_rule'] or not policy['numerical_checks'] or policy['scope'] != component['valid_axes']:
|
| 842 |
+
raise ValueError('incomplete validity rule/scope')
|
| 843 |
+
if policy['official_qa'].get('status') != 'not_provided' or not policy['official_qa'].get('reason'):
|
| 844 |
+
raise ValueError('official QA requires a verified adapter; supervision acceptance paused')
|
| 845 |
+
excluded = policy['local_excluded_frame_indices']
|
| 846 |
+
if any(type(i) is not int or not 0 <= i < count for i in excluded):
|
| 847 |
+
raise ValueError('invalid local exclusion frame index')
|
| 848 |
+
if excluded:
|
| 849 |
+
raise ValueError('local exclusions require a reviewed rule/report; not supported by these adapters')
|
| 850 |
+
if policy['visibility_independent'] is not True:
|
| 851 |
+
raise ValueError('visibility must remain independent of validity')
|
| 852 |
+
|
| 853 |
+
|
| 854 |
+
def validate_view(path):
|
| 855 |
+
"""Validate the persisted contract, not a rendering of the source labels."""
|
| 856 |
+
path = Path(path)
|
| 857 |
+
meta = json.loads((path / 'metainfo.json').read_text())
|
| 858 |
+
n = meta['num_frames']
|
| 859 |
+
check_view_type(meta)
|
| 860 |
+
if meta['schema_version'] != SCHEMA['schema_version'] or meta['hand_slots'] != ['left', 'right'] or n < 1:
|
| 861 |
+
raise ValueError('invalid view header')
|
| 862 |
+
def resolve(ref):
|
| 863 |
+
if Path(ref).is_absolute() or '\\' in ref:
|
| 864 |
+
raise ValueError('component reference must be relative POSIX')
|
| 865 |
+
dest = safe_member(path, ref)
|
| 866 |
+
if not dest.is_file():
|
| 867 |
+
raise ValueError(f'referenced file missing: {ref}')
|
| 868 |
+
return dest
|
| 869 |
+
def tensor(ref):
|
| 870 |
+
def cpu_storage(storage, location):
|
| 871 |
+
if location != 'cpu':
|
| 872 |
+
raise ValueError('PT storage must be on CPU')
|
| 873 |
+
return storage
|
| 874 |
+
value = torch.load(resolve(ref), map_location=cpu_storage, weights_only=True)
|
| 875 |
+
if not isinstance(value, torch.Tensor) or value.device.type != 'cpu':
|
| 876 |
+
raise ValueError('PT must contain only a CPU Tensor')
|
| 877 |
+
return value.numpy()
|
| 878 |
+
frames = [json.loads(line) for line in resolve(meta['sampling']['frames_ref']).read_text().splitlines()]
|
| 879 |
+
if len(frames) != n or [f['frame_index'] for f in frames] != list(range(n)):
|
| 880 |
+
raise ValueError('frame index/count mismatch')
|
| 881 |
+
for f in frames:
|
| 882 |
+
if not all(k in f for k in ('source_frame_id', 'timestamp_ns', 'clock_domain', 'source_locator')):
|
| 883 |
+
raise ValueError('incomplete frame provenance')
|
| 884 |
+
entities = {'hand_left', 'hand_right'}
|
| 885 |
+
parts = {}
|
| 886 |
+
for p in (path / 'annotation/object').glob('*/metainfo.json'):
|
| 887 |
+
obj = json.loads(p.read_text())
|
| 888 |
+
if obj['object_id'] != p.parent.name or obj['identity_scope'] not in ('frame', 'subsequence', 'sequence'):
|
| 889 |
+
raise ValueError('invalid object identity')
|
| 890 |
+
entities.add(obj['object_id'])
|
| 891 |
+
if obj.get('mesh_ref'):
|
| 892 |
+
if not resolve(obj['mesh_ref']).is_relative_to(p.parent.resolve()):
|
| 893 |
+
raise ValueError('mesh must belong to its object')
|
| 894 |
+
if obj.get('articulation_ref'):
|
| 895 |
+
art = json.loads(resolve(obj['articulation_ref']).read_text())
|
| 896 |
+
part_ids = {part['part_id'] for part in art['parts']}
|
| 897 |
+
if len(part_ids) != len(art['parts']):
|
| 898 |
+
raise ValueError('duplicate part ID')
|
| 899 |
+
parents = {part['part_id']: part['parent_id'] for part in art['parts']}
|
| 900 |
+
for part_id in parents:
|
| 901 |
+
visited, cur = set(), part_id
|
| 902 |
+
while cur is not None:
|
| 903 |
+
if cur in visited or cur not in parents:
|
| 904 |
+
raise ValueError('invalid or cyclic part hierarchy')
|
| 905 |
+
visited.add(cur)
|
| 906 |
+
cur = parents[cur]
|
| 907 |
+
parts[obj['object_id']] = part_ids
|
| 908 |
+
video_stats = {}
|
| 909 |
+
for key, component in meta['components'].items():
|
| 910 |
+
if not component.get('available'):
|
| 911 |
+
if not component.get('reason'):
|
| 912 |
+
raise ValueError('unavailable component needs a reason')
|
| 913 |
+
continue
|
| 914 |
+
schema = SCHEMA['components'][component['schema_id']]
|
| 915 |
+
for required in ('axes', 'provenance', 'source_locator'):
|
| 916 |
+
if required not in component:
|
| 917 |
+
raise ValueError(f'{key}: {required} missing')
|
| 918 |
+
for required in schema.get('required_metadata', []):
|
| 919 |
+
if required not in component:
|
| 920 |
+
raise ValueError(f'{key}: {required} missing')
|
| 921 |
+
if component['provenance']['kind'] == 'derived':
|
| 922 |
+
raise ValueError('v1.0 must not synthesize annotations')
|
| 923 |
+
if component['data_ref'].startswith('annotation/') and schema.get('valid_shape'):
|
| 924 |
+
if not component.get('valid_ref') or not component.get('valid_axes'):
|
| 925 |
+
raise ValueError(f'{key}: annotation validity reference/axes missing')
|
| 926 |
+
check_valid_policy(component, n)
|
| 927 |
+
data_path = resolve(component['data_ref'])
|
| 928 |
+
valid = tensor(component['valid_ref']) if component.get('valid_ref', '').endswith('.pt') else None
|
| 929 |
+
valid_shape = schema.get('valid_shape')
|
| 930 |
+
if valid is not None and valid_shape and (len(valid_shape) != valid.ndim or any(
|
| 931 |
+
isinstance(s, int) and valid.shape[i] != s for i, s in enumerate(valid_shape))):
|
| 932 |
+
raise ValueError(f'{key}: validity schema shape mismatch')
|
| 933 |
+
if valid is not None and (valid.dtype != bool or valid.shape[0] != n):
|
| 934 |
+
raise ValueError(f'{key}: invalid validity tensor')
|
| 935 |
+
if component['schema_id'] == 'mesh/obj/v1':
|
| 936 |
+
objroot = next((parent for parent in data_path.parents if parent.parent.name == 'object'), None)
|
| 937 |
+
if objroot is None:
|
| 938 |
+
raise ValueError('mesh must be owned by an object')
|
| 939 |
+
check_mesh(data_path, objroot)
|
| 940 |
+
if data_path.suffix == '.pt':
|
| 941 |
+
arr = tensor(component['data_ref'])
|
| 942 |
+
if arr.dtype != np.float32 or arr.shape[0] != n:
|
| 943 |
+
raise ValueError(f'{key}: float dtype or timeline mismatch')
|
| 944 |
+
shape = schema.get('shape')
|
| 945 |
+
if shape and (len(shape) != arr.ndim or any(isinstance(s, int) and arr.shape[i] != s for i, s in enumerate(shape))):
|
| 946 |
+
raise ValueError(f'{key}: schema shape mismatch')
|
| 947 |
+
if valid is not None:
|
| 948 |
+
if arr.shape[:valid.ndim] != valid.shape or not np.isfinite(arr[valid]).all() or not np.isnan(arr[~valid]).all():
|
| 949 |
+
raise ValueError(f'{key}: invalid finite/NaN/validity values')
|
| 950 |
+
if component['schema_id'] in ('object/rigid/v1', 'transform/se3/v1'):
|
| 951 |
+
check_transform(arr[valid])
|
| 952 |
+
if data_path.suffix == '.mkv':
|
| 953 |
+
cfg = component['storage']
|
| 954 |
+
if cfg['profile'] not in SCHEMA['storage_profiles']:
|
| 955 |
+
raise ValueError('unregistered video profile')
|
| 956 |
+
for field in SCHEMA['video_metadata']['required']:
|
| 957 |
+
if field not in cfg:
|
| 958 |
+
raise ValueError('video storage declaration incomplete')
|
| 959 |
+
w, h = meta['camera']['image_size']
|
| 960 |
+
if cfg['encoded_size'] != [w * (2 if key == 'depth' else 1), h]:
|
| 961 |
+
raise ValueError('encoded raster differs from logical RGB grid')
|
| 962 |
+
actual = probe(data_path)
|
| 963 |
+
if (actual['codec_name'] != cfg['codec'] or actual['pix_fmt'] != cfg['pixel_format'] or
|
| 964 |
+
[actual['width'], actual['height']] != cfg['encoded_size']):
|
| 965 |
+
raise ValueError('video storage metadata differs from file')
|
| 966 |
+
if key == 'rgb':
|
| 967 |
+
fmt, bpp = 'rgb24', 3
|
| 968 |
+
else:
|
| 969 |
+
fmt, bpp = 'gray16le', 2
|
| 970 |
+
digest, size, _ = decoded_digest(data_path, fmt)
|
| 971 |
+
w, h = cfg['encoded_size']
|
| 972 |
+
if size != n * w * h * bpp:
|
| 973 |
+
raise ValueError('raster timeline mismatch')
|
| 974 |
+
video_stats[key] = {'decoded_sha256': digest, 'frames': n}
|
| 975 |
+
if key == 'depth':
|
| 976 |
+
validity = component['valid_storage']
|
| 977 |
+
vp = resolve(component['valid_ref'])
|
| 978 |
+
actual_valid = probe(vp)
|
| 979 |
+
if (validity['profile'] != 'mkv/bool_ffv1/v1' or actual_valid['codec_name'] != 'ffv1'
|
| 980 |
+
or actual_valid['pix_fmt'] != 'gray' or [actual_valid['width'], actual_valid['height']] != [w // 2, h]):
|
| 981 |
+
raise ValueError('invalid depth validity video')
|
| 982 |
+
count = 0
|
| 983 |
+
for encoded, mask in zip(video_frames(data_path, 'gray16le', (h, w), '<u2'),
|
| 984 |
+
video_frames(vp, 'gray', (h, w // 2), np.uint8), strict=True):
|
| 985 |
+
if not np.isin(mask, [0, 1]).all():
|
| 986 |
+
raise ValueError('depth valid pixels must be 0 or 1')
|
| 987 |
+
depth, good = unpack_depth(encoded), mask.astype(bool)
|
| 988 |
+
if not (np.isfinite(depth[good]) & (depth[good] > 0)).all() or not np.isnan(depth[~good]).all():
|
| 989 |
+
raise ValueError('invalid depth/validity semantics')
|
| 990 |
+
count += 1
|
| 991 |
+
if count != n:
|
| 992 |
+
raise ValueError('depth validity timeline mismatch')
|
| 993 |
+
if component['schema_id'].startswith('segment/') and component.get('mapping_ref'):
|
| 994 |
+
rows = [json.loads(line) for line in resolve(component['mapping_ref']).read_text().splitlines()]
|
| 995 |
+
if len(rows) != n or [row['frame_index'] for row in rows] != list(range(n)):
|
| 996 |
+
raise ValueError('segmentation mapping timeline mismatch')
|
| 997 |
+
for row in rows:
|
| 998 |
+
labels = row['labels']
|
| 999 |
+
if len({a['mask_value'] for a in labels}) != len(labels):
|
| 1000 |
+
raise ValueError('duplicate region mapping')
|
| 1001 |
+
for label in labels:
|
| 1002 |
+
if label['entity_id'] is not None and label['entity_id'] not in entities:
|
| 1003 |
+
raise ValueError('unresolved segmentation entity')
|
| 1004 |
+
if label['part_id'] is not None and label['part_id'] not in parts.get(label['entity_id'], set()):
|
| 1005 |
+
raise ValueError('unresolved segmentation part')
|
| 1006 |
+
if component['schema_id'] == 'segment/uint16_labels/v1':
|
| 1007 |
+
width, height = meta['camera']['image_size']
|
| 1008 |
+
for i, mask in enumerate(video_frames(data_path, 'gray16le', (height, width), '<u2')):
|
| 1009 |
+
codes = set(np.unique(mask).tolist()) - {0, 65535}
|
| 1010 |
+
mapped = {label['mask_value'] for label in rows[i]['labels']} - {0, 65535}
|
| 1011 |
+
if codes != mapped or not valid[i] and codes:
|
| 1012 |
+
raise ValueError('mask values differ from declared instances/validity')
|
| 1013 |
+
if component['schema_id'] == 'segment/instance_polygons/v1':
|
| 1014 |
+
polygons = [json.loads(line) for line in data_path.read_text().splitlines()]
|
| 1015 |
+
if len(polygons) != n:
|
| 1016 |
+
raise ValueError('polygon timeline mismatch')
|
| 1017 |
+
for i, row in enumerate(polygons):
|
| 1018 |
+
if row['frame_index'] != i or {x['mask_value'] for x in row['instances']} != {x['mask_value'] for x in rows[i]['labels']}:
|
| 1019 |
+
raise ValueError('polygon/mapping mismatch')
|
| 1020 |
+
if component['schema_id'] == 'contact/relations/v1':
|
| 1021 |
+
rows = [json.loads(line) for line in data_path.read_text().splitlines()]
|
| 1022 |
+
if len(rows) != n:
|
| 1023 |
+
raise ValueError('relation timeline mismatch')
|
| 1024 |
+
for i, row in enumerate(rows):
|
| 1025 |
+
if row['frame_index'] != i or not valid[i] and row['relations']:
|
| 1026 |
+
raise ValueError('relation validity mismatch')
|
| 1027 |
+
for relation in row['relations']:
|
| 1028 |
+
if relation['subject_id'] not in entities or relation['status'] not in ('positive', 'negative', 'unknown', 'target_unannotated'):
|
| 1029 |
+
raise ValueError('invalid relation')
|
| 1030 |
+
if relation['status'] == 'positive' and relation['object_id'] not in entities:
|
| 1031 |
+
raise ValueError('unresolved positive contact')
|
| 1032 |
+
return {'view': str(path), 'num_frames': n, 'videos': video_stats, 'validated': True}
|