File size: 13,264 Bytes
de91df7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6cb106e
 
 
 
de91df7
 
6cb106e
 
 
 
de91df7
 
 
 
 
 
 
6cb106e
 
 
de91df7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6cb106e
de91df7
 
 
 
 
 
 
 
 
 
 
 
6cb106e
 
de91df7
6cb106e
de91df7
 
 
 
6cb106e
de91df7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6cb106e
de91df7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6cb106e
de91df7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6cb106e
de91df7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""DesignWorld explorer: browse DesignWorld-SFT (the dataset perpetual-research/designworld-sft, mounted read-only at
DATA_DIR) and DesignWorld-Bench (perpetual-research/designworld-bench, mounted read-only at BENCH_DIR).

Everything list-like comes from catalog/{traces,designs}.parquet (loaded once, in memory); a trace opens with one
read of its row group (one row per row group in data/<config>/*.parquet, through a 16 MB buffered file so pyarrow's
column reads become one read of the mount); previews/ and targets/ are served as files. Read-only.
"""
from __future__ import annotations

import io
import json
import os
import threading
import time
from collections import OrderedDict
from pathlib import Path

import pyarrow.parquet as pq
from fastapi import FastAPI, HTTPException, Query
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, Response

DATA = Path(os.environ.get("DATA_DIR", "/data"))
BENCH = Path(os.environ.get("BENCH_DIR", "/bench"))
HERE = Path(__file__).parent
EDITORS = ["real_impress", "real_draw", "real_onlyoffice", "real_inkscape", "real_scribus", "real_photocraft",
           "real_penpot", "real_drawio", "gui_figma", "gui_canva", "gui_photoshop", "gui_slides", "gui_powerpoint",
           "gui_inkscape"]
LABEL = {"real_impress": "Impress", "real_draw": "Draw", "real_onlyoffice": "ONLYOFFICE", "real_inkscape": "Inkscape",
         "real_scribus": "Scribus", "real_photocraft": "PhotoCraft", "real_penpot": "Penpot", "real_drawio": "draw.io",
         "gui_figma": "Studio (Figma-like)", "gui_canva": "Template (Canva-like)", "gui_photoshop": "Pixel (Photoshop-like)",
         "gui_slides": "Deck (Slides-like)", "gui_powerpoint": "Present (PowerPoint-like)",
         "gui_inkscape": "Vector (Inkscape-like)", "tools": "tools", "html": "html"}

app = FastAPI(title="DesignWorld explorer")
_lock = threading.Lock()
_state: dict = {}


def _clean(v):
    if isinstance(v, float) and v != v:
        return None
    return v


HIDDEN = {"set", "version", "status", "latest", "superseded_by", "quality_gate", "recorded_at", "in_bucket",
          "recorder_version", "prompt_version", "masked_turns", "mistakes", "generation", "exported_in"}


def load():
    """The two catalog tables, as plain lists/dicts (a few MB)."""
    # only the training set is browsable, and only the fields a reader needs
    traces = [{k: v for k, v in t.items() if k not in HIDDEN}
              for t in pq.read_table(DATA / "catalog/traces.parquet").to_pylist()
              if t["status"] == "kept" and t["latest"] and t["quality_gate"] in ("pass", None) and t["in_bucket"]]
    designs = pq.read_table(DATA / "catalog/designs.parquet").to_pylist()
    summary = json.loads((DATA / "summary.json").read_text()) if (DATA / "summary.json").exists() else {}
    by_id = {t["trace_id"]: t for t in traces}
    by_task: dict[str, list] = {}
    for t in traces:
        by_task.setdefault(t["task_id"], []).append(t)
    for v in by_task.values():
        v.sort(key=lambda t: t["config"])
    designs.sort(key=lambda d: d["task_id"])
    traces.sort(key=lambda t: (t["task_id"], t["config"]))
    d_by = {d["task_id"]: d for d in designs}
    _state.update(traces=traces, designs=designs, summary=summary, by_id=by_id, by_task=by_task, d_by=d_by)


def _ensure():
    """The catalog, loaded on first use (retried while the dataset is still being filled) and reloaded when a newer
    one lands in the dataset (checked at most once a minute)."""
    now = time.time()
    if _state and now - _state.get("checked", 0) < 60:
        return
    try:
        mtime = (DATA / "catalog/traces.parquet").stat().st_mtime
    except OSError:
        if _state:
            return
        raise HTTPException(503, "the dataset has no catalog yet")
    if not _state or mtime != _state.get("mtime"):
        load()
        _state["mtime"] = mtime
    _state["checked"] = now


try:
    load()
except Exception as e:  # noqa: BLE001 - an empty dataset at start: load on the first request instead
    print(f"catalog not loaded yet: {e}", flush=True)

# ------------------------------------------------------------------------------------------------ trace rows
class _Window(io.RawIOBase):
    """A file of which only bytes [start, start + len(data)) exist: what pyarrow reads for one row group."""

    def __init__(self, footer: int, start: int, data: bytes):
        self.start, self.data, self.pos = start, data, 0
        self.size = start + len(data) + footer + 8

    def readable(self):
        return True

    def seekable(self):
        return True

    def seek(self, pos, whence=0):
        self.pos = pos if whence == 0 else self.pos + pos if whence == 1 else self.size + pos
        return self.pos

    def tell(self):
        return self.pos

    def read(self, n=-1):
        a = self.pos - self.start
        b = len(self.data) if n is None or n < 0 else min(len(self.data), a + n)
        self.pos = self.start + b
        return self.data[a:b]


_rows: OrderedDict = OrderedDict()  # trace_id -> decoded row (messages, meta, images), the last few opened
_meta: dict = {}  # shard -> parquet metadata (footer), read once


def _row(trace_id: str) -> dict:
    _ensure()
    with _lock:
        if trace_id in _rows:
            _rows.move_to_end(trace_id)
            return _rows[trace_id]
    t = _state["by_id"].get(trace_id)
    if not t or not t.get("shard"):
        raise HTTPException(404, "trace not in the dataset")
    path, i = DATA / t["shard"], int(t["row"])
    try:
        if t["shard"] not in _meta:
            _meta[t["shard"]] = pq.read_metadata(path)
        md = _meta[t["shard"]]
        with open(path, "rb", buffering=0) as f:
            # the row group's byte range in one read of the mount, then parsed from memory
            cols = [md.row_group(i).column(k) for k in range(md.num_columns)]
            start = min(c.dictionary_page_offset or c.data_page_offset for c in cols)
            end = max((c.dictionary_page_offset or c.data_page_offset) + c.total_compressed_size for c in cols)
            f.seek(start)
            chunk = f.read(end - start)
    except FileNotFoundError:
        raise HTTPException(404, "this trace's shard is not in the dataset") from None
    row = pq.ParquetFile(_Window(md.serialized_size, start, chunk), metadata=md).read_row_group(i).to_pylist()[0]
    with _lock:
        _rows[trace_id] = row
        while len(_rows) > 24:
            _rows.popitem(last=False)
    return row


def _transcript(row: dict) -> list[dict]:
    """The episode as steps a reader follows: who speaks, the words, the tool calls, the images (by index)."""
    out, k = [], 0
    for m in row["messages"]:
        content = m.get("content")
        parts = content if isinstance(content, list) else [{"type": "text", "text": content}] if content else []
        text, imgs = [], []
        for p in parts:
            if p.get("type") == "image":
                imgs.append(k)
                k += 1
            elif p.get("text"):
                text.append(p["text"])
        calls = []
        for c in m.get("tool_calls") or []:
            fn = c.get("function") or {}
            args = fn.get("arguments")
            try:
                args = json.loads(args) if isinstance(args, str) else args
            except ValueError:
                pass
            calls.append({"name": fn.get("name"), "args": args})
        out.append({"role": m["role"], "text": "\n".join(text), "images": imgs, "calls": calls,
                    "name": m.get("name")})
    return out


# ------------------------------------------------------------------------------------------------ API
@app.get("/", response_class=HTMLResponse)
def index():
    return (HERE / "index.html").read_text()


@app.get("/api/summary")
def summary():
    _ensure()
    src = _state["summary"]
    s = {k: src.get(k) for k in ("training_traces", "designs", "designs_complete14", "built")}
    s["editors"] = [{"config": c, "label": LABEL.get(c, c)} for c in EDITORS]
    s["by_config"] = {c: {"training": v.get("training")} for c, v in (src.get("by_config") or {}).items()}
    return s


@app.get("/api/designs")
def designs(q: str = "", complete: str = "", editor: str = "", split: str = "",
            offset: int = 0, limit: int = Query(60, le=500)):
    _ensure()
    ds = _state["designs"]
    by_task = _state["by_task"]
    if q:
        ql = q.lower()
        ds = [d for d in ds if ql in d["task_id"].lower() or ql in (d.get("format") or "").lower()
              or ql in (d.get("category") or "").lower()]
    if complete == "yes":
        ds = [d for d in ds if d["complete14"]]
    elif complete == "no":
        ds = [d for d in ds if not d["complete14"]]
    if editor:
        ds = [d for d in ds if editor in (d.get("editors") or [])]
    if split:
        ds = [d for d in ds if d.get("split") == split]
    page = []
    for d in ds[offset:offset + limit]:
        cells = {}
        for t in by_task.get(d["task_id"], []):
            cells[t["config"]] = {"trace_id": t["trace_id"], "reward": _clean(t["reward"]), "preview": t["preview"]}
        page.append({**{k: _clean(v) for k, v in d.items()}, "cells": cells,
                     "n_traces": len(by_task.get(d["task_id"], []))})
    return {"total": len(ds), "offset": offset, "items": page}


@app.get("/api/design/{task_id}")
def design(task_id: str):
    _ensure()
    d = _state["d_by"].get(task_id)
    if not d:
        raise HTTPException(404)
    ts = [{k: _clean(v) for k, v in t.items()} for t in _state["by_task"].get(task_id, [])]
    return {"design": {k: _clean(v) for k, v in d.items()}, "traces": ts}


@app.get("/api/traces")
def traces(config: str = "", q: str = "",
           offset: int = 0, limit: int = Query(100, le=1000)):
    _ensure()
    ts = _state["traces"]
    if config:
        ts = [t for t in ts if t["config"] == config]
    if q:
        ts = [t for t in ts if q.lower() in t["trace_id"].lower()]
    return {"total": len(ts), "items": [{k: _clean(v) for k, v in t.items()} for t in ts[offset:offset + limit]]}


@app.get("/api/trace/{trace_id}")
def trace(trace_id: str):
    row = _row(trace_id)
    t = _state["by_id"][trace_id]
    meta = {k: _clean(row.get(k)) for k in ("task_id", "design_id", "mode", "surface", "screen", "coordinates", "reward",
                                            "turns", "actions", "n_elements")}
    meta["editor"] = row.get("editor")
    return {"catalog": {k: _clean(v) for k, v in t.items()}, "meta": meta, "steps": _transcript(row),
            "n_images": len(row["images"]), "tools": [x.get("name") if isinstance(x, dict) else x
                                                      for x in (row.get("tools") or [])][:60]}


@app.get("/api/img/{trace_id}/{k}")
def img(trace_id: str, k: int):
    row = _row(trace_id)
    if not 0 <= k < len(row["images"]):
        raise HTTPException(404)
    b = row["images"][k]["bytes"]
    kind = "image/webp" if b[8:12] == b"WEBP" else "image/png" if b[:4] == b"\x89PNG" else "image/jpeg"
    return Response(b, media_type=kind, headers={"Cache-Control": "public, max-age=86400"})


@app.get("/media/{kind}/{name:path}")
def media(kind: str, name: str):
    # previews/<config>/<trace_id>.webp (the catalog's `preview`), targets/<task_id>.webp
    if kind not in ("previews", "targets") or ".." in name or name.count("/") > (1 if kind == "previews" else 0):
        raise HTTPException(404)
    p = DATA / kind / name
    if not p.exists():
        raise HTTPException(404)
    return FileResponse(p, media_type="image/webp", headers={"Cache-Control": "public, max-age=86400"})


_bench: dict = {}


@app.get("/api/bench")
def bench():
    """DesignWorld-Bench: the scores table and the 30 held-out designs (from the episodes table)."""
    if not _bench:
        try:
            scores = pq.read_table(BENCH / "data/scores/scores.parquet").to_pylist()
            eps = pq.read_table(BENCH / "data/episodes/episodes.parquet").to_pylist()
        except OSError:
            raise HTTPException(503, "the bench dataset is not mounted") from None
        tasks = {}
        for e in eps:
            t = tasks.setdefault(e["task_id"], {k: e[k] for k in ("task_id", "design_id", "tier", "format", "category",
                                                                  "n_elements", "difficulty_score")})
            t.setdefault("apps", []).append({"editor": e["editor"], "app": e["app"], "open": e["open"]})
        order = {"easy": 0, "medium": 1, "hard": 2}
        _bench.update(scores=[{k: _clean(v) for k, v in s.items()} for s in scores],
                      tasks=sorted(tasks.values(), key=lambda t: (order.get(t["tier"], 9), t["n_elements"])))
    return _bench


@app.get("/bench-media/{design_id}.jpg")
def bench_media(design_id: str):
    if "/" in design_id or ".." in design_id:
        raise HTTPException(404)
    p = BENCH / "pack/designs" / design_id / "preview.jpg"
    if not p.exists():
        raise HTTPException(404)
    return FileResponse(p, media_type="image/jpeg", headers={"Cache-Control": "public, max-age=86400"})


@app.get("/healthz")
def healthz():
    return JSONResponse({"traces": len(_state.get("traces", [])), "designs": len(_state.get("designs", []))})