File size: 5,410 Bytes
f70bfa9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Make the example predictions: the ground truth of the first N images of a split and
predictions built from it, each showing what one kind of error costs.

    python make_examples.py <variant>/val examples/ [--n 300]

Writes ``examples/gt.jsonl``, ``examples/prompts.jsonl`` (the ground truth as prompt text) and
one ``examples/pred/<name>.jsonl`` per kind (seed 0):

- ``same``: the ground truth, vertex ids renamed and vertices shuffled.
- ``no_text``: ``same`` with every text removed (names, descriptions).
- ``jitter_05`` / ``jitter_15``: every box shifted by a normal 5% / 15% of its size.
- ``flat``: every vertex hung directly off the image (relations kept).
- ``no_relations``: every relation removed.
- ``prompt_roundtrip``: the ground truth written as prompt text and read back
  (``prompt_to_graph.py --types infer``), the best a prompt-text model can reach.
- ``other_image``: each image given another image's graph.
- ``half_missing``: predictions for every other image only.
"""

import argparse
import copy
import json
import random
from pathlib import Path

from kohakugbc_data import PromptDag
from kohakugbc_data.dataset import GbcDataset

from prompt_to_graph import to_graph


def rename(g: dict, rnd: random.Random, text: bool) -> dict:
    """``g`` with new vertex ids, shuffled vertices, and its texts kept or dropped."""
    names = {v["vertex_id"]: f"v{k}" for k, v in enumerate(g["vertices"])}
    out = []
    for v in g["vertices"]:
        edges = [{"target": names[e["target"]], **({"text": e["text"]} if text else {})}
                 for e in v["out_edges"]]  # fmt: skip
        out.append({"vertex_id": names[v["vertex_id"]], "label": v["label"], "bbox": v["bbox"],
                    "descs": v["descs"] if text else [], "out_edges": edges})  # fmt: skip
    rnd.shuffle(out)
    return {"vertices": out}


def jitter(g: dict, rnd: random.Random, sigma: float) -> dict:
    g = copy.deepcopy(g)
    for v in g["vertices"]:
        if v["label"] in ("entity", "composition"):
            b = v["bbox"]
            w, h = b["right"] - b["left"], b["bottom"] - b["top"]
            dx, dy = rnd.gauss(0, sigma) * w, rnd.gauss(0, sigma) * h
            v["bbox"] = {"left": b["left"] + dx, "top": b["top"] + dy, "right": b["right"] + dx,
                         "bottom": b["bottom"] + dy, "confidence": None}  # fmt: skip
    return g


def flat(g: dict) -> dict:
    g = copy.deepcopy(g)
    by = {v["vertex_id"]: v for v in g["vertices"]}
    plain = [v["vertex_id"] for v in g["vertices"] if v["label"] in ("entity", "composition")]
    name = {}
    for v in g["vertices"]:
        for e in v["out_edges"]:
            if e.get("text"):
                name.setdefault(e["target"], e["text"])
    for v in g["vertices"]:
        if v["label"] == "relation":
            continue
        keep = [e for e in v["out_edges"] if by[e["target"]]["label"] == "relation"]
        if v["label"] == "image":
            keep += [{"target": t, "text": name.get(t, "")} for t in plain]
        v["out_edges"] = keep
    return g


def no_relations(g: dict) -> dict:
    g = copy.deepcopy(g)
    rel = {v["vertex_id"] for v in g["vertices"] if v["label"] == "relation"}
    g["vertices"] = [v for v in g["vertices"] if v["vertex_id"] not in rel]
    for v in g["vertices"]:
        v["out_edges"] = [e for e in v["out_edges"] if e["target"] not in rel]
    return g


def write(path: Path, rows: list) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    with open(path, "w", encoding="utf-8") as f:
        f.writelines(json.dumps(r, ensure_ascii=False) + "\n" for r in rows)


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("split_dir")
    ap.add_argument("out")
    ap.add_argument("--n", type=int, default=300)
    a = ap.parse_args()
    out = Path(a.out)
    ds = GbcDataset(a.split_dir, image=None, meta=False)
    samples = [ds[i] for i in range(min(a.n, len(ds)))]
    keys = [s.key for s in samples]
    gts = [json.loads(s.graph.to_json()) for s in samples]
    prompts = [s.graph.prompt(width=s.w, height=s.h) for s in samples]
    write(out / "gt.jsonl", [{"key": k, "graph": g} for k, g in zip(keys, gts, strict=True)])
    write(out / "prompts.jsonl",
          [{"key": k, "prompt": p} for k, p in zip(keys, prompts, strict=True)])  # fmt: skip

    rnd = random.Random(0)
    preds = {
        "same": [rename(g, rnd, True) for g in gts],
        "no_text": [rename(g, rnd, False) for g in gts],
        "jitter_05": [rename(jitter(g, rnd, 0.05), rnd, True) for g in gts],
        "jitter_15": [rename(jitter(g, rnd, 0.15), rnd, True) for g in gts],
        "flat": [rename(flat(g), rnd, True) for g in gts],
        "no_relations": [rename(no_relations(g), rnd, True) for g in gts],
        "prompt_roundtrip": [to_graph(PromptDag.parse(p).to_dict(), "infer") for p in prompts],
        "other_image": [rename(gts[(k + 1) % len(gts)], rnd, True) for k in range(len(gts))],
    }
    for name, graphs in preds.items():
        write(out / "pred" / f"{name}.jsonl",
              [{"key": k, "graph": g} for k, g in zip(keys, graphs, strict=True)])  # fmt: skip
    half = list(zip(keys, preds["same"], strict=True))[::2]
    write(out / "pred" / "half_missing.jsonl", [{"key": k, "graph": g} for k, g in half])
    print(f"{len(keys)} images, {len(preds) + 1} predictions -> {out}")


if __name__ == "__main__":
    main()