Download scripts/materialize_images.py from KangHui2200/PixelOne-Data: direct link, hf CLI and curl.
- Browser
- Download file 6.46 kB
-
https://huggingface.co/datasets/KangHui2200/PixelOne-Data/resolve/main/scripts/materialize_images.py
- Command line
-
hf download hf://datasets/KangHui2200/PixelOne-Data/scripts/materialize_images.py
-
curl -L -o materialize_images.py https://huggingface.co/datasets/KangHui2200/PixelOne-Data/resolve/main/scripts/materialize_images.py
6.46 kB
| 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)) | |