File size: 6,737 Bytes
7ff74f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#!/usr/bin/env python3
"""Upload the staged release to VEHwang/cocogni4d through hf-mirror.com (user-approved repo; own token in /root/.hf-own).

Usage: HF_HOME=/root/.hf-own HF_ENDPOINT=https://hf-mirror.com /root/hf-venv/bin/python upload.py [--phase A|B|C|all]
Re-running resumes: phase A relies on `hf upload` resume, phase B skips zips already on the Hub with the same sha256.

A  everything except assets/isaac-scenes/** and assets/hssd-source/** (loose files, from the merged view /tmp/hfview)
B  per house: build a deterministic stored zip of assets/{isaac-scenes,hssd-source}/<world>/ in work/zips/
   (entries <world>/..., sorted, fixed timestamp), upload it as assets/<kind>/<world>.zip, delete the local zip.
   At most one zip on disk at a time (largest ~1 GB).
C  write assets/ZIPS.sha256, upload it; remove the loose probe copy assets/isaac-scenes/106366173_174226431/** from the
   repo (uploaded during the speed test, now replaced by its zip); verify every repo file against the local manifests.
"""
import hashlib, json, os, subprocess, sys, time, zipfile
from pathlib import Path
from huggingface_hub import HfApi

REPO = 'VEHwang/cocogni4d'; RT = 'dataset'
H = Path('${LOCAL}/simulation-workspace/runs/hf-release-20261120')
VIEW = Path('/tmp/hfview'); ZIPDIR = H / 'work/zips'; LOG = H / 'work/upload.log'
DISK = H / 'stage'
KINDS = ('isaac-scenes', 'hssd-source')
api = HfApi()


def log(msg):
    line = time.strftime('%m-%d %H:%M:%S ') + msg
    print(line, flush=True)
    with open(LOG, 'a') as f:
        f.write(line + '\n')


def sha(p):
    h = hashlib.sha256()
    with open(p, 'rb') as f:
        for b in iter(lambda: f.read(1 << 22), b''):
            h.update(b)
    return h.hexdigest()


def remote():
    info = api.repo_info(REPO, repo_type=RT, files_metadata=True)
    return {s.rfilename: (s.size, getattr(s.lfs, 'sha256', None) if s.lfs is not None else None) for s in info.siblings}


def phase_a():
    log('phase A: loose files')
    cmd = ['/root/hf-venv/bin/hf', 'upload', REPO, '.', '.', '--repo-type', RT,
           '--exclude', 'assets/isaac-scenes/**', '--exclude', 'assets/hssd-source/**',
           '--commit-message', 'Upload CoCogni4D-Bench (questions, media, scripts, render records, code)']
    t0 = time.time()
    r = subprocess.run(cmd, cwd=VIEW, stdout=open(H / 'work/upload-A.log', 'a'), stderr=subprocess.STDOUT)
    log(f'phase A rc={r.returncode} wall={time.time() - t0:.0f}s')
    if r.returncode:
        sys.exit('phase A failed; re-run to resume')


def make_zip(kind, world):
    src = VIEW / 'assets' / kind / world
    out = ZIPDIR / f'{kind}--{world}.zip'
    ZIPDIR.mkdir(parents=True, exist_ok=True)
    files = sorted(str(p.relative_to(src.parent)) for p in src.rglob('*') if p.is_file())
    tmp = out.with_suffix('.zip.part')
    with zipfile.ZipFile(tmp, 'w', compression=zipfile.ZIP_STORED, allowZip64=True) as z:
        for rel in files:
            zi = zipfile.ZipInfo(rel, date_time=(1980, 1, 1, 0, 0, 0))
            zi.external_attr = 0o644 << 16
            with open(src.parent / rel, 'rb') as fi, z.open(zi, 'w', force_zip64=True) as fo:
                for b in iter(lambda: fi.read(1 << 22), b''):
                    fo.write(b)
    tmp.replace(out)
    return out, len(files)


