Datasets:
Download code/tools/normalize.py from VEHwang/cocogni4d: direct link, hf CLI and curl.
- Browser
- Download file 9.79 kB
-
https://huggingface.co/datasets/VEHwang/cocogni4d/resolve/main/code/tools/normalize.py
- Command line
-
hf download hf://datasets/VEHwang/cocogni4d/code/tools/normalize.py
-
curl -L -o normalize.py https://huggingface.co/datasets/VEHwang/cocogni4d/resolve/main/code/tools/normalize.py
9.79 kB
| #!/usr/bin/env python3 | |
| """Normalize local absolute paths / internal host names in the staged upload tree, keeping every sha256 binding valid. | |
| Usage: python3 -I normalize.py [--dry-run] (after stage.py; reads work/scan.json and work/graph.json) | |
| Rules (documented in code/tools/PATHS.md): | |
| - A local path that points to something shipped in this repo becomes a repo-root-relative path (e.g. | |
| assets/capability/<world>/objects.json, v0.2/scripts/<seg>/script.json). Anything not shipped becomes | |
| ${LOCAL}/<path below the workspace root>; the render host name becomes <render-host>. | |
| - Each changed file's new raw sha256 replaces its old one everywhere it is embedded; the two content fingerprints | |
| in facts.json (canonical script JSON; capability.json + static-bands.npz) are recomputed the same way. | |
| - Files are processed dependencies first. The original data is never written: the new bytes go to a new file that | |
| replaces the stage hard link (os.replace), so the source inode is untouched. ent400/* goes to the SHM root, | |
| everything else to the DISK root (the stale link in the other root is removed). | |
| - code/evaluation-code/** is a commit snapshot and is left as is, except the four endpoint configs whose gateway | |
| URL becomes a placeholder. | |
| """ | |
| import collections as C, hashlib, json, os, re, sys | |
| from pathlib import Path | |
| H = Path('${LOCAL}/simulation-workspace/runs/hf-release-20261120') | |
| DISK = H / 'stage'; SHM = Path('${LOCAL}/shm/ent400/hf-release-20261120/stage') | |
| DRY = '--dry-run' in sys.argv | |
| ABS = re.compile(r'(?:${LOCAL}|${LOCAL}|${LOCAL}|${LOCAL}/data|${LOCAL}/shm)(?:/[^"\'\s<>|,;:)\]}\\]*)?') # ':' ends a path (PATH-like lists) | |
| HOST = re.compile(r'dsw-\d+(?:-[0-9a-z]+){0,2}') | |
| GATEWAY = re.compile(r'https://<gateway>') | |
| ENDPOINT_FILES = ('tools/evaluation/endpoints.example.json', 'tools/evaluation/campaigns/api-final.endpoints.json') | |
| SEG = r'(p\d_H\d\d-[^/]+)' | |
| W = r'(\d{9}(?:_\d{9})?)' | |
| def where(rel): | |
| for r in (DISK, SHM): | |
| if (r / rel).is_file() or (r / rel).is_dir(): | |
| return r / rel | |
| return None | |
| HOUSES = json.load(open(DISK / 'assets/houses.json')) | |
| SHORT2W = {h['world'].split('_')[0]: h['world'] for h in HOUSES} | |
| STAGED_ACTORS = {'habitat-humanoid-textured-v2', 'laikago-bullet-3.2.7-v2', 'laikago-red-bullet-3.2.7-v1'} | |
| def shipped(rel): | |
| return rel if where(rel) is not None else None | |
| def map_path(p): | |
| """Absolute local path -> repo-relative path (if shipped) or ${LOCAL}/... placeholder.""" | |
| q = p | |
| for a in ('${LOCAL}', '${LOCAL}'): | |
| if q == a or q.startswith(a + '/'): | |
| q = '${LOCAL}' + q[len(a):]; break | |
| rules = [ | |
| (r'${LOCAL}/simulation-workspace/assets/actors/([^/]+)(/.*)?$', | |
| lambda m: f'assets/actors/source/{m[1]}{m[2] or ""}' if m[1] in STAGED_ACTORS else None), | |
| (rf'${LOCAL}/simulation-workspace/assets/scenes/hssd-{W}-v1(/.*)?$', lambda m: f'assets/hssd-source/{m[1]}{m[2] or ""}'), | |
| (rf'${LOCAL}/agent-jobs/P1/capability-new/{W}(/.*)?$', lambda m: f'assets/capability/{m[1]}{m[2] or ""}'), | |
| (r'${LOCAL}/simulation-workspace/runs/(?:isaac-scenes-20261110/(?:scenes|scenes-approved|candidates/scenes)|isaac-backend-20261023)/scene-(\d+)-fixmat-v2(/.*)?$', | |
| lambda m: f'assets/isaac-scenes/{SHORT2W[m[1]]}{m[2] or ""}' if m[1] in SHORT2W else None), | |
| (r'${LOCAL}/simulation-workspace/runs/isaac-backend-20261023/actors-v2(/.*)?$', lambda m: f'assets/actors/isaac/humanoids-v2{m[1] or ""}'), | |
| (r'${LOCAL}/simulation-workspace/runs/isaac-backend-20261023/quadruped-v2(/.*)?$', lambda m: f'assets/actors/isaac/laikago-v2{m[1] or ""}'), | |
| (r'${LOCAL}/simulation-workspace/runs/ent400-isaac-render/quadruped-red-v1(/.*)?$', lambda m: f'assets/actors/isaac/laikago-red-v1{m[1] or ""}'), | |
| (rf'${LOCAL}/agent-jobs/W59-release/np-bench-v0.2/batches/[^/]+/segs/{SEG}(/.*)?$', lambda m: f'v0.2/scripts/{m[1]}{m[2] or ""}'), | |
| (rf'${LOCAL}/agent-jobs/W59-release/(?:ent400-prev-1112|np-bench-v0.2/ent400)/batches/[^/]+/segs/{SEG}(/.*)?$', lambda m: f'ent400/scripts/{m[1]}{m[2] or ""}'), | |
| ] | |
| for part, base in (('v0.2', r'${LOCAL}/simulation-workspace/runs/v02-isaac-render'), | |
| ('ent400', r'(?:${LOCAL}/shm/ent400/render|${LOCAL}/simulation-workspace/runs/ent400-isaac-render)')): | |
| rules += [ | |
| (rf'{base}/g\d/renders/{SEG}/(?:\.partial|observation)/videos/([^/]+\.mp4)$', lambda m, P=part: f'{P}/media/videos/{m[1]}/{m[2]}'), | |
| (rf'{base}/g\d/renders/{SEG}/(\.partial|observation)(/.*)?$', lambda m, P=part: f'{P}/render/{m[1]}/{m[2].lstrip(".")}{m[3] or ""}'), | |
| (rf'{base}/g\d/renders/{SEG}(/[^/]+)?$', lambda m, P=part: f'{P}/render/{m[1]}{m[2] or ""}'), | |
| (rf'{base}/g\d/fixtures/{SEG}/spec\.json$', lambda m, P=part: f'{P}/render/{m[1]}/render-spec.json'), | |
| (rf'{base}/g\d/scripts/{SEG}(/.*)?$', lambda m, P=part: f'{P}/scripts/{m[1]}{m[2] or ""}'), | |
| ] | |
| for pat, f in rules: | |
| m = re.match(pat, q) | |
| if m: | |
| rel = f(m) | |
| if rel and shipped(rel.rstrip('/')): | |
| return rel | |
| break | |
| for root, ph in (('${LOCAL}', '${LOCAL}'), ('${LOCAL}/shm', '${LOCAL}/shm'), ('${LOCAL}/data', '${LOCAL}/data')): | |
| if q == root or q.startswith(root + '/'): | |
| return ph + q[len(root):] | |
| return q | |
| PATHMAP = C.Counter() | |
| def norm_text(t, rel): | |
| def sub(m): | |
| new = map_path(m[0]); PATHMAP[(re.sub(r'/(?:p\d_H\d\d-[^/]+|\d{9}(?:_\d{9})?|[0-9a-f]{64})(?=/|$)', '/<X>', m[0])[:90], | |
| re.sub(r'/(?:p\d_H\d\d-[^/]+|\d{9}(?:_\d{9})?|[0-9a-f]{64})(?=/|$)', '/<X>', new)[:90])] += 1 | |
| return new | |
| if rel.startswith('code/evaluation-code/'): | |
| return GATEWAY.sub('https://<your-openai-compatible-gateway>', t) if rel.endswith(ENDPOINT_FILES) else t | |
| t = ABS.sub(sub, t) | |
| return HOST.sub('<render-host>', t) | |
| sha = lambda b: hashlib.sha256(b).hexdigest() | |
| canon = lambda o: json.dumps(o, sort_keys=True, ensure_ascii=False).encode() | |
| def main(): | |
| scan = {x['rel']: x for x in json.load(open(H / 'work/scan.json'))} | |
| g = json.load(open(H / 'work/graph.json')) | |
| todo = [r for r in g['changed'] if not r.startswith('code/evaluation-code/') or r.endswith(ENDPOINT_FILES)] | |
| todo_set = set(todo) | |
| deps = {r: set(g['edges'].get(r, [])) & todo_set for r in todo} | |
| for r in todo: # facts.json fingerprints depend on the script and the capability table | |
| if r.endswith('/facts.json'): | |
| d = r.rsplit('/', 1)[0]; deps[r].add(d + '/script.json') | |
| world = json.loads((Path(scan[r]['root']) / (d + '/script.json')).read_bytes())['world_id'] | |
| deps[r].add(f'assets/capability/{world}/capability.json') | |
| deps = {r: {x for x in v if x in todo_set and x != r} for r, v in deps.items()} | |
| order, seen = [], set() | |
| def visit(u, st=()): | |
| if u in seen: return | |
| if u in st: raise RuntimeError('cycle at ' + u) | |
| for v in sorted(deps.get(u, ())): visit(v, st + (u,)) | |
| seen.add(u); order.append(u) | |
| for r in sorted(todo): visit(r) | |
| # digests of files to change must not equal the digest of any file that stays (string replacement would misfire) | |
| old_raw = {} | |
| for r in order: | |
| old_raw[r] = sha((Path(scan[r]['root']) / r).read_bytes()) | |
| stay = {} | |
| for rel, x in scan.items(): | |
| if rel in todo_set: continue | |
| if x['size'] < 50_000_000 and rel.endswith(('.json', '.jsonl', '.usda', '.py', '.md', '.txt', '.tsv', '.log', '.usd', '.npz', '.npy')): | |
| stay[sha((Path(x['root']) / rel).read_bytes())] = rel | |
| clash = [r for r, d in old_raw.items() if d in stay] | |
| if clash: | |
| raise SystemExit(f'digest clash with unchanged files: {clash[:5]}') | |
| rep = {} # old digest -> new digest | |
| stats = C.Counter(); written = 0 | |
| for i, r in enumerate(order): | |
| src = Path(scan[r]['root']) / r | |
| b = src.read_bytes(); t = b.decode('utf-8') | |
| nt = norm_text(t, r) | |
| hs = set(re.findall(r'(?<![0-9a-f])[0-9a-f]{64}(?![0-9a-f])', nt)) | |
| for h in hs & rep.keys(): | |
| nt = nt.replace(h, rep[h]); stats['digest_replaced'] += 1 | |
| nb = nt.encode('utf-8') | |
| if r.endswith('/script.json'): | |
| rep[sha(canon(json.loads(b)))] = sha(canon(json.loads(nb))) | |
| if r.endswith('/capability.json'): | |
| sb = (where(r.rsplit('/', 1)[0] + '/static-bands.npz')).read_bytes() | |
| rep[sha(b + sb)] = sha(nb + sb) | |
| new = sha(nb) | |
| if new != old_raw[r]: | |
| rep[old_raw[r]] = new | |
| if nb == b: | |
| stats['unchanged'] += 1; continue | |
| stats['rewritten'] += 1 | |
| if DRY: continue | |
| root = SHM if r.startswith('ent400/') else DISK | |
| other = DISK if root is SHM else SHM | |
| dst = root / r; dst.parent.mkdir(parents=True, exist_ok=True) | |
| # os.replace swaps only the stage directory entry; the inode it pointed to (the original file) is not modified | |
| tmp = dst.with_name(dst.name + '.norm-tmp') | |
| tmp.write_bytes(nb); os.replace(tmp, dst); written += len(nb) | |
| if (other / r).exists(): | |
| os.unlink(other / r) # removes only the stage link name; the source file is untouched | |
| if i % 500 == 0: | |
| print(f'{i}/{len(order)} {written / 1e9:.1f} GB', flush=True) | |
| json.dump(dict(rep=rep, order=order), open(H / 'work/normalize-digests.json', 'w')) | |
| lines = ['| 原路径(模式) | 上传后 | 次数 |', '|---|---|---:|'] + [f'| `{a}` | `{b}` | {n} |' for (a, b), n in PATHMAP.most_common()] | |
| (H / 'work/path-map.md').write_text('\n'.join(lines) + '\n') | |
| print(dict(stats), 'digests remapped', len(rep), 'written %.2f GB' % (written / 1e9)) | |
| if __name__ == '__main__': | |
| main() | |