Files
hand-motion-pipeline/scripts/check_pipeline_resources.py

163 lines
7.7 KiB
Python

#!/usr/bin/env python3
"""Check local RGB-D pipeline assets without importing GPU packages.
Use --prepare-example to expose a nested recording through relative symlinks.
This never downloads models, overwrites existing paths, or loads pickle files.
"""
import argparse
import json
from pathlib import Path
import sys
sys.path.insert(0, str(Path(__file__).resolve().parent))
from external_resources import load_resources
ROOT = Path(__file__).resolve().parents[1]
LFS_HEADER = b'version https://git-lfs.github.com/spec/v1'
def is_pointer(path):
with path.open('rb') as stream:
return stream.read(len(LFS_HEADER)) == LFS_HEADER
def prepare_recording(recording):
"""Make the existing nested layout usable without moving the source data."""
nested = recording / recording.name
planned = []
for name in ('color.mp4', 'depth', 'intrinsics.json'):
target, source = recording / name, nested / name
if target.exists():
continue
if target.is_symlink():
raise ValueError(f'Broken link; inspect it before retrying: {target}')
if not source.exists():
raise ValueError(f'Missing recording asset: {target}; run git lfs pull or provide the recording.')
planned.append((target, source))
# Check all sources first, so a missing input cannot leave partial links.
for target, source in planned:
target.symlink_to(source.relative_to(recording), target_is_directory=source.is_dir())
print(f'LINK {target.name} -> {source.relative_to(recording)}')
def check_recording(recording):
errors = []
color, depth, metadata = [recording / name for name in ('color.mp4', 'depth', 'intrinsics.json')]
for path in (color, metadata):
if not path.is_file():
errors.append(f'Missing {path}; use --prepare-example for the nested bundled layout.')
elif is_pointer(path):
errors.append(f'Git LFS pointer instead of data: {path}; run git lfs pull.')
elif path.stat().st_size == 0:
errors.append(f'Empty file: {path}')
if not depth.is_dir():
errors.append(f'Missing depth directory: {depth}; use --prepare-example if the recording is nested.')
if errors:
return errors
try:
meta = json.loads(metadata.read_text())
frames = int(meta['frames'])
if frames <= 0:
raise ValueError('frames must be positive')
for index in range(frames):
path = depth / f'{index:06d}.png'
if not path.is_file() or path.stat().st_size == 0:
errors.append(f'Missing/empty depth frame: {path}')
break
if is_pointer(path):
errors.append(f'Git LFS pointer instead of depth: {path}; run git lfs pull.')
break
except (ValueError, KeyError, TypeError) as exc:
errors.append(f'Invalid recording metadata {metadata}: {exc}')
return errors
def check_assets(root, require_left=False):
required = [
'third_party/hamer/_DATA/data/mano/MANO_RIGHT.pkl',
'third_party/hamer/_DATA/hamer_ckpts/checkpoints/hamer.ckpt',
'third_party/Dyn-HaMR/third-party/hamer/pretrained_models/detector.pt',
'third_party/Dyn-HaMR/_DATA/hmp_model/results/model/local_encoder.pth',
'third_party/Dyn-HaMR/_DATA/hmp_model/results/model/nemf.pth',
'third_party/Dyn-HaMR/_DATA/BMC/joint_angles.npy',
'docs/上半.stl', 'docs/下半.stl',
]
if require_left:
required.append('third_party/hamer/_DATA/data/mano/MANO_LEFT.pkl')
for side in ('left', 'right'):
required.append(f'third_party/l20_assets/L20/{side.upper()}/linkerhand_g20_{side}.urdf')
for checkpoint in ('2023-10-28-18-33-37', '2024-01-11-20-02-45'):
required.extend(f'third_party/FoundationPose/weights/{checkpoint}/{name}' for name in ('config.yml', 'model_best.pth'))
errors = []
external = {}
external_entries = {}
if (root / 'configs/external_resources.json').is_file():
for group in load_resources(root):
if group['scope'] == 'rgbd':
for entry in group['files']:
external[entry['path']] = group
external_entries[entry['path']] = entry
required = list(dict.fromkeys([*required, *external]))
by_id = {group['id']: group for group in load_resources(root)}
aliases = {
'third_party/Dyn-HaMR/third-party/hamer/pretrained_models/detector.pt': 'detector',
'third_party/Dyn-HaMR/_DATA/BMC/joint_angles.npy': 'bmc',
}
for path, group_id in aliases.items():
if group_id in by_id:
external[path] = by_id[group_id]
manifest_path = root / 'configs/large_files.json'
manifest = json.loads(manifest_path.read_text()) if manifest_path.is_file() else {'files': []}
expected = {entry['path']: entry['bytes'] for entry in manifest['files']}
expected.update({path: entry['bytes'] for path, entry in external_entries.items() if 'bytes' in entry})
for relative in required:
path = root / relative
if not path.is_file() or path.stat().st_size == 0:
if relative in external:
group = external[relative]
action = f"Obtain locally from {group['source_url']}; see docs/EXTERNAL_RESOURCES.md."
else:
action = 'Provide your MANO model; see docs/EXTERNAL_RESOURCES.md.' if path.suffix == '.pkl' else 'Run git lfs pull for redistributable assets.'
errors.append(f'Missing/empty {relative}. {action}')
elif is_pointer(path):
action = f"Obtain from {external[relative]['source_url']}" if relative in external else 'Run git lfs pull'
errors.append(f'Git LFS pointer: {relative}; {action}.')
elif relative in expected and path.stat().st_size != expected[relative]:
errors.append(f'Wrong reference size: {relative}; check configs/external_resources.json and run external_resources.py check --verify-sha256. Regenerated BMC data may differ; review explicitly.')
for side in ('LEFT', 'RIGHT'):
directory = root / f'third_party/l20_assets/L20/{side}/meshes'
meshes = list(directory.rglob('*.stl')) + list(directory.rglob('*.STL'))
if not meshes:
errors.append(f'Missing L20 meshes: {directory}')
elif any(is_pointer(path) for path in meshes):
errors.append(f'Git LFS pointers in L20 {side} meshes; run git lfs pull.')
return errors
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--recording', type=Path, default=ROOT / 'docs/20260915_171525')
parser.add_argument('--prepare-example', action='store_true', help='Create missing relative links from the nested recording directory; preserve originals.')
parser.add_argument('--recording-only', action='store_true', help='Check/prepare recording layout without requiring model assets.')
parser.add_argument('--require-left-mano', action='store_true', help='Also require MANO_LEFT.pkl for branches which use a separate left model.')
args = parser.parse_args()
recording = args.recording.expanduser().resolve()
try:
if args.prepare_example:
prepare_recording(recording)
errors = check_recording(recording)
if not args.recording_only:
errors.extend(check_assets(ROOT, args.require_left_mano))
except (OSError, ValueError, KeyError, TypeError) as exc:
errors = [str(exc)]
for error in errors:
print(f'FAIL {error}')
if errors:
return 1
print('PASS recording layout and local asset files; model validity, GPU runtime, pose accuracy and grasp success require separate checks.')
return 0
if __name__ == '__main__':
raise SystemExit(main())