"""The Renderer: a page's HTML laid out, measured, placed and exported. WeasyPrint lays the page out (the book designer's engine - HarfBuzz shapes the Arabic, the page is the exact canvas in CSS pixels) and MuPDF rasterises it at 96 dpi, where one CSS pixel is one image pixel: a 1080×1350 design is a 1080×1350 PNG. Two passes: the content is laid out once at the top of its area and measured - its height, and every line of text with where it landed - then placed (centred, or at the area's top or foot) and drawn. The measurements are what the QA agent judges. """ from __future__ import annotations import io from dataclasses import dataclass, field from app.agents.studio.layouts import Page, document @dataclass class Line: id: str x: float y: float w: float h: float @dataclass class Layout: height: float # the content's height lines: list[Line] = field(default_factory=list) boxes: dict[str, tuple] = field(default_factory=dict) # id -> (x, y, w, h) def _weasy(): from app.agents.book_design.render import _weasy as w return w() def _walk(box): """Every box under `box`, into absolutely placed ones too (WeasyPrint keeps those behind a placeholder its own walk does not open).""" yield box inner = getattr(box, "_box", None) if inner is not None: yield from _walk(inner) for child in getattr(box, "children", None) or []: yield from _walk(child) def measure(html: str) -> Layout: doc = _weasy().HTML(string=html, base_url=".").render() page = doc.pages[0]._page_box lines: list[Line] = [] boxes: dict[str, tuple] = {} height = 0.0 for b in _walk(page): el = getattr(b, "element", None) name = type(b).__name__ if name == "AbsolutePlaceholder": continue eid = el.get("id") if el is not None else None if eid == "content" and not height: height = b.margin_height() if eid and name not in ("LineBox", "TextBox", "InlineBox") and eid not in boxes: boxes[eid] = (b.position_x, b.position_y, b.margin_width(), b.margin_height()) if name == "LineBox": # the text's own lines: a line box's width is its text's width lines.append(Line(eid or "", b.position_x, b.position_y, b.width, b.height)) return Layout(height=height, lines=lines, boxes=boxes) def place(p: Page) -> tuple[str, Layout, float]: """The page laid out with its content placed: the HTML, the final layout, and the content's height.""" first = measure(document(p)) x, y, w, h = p.area free = h - first.height if free <= 0 or p.align == "top": top = y elif p.align == "bottom": top = y + free else: top = y + free / 2 html = document(p, top) return html, measure(html), first.height def rasterise(html: str, width: int, height: int, fmt: str = "png") -> bytes: """The page as an image of exactly `width`×`height` pixels.""" import fitz pdf = _weasy().HTML(string=html, base_url=".").write_pdf() doc = fitz.open(stream=pdf, filetype="pdf") pix = doc[0].get_pixmap(dpi=96, alpha=False) if (pix.width, pix.height) != (width, height): from PIL import Image img = Image.frombytes("RGB", (pix.width, pix.height), pix.samples) img = img.resize((width, height), Image.LANCZOS) else: from PIL import Image img = Image.frombytes("RGB", (pix.width, pix.height), pix.samples) out = io.BytesIO() if fmt == "jpg": img.save(out, "JPEG", quality=92, optimize=True) else: img.save(out, "PNG", optimize=True) return out.getvalue()