tjcaspar's picture
ScreenRef annotations: initial release
89552cf
Raw History Blame Contribute Delete
4.49 kB
#!/usr/bin/env python3
"""Export annotations + an image tree to Parquet shards loadable with `datasets`.
Each row embeds the screenshot bytes, so `load_dataset("PrentisAI/ScreenRef")`
works without any path handling and the Hub viewer can render the images.
The `image` column uses the `datasets` Image() feature, so the Parquet schema
metadata carries the Hugging Face feature description. That metadata is written
by Dataset.from_dict(..., features=...); a hand-built pyarrow table would lose it.
Shards are cut per task at roughly --shard-bytes of image data. --task-index
processes the N-th task (in sorted order) only, so tasks can run in parallel and
a failed task can be rerun on its own. Afterwards, finalize.py renames the
shards to the Hub convention data/train-XXXXX-of-YYYYY.parquet.
Normally run through reexport.sh rather than directly.
"""
from __future__ import annotations
import argparse, io, json, os, sys, time
def rows_of(meta_entry):
root = meta_entry["root"]
with open(meta_entry["annotation"]) as f:
for line in f:
line = line.strip()
if not line:
continue
try:
d = json.loads(line)
except json.JSONDecodeError:
continue
im = d.get("image")
if isinstance(im, list):
im = im[0] if im else None
if not im:
continue
yield os.path.join(root, im), im, d
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--meta", default="meta/meta_full.json")
ap.add_argument("--out", default="parquet_out/data")
ap.add_argument("--task", default=None, help="process only this meta entry")
ap.add_argument("--task-index", type=int, default=None, help="process only the N-th task in sorted order")
ap.add_argument("--shard-bytes", type=int, default=800 * 2**20)
ap.add_argument("--limit", type=int, default=0, help="if >0, stop after N rows (smoke test)")
ap.add_argument("--overwrite", action="store_true")
args = ap.parse_args()
from datasets import Dataset, Features, Image, Value
meta = json.load(open(args.meta))
names = sorted(meta)
if args.task_index is not None:
if args.task_index >= len(names):
sys.exit(f"task-index {args.task_index} out of range ({len(names)} tasks)")
targets = [names[args.task_index]]
elif args.task:
targets = [args.task]
else:
targets = names
feats = Features({
"image": Image(),
"width": Value("int32"),
"height": Value("int32"),
"conversations": Value("string"), # raw JSON string, not re-interpreted
"task": Value("string"),
"conv_style": Value("string"),
})
os.makedirs(args.out, exist_ok=True)
for name in targets:
e = meta[name]
buf, nbytes, shard, n_rows, n_miss = [], 0, 0, 0, 0
t0 = time.time()
def flush():
nonlocal buf, nbytes, shard
if not buf:
return
path = os.path.join(args.out, f"{name}-{shard:04d}.parquet")
if os.path.exists(path) and not args.overwrite:
print(f" skip existing {os.path.basename(path)}")
else:
cols = {k: [r[k] for r in buf] for k in feats}
Dataset.from_dict(cols, features=feats).to_parquet(path)
print(f" wrote {os.path.basename(path)} {len(buf)} rows {nbytes/2**20:.0f} MiB")
buf, nbytes, shard = [], 0, shard + 1
for abspath, rel, d in rows_of(e):
if args.limit and n_rows >= args.limit:
break
try:
with open(abspath, "rb") as fh:
raw = fh.read()
except OSError:
n_miss += 1
continue
buf.append({
"image": {"bytes": raw, "path": rel},
"width": int(d.get("width") or 0),
"height": int(d.get("height") or 0),
"conversations": json.dumps(d.get("conversations", []), ensure_ascii=False),
"task": name,
"conv_style": e.get("conv_style", ""),
})
nbytes += len(raw); n_rows += 1
if nbytes >= args.shard_bytes:
flush()
flush()
print(f"[{name}] {n_rows} rows, {n_miss} missing images, {time.time()-t0:.0f}s")
if __name__ == "__main__":
main()