File size: 5,671 Bytes
73feb3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Restore the trusted SimLingo bucket snapshot for a new data location (Python >=3.8)."""
import argparse
import gzip
import hashlib
import json
import os
import pickle
import shutil
import tarfile
import tempfile
from pathlib import Path

TOKEN = '__SIMLINGO_DATA_ROOT__'
CACHE = 'BUCKET2DATA_remove_missing_dream_jianing.pkl'
INDEX = 'bucketsv2_simlingo/buckets_paths.pkl'
FIELDS = ('images', 'boxes', 'measurements', 'alternative_trajectories')


def sha256(path):
    h = hashlib.sha256()
    with Path(path).open('rb') as f:
        for block in iter(lambda: f.read(8 * 1024 * 1024), b''):
            h.update(block)
    return h.hexdigest()


def rewrite_cache(cache, old, new):
    """Rewrite path leaves only; keep scalar values, container types and aliasing."""
    memo = {}
    count = 0

    def walk(value):
        nonlocal count
        ident = id(value)
        if ident in memo:
            return memo[ident][1]
        if type(value) is str:
            if not value.startswith(old + '/'):
                raise ValueError('Unexpected cache path prefix; refusing a partial rewrite')
            out = new + value[len(old):]
            count += 1
        elif type(value) is list:
            out = []
            memo[ident] = (value, out)
            out.extend(walk(x) for x in value)
        elif type(value) is tuple:
            out = tuple(walk(x) for x in value)
        else:
            raise TypeError('Unexpected path container: ' + type(value).__name__)
        memo[ident] = (value, out)
        return out

    for buckets in cache.values():
        for bucket in buckets.values():
            for field in FIELDS:
                if field in bucket:
                    bucket[field] = walk(bucket[field])
    return count


def check_data(root, probes):
    from PIL import Image
    for item in probes:
        path = root / item['path']
        if not path.is_file():
            raise FileNotFoundError(str(path))
        if item['kind'] == 'image':
            with Image.open(str(path)) as im:
                im.verify()
        else:
            with gzip.open(str(path), 'rt') as f:
                data = json.load(f)
            if item['kind'] == 'commentary':
                assert 'commentary' in data
            elif item['kind'] == 'vqa':
                assert data.get('QA')
            elif item['kind'] == 'dreamer':
                assert any(v for k, v in data.items() if 'factor' not in k)
    return len(probes)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--database-root', type=Path, required=True,
                        help='Resource directory containing simlingo_v2_2025_01_10/')
    parser.add_argument('--bundle-dir', type=Path, default=Path(__file__).resolve().parent)
    parser.add_argument('--check-data', action='store_true', help='Decode representative real samples before writing')
    args = parser.parse_args()
    bundle = args.bundle_dir.resolve()
    db = args.database_root.resolve()
    data = (db / 'simlingo_v2_2025_01_10').resolve()
    if args.check_data:
        probes = json.loads((bundle / 'sample-probes.json').read_text())
        print('Verified real data files:', check_data(data, probes), flush=True)
    targets = (db / CACHE, db / INDEX)
    for target in targets:
        if target.exists() or target.is_symlink():
            raise FileExistsError('Refusing to overwrite ' + str(target))
    manifest = json.loads((bundle / 'manifest.json').read_text())
    archive = bundle / manifest['archive']['path']
    assert archive.stat().st_size == manifest['archive']['bytes']
    assert sha256(archive) == manifest['archive']['sha256'], 'Archive checksum mismatch'
    db.mkdir(parents=True, exist_ok=True)
    with tempfile.TemporaryDirectory(prefix='.restore-buckets-', dir=str(db)) as temp:
        temp = Path(temp)
        expected = {x['path']: x for x in manifest['payload']}
        with tarfile.open(str(archive), 'r:gz') as tar:
            members = tar.getmembers()
            assert len(members) == len(expected)
            assert {x.name for x in members} == set(expected)
            for member in members:
                assert member.isfile() and member.size == expected[member.name]['bytes']
                target = temp / member.name
                target.parent.mkdir(parents=True, exist_ok=True)
                with tar.extractfile(member) as src, target.open('wb') as dst:
                    shutil.copyfileobj(src, dst, 8 * 1024 * 1024)
                assert sha256(target) == expected[member.name]['sha256']
        print('Loading portable cache; this may take a few minutes.', flush=True)
        with (temp / 'BUCKET2DATA.portable.pkl').open('rb') as f:
            cache = pickle.load(f)
        rewritten = rewrite_cache(cache, TOKEN, str(data))
        staged_cache = temp / CACHE
        with staged_cache.open('wb') as f:
            pickle.dump(cache, f, protocol=4)
        targets[1].parent.mkdir(parents=True, exist_ok=True)
        # Hard links fail atomically if another process has created either target.
        os.link(str(staged_cache), str(targets[0]))
        try:
            os.link(str(temp / INDEX), str(targets[1]))
        except BaseException:
            targets[0].unlink()
            raise
    report = {'ok': True, 'data_root': str(data), 'rewritten_unique_path_objects': rewritten,
              'cache': str(targets[0]), 'bucket_index': str(targets[1]),
              'sample_counts': manifest['sample_counts'], 'real_samples_checked': args.check_data}
    print(json.dumps(report, indent=2))


if __name__ == '__main__':
    main()