File size: 32,890 Bytes
0cdef60
0718f73
 
 
 
faa8c05
0718f73
faa8c05
 
 
 
0718f73
faa8c05
 
 
 
 
 
 
0718f73
faa8c05
 
 
 
 
 
0718f73
 
faa8c05
 
0718f73
faa8c05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0718f73
 
 
 
faa8c05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0718f73
faa8c05
 
 
 
 
 
 
 
 
 
 
 
 
 
0718f73
faa8c05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0718f73
faa8c05
 
 
 
 
 
 
 
 
0718f73
faa8c05
 
0718f73
 
faa8c05
 
 
0718f73
 
faa8c05
0718f73
faa8c05
 
 
 
 
 
 
 
 
 
0718f73
faa8c05
 
 
 
0718f73
faa8c05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0718f73
faa8c05
 
0718f73
 
faa8c05
 
 
 
 
 
 
 
 
0718f73
 
faa8c05
 
 
0718f73
 
faa8c05
 
 
 
 
 
0718f73
 
faa8c05
 
0718f73
 
faa8c05
8b506d7
 
 
 
 
0718f73
 
 
faa8c05
8b506d7
 
 
 
faa8c05
0718f73
 
faa8c05
 
 
8b506d7
faa8c05
 
8b506d7
 
 
 
 
 
 
 
 
faa8c05
 
 
 
 
8b506d7
 
 
 
faa8c05
 
8b506d7
 
0718f73
faa8c05
8b506d7
0718f73
 
faa8c05
 
0718f73
 
 
faa8c05
 
 
0718f73
faa8c05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0718f73
faa8c05
 
0718f73
faa8c05
0718f73
faa8c05
0718f73
faa8c05
0718f73
faa8c05
 
 
0718f73
faa8c05
0718f73
faa8c05
 
 
 
 
8b506d7
0718f73
faa8c05
0718f73
 
faa8c05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0718f73
 
