clevrer-lite-example / clevrer_lite /generate_dataset.py
jimchen2's picture
Upload folder using huggingface_hub
06b3545 verified
Raw History Blame Contribute Delete
4.61 kB
#!/usr/bin/env python3
"""Generate a small CLEVRER-lite dataset (GIF videos + JSON annotations).
Examples:
python -m clevrer_lite.generate_dataset --num-videos 8 --num-frames 64 --frame-size 128
python -m clevrer_lite.generate_dataset --out data/big --num-videos 1000 --num-frames 128
"""
import argparse
import json
import os
import time
import numpy as np
from PIL import Image
from . import CLEVRERLiteEnv, config, simulate
def describe_events(spec, ev):
"""Human-readable event descriptions for the annotation file."""
objs = {o["idx"]: o for o in spec}
def ref(i):
return "the {} {}".format(objs[i]["color"], objs[i]["shape"])
collisions = [{
"frame": e["frame"],
"objects": e["objects"],
"description": f"{ref(e['objects'][0])} collided with {ref(e['objects'][1])}",
} for e in ev["collisions"]]
motion = []
for o, sts in ev["starts"].items():
for s in sts:
cause = None
for e in ev["collisions"]:
a, b = e["objects"]
if o in (a, b) and abs(e["frame"] - s) <= config.CAUSE_WINDOW_FRAMES:
cause = e
break
motion.append({"object": o, "type": "start", "frame": s,
"cause_collision": cause})
return {"collision_events": collisions, "motion_events": motion,
"initially_moving": ev["initially_moving"]}
def main():
ap = argparse.ArgumentParser(description="Generate a CLEVRER-lite dataset")
ap.add_argument("--out", default="output")
ap.add_argument("--num-videos", type=int, default=8)
ap.add_argument("--num-frames", type=int, default=64)
ap.add_argument("--frame-size", type=int, default=128)
ap.add_argument("--seed", type=int, default=0)
ap.add_argument("--gif-fps", type=int, default=12)
ap.add_argument("--max-questions", type=int, default=8)
args = ap.parse_args()
video_dir = os.path.join(args.out, "videos")
os.makedirs(video_dir, exist_ok=True)
env = CLEVRERLiteEnv(num_frames=args.num_frames, frame_size=args.frame_size)
annotations = []
t0 = time.time()
for v in range(args.num_videos):
obs, info = env.reset(seed=args.seed + v)
frames = [obs]
while True:
obs, reward, terminated, truncated, info = env.step(0) # passive
frames.append(obs)
if truncated:
break
ev = env.extract_events()
qs = env.build_questions(ev, max_questions=args.max_questions)
ev_public = {k: v for k, v in ev.items() if k not in ("moving", "speeds")}
fname = f"video_{v:05d}.gif"
imgs = [Image.fromarray(f) for f in frames]
imgs[0].save(os.path.join(video_dir, fname), save_all=True,
append_images=imgs[1:], duration=int(1000 / args.gif_fps),
loop=0)
record = {
"video_index": v,
"video_filename": f"videos/{fname}",
"num_frames": args.num_frames,
"frame_size": args.frame_size,
"fps": env.metadata["render_fps"],
"scene": {"objects": env.scene},
"events": describe_events(env.scene, ev),
"raw_events": {
"collisions": ev_public["collisions"],
"starts": {str(k): v for k, v in ev_public["starts"].items()},
"stops": {str(k): v for k, v in ev_public["stops"].items()},
"initially_moving": ev_public["initially_moving"],
"wall_hits": [list(map(int, w)) for w in ev_public["wall_hits"]],
},
"questions": qs,
}
annotations.append(record)
n_col = len(ev["collisions"])
print(f"[{v + 1}/{args.num_videos}] {fname}: "
f"{len(env.scene)} objects, {n_col} collisions, {len(qs)} questions")
with open(os.path.join(args.out, "annotations.json"), "w") as f:
json.dump(annotations, f, indent=2)
dt = time.time() - t0
print(f"\nDone: {args.num_videos} videos in {dt:.1f}s "
f"({dt / args.num_videos:.2f}s/video) -> {args.out}/")
print(f"Total questions: {sum(len(a['questions']) for a in annotations)}")
# quick distribution summary
from collections import Counter
types = Counter(q["question_type"] for a in annotations for q in a["questions"])
print("Question types:", dict(types))
answers = Counter(q["answer"] for a in annotations for q in a["questions"])
print("Top answers:", dict(answers.most_common(8)))
if __name__ == "__main__":
main()