def phase_b():
    log('phase B: per-house zips')
    worlds = sorted(json.load(open(DISK / 'assets/houses.json')), key=lambda h: h['world'])
    rem = remote(); sums = json.load(open(H / 'work/zips.json')) if (H / 'work/zips.json').exists() else {}
    for h in worlds:
        for kind in KINDS:
            name = f'assets/{kind}/{h["world"]}.zip'
            if name in sums and rem.get(name, (None, None))[1] == sums[name]['sha256']:
                continue
            t0 = time.time(); z, n = make_zip(kind, h['world']); d = sha(z); size = z.stat().st_size
            api.upload_file(path_or_fileobj=str(z), path_in_repo=name, repo_id=REPO, repo_type=RT,
                            commit_message=f'Add {name}')
            z.unlink()
            sums[name] = dict(sha256=d, size=size, files=n)
            json.dump(sums, open(H / 'work/zips.json', 'w'), indent=1)
            log(f'{name} files={n} {size / 1e6:.0f} MB {time.time() - t0:.0f}s')


def phase_c():
    log('phase C: ZIPS.sha256, remove probe folder, verify')
    sums = json.load(open(H / 'work/zips.json'))
    assert len(sums) == 2 * len(json.load(open(DISK / 'assets/houses.json'))), len(sums)
    zs = DISK / 'assets/ZIPS.sha256'
    zs.write_text(''.join(f'{v["sha256"]}  {k}\n' for k, v in sorted(sums.items())))
    api.upload_file(path_or_fileobj=str(zs), path_in_repo='assets/ZIPS.sha256', repo_id=REPO, repo_type=RT,
                    commit_message='Add assets/ZIPS.sha256')
    rem = remote()
    if any(k.startswith('assets/isaac-scenes/106366173_174226431/') for k in rem):
        api.delete_folder('assets/isaac-scenes/106366173_174226431', repo_id=REPO, repo_type=RT,
                          commit_message='Remove loose copy of one scene (replaced by its zip)')
    rem = remote()
    want = {}
    for m in ('v0.2', 'ent400', 'assets', 'code', 'data'):
        for l in open(VIEW / m / 'MANIFEST.sha256'):
            h, p = l.rstrip('\n').split('  ', 1)
            if not p.startswith(('assets/isaac-scenes/', 'assets/hssd-source/')):
                want[p] = h
    for m in ('v0.2', 'ent400', 'assets', 'code', 'data'):
        want[f'{m}/MANIFEST.sha256'] = sha(VIEW / m / 'MANIFEST.sha256')
    for l in open(VIEW / 'MANIFEST.sha256'):
        h, p = l.rstrip('\n').split('  ', 1); want[p] = h
    want['MANIFEST.sha256'] = sha(VIEW / 'MANIFEST.sha256'); want['assets/ZIPS.sha256'] = sha(zs)
    for k, v in sums.items():
        want[k] = v['sha256']
    missing = [p for p in want if p not in rem]
    extra = [p for p in rem if p not in want and p != '.gitattributes']
    bad = []
    for p, h in want.items():
        if p in rem:
            size, lfs = rem[p]
            if lfs is not None and lfs != h:
                bad.append(p)
            elif lfs is None and size != os.path.getsize(VIEW / p if (VIEW / p).exists() else DISK / p):
                bad.append(p)
    log(f'verify: expected {len(want)} files, on hub {len(rem)}, missing {len(missing)}, extra {len(extra)}, mismatched {len(bad)}')
    json.dump(dict(missing=missing[:200], extra=extra[:200], bad=bad[:200]), open(H / 'work/upload-verify.json', 'w'), indent=1)


if __name__ == '__main__':
    ph = sys.argv[sys.argv.index('--phase') + 1] if '--phase' in sys.argv else 'all'
    assert os.environ.get('HF_HOME') == '/root/.hf-own' and api.whoami()['name'] == 'VEHwang'
    if ph in ('A', 'all'): phase_a()
    if ph in ('B', 'all'): phase_b()
    if ph in ('C', 'all'): phase_c()