File size: 7,976 Bytes
b3e91ab
 
 
 
 
 
 
 
 
 
 
 
 
 
8d60294
 
 
b3e91ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Download, verify and load this DRBenchPro Docker archive (Python 3.10+)."""
import argparse
import hashlib
import json
from pathlib import Path
import re
import shutil
import subprocess
import sys
import urllib.parse
import urllib.request

REPO = 'zhuiluozhiji/DRBenchPro-runtime'
VERSION = '0.3.0-enwiki-20260701-v1-8733db7-linux-amd64'
IMAGE_ID = 'sha256:a5b1f5a2608cf8258a8ebc796f745d775c772d4bccc9faf0bf88410d95f20e37'
IMAGE_TAG = 'drbenchpro/standalone:0.3.0-enwiki-20260701-v1-8733db7'
BUFFER = 8 * 1024**2


def manifest(root):
    folder = root / 'images' / VERSION
    data = json.loads((folder / 'release.json').read_text())
    if data.get('version') != VERSION or data.get('image_id') != IMAGE_ID or data.get('image_tag') != IMAGE_TAG:
        raise ValueError('Release identity does not match this helper')
    if data.get('platform') != 'linux/amd64' or data.get('archive_format') != 'docker-save+gzip':
        raise ValueError('Unexpected platform or archive format')
    records = data['parts']
    if not records or len(records) > 1000:
        raise ValueError('Invalid part count')
    for i, item in enumerate(records):
        if item['filename'] != f'drbenchpro.tar.gz.part-{i:03d}':
            raise ValueError('Missing or unordered part in release manifest')
        if not re.fullmatch('[0-9a-f]{64}', item['sha256']):
            raise ValueError('Invalid SHA-256 in release manifest')
        if type(item['bytes']) is not int or not 0 < item['bytes'] <= data['part_size_bytes']:
            raise ValueError('Invalid part length')
        if i < len(records)-1 and item['bytes'] != data['part_size_bytes']:
            raise ValueError('Unexpected short part before final part')
    if sum(item['bytes'] for item in records) != data['archive_bytes']:
        raise ValueError('Archive size does not match part sizes')
    if not re.fullmatch('[0-9a-f]{64}', data['archive_sha256']):
        raise ValueError('Invalid complete archive SHA-256')
    return folder, data


def verify(root):
    folder, data = manifest(root)
    expected = {item['filename'] for item in data['parts']}
    actual = {p.name for p in folder.glob('drbenchpro.tar.gz.part-*')}
    if actual != expected:
        raise ValueError(f'Part set differs; missing={sorted(expected-actual)}, unexpected={sorted(actual-expected)}')
    sums = ''.join(f"{p['sha256']}  {p['filename']}\n" for p in data['parts'])
    if (folder / 'SHA256SUMS').read_text() != sums:
        raise ValueError('SHA256SUMS disagrees with release manifest')
    if (folder / 'ARCHIVE_SHA256').read_text().split() != [data['archive_sha256'], '-']:
        raise ValueError('ARCHIVE_SHA256 disagrees with release manifest')
    whole = hashlib.sha256()
    for i, item in enumerate(data['parts'], 1):
        path = folder / item['filename']
        if path.is_symlink() or path.stat().st_size != item['bytes']:
            raise ValueError('Incorrect part size or symlink: ' + item['filename'])
        digest = hashlib.sha256()
        with path.open('rb') as stream:
            while block := stream.read(BUFFER):
                digest.update(block)
                whole.update(block)
        if digest.hexdigest() != item['sha256']:
            raise ValueError('SHA-256 mismatch: ' + item['filename'])
        print(f"[{i}/{len(data['parts'])}] OK {item['filename']}", flush=True)
    if whole.hexdigest() != data['archive_sha256']:
        raise ValueError('Complete archive SHA-256 mismatch')
    print('Complete archive SHA-256 verified: ' + whole.hexdigest(), flush=True)
    return folder, data


def inspect_image(name):
    result = subprocess.run(['docker', 'image', 'inspect', name], text=True, capture_output=True)
    if result.returncode:
        return None
    values = json.loads(result.stdout)
    return values[0]


def load(root):
    if shutil.which('docker') is None:
        raise RuntimeError('Docker CLI is required')
    subprocess.run(['docker', 'info', '--format', '{{.DockerRootDir}}'], check=True)
    present = inspect_image(IMAGE_TAG)
    if present and present['Id'] != IMAGE_ID:
        raise RuntimeError('The release tag already points to a different local image; resolve the conflict first')
    folder, data = verify(root)
    print('Importing verified archive into Docker; allow space for the full image and extraction.', flush=True)
    proc = subprocess.Popen(['docker', 'image', 'load'], stdin=subprocess.PIPE)
    try:
        for item in data['parts']:
            with (folder / item['filename']).open('rb') as stream:
                while block := stream.read(BUFFER):
                    proc.stdin.write(block)
        proc.stdin.close()
        if proc.wait() != 0:
            raise RuntimeError('Docker image load failed')
    except BaseException:
        if not proc.stdin.closed:
            proc.stdin.close()
        proc.wait()
        raise
    loaded = inspect_image(IMAGE_ID)
    if not loaded or loaded['Id'] != IMAGE_ID or loaded['Os'] != 'linux' or loaded['Architecture'] != 'amd64':
        raise RuntimeError('Loaded image identity or platform differs')
    present = inspect_image(IMAGE_TAG)
    if present and present['Id'] != IMAGE_ID:
        raise RuntimeError('Local tag changed during import; refusing to overwrite it')
    if not present:
        subprocess.run(['docker', 'image', 'tag', IMAGE_ID, IMAGE_TAG], check=True)
    if inspect_image(IMAGE_TAG)['Id'] != IMAGE_ID:
        raise RuntimeError('Image tag verification failed')
    print('Ready: ' + IMAGE_TAG + '\n' + IMAGE_ID, flush=True)


def download(root, revision):
    if shutil.which('hf') is None:
        raise RuntimeError('Install the Hugging Face hf CLI before downloading')
    ref = urllib.parse.quote(revision, safe='')
    url = f'https://huggingface.co/api/datasets/{REPO}/revision/{ref}'
    with urllib.request.urlopen(url, timeout=60) as response:
        commit = json.load(response)['sha']
    if not re.fullmatch('[0-9a-f]{40}', commit):
        raise ValueError('Unexpected remote revision')
    url = f'https://huggingface.co/datasets/{REPO}/resolve/{commit}/images/{VERSION}/release.json'
    with urllib.request.urlopen(url, timeout=60) as response:
        release = json.load(response)
    if release.get('image_id') != IMAGE_ID:
        raise ValueError('Remote image differs from this helper')
    root.mkdir(parents=True, exist_ok=True)
    already = sum((root / 'images' / VERSION / p['filename']).stat().st_size for p in release['parts'] if (root / 'images' / VERSION / p['filename']).is_file())
    remaining = max(0, release['archive_bytes'] - already)
    print(f"Fixed revision: {commit}\nCompressed archive: {release['archive_bytes']:,} bytes in {len(release['parts'])} parts", flush=True)
    if shutil.disk_usage(root).free < remaining:
        raise RuntimeError('Insufficient download filesystem free space')
    subprocess.run(['hf', 'download', REPO, '--repo-type', 'dataset', '--revision', commit, '--local-dir', str(root), '--include', 'images/'+VERSION+'/*', '--include', 'scripts/*'], check=True)
    print('Download complete. Run verify.sh or load.sh before using the image.', flush=True)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('action', choices=['download', 'verify', 'load'])
    parser.add_argument('--directory', type=Path, default=Path(__file__).resolve().parent.parent)
    parser.add_argument('--revision', default='main', help='HF commit, tag or branch; resolved once before download')
    args = parser.parse_args()
    root = args.directory.resolve()
    if args.action == 'download':
        download(root, args.revision)
    elif args.action == 'verify':
        verify(root)
    else:
        load(root)


if __name__ == '__main__':
    try:
        main()
    except (OSError, ValueError, RuntimeError, KeyError, subprocess.CalledProcessError) as exc:
        print(f'Error: {exc}', file=sys.stderr)
        sys.exit(1)