File size: 15,651 Bytes
94a4005
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
#!/usr/bin/env python3
"""Pinned HF downloads; immutable raw archives; CRC-checked pilot extraction."""
import argparse
import hashlib
import io
import json
import random
import shutil
import struct
import subprocess
import time
import urllib.error
import urllib.request
import zipfile
import zlib
from pathlib import Path, PurePosixPath

REPO = 'ParityLab/Hand-Datasets-Raw'
REVISION = '8818d04d6cbdc0bf32b6ef949257b82310f16798'
HERE = Path(__file__).resolve().parent


def sha(path):
    with open(path, 'rb') as f:
        return hashlib.file_digest(f, 'sha256').hexdigest()


def safe_path(root, name):
    p = PurePosixPath(name)
    if p.is_absolute() or '..' in p.parts or '\\' in name:
        raise ValueError(f'Unsafe archive path: {name}')
    target = root.joinpath(*p.parts)
    if not target.resolve().is_relative_to(root.resolve()):
        raise ValueError(f'Path escapes extraction root: {name}')
    return target


class RemoteFile(io.RawIOBase):
    """Small seekable HTTP range reader, suitable for ZIP central directories."""
    def __init__(self, path, size):
        self.url = f'https://huggingface.co/datasets/{REPO}/resolve/{REVISION}/{path}'
        self.size, self.pos = size, 0
        self.cache_start, self.cache = 0, b''

    def seekable(self):
        return True

    def tell(self):
        return self.pos

    def seek(self, offset, whence=0):
        self.pos = offset + (0 if whence == 0 else self.pos if whence == 1 else self.size)
        if self.pos < 0:
            raise ValueError('Negative offset')
        return self.pos

    def read(self, n=-1):
        n = min(self.size - self.pos, n if n >= 0 else self.size)
        if n <= 0:
            return b''
        if not (self.cache_start <= self.pos and self.pos + n <= self.cache_start + len(self.cache)):
            end = min(self.size, self.pos + max(n, 262144)) - 1
            req = urllib.request.Request(self.url, headers={'Range': f'bytes={self.pos}-{end}'})
            for attempt in range(4):
                try:
                    with urllib.request.urlopen(req, timeout=30) as r:
                        expected = f'bytes {self.pos}-{end}/{self.size}'
                        if r.status != 206 or r.headers.get('Content-Range') != expected:
                            raise RuntimeError(f'Server did not honor byte range {expected}')
                        self.cache = r.read()
                        self.cache_start = self.pos
                        if len(self.cache) != end - self.pos + 1:
                            raise IOError('Truncated HTTP range')
                    break
                except (urllib.error.URLError, TimeoutError, OSError):
                    if attempt == 3:
                        raise
                    time.sleep(attempt + 1)
        start = self.pos - self.cache_start
        self.pos += n
        return self.cache[start:start+n]


def checksums(dataset):
    return json.loads((HERE / 'source_evidence' / f'{dataset}-archive_checksums.json').read_text())['files']


def extract_zip(archive, target, origin, selected=None):
    records = []
    with zipfile.ZipFile(archive) as z:
        for info in z.infolist():
            if info.is_dir() or (selected is not None and info.filename not in selected):
                continue
            # Do not create symlinks/devices. Treat regular members only.
            mode = info.external_attr >> 16
            if mode & 0o170000 not in (0, 0o100000):
                raise ValueError(f'Non-regular archive member: {info.filename}')
            p = safe_path(target, info.filename)
            p.parent.mkdir(parents=True, exist_ok=True)
            if shutil.disk_usage(p.parent).free < info.file_size + 256 * 1024**2:
                raise RuntimeError('Insufficient space for next uncompressed member')
            with z.open(info) as src, p.open('xb') as dst:
                shutil.copyfileobj(src, dst)  # ZipFile checks member CRC at EOF.
            records.append({'path': p.relative_to(target).as_posix(), 'sha256': sha(p),
                            'source_locator': dict(origin, member=info.filename)})
    return records


def download(dataset, root):
    from huggingface_hub import hf_hub_download
    entries = [e for e in checksums(dataset) if '#' not in e['path']]
    need = sum(e['size'] for e in entries if not (root / e['path']).exists())
    root.mkdir(parents=True, exist_ok=True)
    if shutil.disk_usage(root).free < need + 5 * 1024**3:
        raise RuntimeError(f'Insufficient disk; raw downloads need {need / 1e9:.1f} GB plus reserve')
    for e in entries:
        dst = root / e['path']
        if dst.exists():
            if dst.stat().st_size != e['size'] or sha(dst) != e['sha256']:
                raise RuntimeError(f'Existing raw file differs: {dst}')
            print(f'Already verified: {dst}', flush=True)
            continue
        remote = f'{dataset}/raw/{e["path"]}'
        p = Path(hf_hub_download(REPO, remote, repo_type='dataset', revision=REVISION,
                                local_dir=root / '_hf'))
        if p.stat().st_size != e['size'] or sha(p) != e['sha256']:
            raise RuntimeError(f'Archive checksum mismatch: {remote}')
        dst.parent.mkdir(parents=True, exist_ok=True)
        if not dst.exists():
            p.replace(dst)
        elif sha(dst) != e['sha256']:
            raise RuntimeError(f'Existing raw file differs: {dst}')
        print(dst, flush=True)


