File size: 13,783 Bytes
00ff9d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
"""Layout prompts: compile a stored layout into the prompt the model reads.

A stored layout is JSON with three parts:

- ``summary``: ``meta`` tags, ``canvas`` and a ``caption`` of the whole image;
- ``frame``: ``caption``, ``tags`` and ``palette`` of the whole canvas;
- ``items``: boxes, each with a ``label`` (character, object, text), optional
  ``caption``, ``tags`` and ``palette``, a ``box_2d`` ``[y0, x0, y1, x1]`` on a
  0-1000 scale and, for text items, the exact ``text``.

The model was trained on the compiled form, which depends on the image size:
the frame becomes a full-canvas ``panel`` item and every box becomes integer
pixels centred on the image centre (``abs_centralized``, ``yxyx``). Optional
fields may be left out; training dropped them at random.
"""

from __future__ import annotations

import json
import math
from collections.abc import Mapping
from enum import StrEnum

__all__ = [
    "LAYOUT_BOX_SCALE",
    "LayoutError",
    "LayoutLabel",
    "LayoutSizeMismatchError",
    "compile_layout",
    "is_compiled_layout",
    "is_stored_layout",
    "panel_box",
]

# Normalized box scale of stored layouts.
LAYOUT_BOX_SCALE = 1000
# Rounding applied before flooring/ceiling box edges (keeps exact edges exact).
_BOX_EDGE_DECIMALS = 9
# Optional descriptive fields of the frame and of every item, in compiled order.
_ENTRY_FIELDS = ("caption", "tags", "palette")
_SUMMARY_KEYS = frozenset({"meta", "canvas", "caption"})
_STORED_KEYS = frozenset({"summary", "frame", "items"})
_ITEM_KEYS = frozenset({"label", "box_2d", "text", *_ENTRY_FIELDS})
_COORD_SPACE = "abs_centralized"
_BOX_FORMAT = "yxyx"
_COMPILED_KEYS = frozenset({"summary", "items", "bbox_coord_space", "bbox_format"})
# Top-level keys every JSON prompt has; the text encoder tokenizes such prompts
# as structured JSON (character tokens for visible text only).
_JSON_PROMPT_KEYS = frozenset({"summary", "items"})


class LayoutLabel(StrEnum):
    """Item labels of a layout."""

    CHARACTER = "character"
    OBJECT = "object"
    TEXT = "text"
    PANEL = "panel"


class LayoutError(ValueError):
    """A layout is malformed."""


class LayoutSizeMismatchError(LayoutError):
    """A compiled layout prompt was compiled for another image size."""


def _json_object(text: str) -> dict[str, object] | None:
    """Return ``text`` parsed as a JSON object, or None if it is not one."""

    if not text.lstrip().startswith("{"):
        return None
    try:
        parsed = json.loads(text)
    except json.JSONDecodeError:
        return None
    match parsed:
        case dict():
            return parsed
        case _:
            return None


def is_compiled_layout(text: str) -> bool:
    """Whether ``text`` is a JSON layout prompt (an object with ``summary`` and
    ``items``).

    The text encoder tokenizes such prompts as structured JSON and never parses
    them for emphasis markup, exactly as in training. A stored (uncompiled)
    layout also passes this test; ``is_stored_layout`` tells them apart.
    """

    parsed = _json_object(text)
    return parsed is not None and set(parsed) >= _JSON_PROMPT_KEYS


def is_stored_layout(text: str) -> bool:
    """Whether ``text`` is a stored layout (``summary``, ``frame``, ``items``)
    that still needs ``compile_layout`` before it can be encoded."""

    parsed = _json_object(text)
    return parsed is not None and set(parsed) == _STORED_KEYS


