Hand-Datasets-Raw / HOT3D /shared-v1.1 /script /migrate_hot3d.py
orz2333's picture
Migrate HOT3D, OakInk-v1, OakInk-v2 and FreiHAND to shared-v1.1 (#4)
10ed3aa
Raw History Blame Contribute Delete
11.4 kB
#!/usr/bin/env python3
"""Repack pinned HOT3D shared-v1.0 inputs into a non-media v1.1 staging tree.
No download, source deletion, geometry reconstruction, or HF upload. Unchanged
media/assets remain an explicit publisher reuse plan until separately assembled.
"""
import argparse
from collections import Counter
import fcntl
import hashlib
import json
from pathlib import Path
import shutil
import time
import torch
from hot3d_bundle import at, audit_view, check_field, exact, fields, new_metadata, safe_path
REVISION = "54c1bc812b903c2f2b933472163998924588681f"
PILOT = {"P0015_179e1b84", "P0004_1984bf99"}
def write_json(path, obj):
path = Path(path); path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_name(path.name + ".writing")
tmp.write_text(json.dumps(obj, ensure_ascii=False, indent=2) + "\n")
tmp.replace(path)
def digest(path, algorithm="sha256"):
size = path.stat().st_size
h = hashlib.sha1(f"blob {size}\0".encode()) if algorithm == "git_blob_sha1" else hashlib.sha256()
with path.open("rb") as stream:
for chunk in iter(lambda: stream.read(2**20), b""):
h.update(chunk)
return h.hexdigest()
def verify(path, row):
if not path.is_file() or path.stat().st_size != row['size'] or digest(path, row['algorithm']) != row['digest']:
raise ValueError(f"Pinned source size/digest mismatch: {path}")
def atomic_copy(source, target):
target.parent.mkdir(parents=True, exist_ok=True)
tmp = target.with_name(target.name + '.copying')
shutil.copy2(source, tmp)
tmp.replace(target)
def migrate(workspace, scope, revalidate_tools=False):
torch.set_num_threads(1)
workspace = Path(workspace).resolve()
source = workspace/'source/HOT3D/shared-v1.0'
state = workspace/'tmp/hot3d-migration-20261014'/scope
state.mkdir(parents=True, exist_ok=True)
target = workspace/('tmp/hot3d-migration-20261014/pilot/shared-v1.1' if scope == 'pilot' else 'staging/HOT3D/shared-v1.1')
if target.resolve() == source.resolve() or target.resolve().is_relative_to(source.resolve()):
raise ValueError('Never migrate inside the read-only source cache')
manifest_path = workspace/'tmp/remaining-preparation-20261014/HOT3D-manifest.json'
manifest = json.loads(manifest_path.read_text())
if manifest['revision'] != REVISION or manifest['dataset'] != 'HOT3D':
raise ValueError('Wrong fixed source')
registry_path = workspace/'spec/hand-warehouse-1.1/schema.json'
registry = json.loads(registry_path.read_text())
binding = {'source_revision': REVISION, 'source_manifest_sha256': digest(manifest_path),
'schema_sha256': digest(registry_path),
'tools': {p: digest(Path(__file__).parent/p) for p in ['migrate_hot3d.py','hot3d_bundle.py']}}
lock = (state.parent/'migration.lock').open('a+')
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
binding_path = state/'binding.json'
previous_binding = json.loads(binding_path.read_text()) if binding_path.exists() else None
if previous_binding is not None and previous_binding != binding:
if not revalidate_tools or any(previous_binding[k] != binding[k] for k in ['source_revision','source_manifest_sha256','schema_sha256']):
raise ValueError('Resume source/tool binding changed; review before --revalidate-tools')
# Explicitly reviewed tool-only upgrade: old checkpoints/hashes must
# still match and all views are compared again. Adopt only on success.
write_json(state/'binding-before-revalidation.json', previous_binding)
if not binding_path.exists() and target.exists():
raise ValueError('Existing unregistered staging tree; do not overwrite')
if previous_binding is None:
write_json(binding_path, binding)
started = time.monotonic()
entries = [r for r in manifest['files'] if scope == 'all' or not r['relative'].startswith('data/') or r['relative'].split('/')[1] in PILOT]
selected = [r for r in entries if r['action'].startswith('download_')]
status = {'phase': 'verifying_inputs', 'scope': scope, 'source_revision': REVISION,
'complete_release': False, 'verified_views': 0}
write_json(state/'status.json', status)
for i, row in enumerate(selected,1):
verify(source/row['relative'],row)
if i % 2000 == 0: print(f'input hashes {i}/{len(selected)}',flush=True)
metas = sorted(r['relative'] for r in entries if r['relative'].startswith('data/') and len(Path(r['relative']).parts)==4 and r['relative'].endswith('/metainfo.json'))
expected_views = 6 if scope == 'pilot' else 594
if len(metas) != expected_views:
raise ValueError(f'Expected {expected_views} complete views, got {len(metas)}')
expected_new, removed, plans = set(), set(), {}
for relative in metas:
old = json.loads((source/relative).read_text())
new = new_metadata(old)
v = Path(relative).parent
fs = fields(old)
for f in fs:
c = at(old,f['locator'])
removed.update((v/c[k]).as_posix() for k in ['data_ref','valid_ref'])
expected_new.add((v/f['bundle']).as_posix())
plans[v.as_posix()] = (old,new,fs)
# Precisely retain RGB validity; asset validity belongs to unchanged assets.
selected_data = {r['relative']: r for r in selected if r['relative'].startswith('data/')}
actual_pt = {r for r in selected_data if r.endswith('.pt')}
retained_pt = {str(Path(r).parent/'observation/rgb_valid.pt') for r in metas}
if actual_pt != removed | retained_pt:
raise ValueError(f'Unclassified numerical input: {sorted(actual_pt ^ (removed | retained_pt))[:10]}')
write_json(state/'plan.json', {'binding': binding, 'views': list(plans),
'replaced_source_files': sorted(removed), 'new_bundle_files': sorted(expected_new),
'deferred_unchanged': [r for r in entries if r['action'].startswith('defer_')],
'source_preserved': True, 'target_is_non_media_stage': True})
for rel, row in selected_data.items():
if rel in removed or rel in metas: continue
destination = target/rel
if destination.exists(): verify(destination,row)
else: atomic_copy(source/rel,destination)
rows = []
status.update(phase='migrating', verified_input_files=len(selected), total_views=len(metas))
write_json(state/'status.json', status)
for v,(old,new,fs) in plans.items():
old_view, new_view = source/v, target/v
cp = state/'checkpoints'/f"{old['sequence_id']}__{old['camera_id']}.json"
if cp.exists():
checkpoint = json.loads(cp.read_text())
for ref, sha in checkpoint['outputs'].items():
if digest(new_view/ref) != sha: raise ValueError(f'Resume output changed: {v}/{ref}')
else:
bundles = {}
for f in fs:
c = at(old,f['locator'])
data = torch.load(safe_path(old_view,c['data_ref']),map_location='cpu',weights_only=True)
valid = torch.load(safe_path(old_view,c['valid_ref']),map_location='cpu',weights_only=True)
check_field(data,valid,f,c,old['num_frames'],registry)
bundles.setdefault(f['bundle'],{})[f['entry']] = {'data':data,'valid':valid}
for ref,bundle in bundles.items():
path = safe_path(new_view,ref); path.parent.mkdir(parents=True,exist_ok=True)
tmp = path.with_name(path.name+'.writing'); torch.save(bundle,tmp)
reread = torch.load(tmp,map_location='cpu',weights_only=True)
if set(reread) != set(bundle) or any(not exact(bundle[k][kind],reread[k][kind]) for k in bundle for kind in ['data','valid']):
raise ValueError('Tensor bytes changed in serialization')
tmp.replace(path)
write_json(new_view/'metainfo.json',new)
result = audit_view(new_view,registry,source=old_view)
outputs = {ref:digest(new_view/ref) for ref in sorted({f['bundle'] for f in fs}|{'metainfo.json'})}
write_json(cp,{'view':v,'outputs':outputs,'verification':result})
rows.append({'view':v,**result})
status.update(verified_views=len(rows),current_view=v,elapsed_seconds=round(time.monotonic()-started,2))
write_json(state/'status.json',status)
if len(rows)%20==0 or scope=='pilot':print(f'verified {len(rows)}/{len(plans)} {v}',flush=True)
# Independently check full output path set and unchanged bytes, including frame maps.
expected_data = (set(selected_data)-removed)|expected_new
actual_data = {p.relative_to(target).as_posix() for p in (target/'data').rglob('*') if p.is_file()}
if actual_data != expected_data:
raise ValueError(f'Output file set differs: {sorted(actual_data ^ expected_data)[:10]}')
for rel,row in selected_data.items():
verify(source/rel,row)
if rel not in removed and rel not in metas:verify(target/rel,row)
counts=Counter();frames=Counter()
for row in rows:
counts[row['split']]+=1;frames[row['split']]+=row['frames']
deferred = [r for r in entries if r['action'].startswith('defer_')]
report = {'source_revision':REVISION,'scope':scope,'views':len(rows),'sequences':len({r['sequence'] for r in rows}),
'split_views':dict(counts),'split_frames':dict(frames),'fields':sum(len(r['fields']) for r in rows),
'old_numeric_files':len(removed),'new_bundles':len(expected_new),'source_files_verified':len(selected),
'data_files_present':len(actual_data),'exact_data_valid_bytes':True,'unchanged_source_hashes':True,
'unchanged_other_data_hashes':True,'metadata_only_version_storage_changed':True,
'deferred_files':len(deferred),'deferred_bytes':sum(r['size'] for r in deferred),
'complete_release':False,'media_visual_review':'separate_required',
'elapsed_seconds':round(time.monotonic()-started,2),'per_view':rows}
write_json(state/'report.json',report)
output_hashes = [{'path':r,'size':(target/r).stat().st_size,'sha256':digest(target/r)} for r in sorted(actual_data)]
write_json(state/'output-data-manifest.json',{'binding':binding,'files':output_hashes})
write_json(binding_path,binding)
status.update(phase='numerical_stage_verified',complete_release=False,total_fields=report['fields'])
write_json(state/'status.json',status)
print(json.dumps({k:v for k,v in report.items() if k!='per_view'},ensure_ascii=False,indent=2),flush=True)
return target
def main():
p=argparse.ArgumentParser(description=__doc__)
p.add_argument('--workspace',type=Path,required=True)
p.add_argument('--scope',choices=['pilot','all'],default='pilot')
p.add_argument('--revalidate-tools',action='store_true',help='explicit reviewed tool-only upgrade; recheck all source/checkpoint/output bytes before adopting new hashes')
a=p.parse_args()
try: migrate(a.workspace,a.scope,a.revalidate_tools)
except Exception as exc:
status_path=a.workspace/'tmp/hot3d-migration-20261014'/a.scope/'status.json'
if status_path.exists():
status=json.loads(status_path.read_text());status.update(phase='failed',error=str(exc));write_json(status_path,status)
raise
if __name__=='__main__':main()