moss-reverse / layout_convert.py
jing96963's picture
reverse: shrink to 1024, no duplicate boxes, style/camera/interaction/size in captions
159f0ff verified
Raw History Blame Contribute Delete
8.44 kB
"""Pure conversion, deliberately independent of torch/transformers/Pillow."""
import json
import math
import re
def js_round(value):
return math.floor(value + 0.5)
def parse_output(raw):
raw = re.sub(r"<think>.*?</think>", "", raw, flags=re.S | re.I)
raw = re.sub(r"```(?:json)?|```", "", raw, flags=re.I).strip()
decoder = json.JSONDecoder()
for match in re.finditer(r"\{", raw):
try:
value, _ = decoder.raw_decode(raw[match.start():])
if isinstance(value, dict) and isinstance(value.get("caption"), str) and isinstance(value.get("items"), list):
return value
except ValueError:
pass
raise ValueError("模型未返回有效的 caption/items JSON")
def tilt(rotation):
angle = (rotation % 360 + 540) % 360 - 180
if angle == -180:
angle = 180
if abs(angle) < 1:
return ""
direction = "顺时针" if angle > 0 else "逆时针"
degrees = js_round(abs(angle))
if abs(angle) > 45:
return f"旋转约 {degrees}°({direction})"
return f"整体{direction}倾斜约 {degrees}°," + ("左高右低" if angle > 0 else "左低右高")
TEXT_LABELS = {"text", "文字", "文本", "标题", "字"}
BACKGROUND_LABELS = {"background", "背景"}
def normalize_item(source):
"""Models sometimes use Chinese/free-form labels (Qwen3-VL wrote 人物/文字/背景)
and omit `text`; map them onto text/object/background instead of failing."""
label = str(source.get("label", "")).strip().lower()
kind = str(source.get("kind", "")).strip().lower()
item = dict(source)
if kind in ("subject", "shape"):
item["kind"] = kind
if label in TEXT_LABELS and str(source.get("text", "")).strip():
item["kind"] = "text"
else:
label = "object"
elif kind == "text":
label = "text"
if label in BACKGROUND_LABELS:
item["label"] = "background"
return item
if label in TEXT_LABELS or (label not in ("object",) and source.get("text")):
item["label"] = "text"
if not str(item.get("text", "")).strip():
m = re.search(r"内容[为是::]\s*[“\"「]([^”\"」]+)[”\"」]", str(item.get("desc", "")))
if not m:
item["label"] = "object"
else:
item["text"] = m.group(1)
return item
item["label"] = "object"
return item
SUBJECT_WORDS = re.compile(r"人|女|男|孩|娃|爷|奶|他|她|模特|少年|少女|宝宝|猫|狗|动物|person|man|woman|girl|boy", re.I)
def kind_of(item, source):
if item["label"] == "text":
return "text"
kind = source.get("kind")
if kind in ("subject", "shape"):
return kind
first = str(source.get("desc", "")).split(",")[0]
return "subject" if SUBJECT_WORDS.search(first) else "shape"
def short_name(item):
if item["label"] == "text":
return " ".join(str(item.get("text", "")).split())[:12]
m = re.match(r"「(.*?)」", item["caption"])
if m:
return m.group(1)[:12]
head = re.split(r"[,,。]", item["caption"].split(":", 1)[-1])[0]
return (head or "物体")[:12]
def add_relations(items):
"""Same rule as the editor's toMoss(): pairs whose boxes overlap >=15% of the
smaller box get 位于…后面作为底衬 / 叠在…上方 (items are bottom->top)."""
def area(b):
return max(0, b[2] - b[0]) * max(0, b[3] - b[1])
below, above = [[] for _ in items], [[] for _ in items]
for i, a in enumerate(items):
for j in range(i + 1, len(items)):
b = items[j]
ib = [max(a["bbox"][0], b["bbox"][0]), max(a["bbox"][1], b["bbox"][1]),
min(a["bbox"][2], b["bbox"][2]), min(a["bbox"][3], b["bbox"][3])]
small = min(area(a["bbox"]), area(b["bbox"]))
if small and area(ib) >= 0.15 * small:
below[i].append(short_name(b))
above[j].append(short_name(a))
for i, item in enumerate(items):
if below[i]:
item["caption"] += ",位于" + "".join(f"「{n}」" for n in below[i][:3]) + "后面作为底衬"
if above[i]:
item["caption"] += ",叠在" + "".join(f"「{n}」" for n in above[i][:3]) + "上方"
def convert_layout(output, image_width, image_height, relations=True):
if image_width <= 0 or image_height <= 0:
raise ValueError("图像尺寸无效")
scale = min(1, 1024 / max(image_width, image_height))
width, height = [max(256, min(1024, js_round(v * scale / 16) * 16)) for v in (image_width, image_height)]
if not isinstance(output.get("caption"), str) or not isinstance(output.get("items"), list):
raise ValueError("caption/items 无效")
items = []
kinds = []
background = []
for source in output["items"]:
if not isinstance(source, dict):
raise ValueError("图层 label 无效")
source = normalize_item(source)
if source is None:
continue
if source["label"] == "background":
background.append(str(source.get("desc", "")))
continue
box = source.get("bbox_2d")
if not isinstance(box, list) or len(box) != 4 or any(isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v) for v in box):
raise ValueError("bbox_2d 无效")
# Assumption: BOTH Qwen3-VL and Qwen3.5 follow Qwen3-VL's grounding
# convention: bbox_2d = [x1,y1,x2,y2], relative coordinates in 0..1000.
# MOSS uses pixel yxyx with origin at canvas center, as toMoss().
x0, y0, x1, y1 = box
if x1 < x0 or y1 < y0:
raise ValueError("bbox_2d 边界顺序无效")
def coord(v, size):
return max(-size / 2, min(size / 2, js_round(v / 1000 * size - size / 2)))
bbox = [coord(y0, height), coord(x0, width), coord(y1, height), coord(x1, width)]
if bbox[2] - bbox[0] < 4 or bbox[3] - bbox[1] < 4:
continue
text = str(source.get("text", ""))
desc = str(source.get("desc", ""))
caption = f"「{text if source['label'] == 'text' else desc.split(',')[0] or '物体'}」,{desc.strip().rstrip('。')}".rstrip(",")
rotation = source.get("rotation")
if rotation is not None:
if isinstance(rotation, bool) or not isinstance(rotation, (int, float)) or not math.isfinite(rotation):
raise ValueError("rotation 无效")
# Explicit rotation takes precedence over conflicting descriptive tilt.
caption = re.sub(r"(?:整体)?(?:逆|顺)时针倾斜约\s*[\d.]+°(?:,左[低高]右[高低])?", "", caption).rstrip(",")
phrase = tilt(rotation)
if phrase:
caption += "," + phrase
item = {"label": source["label"], "caption": caption, "bbox": bbox}
if source["label"] == "text":
item["text"] = text
kinds.append(kind_of(item, source))
# Keep toMoss's public item keys unchanged. Rotation lives in the caption
# and remains available verbatim in raw; frontend also accepts item.rotation.
items.append(item)
# Stable bottom->top fix-up: large panels, then subjects, then small shapes
# (底衬/笔刷), then text; within a rank the model's order is kept.
canvas = width * height
def rank(k):
b, kind = items[k]["bbox"], kinds[k]
if kind == "shape" and (b[2] - b[0]) * (b[3] - b[1]) > 0.4 * canvas:
return 0
return {"subject": 1, "shape": 2, "text": 3}[kind]
order = sorted(range(len(items)), key=lambda k: (rank(k), k))
items, kinds = [items[k] for k in order], [kinds[k] for k in order]
if relations:
add_relations(items)
summary = output["caption"]
if background and all(b and b not in summary for b in background):
summary = summary.rstrip("。") + "。背景:" + ";".join(background)
return {"layout": {"summary": {"meta": ["poster"], "canvas": "single", "caption": summary},
"items": items, "bbox_coord_space": "abs_centralized", "bbox_format": "yxyx"},
"width": width, "height": height, "kinds": kinds}