def panel_box(width: int, height: int) -> list[int]:
    """Return the compiled full-canvas ``panel`` box ``[y0, x0, y1, x1]``.

    Raises:
        LayoutError: If the size is not positive.
    """

    if width <= 0 or height <= 0:
        raise LayoutError(f"Layout size must be positive, got {width}x{height}.")
    return [-(height // 2), -(width // 2), height - height // 2, width - width // 2]


def _four_ints(value: object, *, where: str) -> tuple[int, int, int, int]:
    """Return ``value`` as four integers (booleans excluded).

    Raises:
        LayoutError: If it is not a list of four integers.
    """

    match value:
        case list() if len(value) == 4 and all(
            isinstance(item, int) and not isinstance(item, bool) for item in value
        ):
            a, b, c, d = (int(item) for item in value)
            return a, b, c, d
        case _:
            raise LayoutError(f"{where} must be four integers, got {value!r}.")


def _box_pixels(box: object, *, width: int, height: int, where: str) -> list[int]:
    """Return a 0-1000 ``yxyx`` box as centred integer pixels.

    Min edges are floored and max edges ceiled after rounding to 9 decimals,
    then shifted by ``height // 2`` / ``width // 2``.

    Raises:
        LayoutError: If ``box`` is not four ordered integers in 0..1000.
    """

    y0, x0, y1, x1 = _four_ints(box, where=f"{where}.box_2d")
    if not (0 <= y0 < y1 <= LAYOUT_BOX_SCALE and 0 <= x0 < x1 <= LAYOUT_BOX_SCALE):
        raise LayoutError(
            f"{where}.box_2d {box!r} must be [y0, x0, y1, x1] with "
            f"0 <= y0 < y1 <= {LAYOUT_BOX_SCALE} and 0 <= x0 < x1 <= "
            f"{LAYOUT_BOX_SCALE}."
        )

    def edge(value: int, size: int) -> float:
        return round(value * size / LAYOUT_BOX_SCALE, _BOX_EDGE_DECIMALS)

    return [
        math.floor(edge(y0, height)) - height // 2,
        math.floor(edge(x0, width)) - width // 2,
        math.ceil(edge(y1, height)) - height // 2,
        math.ceil(edge(x1, width)) - width // 2,
    ]


def _require_object(value: object, *, where: str) -> Mapping[str, object]:
    """Return ``value`` as a JSON object.

    Raises:
        LayoutError: If it is not one.
    """

    match value:
        case Mapping():
            return value
        case _:
            raise LayoutError(f"{where} must be a JSON object.")


def _require_keys(
    entry: Mapping[str, object], *, allowed: frozenset[str], where: str
) -> None:
    """Raise unless every key of ``entry`` is in ``allowed``."""

    unknown = sorted(set(entry) - allowed)
    if unknown:
        raise LayoutError(
            f"{where} has unknown keys {unknown}; allowed: {sorted(allowed)}."
        )


def _require_string_list(value: object, *, where: str) -> None:
    """Raise unless ``value`` is a list of strings."""

    match value:
        case list() if all(isinstance(item, str) for item in value):
            return
        case _:
            raise LayoutError(f"{where} must be a list of strings.")


def _require_string(value: object, *, where: str) -> None:
    """Raise unless ``value`` is a string."""

    if not isinstance(value, str):
        raise LayoutError(f"{where} must be a string.")


def _validated_entry_fields(entry: Mapping[str, object], *, where: str) -> None:
    """Check the optional ``caption``, ``tags`` and ``palette`` fields."""

    if "caption" in entry:
        _require_string(entry["caption"], where=f"{where}.caption")
    for key in ("tags", "palette"):
        if key in entry:
            _require_string_list(entry[key], where=f"{where}.{key}")


def _validated_summary(value: object) -> Mapping[str, object]:
    """Return the checked ``summary`` object."""

    summary = _require_object(value, where="summary")
    _require_keys(summary, allowed=_SUMMARY_KEYS, where="summary")
    if "meta" in summary:
        _require_string_list(summary["meta"], where="summary.meta")
    for key in ("canvas", "caption"):
        if key in summary:
            _require_string(summary[key], where=f"summary.{key}")
    return summary


def _validated_items(value: object) -> list[Mapping[str, object]]:
    """Return the checked ``items`` list."""

    match value:
        case list():
            raw_items: list[object] = value
        case _:
            raise LayoutError("items must be a JSON list.")
    items: list[Mapping[str, object]] = []
    for pos, raw in enumerate(raw_items):
        where = f"items[{pos}]"
        item = _require_object(raw, where=where)
        _require_keys(item, allowed=_ITEM_KEYS, where=where)
        label = item.get("label")
        if label not in {member.value for member in LayoutLabel}:
            raise LayoutError(
                f"{where}.label must be one of {[m.value for m in LayoutLabel]}, "
                f"got {label!r}."
            )
        if "box_2d" not in item:
            raise LayoutError(f"{where} needs a box_2d [y0, x0, y1, x1] on 0-1000.")
        if label == LayoutLabel.TEXT and "text" not in item:
            raise LayoutError(f"{where} is a text item and needs its exact 'text'.")
        if "text" in item:
            _require_string(item["text"], where=f"{where}.text")
        _validated_entry_fields(item, where=where)
        items.append(item)
    return items


def _compile_stored(layout: Mapping[str, object], *, width: int, height: int) -> str:
    """Compile a stored layout at ``width`` x ``height``.

    Raises:
        LayoutError: If the layout is malformed.
    """

    if set(layout) != _STORED_KEYS:
        raise LayoutError(
            "A stored layout needs exactly the keys summary, frame and items; got "
            f"{sorted(layout)}."
        )
    summary = _validated_summary(layout["summary"])
    frame = _require_object(layout["frame"], where="frame")
    _require_keys(frame, allowed=frozenset(_ENTRY_FIELDS), where="frame")
    _validated_entry_fields(frame, where="frame")
    items = _validated_items(layout["items"])
    panel: dict[str, object] = {"label": LayoutLabel.PANEL.value}
    panel.update({key: frame[key] for key in _ENTRY_FIELDS if key in frame})
    panel["bbox"] = panel_box(width, height)
    compiled_items: list[dict[str, object]] = [panel]
    for pos, item in enumerate(items):
        out: dict[str, object] = {"label": item["label"]}
        out.update({key: item[key] for key in _ENTRY_FIELDS if key in item})
        out["bbox"] = _box_pixels(
            item["box_2d"], width=width, height=height, where=f"items[{pos}]"
        )
        if "text" in item:
            out["text"] = item["text"]
        compiled_items.append(out)
    prompt = {
        "summary": dict(summary),
        "items": compiled_items,
        "bbox_coord_space": _COORD_SPACE,
        "bbox_format": _BOX_FORMAT,
    }
    return json.dumps(prompt, ensure_ascii=False, separators=(",", ":"))


def _compiled_size(items: object) -> tuple[int, int] | None:
    """Return the ``(width, height)`` a compiled prompt's panel encodes, or None."""

    match items:
        case [{"label": "panel", "bbox": list() as box}, *_]:
            try:
                y0, x0, y1, x1 = _four_ints(box, where="panel bbox")
            except LayoutError:
                return None
            width, height = x1 - x0, y1 - y0
            if width <= 0 or height <= 0 or box != panel_box(width, height):
                return None
            return width, height
        case _:
            return None


def _check_compiled(parsed: Mapping[str, object], *, width: int, height: int) -> None:
    """Check a compiled prompt's format and that its panel matches the size.

    Raises:
        LayoutSizeMismatchError: If the panel box is for another size.
        LayoutError: If the prompt is not a compiled layout.
    """

    if set(parsed) != _COMPILED_KEYS:
        raise LayoutError(
            "A compiled layout needs exactly the keys summary, items, "
            f"bbox_coord_space and bbox_format; got {sorted(parsed)}."
        )
    if (
        parsed["bbox_coord_space"] != _COORD_SPACE
        or parsed["bbox_format"] != _BOX_FORMAT
    ):
        raise LayoutError(
            f"A compiled layout must use bbox_coord_space={_COORD_SPACE!r} and "
            f"bbox_format={_BOX_FORMAT!r}."
        )
    size = _compiled_size(parsed["items"])
    if size is None:
        raise LayoutError(
            "A compiled layout's first item must be the full-canvas panel with an "
            "integer bbox."
        )
    if size != (width, height):
        raise LayoutSizeMismatchError(
            f"This layout prompt was compiled for {size[0]}x{size[1]} "
            f"(width x height); the image is {width}x{height}. Compile the "
            "stored layout again at the image size."
        )


def compile_layout(
    layout_json: str | Mapping[str, object], width: int, height: int
) -> str:
    """Return the layout prompt the model reads for a ``width`` x ``height`` image.

    Args:
        layout_json: A stored layout (JSON text or a parsed mapping), or an
            already compiled prompt (JSON text only), which is returned
            verbatim after its panel box is checked against the size.
        width: Image width in pixels.
        height: Image height in pixels.

    Returns:
        The compiled prompt: one-line JSON, byte-identical to the training-time
        compile of the same stored layout at this size.

    Raises:
        LayoutSizeMismatchError: If a compiled prompt is for another size.
        LayoutError: If the layout is malformed or the size is not positive.
    """

    panel_box(width, height)
    match layout_json:
        case str() as text:
            parsed = _json_object(text)
            if parsed is None:
                raise LayoutError("The layout is not a JSON object.")
            # Only compiled prompts carry a coordinate space; anything else is
            # read as a stored layout, whose own checks name a bad key.
            if "bbox_coord_space" not in parsed:
                return _compile_stored(parsed, width=width, height=height)
            _check_compiled(parsed, width=width, height=height)
            return text
        case Mapping() as layout:
            return _compile_stored(layout, width=width, height=height)
        case _:
            raise TypeError("layout_json must be JSON text or a mapping.")