File size: 25,912 Bytes
f18dc4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Ming Layer Studio</title>
<style>
  :root {
    --bg:#0b1117; --panel:#101923; --panel2:#15212d; --raised:#1a2936;
    --border:#29404d; --text:#eef7f5; --muted:#96aaa9; --dim:#647b7d;
    --accent:#55e6be; --accent2:#2fc9b1; --accent-soft:rgba(85,230,190,.11);
    --gold:#f3c969; --stage:#091016; --checker:#12202a; --shadow:0 24px 70px rgba(0,0,0,.28);
  }
  body.light {
    --bg:#f2f7f5; --panel:#ffffff; --panel2:#edf4f1; --raised:#e4eeea;
    --border:#c8dad3; --text:#10231f; --muted:#536d67; --dim:#7e9690;
    --accent:#087f6a; --accent2:#086c5b; --accent-soft:rgba(8,127,106,.09);
    --gold:#9c6b08; --stage:#e5eeeb; --checker:#d4e2dc; --shadow:0 24px 60px rgba(30,70,55,.10);
  }
  * { box-sizing:border-box; margin:0; padding:0; }
  [hidden] { display:none !important; }
  body { min-height:100vh; background:var(--bg); color:var(--text); font:14px/1.45 Inter,ui-sans-serif,system-ui,-apple-system,sans-serif; }
  button,textarea,input,select { font:inherit; }
  button,a { -webkit-tap-highlight-color:transparent; }
  .topbar { height:64px; display:flex; align-items:center; gap:18px; padding:0 22px; background:var(--panel); border-bottom:1px solid var(--border); }
  .brand { display:flex; align-items:center; gap:11px; font-weight:750; letter-spacing:-.03em; font-size:17px; }
  .mark { width:30px; height:30px; display:grid; place-items:center; border-radius:9px; background:var(--accent); color:#07251e; font-weight:900; }
  .brand small { display:block; color:var(--muted); font-size:10px; font-weight:600; letter-spacing:.12em; text-transform:uppercase; }
  .tabs { display:flex; gap:4px; padding:4px; border:1px solid var(--border); border-radius:10px; background:var(--panel2); }
  .tabs button { border:0; border-radius:7px; padding:7px 15px; background:transparent; color:var(--muted); cursor:pointer; }
  .tabs button.active { background:var(--raised); color:var(--text); }
  .spacer { flex:1; }
  .toplink { color:var(--muted); text-decoration:none; font-size:12px; }
  .toplink:hover { color:var(--accent); }
  .theme { width:34px; height:34px; border:1px solid var(--border); border-radius:9px; color:var(--muted); background:transparent; cursor:pointer; }
  .layout { display:grid; grid-template-columns:minmax(0,1fr) 360px; height:calc(100vh - 96px); min-height:600px; }
  .workspace { min-width:0; display:flex; flex-direction:column; padding:22px; gap:12px; }
  .canvas { flex:1; min-height:0; position:relative; display:flex; align-items:center; justify-content:center; overflow:hidden; border:1px solid var(--border); border-radius:16px; box-shadow:var(--shadow); background-color:var(--stage); background-image:linear-gradient(45deg,var(--checker) 25%,transparent 25%),linear-gradient(-45deg,var(--checker) 25%,transparent 25%),linear-gradient(45deg,transparent 75%,var(--checker) 75%),linear-gradient(-45deg,transparent 75%,var(--checker) 75%); background-size:24px 24px; background-position:0 0,0 12px,12px -12px,-12px 0; }
  .canvas.dropping { border-color:var(--accent); }
  .canvas img { max-width:100%; max-height:100%; object-fit:contain; display:block; }
  .empty { max-width:360px; text-align:center; color:var(--muted); padding:30px; }
  .empty-icon { width:62px; height:62px; margin:0 auto 18px; display:grid; place-items:center; border:1px solid var(--border); border-radius:18px; color:var(--accent); font-size:26px; background:var(--accent-soft); }
  .empty b { display:block; color:var(--text); font-size:17px; margin-bottom:7px; }
  .canvas-top { position:absolute; top:12px; left:12px; right:12px; display:flex; align-items:center; gap:8px; z-index:2; }
  .pill { padding:5px 9px; border:1px solid var(--border); border-radius:999px; background:rgba(10,18,24,.75); backdrop-filter:blur(8px); color:#d7e8e3; font-size:11px; }
  body.light .pill { background:rgba(255,255,255,.8); color:var(--text); }
  .download { margin-left:auto; display:none; padding:6px 11px; border-radius:8px; background:var(--accent); color:#07251e; text-decoration:none; font-weight:700; font-size:11px; }
  .loader { position:absolute; inset:0; display:flex; align-items:center; justify-content:center; flex-direction:column; gap:14px; background:rgba(7,14,19,.74); backdrop-filter:blur(4px); color:#eef7f5; z-index:3; }
  .spinner { width:38px; height:38px; border:3px solid rgba(255,255,255,.18); border-top-color:var(--accent); border-radius:50%; animation:spin .8s linear infinite; }
  @keyframes spin { to { transform:rotate(360deg); } }
  .strip { display:flex; align-items:center; gap:9px; min-height:64px; overflow-x:auto; }
  .strip-label { color:var(--dim); text-transform:uppercase; letter-spacing:.12em; font-size:10px; font-weight:700; margin-right:4px; flex:0 0 auto; }
  .tile { position:relative; flex:0 0 auto; width:56px; height:56px; border:2px solid var(--border); border-radius:9px; overflow:hidden; cursor:pointer; background-color:var(--stage); background-image:linear-gradient(45deg,var(--checker) 25%,transparent 25%),linear-gradient(-45deg,var(--checker) 25%,transparent 25%); background-size:12px 12px; }
  .tile:hover { border-color:var(--accent); }
  .tile.active { border-color:var(--accent); box-shadow:0 0 0 3px var(--accent-soft); }
  .tile img { width:100%; height:100%; object-fit:contain; }
  .tile .tile-name { position:absolute; inset:auto 0 0 0; font-size:8px; text-align:center; color:#d7e8e3; background:rgba(10,18,24,.75); padding:1px 0; }
  .tile .tile-save { position:absolute; top:2px; right:2px; width:16px; height:16px; border-radius:5px; border:0; background:rgba(10,18,24,.75); color:#d7e8e3; font-size:10px; line-height:16px; text-align:center; text-decoration:none; cursor:pointer; }
  .tile .tile-save:hover { background:var(--accent); color:#07251e; }
  .controls { overflow-y:auto; padding:18px; background:var(--panel); border-left:1px solid var(--border); }
  .section { margin-bottom:14px; padding:15px; border:1px solid var(--border); border-radius:13px; background:var(--panel2); }
  .section h2 { margin-bottom:11px; color:var(--dim); text-transform:uppercase; letter-spacing:.12em; font-size:10px; }
  textarea,input[type="number"],select { width:100%; border:1px solid var(--border); border-radius:9px; background:var(--raised); color:var(--text); padding:10px 11px; outline:none; }
  textarea { min-height:150px; resize:vertical; }
  textarea:focus,input:focus,select:focus { border-color:var(--accent2); box-shadow:0 0 0 3px var(--accent-soft); }
  label { display:block; color:var(--muted); font-size:12px; margin:11px 0 5px; }
  label:first-child { margin-top:0; }
  .range-row { display:grid; grid-template-columns:1fr 54px; gap:10px; align-items:center; }
  input[type="range"] { width:100%; accent-color:var(--accent); }
  .range-value { color:var(--accent); font:12px ui-monospace,monospace; text-align:right; }
  .check { display:flex; align-items:center; gap:8px; margin-top:12px; color:var(--muted); font-size:12px; }
  .check input { accent-color:var(--accent); }
  .example { width:100%; display:flex; justify-content:space-between; gap:10px; text-align:left; padding:9px 10px; margin-top:7px; border:1px solid var(--border); border-radius:9px; background:var(--raised); color:var(--text); cursor:pointer; }
  .example:hover { border-color:var(--accent); }
  .example span:last-child { color:var(--accent); font-size:10px; white-space:nowrap; }
  .upload { display:grid; place-items:center; gap:6px; width:100%; padding:22px 12px; border:1.5px dashed var(--border); border-radius:10px; background:var(--raised); color:var(--muted); font-size:12px; text-align:center; cursor:pointer; }
  .upload:hover { border-color:var(--accent); color:var(--text); }
  .upload strong { color:var(--text); font-size:13px; }
  .upload .chip { display:inline-block; margin-top:2px; max-width:100%; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; font:11px ui-monospace,monospace; color:var(--accent); }
  .hint { margin-top:10px; color:var(--dim); font-size:11px; line-height:1.5; }
  #run { width:100%; padding:13px; border:0; border-radius:10px; background:var(--accent); color:#07251e; font-weight:800; cursor:pointer; }
  #run:hover { filter:brightness(1.06); }
  #run:disabled { opacity:.55; cursor:wait; }
  .statusbar { height:32px; display:flex; align-items:center; gap:9px; padding:0 22px; border-top:1px solid var(--border); background:var(--panel); color:var(--muted); font-size:11px; }
  .dot { width:7px; height:7px; border-radius:50%; background:var(--accent); }
  .statusbar.busy .dot { animation:blink .8s infinite alternate; }
  @keyframes blink { from { opacity:.25; } to { opacity:1; } }
  #workflow { height:calc(100vh - 96px); min-height:600px; padding:14px; }
  #workflow iframe { width:100%; height:100%; border:1px solid var(--border); border-radius:14px; background:var(--panel); }
  @media(max-width:900px) {
    .topbar { height:auto; min-height:64px; flex-wrap:wrap; gap:10px; padding:12px; }
    .toplink { display:none; }
    .layout { display:block; height:auto; min-height:0; }
    .workspace { height:65vh; min-height:450px; padding:12px; }
    .controls { border-left:0; border-top:1px solid var(--border); overflow:visible; padding:12px; }
    #workflow { height:80vh; padding:8px; }
    .statusbar { position:sticky; bottom:0; }
  }
</style>
</head>
<body>
<header class="topbar">
  <div class="brand"><span class="mark">L</span><div>Ming Layer Studio<small>Official 0.2 Design-Layer pipeline</small></div></div>
  <nav class="tabs" aria-label="Views">
    <button id="studio-tab" class="active">Studio</button>
    <button id="workflow-tab">Workflow</button>
  </nav>
  <div class="spacer"></div>
  <a class="toplink" href="https://huggingface.co/inclusionAI/Ming-Image-0.2-Design-Layer" target="_blank" rel="noopener">Model card ↗</a>
  <a class="toplink" href="https://github.com/inclusionAI/Ming-Image" target="_blank" rel="noopener">Official code ↗</a>
  <button class="theme" id="theme" aria-label="Toggle color theme">◐</button>
</header>

<div id="studio" class="layout">
  <main class="workspace">
    <section class="canvas" id="canvas" aria-label="Input image and decomposed layers">
      <div class="canvas-top"><span class="pill" id="mode-pill">Input</span><span class="pill" id="size-pill">—</span><a class="download" id="download" download="ming-layer.png">Download PNG</a></div>
      <div class="empty" id="empty"><div class="empty-icon">⬗</div><b>Drop in a design or character</b>Upload a poster, product shot, or character illustration and decompose it into independently editable RGBA layers.</div>
      <img id="stage" alt="Selected layer" hidden />
      <div class="loader" id="loader" hidden><div class="spinner"></div><span id="loader-text">Loading the official Ming pipeline…</span></div>
    </section>
    <div class="strip" id="layer-strip"><span class="strip-label">Layers</span></div>
    <div class="strip" id="history"><span class="strip-label">History</span></div>
  </main>

  <aside class="controls">
    <section class="section"><h2>Starting points</h2><div id="examples"></div></section>
    <section class="section">
      <h2>Input image</h2>
      <label class="upload" for="file"><strong>Choose or drop an image</strong>PNG, JPEG, or WebP<span class="chip" id="file-name"></span></label>
      <input id="file" type="file" accept="image/*" hidden />
      <div class="hint">Downscaled to 1600 px on the long side before the run.</div>
    </section>
    <section class="section">
      <h2>Layer specification</h2>
      <textarea id="spec" placeholder="Optional. Describe each layer to extract — or leave empty for the default request."></textarea>
      <label for="layers">Layer count (used when the spec is empty)</label>
      <input id="layers" type="number" min="1" max="12" value="5" />
      <div class="hint">With a spec, its 'Number of layers:' line controls the count. Bounding boxes use normalized 0–999 xyxy coordinates on a 1000×1000 scale.</div>
    </section>
    <section class="section">
      <h2>Sampling</h2>
      <label for="resolution">Working resolution</label>
      <select id="resolution">
        <option selected>512 · fastest</option>
        <option>1024 · high quality</option>
      </select>
      <label for="steps">Denoising steps</label>
      <div class="range-row"><input id="steps" type="range" min="4" max="24" value="12" /><span class="range-value" id="steps-value">12</span></div>
      <label for="guidance">CFG scale</label>
      <div class="range-row"><input id="guidance" type="range" min="1" max="4" step="0.1" value="2" /><span class="range-value" id="guidance-value">2.0</span></div>
      <label for="seed">Seed</label>
      <input id="seed" type="number" min="0" max="2147483647" value="42" />
      <label class="check"><input id="randomize" type="checkbox" /> Randomize on every run</label>
      <div class="hint">Recommended: 12 steps, CFG 2.0, BF16. The output preserves the input's aspect ratio.</div>
    </section>
    <button id="run">Decompose into layers</button>
  </aside>
</div>

<div id="workflow" hidden><iframe src="/workflow/?ui=canvas" title="Ming node workflow"></iframe></div>
<footer class="statusbar" id="statusbar"><span class="dot"></span><span id="status">Ready · 96 GB ZeroGPU xlarge</span><div class="spacer"></div><span id="meta">12 steps · CFG 2.0</span></footer>

<script type="module">
  import { client } from "https://cdn.jsdelivr.net/npm/@gradio/client@2.5.0/dist/index.min.js";
  const $ = id => document.getElementById(id);
  const COMMIT = "041945f5c36d20cbf0fc6debc0a810a747e19644";
  const RAW = `https://raw.githubusercontent.com/inclusionAI/Ming-Image/${COMMIT}/assets/layer_samples/`;
  const state = { app:null, input:null, inputName:"", results:null, history:[], view:{kind:"input"} };
  const SPEC = {
    christmas:
`Decompose this image into 6 layers with the following specifications:

Number of layers: 6
Layer 1: The centered lower-middle typography stack reading "MERRY" in a dark teal high-contrast serif, "CHRISTMAS" directly below in a large bold red serif, and "AND HAPPY NEW YEAR" beneath that in a widely letter-spaced dark teal sans-serif.
Layer 2: A short horizontal flat-illustrated green holly-leaf garland dotted with small red berries, finished by a red ribbon bow tied at its center, placed just under the text and above the bottom baubles.
Layer 3: A centered stylized red line-art Christmas tree formed by swirling spiral ribbons, decorated with scattered red five-point stars and small red dots, topped by a single larger red star.
Layer 4: The six flat hanging ornaments suspended by thin dotted gold strings along the top edge — left to right, a dark-teal circular snowflake medallion, a red three-lobed bauble with white floral motifs, a dark-teal twisted icicle, then mirrored on the right by a dark-teal twisted icicle, a red floral bauble, and a dark-teal snowflake medallion.
Layer 5: Two flat-illustrated pine branches with brown stems and green needles stretching inward from the top-left and top-right corners, framing the upper edge.
Layer 6: The soft-focus photographic winter background showing frosted snowy pine branches across the top, glowing white bokeh light circles through the middle, and a row of frosted silver, pale-blue, and red glitter baubles (including an etched glass snow-globe with a white deer on the left) along the bottom.`,
    rigging:
`Decompose this image into 11 layers with the following specifications:

Number of layers: 11
Layer 1: Front Hair. Brown front bangs and top hair covering the forehead and framing the upper face.
Layer 2: Eyes. Large brown eyes with distinct irises, pupils, highlights, sclera, and simple upper eyelids.
Layer 3: Eyebrows. Two short, gently curved dark brown eyebrows positioned above the respective eyes.
Layer 4: Mouth. A small, simple curved dark line indicating a subtle smile centered on the lower face.
Layer 5: Head (Source Base). Light peach skin base forming the face, ears, and neck, outlined in dark brown.
Layer 6: Topwear. Light orange hoodie featuring a hood, dangling drawstrings, and a ribbed hem at the waist.
Layer 7: Arms, Sleeves and Hands. Outstretched bare hands attached to outstretched light orange sleeves and cuffs.
Layer 8: Bottomwear. Dark blue, short pleated skirt covering the waist and upper thigh area.
Layer 9: Legs and Footwear (Both). Two unoccluded legs wearing white knee-high socks and reddish-brown flat shoes.
Layer 10: Back Hair. Two rounded brown hair buns secured with dark hair ties positioned at the sides of the head.
Layer 11: Background. Plain, solid light off-white backdrop with no visible gradients, shadows, or background symbols.`,
    bbox:
`Decompose this image into 6 layers with the following specifications:

Number of layers: 6
Layer 1: The foreground element at bbox [491, 546, 624, 813] (normalized 0-999 coordinates on a 1000x1000 scale, xyxy); target: The cat figurine.
Layer 2: The foreground element at bbox [292, 548, 383, 756] (normalized 0-999 coordinates on a 1000x1000 scale, xyxy); target: The vase.
Layer 3: The foreground element at bbox [612, 613, 926, 820] (normalized 0-999 coordinates on a 1000x1000 scale, xyxy); target: The books.
Layer 4: The foreground element at bbox [402, 162, 697, 725] (normalized 0-999 coordinates on a 1000x1000 scale, xyxy); target: The framed picture.
Layer 5: The foreground element at bbox [202, 360, 394, 719] (normalized 0-999 coordinates on a 1000x1000 scale, xyxy); target: The table lamp.
Layer 6: The remaining background.`
  };
  const EXAMPLES = [
    {name:"Christmas poster · design layers", file:"christmas_poster_input.png", spec:"christmas"},
    {name:"Character rigging · 11 body parts", file:"rigging_input.png", spec:"rigging"},
    {name:"Bounding boxes · no prompt rewriting", file:"bbox_input.png", spec:"bbox"}
  ];

  function setStatus(text, busy=false) {
    $("status").textContent = text;
    $("statusbar").classList.toggle("busy", busy);
    $("run").disabled = busy;
    $("loader").hidden = !busy;
  }
  function setView(workflow) {
    $("studio").hidden = workflow;
    $("workflow").hidden = !workflow;
    $("studio-tab").classList.toggle("active", !workflow);
    $("workflow-tab").classList.toggle("active", workflow);
  }
  $("studio-tab").onclick = () => setView(false);
  $("workflow-tab").onclick = () => setView(true);
  $("theme").onclick = () => document.body.classList.toggle("light");
  $("steps").oninput = () => { $("steps-value").textContent = $("steps").value; $("meta").textContent = `${$("steps").value} steps · CFG ${Number($("guidance").value).toFixed(1)}`; };
  $("guidance").oninput = () => { $("guidance-value").textContent = Number($("guidance").value).toFixed(1); $("meta").textContent = `${$("steps").value} steps · CFG ${Number($("guidance").value).toFixed(1)}`; };

  async function toDataUrl(blob) {
    const bitmap = await createImageBitmap(blob);
    const maxSide = 1600;
    const scale = Math.min(1, maxSide / Math.max(bitmap.width, bitmap.height));
    const canvas = document.createElement("canvas");
    canvas.width = Math.round(bitmap.width * scale);
    canvas.height = Math.round(bitmap.height * scale);
    canvas.getContext("2d").drawImage(bitmap, 0, 0, canvas.width, canvas.height);
    return canvas.toDataURL("image/png");
  }

  function showStage(url, kind, label, saveName) {
    state.view = {kind, url, saveName};
    $("stage").src = url;
    $("stage").hidden = false;
    $("empty").hidden = true;
    $("mode-pill").textContent = label;
    $("download").href = url;
    $("download").download = saveName || "ming-layer.png";
    $("download").style.display = "block";
    $("stage").onload = () => { $("size-pill").textContent = `${$("stage").naturalWidth} × ${$("stage").naturalHeight}`; };
  }

  function setInput(dataUrl, name) {
    state.input = dataUrl;
    state.inputName = name || "";
    $("file-name").textContent = state.inputName;
    showStage(dataUrl, "input", "Input", "input.png");
    $("layer-strip").innerHTML = '<span class="strip-label">Layers</span>';
    state.results = null;
  }

  $("file").onchange = async event => {
    const file = event.target.files?.[0];
    if (!file) return;
    try {
      setInput(await toDataUrl(file), file.name);
      setStatus("Input loaded · ready to decompose");
    } catch (error) {
      setStatus("Could not read that image file");
    }
  };
  const canvasEl = $("canvas");
  ["dragover", "dragenter"].forEach(name => canvasEl.addEventListener(name, event => { event.preventDefault(); canvasEl.classList.add("dropping"); }));
  ["dragleave", "drop"].forEach(name => canvasEl.addEventListener(name, event => { event.preventDefault(); canvasEl.classList.remove("dropping"); }));
  canvasEl.addEventListener("drop", async event => {
    const file = event.dataTransfer?.files?.find(item => item.type.startsWith("image/"));
    if (file) {
      try { setInput(await toDataUrl(file), file.name); setStatus("Input loaded · ready to decompose"); }
      catch { setStatus("Could not read that image file"); }
    }
  });

  EXAMPLES.forEach(example => {
    const button = document.createElement("button");
    button.className = "example";
    const name = document.createElement("span"); name.textContent = example.name;
    const tag = document.createElement("span"); tag.textContent = "sample";
    button.append(name, tag);
    button.onclick = async () => {
      $("spec").value = SPEC[example.spec];
      setStatus(`Fetching ${example.file} from the official samples…`, false);
      try {
        const response = await fetch(RAW + example.file, {mode:"cors"});
        if (!response.ok) throw new Error(response.status);
        const blob = await response.blob();
        setInput(await toDataUrl(blob), example.file);
        setStatus("Official sample loaded · ready to decompose");
      } catch (error) {
        setStatus("Could not fetch the sample (network/CORS). Upload an image manually.");
      }
    };
    $("examples").appendChild(button);
  });

  function renderResults(payload, spec) {
    state.results = payload;
    const strip = $("layer-strip");
    strip.innerHTML = '<span class="strip-label">Layers</span>';
    const entries = [{url:payload.composite, name:"composite"}]
      .concat((payload.layers || []).map((url, index) => ({url, name:`layer ${index + 1}`.padStart(8, "0")})));
    entries.forEach((entry, index) => {
      const tile = document.createElement("div");
      tile.className = "tile" + (index === 0 ? " active" : "");
      const image = document.createElement("img"); image.src = entry.url; image.alt = entry.name;
      const label = document.createElement("span"); label.className = "tile-name"; label.textContent = index === 0 ? "composite" : `layer ${index}`;
      const save = document.createElement("a");
      save.className = "tile-save"; save.textContent = "⭳";
      save.href = entry.url; save.download = `${entry.name.replace(" ", "_")}.png`;
      save.onclick = event => event.stopPropagation();
      tile.append(image, label, save);
      tile.onclick = () => {
        strip.querySelectorAll(".tile").forEach(node => node.classList.remove("active"));
        tile.classList.add("active");
        showStage(entry.url, "layer", index === 0 ? "Composite" : `Layer ${index}`, `${entry.name.replace(" ", "_")}.png`);
      };
      strip.appendChild(tile);
    });
    showStage(payload.composite, "layer", "Composite", "composite.png");
    addHistory({composite:payload.composite, seed:payload.seed, spec});
  }

  function addHistory(item) {
    state.history.unshift(item);
    if (state.history.length > 8) state.history.pop();
    const strip = $("history");
    strip.innerHTML = '<span class="strip-label">History</span>';
    state.history.forEach(entry => {
      const tile = document.createElement("button");
      tile.className = "tile"; tile.title = `Seed ${entry.seed}`;
      const image = document.createElement("img"); image.src = entry.composite; image.alt = "Previous run";
      tile.appendChild(image);
      tile.onclick = () => {
        $("seed").value = entry.seed;
        $("spec").value = entry.spec || "";
        setStatus(`Restored seed ${entry.seed}`);
      };
      strip.appendChild(tile);
    });
  }

  async function getApp() {
    if (!state.app) state.app = await client(location.origin);
    return state.app;
  }
  function unwrap(result) {
    return (Array.isArray(result?.data) ? result.data[0] : result?.data) ?? {};
  }
  $("run").onclick = async () => {
    if (!state.input) { setStatus("Upload an input image first"); return; }
    const spec = $("spec").value.trim();
    const seed = $("randomize").checked ? Math.floor(Math.random() * 2147483647) : Number($("seed").value);
    setStatus("Decomposing on the 96 GB worker…", true);
    $("loader-text").textContent = "Reading the layers and sampling the decomposition…";
    try {
      const app = await getApp();
      const result = await app.predict("/decompose", {
        image_data: state.input,
        resolution: $("resolution").value,
        steps: Number($("steps").value),
        guidance: Number($("guidance").value),
        seed,
        num_layers: Number($("layers").value),
        spec,
      });
      const payload = unwrap(result);
      if (!payload.composite) throw new Error("The run finished without a composite.");
      $("seed").value = payload.seed;
      setStatus(`${payload.info} · seed ${payload.seed}`);
      renderResults(payload, spec);
    } catch (error) {
      setStatus(error?.message || String(error));
    } finally {
      $("loader").hidden = true;
      $("run").disabled = false;
      $("statusbar").classList.remove("busy");
    }
  };
</script>
</body>
</html>