def pilot_ego(target, count, seed):
    e = checksums('EgoHOS')[0]
    remote = f'EgoHOS/raw/{e["path"]}'
    f = RemoteFile(remote, e['size'])
    with zipfile.ZipFile(f) as z:
        images = [n for n in z.namelist() if '/image/' in n and n.lower().endswith(('.jpg', '.jpeg', '.png'))]
        chosen = []
        for split in ('train', 'val', 'test_indomain', 'test_outdomain'):
            pool = sorted(n for n in images if f'/{split}/image/' in n)
            chosen.extend(random.Random(seed).sample(pool, min(count, len(pool))))
        if not chosen:
            raise RuntimeError('Expected outer ZIP image layout not found')
        names = set(z.namelist())
        members = set(chosen)
        for name in chosen:
            label = str(PurePosixPath(name.replace('/image/', '/label/')).with_suffix('.png'))
            if label not in names:
                raise RuntimeError(f'Label missing: {label}')
            members.add(label)
    records = extract_zip(f, target, {'repo': REPO, 'revision': REVISION, 'file': remote,
                          'archive_sha256_expected': e['sha256'],
                          'verification': 'selected member CRC + SHA256; full archive NOT downloaded/verified'}, members)
    return records


def pilot_oak_rgb(target, count, seed):
    """Pilot-only: sample first 128 PNG local entries from volume z01, stratified by camera.

    This is NOT a whole-dataset random sample and cannot substitute for a full download.
    Known split ZIP uses local CRC/sizes; other layouts fail closed.
    """
    entry = next(e for e in checksums('OakInk-v1') if e['path'].endswith('.z01'))
    remote = f'OakInk-v1/raw/{entry["path"]}'
    f = RemoteFile(remote, entry['size'])
    if f.read(4) != b'PK\x07\x08':
        raise ValueError('Unexpected split ZIP signature')
    pool = {}
    seen = 0
    while seen < 128:
        header = f.read(30)
        if len(header) != 30 or header[:4] != b'PK\x03\x04':
            raise ValueError('Unsupported split ZIP local header; use full download + 7z')
        _, version, flags, method, _, _, crc, compressed, size, nlen, xlen = struct.unpack('<4s5H3I2H', header)
        name = f.read(nlen).decode('utf-8' if flags & 2048 else 'cp437')
        f.read(xlen)
        if flags & 9 or compressed == 0xffffffff or method not in (0, 8):
            raise ValueError('Unsupported encrypted/descriptor/ZIP64 local member; use full extraction')
        offset = f.tell()
        if offset + compressed > entry['size']:
            raise ValueError('Pilot member crosses volume; use full extraction')
        if name.endswith('.png'):
            seen += 1
            camera = PurePosixPath(name).stem.rsplit('_', 1)[0]
            pool.setdefault(camera, []).append((name, offset, compressed, size, method, crc))
        f.seek(offset + compressed)
    rng = random.Random(seed)
    records = []
    for camera in sorted(pool):
        for name, offset, compressed, size, method, crc in rng.sample(pool[camera], min(count, len(pool[camera]))):
            f.seek(offset)
            packed = f.read(compressed)
            content = packed if method == 0 else zlib.decompress(packed, -15)
            if len(content) != size or zlib.crc32(content) & 0xffffffff != crc:
                raise ValueError(f'Pilot member CRC/size mismatch: {name}')
            path = safe_path(target / 'image', name)
            path.parent.mkdir(parents=True, exist_ok=True)
            path.write_bytes(content)
            records.append({'path': path.relative_to(target).as_posix(), 'sha256': sha(path),
                'source_locator': {'repo': REPO, 'revision': REVISION, 'file': remote, 'member': name,
                    'compressed_member_offset': offset, 'archive_sha256_expected': entry['sha256'],
                    'verification': 'selected member CRC + SHA256; complete volume NOT verified',
                    'selection_scope': 'first 128 PNG entries in z01; camera-stratified, NOT global random'}})
    return records


