File size: 21,138 Bytes
6daffc2 0957ad9 6daffc2 0957ad9 6daffc2 0957ad9 6daffc2 0957ad9 6daffc2 0957ad9 6daffc2 0957ad9 6daffc2 0957ad9 6daffc2 0957ad9 6daffc2 0957ad9 6daffc2 0957ad9 6daffc2 0957ad9 6daffc2 0957ad9 6daffc2 0957ad9 6daffc2 0957ad9 6daffc2 0957ad9 6daffc2 0957ad9 6daffc2 0957ad9 6daffc2 0957ad9 6daffc2 0957ad9 6daffc2 0957ad9 6daffc2 0957ad9 6daffc2 0957ad9 6daffc2 0957ad9 6daffc2 0957ad9 6daffc2 0957ad9 6daffc2 0957ad9 6daffc2 0957ad9 6daffc2 | 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 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 | """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.
MOSS-Image layouts are accepted too and converted to that form:
- a model-facing MOSS prompt (``bbox`` in ``abs_centralized`` ``yxyx`` pixels)
keeps its items, with a bare full-canvas ``panel`` put first when it has
none (every training layout had one);
- a MOSS editable draft (``width``, ``height``, ``bbox`` in ``abs`` ``xyxy``
pixels from the top-left) is compiled as MOSS's ``compile_prompt.py`` does,
then given the panel the same way.
"""
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_uncompiled_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"})
# MOSS-Image editable drafts: top-left pixel boxes on a canvas they name.
_DRAFT_COORD_SPACE = "abs"
_DRAFT_BOX_FORMAT = "xyxy"
_DRAFT_KEYS = frozenset({"width", "height", *_COMPILED_KEYS})
_DRAFT_SUMMARY_KEYS = frozenset({*_SUMMARY_KEYS, "palette"})
_DRAFT_ITEM_KEYS = frozenset({"label", "bbox", "text", *_ENTRY_FIELDS})
# 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"
# Labels a MOSS editable draft may use (its compiler adds no panel).
_DRAFT_LABELS = frozenset({LayoutLabel.CHARACTER, LayoutLabel.OBJECT, LayoutLabel.TEXT})
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 or a MOSS draft also passes; ``is_uncompiled_layout`` tells them apart.
"""
parsed = _json_object(text)
return parsed is not None and set(parsed) >= _JSON_PROMPT_KEYS
def is_uncompiled_layout(text: str) -> bool:
"""Whether ``text`` is a stored layout (``summary``, ``frame``, ``items``)
or a MOSS editable draft (``bbox_coord_space`` ``abs``), either of which
needs ``compile_layout`` at the image size before it can be encoded."""
parsed = _json_object(text)
return parsed is not None and (
set(parsed) == _STORED_KEYS
or parsed.get("bbox_coord_space") == _DRAFT_COORD_SPACE
)
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 _require_list(value: object, *, where: str) -> list[object]:
"""Return ``value`` as a JSON list.
Raises:
LayoutError: If it is not one.
"""
match value:
case list():
return value
case _:
raise LayoutError(f"{where} must be a JSON list.")
def _check_canvas_box(box: object, *, width: int, height: int, where: str) -> None:
"""Check that a compiled (``abs_centralized``, ``yxyx``) box lies on the
``width`` x ``height`` canvas.
Raises:
LayoutSizeMismatchError: If it leaves the canvas.
LayoutError: If it is not four ordered integers.
"""
y0, x0, y1, x1 = _four_ints(box, where=f"{where}.bbox")
if not (y0 < y1 and x0 < x1):
raise LayoutError(f"{where}.bbox {box!r} must be [y0, x0, y1, x1], ordered.")
top, left, bottom, right = panel_box(width, height)
if y0 < top or x0 < left or y1 > bottom or x1 > right:
raise LayoutSizeMismatchError(
f"{where}.bbox {box!r} leaves the {width}x{height} canvas "
f"[{top}, {left}, {bottom}, {right}]: the layout is for a larger image."
)
def _checked_compiled(
layout: Mapping[str, object], *, width: int, height: int
) -> list[Mapping[str, object]]:
"""Check a compiled prompt (this package's or a MOSS-Image one) against
the image size and return its items.
Raises:
LayoutSizeMismatchError: If a box leaves the canvas.
LayoutError: If the prompt is not a compiled layout.
"""
if set(layout) != _COMPILED_KEYS:
raise LayoutError(
"A compiled layout needs exactly the keys summary, items, "
f"bbox_coord_space and bbox_format; got {sorted(layout)}."
)
if (
layout["bbox_coord_space"] != _COORD_SPACE
or layout["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}."
)
raw_items = _require_list(layout["items"], where="items")
items = [
_require_object(raw, where=f"items[{p}]") for p, raw in enumerate(raw_items)
]
for pos, item in enumerate(items):
if "bbox" not in item:
raise LayoutError(f"items[{pos}] needs a bbox [y0, x0, y1, x1].")
_check_canvas_box(
item["bbox"], width=width, height=height, where=f"items[{pos}]"
)
return items
def _with_panel(
summary: Mapping[str, object],
items: list[Mapping[str, object]],
*,
width: int,
height: int,
) -> str:
"""Serialize a compiled prompt as one-line JSON, with a bare full-canvas
``panel`` put first when the first item is not a panel."""
if not items or items[0].get("label") != LayoutLabel.PANEL:
items = [
{"label": LayoutLabel.PANEL.value, "bbox": panel_box(width, height)},
*items,
]
prompt = {
"summary": dict(summary),
"items": [dict(item) for item in items],
"bbox_coord_space": _COORD_SPACE,
"bbox_format": _BOX_FORMAT,
}
return json.dumps(prompt, ensure_ascii=False, separators=(",", ":"))
def _finite_number(value: object) -> bool:
"""Whether ``value`` is a finite int or float (booleans excluded)."""
match value:
case bool():
return False
case int():
return True
case float():
return math.isfinite(value)
case _:
return False
def _draft_box(box: object, *, width: int, height: int, where: str) -> list[int]:
"""Return a MOSS draft box (``xyxy`` pixels from the top-left) as centred
``yxyx`` pixels, as MOSS's ``compile_prompt.py`` does: min edges floored
and max edges ceiled after rounding to 9 decimals, then shifted by
``height // 2`` / ``width // 2``.
Raises:
LayoutError: If it is not four ordered finite numbers on the canvas.
"""
match box:
case list() if len(box) == 4 and all(_finite_number(v) for v in box):
x0, y0, x1, y1 = (float(v) for v in box)
case _:
raise LayoutError(f"{where}.bbox must be four finite numbers, got {box!r}.")
if not (0 <= x0 < x1 <= width and 0 <= y0 < y1 <= height):
raise LayoutError(
f"{where}.bbox {box!r} must be [x0, y0, x1, y1] inside the "
f"{width}x{height} canvas."
)
return [
math.floor(round(y0, _BOX_EDGE_DECIMALS)) - height // 2,
math.floor(round(x0, _BOX_EDGE_DECIMALS)) - width // 2,
math.ceil(round(y1, _BOX_EDGE_DECIMALS)) - height // 2,
math.ceil(round(x1, _BOX_EDGE_DECIMALS)) - width // 2,
]
def _draft_summary(value: object) -> Mapping[str, object]:
"""Return a MOSS draft's checked ``summary`` (it may carry a palette)."""
summary = _require_object(value, where="summary")
_require_keys(summary, allowed=_DRAFT_SUMMARY_KEYS, where="summary")
for key in ("meta", "palette"):
if key in summary:
_require_string_list(summary[key], where=f"summary.{key}")
for key in ("canvas", "caption"):
if key in summary:
_require_string(summary[key], where=f"summary.{key}")
return summary
def _draft_item(
raw: object, *, width: int, height: int, where: str
) -> dict[str, object]:
"""Return a MOSS draft item with its box compiled, keys in draft order."""
item = _require_object(raw, where=where)
_require_keys(item, allowed=_DRAFT_ITEM_KEYS, where=where)
if item.get("label") not in _DRAFT_LABELS:
raise LayoutError(
f"{where}.label must be one of {sorted(_DRAFT_LABELS)}, "
f"got {item.get('label')!r}."
)
if "bbox" not in item:
raise LayoutError(f"{where} needs a bbox [x0, y0, x1, y1] in pixels.")
if item["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)
return {
key: _draft_box(value, width=width, height=height, where=where)
if key == "bbox"
else value
for key, value in item.items()
}
def _compile_draft(layout: Mapping[str, object], *, width: int, height: int) -> str:
"""Compile a MOSS-Image editable draft at ``width`` x ``height``.
Raises:
LayoutSizeMismatchError: If the draft is for another size.
LayoutError: If the draft is malformed.
"""
if set(layout) != _DRAFT_KEYS:
raise LayoutError(
f"A MOSS draft needs exactly the keys {sorted(_DRAFT_KEYS)}; "
f"got {sorted(layout)}."
)
if layout["bbox_format"] != _DRAFT_BOX_FORMAT:
raise LayoutError(f"A MOSS draft must use bbox_format={_DRAFT_BOX_FORMAT!r}.")
if (layout["width"], layout["height"]) != (width, height):
raise LayoutSizeMismatchError(
f"This MOSS draft is for {layout['width']}x{layout['height']} "
f"(width x height); the image is {width}x{height}."
)
summary = _draft_summary(layout["summary"])
raw_items = _require_list(layout["items"], where="items")
items: list[Mapping[str, object]] = [
_draft_item(raw, width=width, height=height, where=f"items[{pos}]")
for pos, raw in enumerate(raw_items)
]
return _with_panel(summary, items, width=width, height=height)
def _compile_parsed(layout: Mapping[str, object], *, width: int, height: int) -> str:
"""Compile a parsed layout of any accepted kind (see the module docstring).
Raises:
LayoutSizeMismatchError: If the layout is for another size.
LayoutError: If the layout is malformed.
"""
match layout.get("bbox_coord_space"):
case None:
return _compile_stored(layout, width=width, height=height)
case str() as space if space == _DRAFT_COORD_SPACE:
return _compile_draft(layout, width=width, height=height)
case _:
items = _checked_compiled(layout, width=width, height=height)
summary = _require_object(layout["summary"], where="summary")
return _with_panel(summary, items, width=width, height=height)
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, a MOSS-Image editable draft or a compiled
prompt (this package's or a MOSS-Image one), as JSON text or a
parsed mapping.
width: Image width in pixels.
height: Image height in pixels.
Returns:
The compiled prompt as one-line JSON. A stored layout compiles
byte-identically to the training-time compile, and this package's
compiled prompts come back unchanged; any other prompt keeps its items
and gets a bare full-canvas panel first if it has none.
Raises:
LayoutSizeMismatchError: If the layout 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.")
return _compile_parsed(parsed, width=width, height=height)
case Mapping() as layout:
return _compile_parsed(layout, width=width, height=height)
case _:
raise TypeError("layout_json must be JSON text or a mapping.")
|