File size: 4,985 Bytes
44c8862
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
"""Build caption comparisons from CLEVR-CoGenT scene annotations."""

import json
import random
import re
from collections import defaultdict
from dataclasses import dataclass
from itertools import combinations
from pathlib import Path

import numpy as np
import torch
from PIL import Image
from torch.utils.data import Dataset

COLORS = ("gray", "red", "blue", "green", "brown", "purple", "cyan", "yellow")
SHAPES = ("cube", "cylinder", "sphere")
RELATIONS = ("left", "right")
VOCAB = COLORS + SHAPES + RELATIONS
TOKEN = {word: index for index, word in enumerate(VOCAB)}
MARGIN = 0.08
CAPTION = re.compile(
    rf"(?:a )?({'|'.join(COLORS)}) ({'|'.join(SHAPES)}) (left|right) of "
    rf"(?:a )?({'|'.join(COLORS)}) ({'|'.join(SHAPES)})[.]?"
)


def encode_caption(caption):
    match = CAPTION.fullmatch(" ".join(caption.lower().split()))
    if not match:
        raise ValueError("Use captions such as 'a red cube left of a blue cylinder'.")
    return [TOKEN[word] for word in match.groups()]


@dataclass
class Comparison:
    captions: tuple
    centers: tuple
    cross_shape: bool


def compare_scene(objects):
    """Use image-plane x for truth and reject negatives true of any scene objects."""
    locations = defaultdict(list)
    for obj in objects:
        locations[obj[:2]].append(obj[2:])

    for first, second in combinations(objects, 2):
        color_a, shape_a, x_a, y_a = first
        color_b, shape_b, x_b, y_b = second
        if color_a == color_b or abs(x_a - x_b) < MARGIN:
            continue
        if len(locations[first[:2]]) != 1 or len(locations[second[:2]]) != 1:
            continue
        for a, b in ((first, second), (second, first)):
            color_a, shape_a, x_a, y_a = a
            color_b, shape_b, x_b, y_b = b
            sign = 1 if x_a > x_b else -1
            direct = "right" if sign == 1 else "left"
            flipped = "left" if sign == 1 else "right"
            swapped_a = locations[(color_b, shape_a)]
            swapped_b = locations[(color_a, shape_b)]
            if any(sign * (u[0] - v[0]) >= -MARGIN / 2 for u in swapped_a for v in swapped_b):
                continue
            yield Comparison(
                captions=(
                    (color_a, shape_a, direct, color_b, shape_b),
                    (color_b, shape_a, direct, color_a, shape_b),
                    (color_a, shape_a, flipped, color_b, shape_b),
                ),
                centers=((x_a, y_a), (x_b, y_b)),
                cross_shape=shape_a != shape_b,
            )


def image_array(image, resolution):
    with image.convert("RGB").resize((resolution, resolution), Image.Resampling.BILINEAR) as resized:
        return np.array(resized, dtype=np.uint8)


class CoGenT(Dataset):
    def __init__(self, root, split, resolution, limit=None):
        root = Path(root)
        annotations = json.loads((root / "scenes" / f"CLEVR_{split}_scenes.json").read_text())
        image_dir = root / "images" / split
        manifest = root / f"{split}.txt"
        files = manifest.read_text().splitlines() if manifest.exists() else sorted(p.name for p in image_dir.glob("*.png"))
        scenes = {scene["image_filename"]: scene for scene in annotations["scenes"]}
        self.images = []
        self.records = []
        self.index = []
        self.split = split
        self.epoch = 0
        for filename in files[:limit]:
            scene = scenes[filename]
            with Image.open(image_dir / filename) as image:
                width, height = image.size
                objects = [
                    (obj["color"], obj["shape"], obj["pixel_coords"][0] / width, obj["pixel_coords"][1] / height)
                    for obj in scene["objects"]
                    if 0 <= obj["pixel_coords"][0] < width and 0 <= obj["pixel_coords"][1] < height
                ]
                records = list(compare_scene(objects))
                if not records:
                    continue
                self.images.append(torch.from_numpy(image_array(image, resolution)))
            random.Random(scene["image_index"]).shuffle(records)
            self.records.append(records)
            if split == "trainA":
                self.index.append((len(self.records) - 1, 0))
            else:
                self.index.extend((len(self.records) - 1, i) for i in range(min(len(records), 4)))
        if not self.index:
            raise ValueError(f"No usable comparisons for {split} under {root}")

    def __len__(self):
        return len(self.index)

    def __getitem__(self, index):
        image_index, record_index = self.index[index]
        records = self.records[image_index]
        if self.split == "trainA":
            record_index = self.epoch % len(records)
        record = records[record_index]
        tokens = torch.tensor([[TOKEN[word] for word in caption] for caption in record.captions])
        return self.images[image_index], tokens, torch.tensor(record.centers), record.cross_shape, image_index