ScreenRef-Annotations / scripts /parquet_to_tree.py
tjcaspar's picture
ScreenRef annotations: initial release
89552cf
Raw History Blame Contribute Delete
3.45 kB
#!/usr/bin/env python3
"""Unpack the ScreenRef Parquet shards back into the images/ tree used by meta/.
Each Parquet row stores the screenshot bytes plus its path relative to the task's
image root; the root itself comes from meta/meta_full.json. The file lands at
<out>/<meta root>/<path>, which is exactly the path recorded in
stats/image_manifest.tsv.gz.
python scripts/parquet_to_tree.py --shards /path/to/ScreenRef/data \
--meta meta/meta_full.json --out . # writes ./images/...
python scripts/parquet_to_tree.py ... --verify stats/image_manifest.tsv.gz
A screenshot referenced by several rows is written once. Existing files are skipped,
so an interrupted run can simply be restarted.
"""
import argparse, glob, gzip, hashlib, json, os, sys
import pyarrow.parquet as pq
def main():
ap = argparse.ArgumentParser()
ap.add_argument('--shards', required=True, help='directory holding train-*.parquet')
ap.add_argument('--meta', default='meta/meta_full.json')
ap.add_argument('--out', default='.', help='images/ is created under this directory')
ap.add_argument('--verify', metavar='MANIFEST',
help='check size and sha256 of every written file against the manifest')
args = ap.parse_args()
roots = {task: ent['root'] for task, ent in json.load(open(args.meta)).items()}
manifest = None
if args.verify:
with gzip.open(args.verify, 'rt') as fh:
next(fh)
manifest = {}
for line in fh:
p, s, h = line.rstrip('\n').split('\t')
manifest[p] = (int(s), h)
shards = sorted(glob.glob(os.path.join(args.shards, 'train-*.parquet')))
if not shards:
sys.exit(f'no train-*.parquet under {args.shards}')
written = skipped = rows = bad = 0
for i, shard in enumerate(shards, 1):
pf = pq.ParquetFile(shard)
for rg in range(pf.num_row_groups):
for r in pf.read_row_group(rg, columns=['image', 'task']).to_pylist():
rows += 1
root = roots.get(r['task'])
if root is None:
sys.exit(f'task {r["task"]!r} not in {args.meta}')
rel = os.path.join(root, r['image']['path'])
dst = os.path.join(args.out, rel)
if os.path.exists(dst):
skipped += 1
continue
raw = r['image']['bytes']
if manifest is not None:
key = os.path.relpath(rel, 'images')
want = manifest.get(key)
if want is None or want != (len(raw), hashlib.sha256(raw).hexdigest()):
print(f'MISMATCH {key}', file=sys.stderr)
bad += 1
continue
os.makedirs(os.path.dirname(dst), exist_ok=True)
tmp = dst + '.part'
with open(tmp, 'wb') as fo:
fo.write(raw)
os.replace(tmp, dst)
written += 1
print(f'[{i}/{len(shards)}] {os.path.basename(shard)} '
f'rows {rows:,} written {written:,} already present {skipped:,}', flush=True)
print(f'done: {rows:,} rows, {written:,} files written, {skipped:,} skipped'
+ (f', {bad:,} mismatches' if manifest is not None else ''))
return 1 if bad else 0
if __name__ == '__main__':
sys.exit(main())