dflow_2b / dflow /layout.py
data-archetype's picture
dflow_2b 0.215: MOSS layout support
0957ad9 verified
Raw History Blame Contribute Delete
21.1 kB
"""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.")