0cdef60
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<title>Jeveration WebGPU</title>
<meta name="description" content="Type a sentence and watch it become a picture in one forward pass, on your own GPU in the browser.">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Fraunces:opsz,wght@9..144,300;9..144,400&display=swap" rel="stylesheet">
<style>
  :root {
    --bg: #f3f1ec; --surface: #fffdf9; --ink: #1f1c18; --muted: #77706a; --faint: #b9b2aa; --line: #e6e1d9;
    --accent: #5b4bdb; --accent-soft: rgb(91 75 219 / .14); --on-accent: #fff; --err: #b3261e;
    --shadow: 0 1px 2px rgb(31 28 24 / .05), 0 10px 30px rgb(31 28 24 / .07);
    --hero-shadow: 0 30px 80px rgb(31 28 24 / .18);
    --serif: "Fraunces", Georgia, "Times New Roman", serif;
  }
  @media (prefers-color-scheme: dark) {
    :root {
      --bg: #12110f; --surface: #1d1b18; --ink: #f2eee8; --muted: #a39b92; --faint: #5a544d; --line: #2c2925;
      --accent: #a99cff; --accent-soft: rgb(169 156 255 / .2); --on-accent: #12110f; --err: #ff8a80;
      --shadow: 0 1px 2px rgb(0 0 0 / .3), 0 10px 30px rgb(0 0 0 / .35);
      --hero-shadow: 0 30px 80px rgb(0 0 0 / .55);
    }
  }
  *, *::before, *::after { box-sizing: border-box; }
  html, body { margin: 0; background: var(--bg); color: var(--ink); }
  body { font: 15px/1.45 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; -webkit-font-smoothing: antialiased; }
  [hidden] { display: none !important; }
  button { font: inherit; color: inherit; }
  img, canvas, video { max-width: 100%; }
  .sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }

  main {
    --hero: min(620px, calc(100dvh - 150px), 46vw);
    min-height: 100dvh; display: flex; flex-direction: column; padding: 24px 32px 32px;
  }

  /* Header: brand, mode switch, info. */
  header { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 10px; }
  .pill { display: inline-flex; align-items: center; gap: 8px; min-height: 40px; padding: 0 16px; border: 0; border-radius: 999px;
    background: var(--surface); color: var(--muted); text-decoration: none; white-space: nowrap; box-shadow: var(--shadow); cursor: pointer; }
  .brand { color: var(--ink); font-weight: 650; }
  .brand small { color: var(--muted); font-weight: 450; }
  .icon { width: 40px; padding: 0; justify-content: center; }
  .seg { display: inline-flex; gap: 2px; padding: 4px; border-radius: 999px; background: var(--surface); box-shadow: var(--shadow); min-width: 0; }
  .seg button { min-height: 32px; padding: 0 14px; border: 0; border-radius: 999px; background: transparent; color: var(--muted); cursor: pointer;
    white-space: nowrap; }
  .seg button[aria-selected="true"] { background: var(--ink); color: var(--bg); }

  /* Info popover: what made this picture. */
  .info-wrap { position: relative; }
  .info { position: absolute; right: 0; top: 50px; z-index: 5; width: min(330px, calc(100vw - 32px)); max-height: calc(100dvh - 100px);
    overflow-y: auto; overscroll-behavior: contain; padding: 16px 18px 8px; border-radius: 18px; background: var(--surface);
    box-shadow: var(--shadow), 0 20px 50px rgb(0 0 0 / .18); font-size: 14px; animation: pop .16s ease-out; }
  .info h2 { margin: 0 0 6px; font: 400 22px/1.1 var(--serif); }
  .info p { margin: 0 0 10px; color: var(--muted); }
  .info dl { margin: 8px 0 0; font-variant-numeric: tabular-nums; }
  .info dl div { display: flex; justify-content: space-between; gap: 12px; padding: 3px 0; }
  .info dt { color: var(--muted); min-width: 0; }
  .info dd { margin: 0; text-align: right; min-width: 0; overflow-wrap: anywhere; }
  .info .sum { margin-top: 6px; padding-top: 8px; border-top: 1px dashed var(--line); font-weight: 650; }
  .info .sum dt { color: var(--ink); }
  .info .label { margin: 14px 0 2px; color: var(--muted); font-size: 11.5px; letter-spacing: .07em; text-transform: uppercase; }
  .info a { display: flex; justify-content: space-between; align-items: baseline; gap: 12px; padding: 9px 0; border-top: 1px solid var(--line);
    color: var(--ink); text-decoration: none; }
  .info a small { color: var(--muted); text-align: right; min-width: 0; overflow-wrap: anywhere; }
  @media (hover: hover) { .info a:hover span { text-decoration: underline; text-underline-offset: 3px; } }

  /* Stage: words on the left, picture on the right. */
  .stage { flex: 1; display: grid; grid-template-columns: minmax(0, 1fr) var(--hero); align-items: center;
    gap: clamp(28px, 5vw, 72px); padding: 20px clamp(0px, 3vw, 48px) 8px; }
  .words { min-width: 0; display: flex; flex-direction: column; gap: 24px; }
  .kicker { margin: 0; color: var(--muted); font-size: 13px; letter-spacing: .08em; text-transform: uppercase; }

  .sentence { position: relative; font-family: var(--serif); font-weight: 300; font-variation-settings: "opsz" 120;
    line-height: 1.08; letter-spacing: -.015em; font-size: var(--size); }
  .sentence.xl { --size: clamp(42px, 5.2vw, 76px); }
  .sentence.lg { --size: clamp(36px, 4.2vw, 60px); }
  .sentence.md { --size: clamp(30px, 3.3vw, 48px); }
  .sentence.sm { --size: clamp(24px, 2.5vw, 36px); }
  .mirror, .sentence textarea { margin: 0; padding: 0; font: inherit; font-variation-settings: inherit; letter-spacing: inherit;
    white-space: pre-wrap; overflow-wrap: break-word; }
  .mirror { min-height: 1.08em; }
  .mirror .done { color: var(--ink); }
  /* Not yet in the picture: same glyphs (so the caret lines up), lighter ink with an accent underline. */
  .mirror .todo { color: var(--muted); text-decoration: underline 2px var(--accent); text-underline-offset: .14em; }
  .mirror .ph { color: var(--faint); }
  .sentence textarea { position: absolute; inset: 0; width: 100%; height: 100%; border: 0; outline: 0; resize: none; overflow: hidden;
    background: transparent; color: transparent; caret-color: var(--accent); }
  .sentence textarea::selection { background: var(--accent-soft); }

  .film { display: flex; gap: 10px; overflow-x: auto; overscroll-behavior-x: contain; scrollbar-width: none; padding: 4px; margin: -4px -4px 0; }
  .film:empty { display: none; }
  .shot { flex: none; width: 84px; padding: 0; border: 0; background: none; text-align: left; cursor: pointer; animation: slide .35s cubic-bezier(.2,.9,.3,1.1); }
  .shot img { display: block; width: 84px; height: 84px; border-radius: 10px; object-fit: cover; background: var(--line); opacity: .8; transition: opacity .15s; }
  .shot span { display: block; margin-top: 5px; color: var(--muted); font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
  .shot.on img { opacity: 1; box-shadow: 0 0 0 2px var(--bg), 0 0 0 4px var(--accent); }
  .shot.on span { color: var(--ink); }

  .hint { margin: 0; color: var(--muted); font-size: 14.5px; }
  kbd { padding: 1px 6px; border-radius: 6px; border: 1px solid var(--line); background: var(--surface); font: 12px/1.5 ui-monospace, monospace; }
  .picks { display: flex; flex-wrap: wrap; gap: 8px; }
  .pick { min-height: 36px; padding: 0 14px; color: var(--ink); font-size: 14px; }
  .pick[aria-pressed="true"] { background: var(--ink); color: var(--bg); }
  .pick:disabled { cursor: default; opacity: .5; }
  @media (hover: hover) {
    .pick:not(:disabled):hover { box-shadow: 0 0 0 1.5px var(--accent); }
    .shot:hover img { opacity: 1; }
  }

  /* Style mode: the photo card. */
  .heading { margin: 0; font: 300 clamp(34px, 4vw, 56px)/1.08 var(--serif); font-variation-settings: "opsz" 120; letter-spacing: -.015em;
    overflow-wrap: anywhere; }
  .heading em { font-style: italic; color: var(--accent); }
  .source { display: flex; gap: 16px; align-items: center; flex-wrap: wrap; min-width: 0; }
  .drop { position: relative; flex: none; width: 168px; aspect-ratio: 1; border-radius: 14px; overflow: hidden; background: var(--line);
    box-shadow: var(--shadow); cursor: pointer; }
  .drop canvas, .drop video { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; display: block; }
  .drop video { transform: scaleX(-1); }
  .drop.over { box-shadow: 0 0 0 3px var(--accent); }
  .drop .tag { position: absolute; left: 8px; right: 8px; bottom: 8px; width: fit-content; max-width: calc(100% - 16px); padding: 3px 9px;
    border-radius: 999px; background: rgb(0 0 0 / .55); color: #fff; font-size: 12px; backdrop-filter: blur(6px); overflow-wrap: anywhere; }
  .source-side { flex: 1 1 200px; min-width: 0; display: flex; flex-direction: column; gap: 10px; }
  .thumbs { display: flex; flex-wrap: wrap; gap: 6px; }
  .thumbs button { width: 44px; height: 44px; padding: 0; border: 0; border-radius: 9px; overflow: hidden; background: var(--line); cursor: pointer;
    opacity: .85; }
  .thumbs button:hover, .thumbs button:focus-visible { opacity: 1; box-shadow: 0 0 0 2px var(--accent); }
  .thumbs img { width: 100%; height: 100%; object-fit: cover; display: block; }
  .rec { width: 8px; height: 8px; border-radius: 50%; background: var(--err); animation: blink 1.2s infinite; }

  /* The picture. */
  .hero { position: relative; margin: 0; width: var(--hero); aspect-ratio: 1; border-radius: 10px; overflow: hidden; background: var(--line);
    box-shadow: var(--hero-shadow); }
  .hero img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; animation: arrive .24s ease-out; }
  .hero img.behind, .hero.camera img { animation: none; }
  .placeholder { position: absolute; inset: 0; display: grid; place-items: center; padding: 24px; text-align: center; color: var(--muted);
    font: 300 clamp(22px, 2.4vw, 32px)/1.2 var(--serif); }
  .overlay { position: absolute; inset: auto 0 0 0; z-index: 2; padding: 16px; display: flex; flex-direction: column; align-items: flex-start;
    gap: 10px; background: linear-gradient(to top, rgb(0 0 0 / .45), transparent); }
  .badge { max-width: 100%; padding: 6px 12px; border-radius: 999px; background: rgb(255 255 255 / .92); color: #1f1c18; font-size: 14px;
    font-weight: 600; font-variant-numeric: tabular-nums; backdrop-filter: blur(8px); overflow-wrap: anywhere; }
  .badge.err { color: #b3261e; font-weight: 500; line-height: 1.35; border-radius: 14px; }
  .corner { position: absolute; left: 16px; bottom: 16px; z-index: 1; display: flex; gap: 6px; flex-wrap: wrap; max-width: calc(100% - 32px); }
  .go { min-height: 44px; padding: 8px 20px; border: 0; border-radius: 999px; background: var(--accent); color: var(--on-accent); font-weight: 650;
    cursor: pointer; box-shadow: 0 6px 20px rgb(0 0 0 / .25); max-width: 100%; text-align: left; }
  .go:disabled { opacity: .6; cursor: default; }
  .bar { width: 100%; height: 4px; border-radius: 2px; background: rgb(255 255 255 / .3); overflow: hidden; }
  .bar div { height: 100%; width: 0; background: #fff; transition: width .2s linear; }

  /* Narrow screens: picture first. */
  @media (max-width: 900px) {
    main { --hero: min(620px, calc(100vw - 32px)); padding: 16px 16px 28px; }
    .stage { grid-template-columns: minmax(0, 1fr); justify-items: center; align-items: start; gap: 22px; padding: 14px 0 0; }
    .hero { order: -1; }
    .words { width: 100%; gap: 18px; }
    .sentence.xl { --size: clamp(32px, 8.5vw, 52px); }
    .sentence.lg { --size: clamp(28px, 7vw, 44px); }
    .sentence.md { --size: clamp(24px, 5.8vw, 36px); }
    .sentence.sm { --size: clamp(21px, 4.8vw, 30px); }
    .heading { font-size: clamp(28px, 7vw, 42px); }
    .shot, .shot img { width: 68px; }
    .shot img { height: 68px; }
    .drop { width: 128px; }
  }
  @media (max-width: 520px) { .brand small { display: none; } header .seg { order: 3; width: 100%; } header .seg button { flex: 1 1 0; min-width: 0; } }

  @keyframes pop { from { opacity: 0; transform: translateY(-4px) scale(.98); } }
  @keyframes arrive { from { opacity: 0; filter: blur(10px); transform: scale(1.02); } }
  @keyframes slide { from { opacity: 0; transform: translateX(16px); } }
  @keyframes blink { 50% { opacity: .3; } }
  @media (prefers-reduced-motion: reduce) { .hero img, .shot, .info, .rec { animation: none; } }
</style>
</head>
<body>
<main>
  <header>
    <a class="pill brand" href="https://huggingface.co/linlinlinlinsdada/Jeveration" target="_blank" rel="noopener">
      <span aria-hidden="true">⚡</span> Jeveration <small>WebGPU</small>
    </a>
    <div class="seg" role="tablist" id="modes">
      <button role="tab" id="tab-t2i" aria-selected="true">Text to image</button>
      <button role="tab" id="tab-i2i" aria-selected="false">Style transfer</button>
    </div>
    <div class="info-wrap" id="info-wrap">
      <button class="pill icon" id="info-btn" aria-label="About this picture" aria-expanded="false" aria-controls="info">
        <svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true"><circle cx="12" cy="12" r="9" fill="none" stroke="currentColor" stroke-width="1.8"/>
          <path d="M12 11v6M12 7.5v.01" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>
      </button>
      <div class="info" id="info" hidden>
        <h2>One pass, on your GPU</h2>
        <p>Jeveration turns text into a picture in a single forward pass of a 4B model. Here it runs in your browser with ONNX Runtime Web, and nothing is uploaded.</p>
        <dl id="receipt"></dl>
        <p class="label">Made possible by</p>
        <a href="https://huggingface.co/linlinlinlinsdada/Jeveration" target="_blank" rel="noopener"><span>Jeveration</span><small>Qwen3.5-4B + LoRA</small></a>
        <a href="https://github.com/Carol-lyh/Jeveration" target="_blank" rel="noopener"><span>Code</span><small>GitHub</small></a>
        <a href="https://huggingface.co/linoyts/Jeveration-int8-ONNX" target="_blank" rel="noopener"><span>WebGPU weights</span><small>ONNX · int8</small></a>
      </div>
    </div>
  </header>

  <section class="stage">
    <div class="words">
      <!-- Text to image -->
      <div id="t2i-panel" class="words">
        <div class="sentence lg" id="sentence">
          <div class="mirror" id="mirror" aria-hidden="true"></div>
          <textarea id="prompt" rows="1" maxlength="600" aria-label="Describe a picture" autocomplete="off" spellcheck="false"></textarea>
        </div>
        <div class="film" id="film" aria-label="Recent pictures"></div>
        <p class="hint">Keep typing and the picture follows. <kbd>Enter</kbd> rolls a new seed.</p>
        <div class="picks" id="examples"></div>
      </div>
      <!-- Style transfer -->
      <div id="i2i-panel" class="words" hidden>
        <p class="kicker">Style transfer</p>
        <h1 class="heading">Turn this photo <em id="style-word">watercolor</em>.</h1>
        <div class="source">
          <label class="drop" id="drop" title="Drop a photo or click to choose one">
            <canvas id="src" width="512" height="512"></canvas>
            <video id="video" playsinline muted hidden></video>
            <span class="tag" id="drop-tag">Drop or choose a photo</span>
            <input type="file" id="file" accept="image/*" class="sr-only">
          </label>
          <div class="source-side">
            <div class="thumbs" id="thumbs"></div>
            <div><button class="pill pick" id="cam" type="button">📷 Live camera</button></div>
          </div>
        </div>
        <div class="picks" id="styles"></div>
      </div>
    </div>

    <figure class="hero" id="hero">
      <div class="placeholder" id="placeholder">Your picture appears here.</div>
      <div class="corner" id="corner" hidden></div>
      <div class="overlay" id="overlay">
        <span class="badge" id="gpu">Checking WebGPU...</span>
        <button class="go" id="load" disabled>Load the model</button>
        <div class="bar" id="bar-wrap" hidden><div id="bar"></div></div>
      </div>
    </figure>
  </section>
</main>
<script type="module">
  const I2I = true;                     // false in the text-only Space
  const TOTAL = I2I ? 7.55e9 : 6.24e9;  // bytes downloaded on the first visit
  const FILM_LIMIT = 14, SETTLE_MS = 900;
  const $ = (id) => document.getElementById(id);
  const worker = new Worker(new URL("./worker.js", import.meta.url), { type: "module" });

  const EXAMPLES = [
    ["👾", "pixel art", "Pixel art of a cozy wooden cabin in a snowy pine forest at night, warm light glowing in the windows."],
    ["🎨", "watercolor", "A watercolor painting of a red fox curled up asleep under an autumn tree, soft washes on textured paper."],
    ["💥", "comic", "A comic book panel of a cat in a superhero cape leaping between city rooftops, bold ink lines and halftone dots."],
    ["☂️", "anime", "An anime illustration of a girl holding a red umbrella on a rainy street at dusk, glowing shop signs."],
    ["🔺", "low poly", "A low-poly 3D illustration of a lighthouse on a rocky cliff at sunset, pastel colors."],
    ["🏯", "woodblock", "A Japanese woodblock print of a crane flying over snowy mountains, flat colors and fine outlines."],
    ["🖍️", "storybook", "A children's book illustration of a bear reading a book under a lamp, crayon and colored pencil texture."],
    ["🦚", "stained glass", "A stained glass window of a peacock with its tail spread, bright jewel tones and thick black leading."],
    ["🎈", "flat vector", "A flat vector illustration of hot air balloons over a patchwork of green fields, simple shapes."],
    ["🌻", "impasto", "An oil painting in thick impasto strokes of a sunflower field under a swirling blue sky."],
  ];
  const STYLES = [["watercolor", "🎨 Watercolor", "watercolor"], ["anime", "✨ Anime", "anime"], ["ghibli", "🌿 Ghibli", "Ghibli"],
                  ["colorize", "🖌️ Colorize", "into color"]];
  const PHOTOS = !I2I ? [] : ["photo_snowcabin", "photo_owl", "photo_valley", "photo_boathouse", "photo_croissant", "photo_waterfall", "gray_pancakes"];
  const newSeed = () => Math.floor(Math.random() * 1e6);

  let mode = "t2i", task = "watercolor", imageId = 0, haveImage = false, ready = false, reqId = 0, gpuName = "your GPU";
  let seed = newSeed(), lastAsked = "", stream = null, camBusy = false, settleTimer = 0;
  let shown = null;          // the picture on screen: { url, prompt, mode, seed, timings, label }
  let painted = "";          // the prompt that picture was made from
  const film = [], sent = new Map(), stamps = [];

  $("load").textContent = `Load the model (~${(TOTAL / 1e9).toFixed(1)} GB, cached after the first visit)`;
  if (!I2I) $("modes").hidden = true;

  // ---------- the sentence: words already in the picture in ink, newer words underlined ----------
  const prompt = $("prompt");
  prompt.value = EXAMPLES[0][2];
  function sharedWords(a, b) {
    let i = 0; while (i < a.length && i < b.length && a[i] === b[i]) i++;
    if (i === b.length || i === a.length) return b.slice(0, i);
    return b.slice(0, b.lastIndexOf(" ", i) + 1);
  }
  function renderSentence() {
    const text = prompt.value, m = $("mirror"); m.textContent = "";
    if (!text) {
      const s = document.createElement("span"); s.className = "ph"; s.textContent = "Describe a picture..."; m.append(s);
    } else {
      const done = !ready ? text : painted ? sharedWords(painted, text) : "";
      const a = document.createElement("span"), b = document.createElement("span");
      a.className = "done"; a.textContent = done; b.className = "todo"; b.textContent = text.slice(done.length);
      m.append(a, b, "​");
    }
    const n = text.length;
    $("sentence").className = "sentence " + (n < 60 ? "xl" : n < 110 ? "lg" : n < 180 ? "md" : "sm");
  }
  prompt.addEventListener("input", () => { renderSentence(); request(); });
  prompt.addEventListener("keydown", (e) => {
    if (e.key !== "Enter" || e.shiftKey || e.isComposing) return;
    e.preventDefault(); seed = newSeed(); request();
  });

  for (const [emoji, label, text] of EXAMPLES) {
    const b = document.createElement("button");
    b.type = "button"; b.className = "pill pick"; b.title = text; b.textContent = `${emoji} ${label}`;
    b.onclick = () => { prompt.value = text; renderSentence(); request(); };
    $("examples").append(b);
  }
  const surprise = document.createElement("button");
  surprise.type = "button"; surprise.className = "pill pick"; surprise.textContent = "🎲 surprise me";
  surprise.onclick = () => {
    const opts = EXAMPLES.filter((e) => e[2] !== prompt.value);
    prompt.value = opts[Math.floor(Math.random() * opts.length)][2]; seed = newSeed(); renderSentence(); request();
  };
  $("examples").append(surprise);

  // ---------- style transfer ----------
  for (const [key, name] of STYLES) {
    const b = document.createElement("button");
    b.type = "button"; b.className = "pill pick"; b.textContent = name; b.dataset.task = key;
    b.setAttribute("aria-pressed", String(key === task));
    b.onclick = () => setTask(key);
    $("styles").append(b);
  }
  function setTask(key) {
    task = key;
    for (const c of $("styles").children) c.setAttribute("aria-pressed", String(c.dataset.task === key));
    $("style-word").textContent = STYLES.find((s) => s[0] === key)[2];
    request();
  }
  for (const f of PHOTOS) {
    const b = document.createElement("button"), im = document.createElement("img");
    b.type = "button"; b.title = f.replace(/^(photo|gray)_/, ""); im.src = `examples/${f}.jpg`; im.alt = b.title; im.loading = "lazy"; b.append(im);
    b.onclick = async () => { await setPhoto(await (await fetch(`examples/${f}.jpg`)).blob()); if (f.startsWith("gray_")) setTask("colorize"); };
    $("thumbs").append(b);
  }
  /** picture or video frame -> 512 x 512 RGB (short side to 512, centre crop, mirrored for the camera) -> worker */
  function sendFrame(src, sw, sh, mirror = false) {
    const s = 512 / Math.min(sw, sh), w = Math.max(512, Math.round(sw * s)), h = Math.max(512, Math.round(sh * s));
    const ctx = $("src").getContext("2d", { willReadFrequently: true }); ctx.imageSmoothingQuality = "high";
    ctx.save(); if (mirror) { ctx.translate(512, 0); ctx.scale(-1, 1); }
    ctx.drawImage(src, -Math.floor((w - 512) / 2), -Math.floor((h - 512) / 2), w, h); ctx.restore();
    const px = ctx.getImageData(0, 0, 512, 512).data, rgb = new Uint8Array(512 * 512 * 3);
    for (let i = 0; i < 512 * 512; i++) { rgb[3 * i] = px[4 * i]; rgb[3 * i + 1] = px[4 * i + 1]; rgb[3 * i + 2] = px[4 * i + 2]; }
    worker.postMessage({ type: "image", data: { rgb, imageId: ++imageId } }, [rgb.buffer]);
    haveImage = true; $("drop-tag").hidden = true;
  }
  async function setPhoto(blob) {
    stopCamera();
    const bmp = await createImageBitmap(blob);
    sendFrame(bmp, bmp.width, bmp.height); request();
  }
  $("file").onchange = (e) => { if (e.target.files[0]) setPhoto(e.target.files[0]); e.target.value = ""; };
  $("drop").ondragover = (e) => { e.preventDefault(); $("drop").classList.add("over"); };
  $("drop").ondragleave = () => $("drop").classList.remove("over");
  $("drop").ondrop = (e) => { e.preventDefault(); $("drop").classList.remove("over"); if (e.dataTransfer.files[0]) setPhoto(e.dataTransfer.files[0]); };

  // Camera: one frame in flight. The next frame is grabbed when the previous picture comes back, so the output lags the
  // camera by one generation at most, and the seed stays fixed for a steadier picture.
  function camTick() {
    if (!stream || !ready || camBusy || mode !== "i2i") return;
    const v = $("video");
    if (v.readyState < 2) { requestAnimationFrame(camTick); return; }
    camBusy = true; sendFrame(v, v.videoWidth, v.videoHeight, true); request(true);
  }
  async function startCamera() {
    try {
      stream = await navigator.mediaDevices.getUserMedia({ video: { width: { ideal: 640 }, height: { ideal: 640 }, facingMode: "user" }, audio: false });
    } catch (e) { showError("Camera unavailable: " + (e.message || e)); stream = null; return; }
    $("video").srcObject = stream; $("video").hidden = false; await $("video").play();
    $("cam").innerHTML = '<span class="rec" aria-hidden="true"></span> Stop camera';
    $("drop-tag").hidden = true; $("hero").classList.add("camera");
    camBusy = false; camTick();
  }
  function stopCamera() {
    if (!stream) return;
    for (const t of stream.getTracks()) t.stop();
    stream = null; camBusy = false; $("video").srcObject = null; $("video").hidden = true;
    $("cam").textContent = "📷 Live camera"; $("hero").classList.remove("camera"); renderCorner();
  }
  $("cam").onclick = () => (stream ? stopCamera() : startCamera());

  function setMode(m) {
    mode = m; if (m !== "i2i") stopCamera();
    $("tab-t2i").setAttribute("aria-selected", String(m === "t2i")); $("tab-i2i").setAttribute("aria-selected", String(m === "i2i"));
    $("t2i-panel").hidden = m !== "t2i"; $("i2i-panel").hidden = m !== "i2i";
    if (m === "i2i" && !haveImage) $("thumbs").children[0].click(); else request();
  }
  $("tab-t2i").onclick = () => setMode("t2i");
  $("tab-i2i").onclick = () => setMode("i2i");

  // ---------- requests: latest wins (the worker drops stale ones) ----------
  function request(fromCamera = false) {
    if (!ready) return;
    if (mode === "i2i" && !haveImage) return;
    if (stream && !fromCamera) return;              // the camera loop drives requests while it runs
    const text = prompt.value.trim();
    if (mode === "t2i" && !text) return;
    const key = mode === "t2i" ? `t:${seed}:${text}` : `i:${seed}:${task}:${imageId}`;
    if (key === lastAsked) return;
    lastAsked = key;
    const id = ++reqId; sent.set(id, { prompt: text, mode, seed });
    worker.postMessage({ type: "generate", data: { mode, prompt: text, task, seed, id } });
  }

  // ---------- the picture ----------
  const draw = document.createElement("canvas"); draw.width = draw.height = 512;
  async function toUrl(rgb) {
    const img = new ImageData(512, 512);
    for (let i = 0; i < 512 * 512; i++) { img.data[4 * i] = rgb[3 * i]; img.data[4 * i + 1] = rgb[3 * i + 1]; img.data[4 * i + 2] = rgb[3 * i + 2]; img.data[4 * i + 3] = 255; }
    draw.getContext("2d").putImageData(img, 0, 0);
    const blob = await new Promise((r) => draw.toBlob(r, "image/webp", 0.92));
    return URL.createObjectURL(blob);
  }
  const inUse = (u) => u === shown?.url || film.some((f) => f.url === u);
  /** fade the new picture in over the previous one; drop older layers and free their memory */
  function setHero(frame) {
    const hero = $("hero"), layers = [...hero.querySelectorAll("img")];
    const img = document.createElement("img"); img.src = frame.url; img.alt = frame.prompt || "Styled photo";
    hero.insertBefore(img, $("corner")); $("placeholder").hidden = true;
    shown = frame;
    layers.forEach((o, i) => {
      if (i < layers.length - 1) { o.remove(); if (!inUse(o.src)) URL.revokeObjectURL(o.src); }
      else o.className = "behind";
    });
    renderCorner(); if (!$("info").hidden) renderReceipt();
  }
  const labelFor = (prev, next) => (prev && next.startsWith(prev) ? next.slice(prev.length).replace(/^[\s,.;]+/, "") || next : next);
  /** keep a picture in the strip once typing settles, replacing a repaint of the same prompt */
  function commitToFilm() {
    if (!shown || shown.mode !== "t2i" || film.includes(shown)) return;
    const last = film.at(-1), same = last?.prompt === shown.prompt;
    shown.label = same ? last.label : labelFor(last?.prompt ?? "", shown.prompt);
    if (same) film.pop();
    film.push(shown);
    while (film.length > FILM_LIMIT) film.shift();
    renderFilm(true);
  }
  function renderFilm(scroll = false) {
    const el = $("film"); el.textContent = "";
    for (const f of film) {
      const b = document.createElement("button"), im = document.createElement("img"), s = document.createElement("span");
      b.className = "shot" + (f === shown ? " on" : ""); b.title = f.prompt; im.src = f.url; im.alt = f.prompt; s.textContent = f.label;
      b.append(im, s);
      b.onclick = () => {
        seed = f.seed; prompt.value = f.prompt; painted = f.prompt; lastAsked = `t:${f.seed}:${f.prompt}`;
        setHero(f); renderSentence(); renderFilm();
      };
      el.append(b);
    }
    if (scroll) el.scrollTo({ left: el.scrollWidth, behavior: "smooth" });
  }
  function renderCorner() {
    const c = $("corner"); c.textContent = ""; c.hidden = !shown || !ready;
    if (c.hidden) return;
    const add = (t) => { const s = document.createElement("span"); s.className = "badge"; s.textContent = t; c.append(s); };
    add(`${(shown.timings.total / 1000).toFixed(2)} s`);
    if (stream && stamps.length > 1) add(`${((stamps.length - 1) / ((stamps.at(-1) - stamps[0]) / 1000)).toFixed(1)} fps`);
  }
  function renderReceipt() {
    const t = shown?.timings, rows = [["Picture", "512 × 512"], ["Forward passes", "1"], ["Seed", String(shown ? shown.seed : seed)]];
    if (t) {
      if (shown.mode === "i2i") rows.push(["Vision encoder", t.vision]);
      rows.push(["Backbone (Qwen3.5-4B, int8)", t.backbone], ["Image head", t.head], ["Sampling", t.sample], ["CLIP + decoder", t.decode]);
    }
    rows.push(["Ran on", gpuName], ["Uploaded", "nothing"]);
    if (t) rows.push(["Total", t.total, "sum"]);
    const dl = $("receipt"); dl.textContent = "";
    for (const [k, v, cls] of rows) {
      const d = document.createElement("div"), dt = document.createElement("dt"), dd = document.createElement("dd");
      if (cls) d.className = cls;
      dt.textContent = k; dd.textContent = typeof v === "number" ? `${(v / 1000).toFixed(2)} s` : v;
      d.append(dt, dd); dl.append(d);
    }
  }

  // ---------- loading, status and errors ----------
  function showError(text) {
    $("overlay").hidden = false; $("bar-wrap").hidden = true; if (ready) $("load").hidden = true;
    $("gpu").textContent = text; $("gpu").className = "badge err";
    if (ready) setTimeout(() => { if (ready) $("overlay").hidden = true; }, 6000);
  }
  const files = new Map();
  worker.onmessage = async ({ data: m }) => {
    if (m.status === "checked") {
      gpuName = `${m.data.vendor || ""} ${m.data.architecture || ""}`.trim() || "your GPU";
      $("gpu").textContent = `WebGPU ready · ${gpuName}`; $("load").disabled = false;
    } else if (m.status === "loading") {
      $("gpu").textContent = `Loading ${m.file}...`;
    } else if (m.status === "progress") {
      files.set(m.file, m); let loaded = 0; for (const f of files.values()) loaded += f.loaded;
      $("bar").style.width = Math.min(100, (100 * loaded) / TOTAL) + "%";
      $("gpu").textContent = `${m.fromCache ? "From cache" : "Downloading"} · ${(Math.min(loaded, TOTAL) / 1e9).toFixed(2)} / ${(TOTAL / 1e9).toFixed(1)} GB`;
    } else if (m.status === "ready") {
      ready = true; $("overlay").hidden = true; $("placeholder").textContent = "Painting...";
      renderSentence();
      if (stream) camTick(); else request();
    } else if (m.status === "image") {
      const req = sent.get(m.data.id) ?? { prompt: prompt.value.trim(), mode, seed };
      sent.forEach((_, k) => { if (k <= m.data.id) sent.delete(k); });
      const now = performance.now(); stamps.push(now); while (stamps.length && now - stamps[0] > 5000) stamps.shift();
      const frame = { url: await toUrl(m.data.rgb), prompt: req.prompt, mode: req.mode, seed: req.seed, timings: m.data.timings };
      if (req.mode === "t2i") painted = req.prompt;
      setHero(frame); renderSentence(); renderFilm();
      clearTimeout(settleTimer); settleTimer = setTimeout(commitToFilm, SETTLE_MS);
      if (stream) { camBusy = false; requestAnimationFrame(camTick); }
    } else if (m.status === "error") {
      camBusy = false; lastAsked = ""; showError("Error: " + m.data);
    }
  };
  $("load").onclick = () => {
    $("load").hidden = true; $("bar-wrap").hidden = false; $("gpu").textContent = "Starting...";
    worker.postMessage({ type: "load" });
  };
  worker.onerror = (e) => showError("Worker error: " + (e.message || e));
  if (!navigator.gpu) { $("gpu").textContent = "This needs WebGPU. Try Chrome or Edge on a laptop or desktop."; $("gpu").className = "badge err"; $("load").hidden = true; }
  else worker.postMessage({ type: "check" });

  // ---------- info popover ----------
  const info = $("info"), infoBtn = $("info-btn");
  const setInfo = (open) => { info.hidden = !open; infoBtn.setAttribute("aria-expanded", String(open)); if (open) renderReceipt(); };
  infoBtn.onclick = () => setInfo(info.hidden);
  addEventListener("keydown", (e) => { if (e.key === "Escape") setInfo(false); });
  addEventListener("pointerdown", (e) => { if (!info.hidden && !$("info-wrap").contains(e.target)) setInfo(false); });

  renderSentence();
</script>
</body>
</html>