Gasformer / verify.py
toqi's picture
Add Gasformer dataset
c45f452 verified
Raw History Blame Contribute Delete
5.28 kB
"""Check the release folder against the source files.
Usage: python verify.py <release_dir> [--mr-src DIR] [--cr-src DIR]
--mr-src : folder with <video>/images and <video>/masks, plus original_splits.csv
--cr-src : folder with {train,validation,test}/{images,masks}
Needs pyarrow and PIL. The `datasets` library is used for the load check if installed.
"""
import argparse, csv, glob, hashlib, io, os, re, shutil, subprocess, sys
import pyarrow.parquet as pq
ap = argparse.ArgumentParser()
ap.add_argument('release'); ap.add_argument('--mr-src'); ap.add_argument('--cr-src')
a = ap.parse_args()
R = a.release
res = []
def sha(b): return hashlib.sha256(b).hexdigest()
def shaf(p):
with open(p, 'rb') as f: return sha(f.read())
def rec(name, ok, note=''):
res.append((name, 'PASS' if ok else 'FAIL', note)); print(res[-1], flush=True)
def rows(ds):
for f in sorted(glob.glob(f'{R}/{ds}/data/*.parquet')):
for b in pq.ParquetFile(f).iter_batches(batch_size=64):
yield from b.to_pylist()
def read_csv(p):
with open(p, newline='') as fh: return {(r['video_id'], int(r['frame_index'])): r['splits'] for r in csv.DictReader(fh)}
def decode(b):
import numpy as np; from PIL import Image
return np.array(Image.open(io.BytesIO(b)))
def source_paths(ds, v, fi, split):
n = f'{v}_frame_{fi:04d}.png'
if ds == 'MR':
return f'{a.mr_src}/{v}/images/{n}', f'{a.mr_src}/{v}/masks/{n}'
sp = split.split('+')[0]
return f'{a.cr_src}/{sp}/images/{n}', f'{a.cr_src}/{sp}/masks/{n}'
for ds, nfiles, src in (('MR', 15, a.mr_src), ('CR', 1, a.cr_src)):
files = sorted(glob.glob(f'{R}/{ds}/data/*.parquet'))
csvsplit = read_csv(f'{R}/{ds}/official_split.csv')
seen = set(); nrows = 0; bytes_ok = True; cls_ok = True; split_ok = True; bad = []
maskvals_ok = True
for r in rows(ds):
nrows += 1; k = (r['video_id'], r['frame_index'])
seen.add(k)
if r['official_split'] != csvsplit.get(k): split_ok = False
m = decode(r['mask']['bytes'])
u = sorted(set(m.flatten().tolist()) - {0})
if ds == 'MR':
if not (len(u) == 1 and r['flow_rate_class'] == u[0]): cls_ok = False
else:
if not set(m.flatten().tolist()) <= {0, 1}: maskvals_ok = False
if src:
ip, mp = source_paths(ds, k[0], k[1], r['official_split'])
if not (sha(r['image']['bytes']) == shaf(ip) and sha(r['mask']['bytes']) == shaf(mp)):
bytes_ok = False; bad.append(k)
expect = 9009 if ds == 'MR' else None
rec(f'{ds} (a) {nfiles} parquet file(s)', len(files) == nfiles, str(len(files)))
rec(f'{ds} (a) rows {expect or ""} and each (video,frame) once', nrows == len(seen) and (expect is None or nrows == expect), f'{nrows} rows, {len(seen)} unique')
rec(f'{ds} (a2) rows match official_split.csv keys', seen == set(csvsplit), f'{len(csvsplit)} csv rows')
if src: rec(f'{ds} (b) image+mask sha256 equal source, all rows', bytes_ok, f'{len(bad)} differ')
rec(f'{ds} (c) ' + ('flow_rate_class == unique nonzero mask value' if ds == 'MR' else 'mask values only 0/1'), cls_ok if ds == 'MR' else maskvals_ok)
rec(f'{ds} (d) official_split equals csv', split_ok)
if ds == 'MR' and a.mr_src:
same = open(f'{R}/MR/official_split.csv', 'rb').read() == open(f'{a.mr_src}/original_splits.csv', 'rb').read()
rec('MR (d2) official_split.csv byte-identical to original_splits.csv', same)
# (e) load_dataset
try:
from datasets import load_dataset
for ds in ('MR', 'CR'):
d = load_dataset(R, ds, split='all', streaming=True)
r = next(iter(d)); im = r['image']; mk = r['mask']
import numpy as np
ok = np.array(im).shape[:2] == (480, 640) and np.array(mk).shape[:2] == (480, 640)
rec(f'{ds} (e) load_dataset ok, decoded shape', ok, str(np.array(im).shape))
except ImportError:
print('datasets not installed: skipping (e)')
# (f) unpack round trip
tmp = os.path.join(R, '_tmp_unpack')
shutil.rmtree(tmp, ignore_errors=True)
subprocess.run([sys.executable, os.path.join(R, 'unpack_to_png.py'), R, tmp], check=True)
for ds in ('MR', 'CR'):
ok = True; n = 0
for r in rows(ds):
stem = f"{r['video_id']}_frame_{r['frame_index']:04d}"
for kind in ('image', 'mask'):
p = f'{tmp}/{ds}/{kind}s/{r["video_id"]}/{stem}.png'
n += 1
if not os.path.exists(p) or shaf(p) != sha(r[kind]['bytes']): ok = False
cs = read_csv(f'{R}/{ds}/official_split.csv')
exp = {'train': set(), 'validation': set(), 'test': set()}
for (v, fi), s in cs.items():
for p in s.split('+'): exp[p].add(f'{v}/{v}_frame_{fi:04d}')
for part, name in (('train', 'train.txt'), ('validation', 'val.txt'), ('test', 'test.txt')):
got = open(f'{tmp}/{ds}/{name}').read().split()
ok = ok and set(got) == exp[part] and len(got) == len(exp[part])
rec(f'{ds} (f) unpack round trip: {n} files sha256 equal, lists correct', ok)
shutil.rmtree(tmp, ignore_errors=True)
print('\n%-72s %s' % ('check', 'result'))
for n, s, note in res: print('%-72s %s %s' % (n, s, note))
print('OVERALL', 'PASS' if all(s == 'PASS' for _, s, _ in res) else 'FAIL')
sys.exit(0 if all(s == 'PASS' for _, s, _ in res) else 1)