dflow-2b / dflow /layout.py
multimodalart's picture
multimodalart HF Staff
Upload folder using huggingface_hub
00ff9d7 verified
Raw History Blame Contribute Delete
13.8 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.
"""
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.")