File size: 7,121 Bytes
ec627db
5042c76
 
ec627db
 
 
5042c76
ec627db
 
 
 
5042c76
ec627db
5042c76
ec627db
 
 
 
 
 
 
 
 
 
 
 
5042c76
365f8e2
5042c76
 
 
 
 
 
 
 
 
ec627db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5042c76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec627db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5042c76
 
ec627db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5042c76
 
 
 
ec627db
 
 
 
 
 
 
 
 
 
 
 
 
365f8e2
ec627db
 
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
"""Writes the situate_diffuse subset from a finished 3_situate_diffuse run: one row per scene, one picture column per model,
with what Sam 3.1 found, its masks and the scene's points next to each picture. The scoring is 3_situate_diffuse's own (scoring.py),
the mask colours are 4_visualize.py's.

    python make_situate_diffuse.py ../SITUATE-DIFFUSER26/3_situate_diffuse/results/v6_reprompts_hues
"""
import io
import json
import sys
from pathlib import Path

import numpy as np
from datasets import Dataset, Features, Image, Value
from PIL import Image as Picture, ImageChops, ImageFilter

HERE = Path(__file__).resolve().parent
CODE = HERE.parent / "situate-diffuse-clean/3_situate_diffuse"
sys.path.append(str(CODE))

from scoring import scene_hits, scene_points  # noqa: E402
from settings import MODELS  # noqa: E402

RUN = Path(sys.argv[1])
OUT = HERE / "situate_diffuse"
JUDGE = "sam3.1"
UNSCORED = {("chess", "pawns")}  # as in 3_score.py: left out of the points, still in found
SHARDS = 6  # parquet files of about 250 MB
ROW_GROUP = 20  # rows; with the page index the viewer reads only the rows it shows
COLOURS = {  # what Sam read -> mask colour, as in 4_visualize.py
    "red": (225, 40, 40), "orange": (245, 140, 30), "yellow": (245, 215, 30), "green": (40, 190, 60), "cyan": (40, 200, 220),
    "blue": (40, 90, 230), "purple": (150, 60, 200), "magenta": (230, 60, 190), "white": (250, 250, 250), "transparent": (190, 190, 190),
    "black": (30, 30, 30), "grey": (150, 150, 150), "solid": (40, 90, 230), "striped": (245, 140, 30), "cue or eight": (250, 250, 250),
    "cherry": (170, 0, 50), "strawberry": (255, 90, 90), "blackberry": (90, 30, 110), "blueberry": (60, 120, 245),
    "hazelnut": (245, 140, 30), "peanut": (40, 90, 230), "walnut": (230, 60, 190), "pine cone": (150, 150, 150),
    "bottle": (245, 140, 30), "glass": (90, 220, 240), "candle": (250, 250, 250), "flame": (245, 140, 30),
    "track": (0, 200, 255), "home": (255, 60, 200), "chess piece": (230, 60, 190),
}


def column(model):  # "qwen-image-2.1-turbo-reprompt" -> "qwen_image_2_1_turbo_reprompt", so SQL needs no quotes

    return model.replace("-", "_").replace(".", "_")


def read_rows(path):  # scene_id -> its row of a jsonl file

    rows = {}

    for line in path.read_text().splitlines():
        row = json.loads(line)
        rows[row["scene_id"]] = row

    return rows


def colour_of(thing):

    if thing["colour"]:
        return COLOURS[thing["colour"]]

    return COLOURS.get(thing["what"], COLOURS["grey"])


