File size: 6,457 Bytes
c568119
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import argparse
from collections import defaultdict
import gzip
import hashlib
import io
import json
from pathlib import Path, PurePosixPath
import tarfile
import zipfile

from PIL import Image


FOLDERS = {'groundcua': 'GroundCUA-train', 'showui_web': 'ShowUI-web', 'showui_desktop': 'ShowUI-desktop',
           'osatlas_linux': 'OS-Atlas-data', 'osatlas_macos': 'OS-Atlas-data',
           'osatlas_rico': 'OS-Atlas-data', 'osatlas_uibert': 'OS-Atlas-data'}
ARCHIVES = {'osatlas_linux': 'desktop_domain/linux_images.zip', 'osatlas_macos': 'desktop_domain/macos_images.zip',
            'osatlas_rico': 'mobile_domain/rico_imgs.zip', 'osatlas_uibert': 'mobile_domain/UIBert.zip'}


def rows(path):
    opener = gzip.open if str(path).endswith('.gz') else open
    with opener(path, 'rt', encoding='utf-8') as stream:
        yield from (json.loads(line) for line in stream)


def relative(value):
    path = PurePosixPath(value)
    if not value or path.is_absolute() or '..' in path.parts or '\\' in value or '://' in value:
        raise ValueError('Unsafe relative image path')
    return path.as_posix()


def verify_image(raw, asset):
    if hashlib.sha256(raw).hexdigest() != asset['image_sha256']:
        raise ValueError('Image bytes differ from the pinned source: ' + asset['image'])
    with Image.open(io.BytesIO(raw)) as opened:
        image = opened.convert('RGB')
        if list(image.size) != asset['image_size']:
            raise ValueError('Image dimensions differ')
        pixel_hash = hashlib.sha256(str(image.size).encode() + image.tobytes()).hexdigest()
    if pixel_hash != asset['pixel_sha256']:
        raise ValueError('Decoded RGB pixels differ')


def save_image(raw, asset, output):
    verify_image(raw, asset)
    root = output.resolve()
    destination = root / relative(asset['image'])
    if not destination.resolve().is_relative_to(root):
        raise ValueError('Image output escapes destination')
    destination.parent.mkdir(parents=True, exist_ok=True)
    if destination.exists():
        verify_image(destination.read_bytes(), asset)
        return
    with destination.open('xb') as stream:
        stream.write(raw)


def materialize(annotations, image_manifest, source_root, output):
    wanted = {relative(row['image']) for path in annotations for row in rows(path)}
    assets = {row['image']: row for row in rows(image_manifest) if row['image'] in wanted}
    if assets.keys() != wanted:
        raise ValueError('The image manifest does not cover the selected annotations')
    pending = defaultdict(dict)
    for asset in assets.values():
        existing = output / relative(asset['image'])
        if not existing.resolve().is_relative_to(output.resolve()):
            raise ValueError('Image output escapes destination')
        if existing.exists():
            verify_image(existing.read_bytes(), asset)
        else:
            pending[asset['source']][relative(asset['source_image'])] = asset
    counts = {}
    for family, requested in pending.items():
        folder = source_root / FOLDERS[family]
        original_count = len(requested)
        if family == 'showui_desktop':
            for key, asset in list(requested.items()):
                path = folder / 'images' / key.removeprefix('images/')
                save_image(path.read_bytes(), asset, output)
                del requested[key]
        elif family == 'showui_web':
            with tarfile.open(folder / 'images.tar.gz', 'r|gz') as archive:
                for member in archive:
                    key = member.name.removeprefix('./')
                    if member.isfile() and key in requested:
                        save_image(archive.extractfile(member).read(), requested.pop(key), output)
        elif family in ARCHIVES:
            with zipfile.ZipFile(folder / ARCHIVES[family]) as archive:
                entries = {}
                for entry in archive.infolist():
                    if entry.filename not in requested or entry.is_dir():
                        continue
                    previous = entries.get(entry.filename)
                    if previous and (previous.CRC, previous.file_size) != (entry.CRC, entry.file_size):
                        raise ValueError('Conflicting ZIP image member: ' + entry.filename)
                    entries.setdefault(entry.filename, entry)
                for key, asset in list(requested.items()):
                    if key not in entries:
                        raise ValueError('Missing ZIP image member: ' + key)
                    save_image(archive.read(entries[key]), asset, output)
                    del requested[key]
        elif family == 'groundcua':
            import pyarrow.parquet as parquet
            files = sorted({asset['parquet_file'] for asset in requested.values()})
            for name in files:
                for batch in parquet.ParquetFile(folder / relative(name)).iter_batches(batch_size=8, columns=['image_id', 'image']):
                    for record in batch.to_pylist():
                        key = record['image_id']
                        if key not in requested:
                            continue
                        raw = record['image'].get('bytes')
                        if raw is None:
                            raw = (folder / relative(record['image']['path'])).read_bytes()
                        save_image(raw, requested.pop(key), output)
        else:
            raise ValueError('Unknown source: ' + family)
        if requested:
            raise ValueError(f'{family}: {len(requested)} selected images were not found')
        counts[family] = original_count
        print(json.dumps({'source': family, 'images_materialized': original_count}), flush=True)
    return {'selected_image_references': len(assets), 'new_images_by_source': counts}


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Materialize only selected images from separately downloaded upstream data. No network or resizing.')
    parser.add_argument('--annotations', nargs='+', type=Path, required=True)
    parser.add_argument('--image-manifest', type=Path, required=True)
    parser.add_argument('--source-root', type=Path, required=True)
    parser.add_argument('--image-root', type=Path, required=True)
    arguments = parser.parse_args()
    print(json.dumps(materialize(arguments.annotations, arguments.image_manifest, arguments.source_root, arguments.image_root), indent=2))