def extract_local(dataset, raw, target):
    entries = [e for e in checksums(dataset) if '#' not in e['path']]
    for e in entries:
        p = raw / e['path']
        if not p.exists() or p.stat().st_size != e['size'] or sha(p) != e['sha256']:
            raise RuntimeError(f'Download/verify raw first: {p}')
    records = []
    for e in entries:
        p = raw / e['path']
        if p.suffix != '.zip':
            continue
        origin = {'repo': REPO, 'revision': REVISION, 'file': f'{dataset}/raw/{e["path"]}',
                  'archive_sha256': e['sha256']}
        if dataset == 'EgoHOS':
            with zipfile.ZipFile(p) as z:
                members = {n for n in z.namelist() if '/image/' in n or '/label/' in n or '/contact/' in n}
            records.extend(extract_zip(p, target, origin, members))
        elif '/stream_zipped/' in e['path']:
            tool = shutil.which('7zz') or shutil.which('7z')
            if not tool:
                raise RuntimeError('Install 7zip (7zz or 7z) for OakInk split ZIP volumes')
            # Official immutable archives were SHA256 checked above. Never concatenate volumes.
            dest = target / 'image'
            subprocess.run([tool, 'x', '-y', '-o' + str(dest), str(p)], check=True)
            volumes = [dict(file=f'{dataset}/raw/{v["path"]}', sha256=v['sha256'])
                       for v in entries if '/stream_zipped/' in v['path']]
            for image in sorted((dest / 'stream_release_v2').rglob('*.png')):
                records.append({'path': image.relative_to(target).as_posix(), 'sha256': sha(image),
                                'source_locator': dict(origin, volumes=volumes,
                                                       member=image.relative_to(dest).as_posix())})
        else:
            dest = target / ('image' if '/image/' in e['path'] else 'shape' if '/shape/' in e['path'] else '')
            batch = extract_zip(p, dest, origin)
            for r in batch:
                r['path'] = (dest.relative_to(target) / r['path']).as_posix()
            records.extend(batch)
    return records


def main():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('command', choices=['download', 'extract', 'pilot-egohos', 'pilot-oakink-rgb', 'extract-annotations', 'fetch-oakink-objects'])
    p.add_argument('--dataset', choices=['EgoHOS', 'OakInk-v1'], default='EgoHOS')
    p.add_argument('--raw', type=Path)
    p.add_argument('--out', type=Path)
    p.add_argument('--archive', type=Path, help='Official anno_v2_1.zip for extract-annotations')
    p.add_argument('--per-split', type=int, default=4)
    p.add_argument('--seed', type=int, default=20260928)
    a = p.parse_args()
    if a.command == 'fetch-oakink-objects':
        if not a.out or not (a.out / 'sources.jsonl').is_file():
            p.error('Existing extracted --out with sources.jsonl required')
        entry = next(e for e in checksums('OakInk-v1') if e['path'] == 'data/image/obj.zip')
        remote = 'OakInk-v1/raw/' + entry['path']
        archive = a.out.parent / 'raw-pilot' / remote
        archive.parent.mkdir(parents=True, exist_ok=True)
        if not archive.exists():
            archive.write_bytes(RemoteFile(remote, entry['size']).read())
        if sha(archive) != entry['sha256']:
            raise ValueError('Object archive checksum mismatch')
        rows = extract_zip(archive, a.out / 'image', {'repo': REPO, 'revision': REVISION,
            'file': remote, 'archive_sha256': entry['sha256']})
        with (a.out / 'sources.jsonl').open('a') as f:
            for r in rows:
                r['path'] = 'image/' + r['path']
                f.write(json.dumps(r, ensure_ascii=False) + '\n')
        print(f'Imported {len(rows)} object assets; original zip retained at {archive}')
        return
    if a.command == 'extract-annotations':
        if not a.archive or not a.out or not (a.out / 'sources.jsonl').is_file():
            p.error('--archive and existing extracted --out with sources.jsonl required')
        with zipfile.ZipFile(a.archive) as z:
            regular = [n for n in z.namelist() if not n.endswith('/')]
            if not regular or not all(n.startswith('anno/') for n in regular):
                p.error('Expected archive rooted at anno/; inspect actual layout before importing')
            if any(safe_path(a.out / 'image', n).exists() for n in regular):
                p.error('Annotation target already exists; refusing to overwrite')
        rows = extract_zip(a.archive, a.out / 'image', {'file': str(a.archive.resolve()),
            'archive_sha256': sha(a.archive), 'origin': 'user-supplied official annotation archive; not present in pinned HF raw'})
        with (a.out / 'sources.jsonl').open('a') as f:
            for r in rows:
                r['path'] = 'image/' + r['path']
                f.write(json.dumps(r, ensure_ascii=False) + '\n')
        print(f'Imported {len(rows)} annotation files with provenance')
        return
    if a.command == 'download':
        if not a.raw:
            p.error('--raw required')
        download(a.dataset, a.raw)
        return
    if not a.out or a.out.exists():
        p.error('--out must be a new directory (raw is never modified)')
    if a.command == 'extract' and not a.raw:
        p.error('--raw required')
    if a.per_split < 1:
        p.error('--per-split must be positive')
    a.out.mkdir(parents=True)
    if a.command == 'pilot-egohos':
        a.dataset = 'EgoHOS'
        records = pilot_ego(a.out, a.per_split, a.seed)
    elif a.command == 'pilot-oakink-rgb':
        a.dataset = 'OakInk-v1'
        records = pilot_oak_rgb(a.out, a.per_split, a.seed)
    else:
        records = extract_local(a.dataset, a.raw, a.out)
    with (a.out / 'sources.jsonl').open('w') as f:
        for r in records:
            f.write(json.dumps(r, ensure_ascii=False) + '\n')
    (a.out / 'acquisition.json').write_text(json.dumps({'dataset': a.dataset, 'revision': REVISION,
        'command': a.command, 'seed': a.seed, 'files': len(records)}, indent=2))
    print(f'{len(records)} extracted files -> {a.out}')


if __name__ == '__main__':
    main()