def mask_layer(masks, objects):  # transparent png: each object lightly filled and outlined in its colour on a contrasting rim

    layer = Picture.new("RGBA", (masks.shape[2], masks.shape[1]))

    for thing, mask in zip(objects, masks):
        rows, columns = np.nonzero(mask)

        if not len(rows):
            continue

        top, left = max(0, rows.min() - 8), max(0, columns.min() - 8)  # draw only round the object, filtering all 1024 is slow
        bottom, right = rows.max() + 9, columns.max() + 9
        shape = Picture.fromarray(mask[top:bottom, left:right].astype(np.uint8) * 255)
        rim = ImageChops.difference(shape.filter(ImageFilter.MaxFilter(7)), shape.filter(ImageFilter.MinFilter(3)))
        edge = ImageChops.difference(shape.filter(ImageFilter.MaxFilter(5)), shape.filter(ImageFilter.MinFilter(3)))
        colour = colour_of(thing)
        rim_colour = (25, 25, 30) if sum(colour) > 300 else (255, 255, 255)
        corner = (int(left), int(top))
        layer.paste(Picture.new("RGBA", shape.size, colour + (70,)), corner, shape)
        layer.paste(Picture.new("RGBA", shape.size, rim_colour + (255,)), corner, rim)
        layer.paste(Picture.new("RGBA", shape.size, colour + (255,)), corner, edge)

    out = io.BytesIO()
    layer.save(out, "PNG", optimize=True)

    return out.getvalue()


def features():

    fields = {"scene_id": Value("string"),
              "category": Value("string"),
              "objects": Value("int32"),
              "seed": Value("int32"),
              "prompt": Value("string"),
              "expected": Value("string"),
              "possible_points": Value("int32")}

    for model in MODELS:
        name = column(model)
        fields[name] = Image()

        if model.endswith("-reprompt"):
            fields[f"{name}_rewrite"] = Value("string")

        fields[f"{name}_masks"] = Image()
        fields[f"{name}_objects"] = Value("string")
        fields[f"{name}_found"] = Value("string")
        fields[f"{name}_points"] = Value("int32")
        fields[f"{name}_uncapped"] = Value("int32")
        fields[f"{name}_hits"] = Value("int32")

    return Features(fields)


def rows():

    scenes = [json.loads(line) for line in (RUN / "scenes.jsonl").read_text().splitlines()]
    answers = {model: read_rows(RUN / model / JUDGE / "answers.jsonl") for model in MODELS}
    rewrites = {model: read_rows(RUN / model / "reprompts.jsonl") for model in MODELS if model.endswith("-reprompt")}

    for scene in scenes:
        scene_id = scene["scene_id"]
        checks = answers[MODELS[0]][scene_id]["checks"]
        expected = {check["check"]: check["expected"] for check in checks}
        scored = [check for check in checks if (scene["category"], check["check"]) not in UNSCORED]
        _, possible = scene_points(scored)
        row = {"scene_id": scene_id,
               "category": scene["category"],
               "objects": int(scene_id.split("_")[-2]),
               "seed": scene["seed"],
               "prompt": scene["prompt"],
               "expected": json.dumps(expected),
               "possible_points": possible}

        for model in MODELS:
            name = column(model)
            checks = answers[model][scene_id]["checks"]
            scored = [check for check in checks if (scene["category"], check["check"]) not in UNSCORED]
            points, _ = scene_points(scored)
            picture = RUN / model / f"{scene_id}.jpg"
            row[name] = {"bytes": picture.read_bytes(), "path": f"{model}/{scene_id}.jpg"}

            if model in rewrites:
                row[f"{name}_rewrite"] = rewrites[model][scene_id]["reprompt"]

            objects = answers[model][scene_id]["objects"]
            masks = np.load(RUN / model / JUDGE / "masks" / f"{scene_id}.npz")["masks"]
            row[f"{name}_masks"] = {"bytes": mask_layer(masks, objects), "path": f"{model}/{scene_id}_masks.png"}
            row[f"{name}_objects"] = json.dumps(objects)
            row[f"{name}_found"] = json.dumps({check["check"]: check["found"] for check in checks})
            row[f"{name}_points"] = max(0, points)
            row[f"{name}_uncapped"] = points
            row[f"{name}_hits"] = scene_hits(scored)

        yield row


data = Dataset.from_generator(rows, features=features())
OUT.mkdir(exist_ok=True)

for index in range(SHARDS):
    shard = data.shard(SHARDS, index, contiguous=True)
    shard.to_parquet(OUT / f"test-{index:05d}-of-{SHARDS:05d}.parquet", batch_size=ROW_GROUP, write_page_index=True)

print(f"{len(data)} scenes, {len(data.column_names)} columns -> {OUT}")