partial-prompting-ds / scripts /visualize.py
Enzo-py's picture
Sync from local folder
e2cf5a4 verified
Raw History Blame Contribute Delete
6.06 kB
"""Show a stimulus (image, prompt, segmentation) or a whole minimal pair.
python scripts/visualize.py S46 # one stimulus
python scripts/visualize.py X-REL-CAT-LEFT-DOG-RICH # every member of a pair, side by side
python scripts/visualize.py S46 --out s46.png # save instead of opening a window
python scripts/visualize.py --list # list the stimuli and the pairs
Objects named in the prompt are outlined in green, unmentioned ones in orange, negated ones
("with no lamp") in purple; background regions (sky, wall, floor...) are labelled in grey.
Run it from a local copy of the dataset (git clone, or huggingface_hub.snapshot_download), or point
--root at one. Needs: pip install matplotlib pillow numpy
"""
import argparse
import json
import sys
import textwrap
from pathlib import Path
import numpy as np
from PIL import Image
STATUS = {"mentioned": "#2e9e44", "unmentioned": "#e07b00", "negated": "#8e44ad", "background": "#7f7f7f"}
def load(root):
rows = [json.loads(l) for l in open(root / "data" / "metadata.jsonl", encoding="utf-8") if l.strip()]
pairs = [json.loads(l) for l in open(root / "pairs" / "pairs.jsonl", encoding="utf-8") if l.strip()]
return {r["sample_id"]: r for r in rows}, {p["pair_id"]: p for p in pairs}
def segment_ids(root, row):
seg = np.asarray(Image.open(root / row["segmentation"]).convert("RGB"), dtype=np.uint32)
return seg[..., 0] + 256 * seg[..., 1] + 256 ** 2 * seg[..., 2]
def status(obj, stuff_ids):
if obj["negated"]:
return "negated"
if obj["mentioned"]:
return "mentioned"
return "background" if obj["segment_id"] in stuff_ids else "unmentioned"
def draw(ax_img, ax_seg, root, row, role=None):
import matplotlib.patches as patches
image = np.asarray(Image.open(root / "data" / row["file_name"]).convert("RGB"))
title = f'{row["sample_id"]}{f" ({role})" if role else ""}: "{row["prompt"]}"'
ax_img.imshow(image)
ax_img.set_title(textwrap.fill(title, 75), fontsize=10)
if row.get("control_type"):
sub = f'control [{row["control_type"]}]'
else:
sub = f'{row["case_id"]} {row["subcategory"]}' + (f' [{row["case_variant"]}]' if row.get("case_variant") else "")
ax_img.set_xlabel(textwrap.fill(f"{sub}. Unmentioned: {row['unmentioned_content']}", 80), fontsize=8)
for ax in (ax_img, ax_seg):
ax.set_xticks([])
ax.set_yticks([])
if not row.get("segmentation"): # generated images: no segmentation yet, show the human description
ax_seg.axis("off")
text = row.get("description") or "(no segmentation)"
if row.get("generation_prompt"):
text += f'\n\nGeneration prompt ({row["image_source"]}, seed {row.get("generation_seed")}): {row["generation_prompt"]}'
ax_seg.text(0, 1, textwrap.fill(text, 70, replace_whitespace=False), va="top", fontsize=8, wrap=True)
return
ids = segment_ids(root, row)
info = json.load(open((root / row["segmentation"]).with_suffix(".json"), encoding="utf-8"))["segments_info"]
stuff_ids = {s["id"] for s in info if not s["isthing"]}
rng = np.random.default_rng(0)
overlay = image.astype(float) * 0.35
for obj in row["objects"]:
m = ids == obj["segment_id"]
overlay[m] += rng.integers(60, 255, 3) * 0.65
ax_seg.imshow(overlay.clip(0, 255).astype(np.uint8))
ax_seg.set_title("segmentation", fontsize=10)
for obj in row["objects"]:
st = status(obj, stuff_ids)
x, y, w, h = obj["bbox"]
if st != "background":
ax_seg.add_patch(patches.Rectangle((x, y), w, h, fill=False, edgecolor=STATUS[st], linewidth=1.8))
ax_seg.text(x + 3, y + 14, obj["label"], fontsize=7, color="white",
bbox=dict(facecolor=STATUS[st], edgecolor="none", pad=1.2, alpha=0.9))
def main():
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("id", nargs="?", help="a sample_id (S46) or a pair_id (P-C2, X-REL-...)")
p.add_argument("--root", type=Path, default=Path(__file__).resolve().parent.parent, help="dataset folder")
p.add_argument("--out", type=Path, help="save the figure to this file instead of showing it")
p.add_argument("--list", action="store_true", help="list the stimuli and the pairs")
args = p.parse_args()
samples, pairs = load(args.root)
if args.list or not args.id:
for s in samples.values():
print(f'{s["sample_id"]:5} {s["case_id"] or "ctl":3} "{s["prompt"]}"')
print()
for pr in pairs.values():
print(f'{pr["pair_id"]:30} {pr["axis"]:6} {pr["family_expected"]:11} {", ".join(m["sample_id"] for m in pr["members"])}')
return
import matplotlib
if args.out:
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
if args.id in samples:
members, title = [(samples[args.id], None)], None
elif args.id in pairs:
pr = pairs[args.id]
members = [(samples[m["sample_id"]], m["role"]) for m in pr["members"]]
title = f'{pr["pair_id"]}: same {"prompt" if pr["axis"] == "image" else "image"}, ' \
f'expected {pr["family_expected"]}'
else:
sys.exit(f"unknown id {args.id!r} (try --list)")
fig, axes = plt.subplots(len(members), 2, figsize=(11, 3.9 * len(members) + 0.4), squeeze=False)
for (row, role), (ax_img, ax_seg) in zip(members, axes):
draw(ax_img, ax_seg, args.root, row, role)
legend = [Line2D([0], [0], color=c, lw=4, label=k) for k, c in STATUS.items()]
fig.legend(handles=legend, loc="lower center", ncol=4, fontsize=8, frameon=False)
if title:
fig.suptitle(title, fontsize=11)
fig.tight_layout(rect=(0, 0.06 / len(members), 1, 1 - 0.04 / len(members) if title else 1))
if args.out:
fig.savefig(args.out, dpi=110)
print(f"saved {args.out}")
else:
plt.show()
if __name__ == "__main__":
main()