-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.py
More file actions
2240 lines (1982 loc) · 81.3 KB
/
Copy pathapp.py
File metadata and controls
2240 lines (1982 loc) · 81.3 KB
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Gradio interface for Ideogram4 NF4 on Apple Silicon."""
import sys
import os
import json
import time
import dataclasses
import gc
import hashlib
import glob
import subprocess
import selectors
import random
import html
import urllib.parse
sys.path.insert(0, os.path.dirname(__file__))
# Optional: override MLX and mlx-vlm paths via environment variables.
_MLX_PATH = os.environ.get("MLX_FORK_PATH", "")
if _MLX_PATH and os.path.isdir(_MLX_PATH):
sys.path.insert(0, _MLX_PATH)
_VLM_PATH = os.environ.get("MLX_VLM_PATH", "")
if _VLM_PATH and os.path.isdir(_VLM_PATH):
sys.path.insert(0, _VLM_PATH)
import mlx.core as mx
import numpy as np
from PIL import Image
import gradio as gr
from scheduler import LogitNormalSchedule, make_step_intervals
from transformer import Ideogram4Transformer
from load_weights import load_nf4_transformer
from load_text_encoder import load_nf4_text_encoder
from pipeline import build_inputs, LATENT_SHIFT, LATENT_SCALE
from vae import Decoder, decode_latents
ACTIVATION_LAYERS = (0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 35)
PRESETS = {
"V4_TURBO_12": {"steps": 12, "mu": 0.5, "std": 1.75,
"guidance": (3.0,)*1 + (7.0,)*11},
"V4_DEFAULT_20": {"steps": 20, "mu": 0.0, "std": 1.75,
"guidance": (3.0,)*2 + (7.0,)*18},
"V4_QUALITY_48": {"steps": 48, "mu": 0.0, "std": 1.5,
"guidance": (3.0,)*3 + (7.0,)*45},
}
MODEL_ID = "ideogram-ai/ideogram-4-nf4"
MODEL_REVISION = "f664347839e0a87bc495f5c9483cc0014b8e344e"
ROUTE_ID = "nf4-mlx-metal"
QUANT_FORMAT = "bitsandbytes NF4 (4-bit, blocksize=64)"
BACKEND = "MLX + custom NF4 Metal kernels"
# Global model state — load once, reuse
_state = {}
# Rate limiting
import threading
_rate_lock = threading.Lock()
_last_gen_time = 0.0
_MIN_COOLDOWN = 30.0 # seconds between generations
PUBLIC_WIDTH = 512
PUBLIC_HEIGHT = 512
PUBLIC_MIN_WIDTH = 256
PUBLIC_MIN_HEIGHT = 256
PUBLIC_MAX_WIDTH = 512
PUBLIC_MAX_HEIGHT = 512
PUBLIC_STEPS = 20
PUBLIC_MIN_STEPS = 4
PUBLIC_MAX_STEPS = 20
PUBLIC_PRESET = "V4_DEFAULT_20"
PUBLIC_EXPECTED_LATENCY = "10-15 minutes"
PUBLIC_HARDWARE = "16 GB M2 Pro MacBook Pro"
PUBLIC_QUEUE_SIZE = 10
PUBLIC_STATUS_HEARTBEAT_SECONDS = 5
MAX_PROMPT_CHARS = 2000
QUEUE_STATUS_TIMER_SECONDS = 3
QUEUE_STATUS_ELEM_ID = "public-queue-status"
QUEUE_ADMIN_TIMER_SECONDS = 3
QUEUE_ADMIN_ELEM_ID = "admin-queue-status"
PUBLIC_GALLERY_FILES = [
"evidence/smoke_16gb_512_20step.png",
"evidence/hero_nf4_apple_1024x1024.png",
]
GALLERY_ROTATE_SECONDS = 5
GALLERY_SLOT_COUNT = 40
GALLERY_CONSOLE_ELEM_ID = "gallery-visibility-console"
GALLERY_ADMIN_QUERY_PARAM = "gallery_admin"
GALLERY_ADMIN_QUERY_VALUE = "1"
GALLERY_MANIFEST_PATH = os.path.join(os.path.dirname(__file__), "evidence", "gallery_manifest.json")
REQUEST_LOG_PATH = os.path.join(os.path.dirname(__file__), "evidence", "live_runs", "requests.jsonl")
PRESET_PLACEHOLDER = "Pick a preset"
_queue_lock = threading.Lock()
_queue_active = 0
_queue_waiting = 0
_queue_next_id = 0
_queue_tokens = {}
_queue_records = {}
PROMPT_PRESETS = [
("Red cat on couch", "a red cat sitting on a blue couch"),
("Text poster", "the word HELLO written in neon lights on a brick wall at night"),
("NF4 Apple mark", "bold black letters NF4 inside an Apple logo silhouette"),
("Coffee study", "a cup of coffee with latte art on a wooden table"),
("Bookshop cat", "a cozy bookshop interior with a cat curled up in an armchair"),
("Product mockup", "a clean product photo of a translucent cassette labeled NF4"),
("Sticker mascot", "a cheerful robot sticker holding a tiny metal kernel"),
("Mountain lake", "a serene mountain lake at sunset with snow-capped peaks reflected in still water"),
]
AESTHETICS_PRESETS = [
("Minimal graphic design", "minimal graphic design"),
("Clean product photo", "clean product photography"),
("Editorial magazine", "editorial magazine spread"),
("Playful sticker", "playful vinyl sticker style"),
("Cinematic realism", "cinematic realism"),
("Retro computer ad", "1980s computer magazine advertisement"),
("Soft painterly", "soft painterly illustration"),
("Bold typography", "bold typography-focused poster design"),
]
LIGHTING_PRESETS = [
("Flat studio", "flat studio lighting"),
("Golden hour", "warm golden hour light"),
("Neon night", "neon signage at night"),
("Soft window", "soft window light"),
("High-key", "bright high-key lighting"),
("Low-key", "moody low-key lighting"),
("Backlit rim", "backlit with crisp rim light"),
("Overcast", "diffuse overcast daylight"),
]
MEDIUM_PRESETS = [
("Digital vector", "digital vector art"),
("Photograph", "high-resolution photograph"),
("Screen print", "two-color screen print"),
("Oil painting", "oil painting on canvas"),
("3D render", "polished 3D render"),
("Risograph", "risograph print"),
("Ink drawing", "clean ink drawing"),
("UI mockup", "product interface mockup"),
]
COLOR_PALETTE_PRESETS = [
("Black / white", "#000000, #FFFFFF"),
("Blue couch / orange cat", "#1F5E7A, #D76B2A, #F4D6A0"),
("NF4 orange", "#FF6B1A, #202020, #F7F7F2"),
("Neon", "#FF2D95, #00E5FF, #111111"),
("Forest", "#12372A, #6B8E23, #F3E9D2"),
("Warm paper", "#2F2A24, #E7D4B5, #B85C38"),
("Candy", "#FF7AB6, #7AE7FF, #FFF7A8"),
("Metal", "#C9CED6, #3B4452, #111820"),
]
CANVAS_PRESETS = [
("Square 512", "512 x 512 square canvas"),
("Square 384", "384 x 384 square canvas"),
("Small square", "256 x 256 square canvas"),
("Poster crop", "portrait poster crop"),
("Wide banner", "wide banner composition"),
("Album cover", "centered square album-cover crop"),
("Icon tile", "single app-icon tile"),
("Product card", "clean product-card canvas"),
]
BACKGROUND_PRESETS = [
("Pure white", "pure white background"),
("Blue couch", "deep blue couch in the background"),
("Brick wall", "dark brick wall background"),
("Warm desk", "warm wooden desk surface"),
("Mountain dusk", "distant mountain landscape at dusk"),
("Transparent feel", "plain light background with transparent-object feel"),
("Grid paper", "subtle graph-paper background"),
("Black stage", "matte black studio stage"),
]
LAYOUT_PRESETS = [
("Centered", "centered single subject"),
("Rule of thirds", "subject placed on the left third with open space"),
("Text dominant", "large readable text dominates the center"),
("Hero product", "hero object centered with small supporting details"),
("Diagonal", "diagonal movement from lower left to upper right"),
("Badge", "compact badge-like composition"),
("Split stack", "stacked text above object"),
("Symmetric", "symmetrical composition with balanced margins"),
]
ELEMENTS_PRESETS = [
("NF4 logo text", "text | Large bold black letters NF4\nobj | Apple logo silhouette behind the letters"),
("Cat portrait", "animal | Orange cat with visible whiskers\nobj | Blue couch cushions"),
("Coffee table", "obj | Ceramic latte cup\nobj | Wooden table\nlight | Morning light across the surface"),
("Neon wall", "text | The word HELLO in bright neon tubing\nbg | Dark brick wall"),
("Product label", "obj | Translucent cassette shell\ntext | Small label reading NF4"),
("Bookshop", "animal | Cat curled in a worn armchair\nobj | Tall shelves of books"),
("Sticker", "character | Cheerful robot mascot\nobj | Tiny glowing metal kernel"),
("Landscape", "env | Still mountain lake\nenv | Snow-capped peaks reflected in water"),
]
ADVANCED_RUN_PRESETS = [
{"key": "balanced_512", "label": "512 balanced", "seed": 42, "width": 512, "height": 512, "steps": 20},
{"key": "quick_384", "label": "384 quicker", "seed": 101, "width": 384, "height": 384, "steps": 12},
{"key": "probe_256", "label": "256 probe", "seed": 2025, "width": 256, "height": 256, "steps": 8},
{"key": "square_320", "label": "320 square", "seed": 31415, "width": 320, "height": 320, "steps": 12},
{"key": "small_detail", "label": "448 detail", "seed": 777, "width": 448, "height": 448, "steps": 20},
{"key": "wide_local", "label": "Wide local", "seed": 1234, "width": 512, "height": 320, "steps": 16},
{"key": "tall_local", "label": "Tall local", "seed": 5678, "width": 320, "height": 512, "steps": 16},
{"key": "text_test", "label": "Text test", "seed": 9001, "width": 512, "height": 512, "steps": 20},
]
def _is_public_mode():
return os.environ.get("NF4_PUBLIC_MODE") == "1" or "--public" in sys.argv
def _gallery_console_visibility_css(public_mode):
css_parts = []
if public_mode:
css_parts.append(f"""
#{GALLERY_CONSOLE_ELEM_ID} {{
display: none !important;
}}
.gallery-admin-enabled #{GALLERY_CONSOLE_ELEM_ID} {{
display: block !important;
}}
html.gallery-admin-enabled .gradio-container .contain #{GALLERY_CONSOLE_ELEM_ID},
body.gallery-admin-enabled .gradio-container .contain #{GALLERY_CONSOLE_ELEM_ID} {{
display: block !important;
}}
""")
css_parts.append("""
.admin-queue-panel {
background: #18181c;
border: 1px solid #3a3a42;
border-radius: 8px;
color: #f2f2f4;
margin: 8px 0 16px;
padding: 12px;
}
.admin-queue-header {
align-items: center;
display: flex;
gap: 12px;
justify-content: space-between;
margin-bottom: 10px;
}
.admin-queue-header span,
.admin-queue-note {
color: #b9bbc6;
font-size: 13px;
}
.admin-queue-table {
border-collapse: collapse;
font-size: 13px;
width: 100%;
}
.admin-queue-table th,
.admin-queue-table td {
border-top: 1px solid #34343b;
padding: 8px 6px;
text-align: left;
vertical-align: top;
}
.admin-queue-table th {
color: #d8d9df;
font-weight: 600;
}
.admin-queue-table code {
color: #f2f2f4;
white-space: nowrap;
}
.queue-state {
border-radius: 999px;
display: inline-block;
font-size: 12px;
font-weight: 700;
line-height: 1;
padding: 5px 8px;
}
.queue-state-active {
background: #1d7f4f;
color: #fff;
}
.queue-state-waiting {
background: #6246ea;
color: #fff;
}
.queue-empty {
color: #b9bbc6;
text-align: center !important;
}
""")
return "\n".join(css_parts)
def _gallery_console_visibility_head():
return f"""
<script>
(function() {{
function enableGalleryAdmin() {{
document.documentElement.classList.add("gallery-admin-enabled");
if (document.body) {{
document.body.classList.add("gallery-admin-enabled");
}}
}}
const params = new URLSearchParams(window.location.search);
if (params.get("{GALLERY_ADMIN_QUERY_PARAM}") === "{GALLERY_ADMIN_QUERY_VALUE}") {{
enableGalleryAdmin();
document.addEventListener("DOMContentLoaded", enableGalleryAdmin);
}}
}})();
</script>
"""
def _clamp_public_dimension(value, minimum, maximum):
value = int(value)
value = max(minimum, min(maximum, value))
return value - (value % 16)
def _clamp_public_steps(value):
value = int(value)
return max(PUBLIC_MIN_STEPS, min(PUBLIC_MAX_STEPS, value))
def _effective_request(prompt_text, use_json, preset_name, width, height, steps):
prompt_text = (prompt_text or "").strip()[:MAX_PROMPT_CHARS]
if _is_public_mode():
return (
prompt_text,
False,
PUBLIC_PRESET,
_clamp_public_dimension(width, PUBLIC_MIN_WIDTH, PUBLIC_MAX_WIDTH),
_clamp_public_dimension(height, PUBLIC_MIN_HEIGHT, PUBLIC_MAX_HEIGHT),
_clamp_public_steps(steps),
)
return prompt_text, bool(use_json), preset_name, min(int(width), 1024), min(int(height), 1024), int(steps)
def _public_queue_snapshot():
with _queue_lock:
active = int(_queue_active)
waiting = int(_queue_waiting)
entries = [dict(record) for record in _queue_records.values()]
admitted = active + waiting
free = max(0, PUBLIC_QUEUE_SIZE - admitted)
entries.sort(key=lambda entry: (0 if entry.get("state") == "active" else 1, entry.get("sequence", 0)))
return {
"active": active,
"waiting": waiting,
"admitted": admitted,
"free": free,
"full": admitted >= PUBLIC_QUEUE_SIZE,
"capacity": PUBLIC_QUEUE_SIZE,
"entries": entries,
}
def _public_queue_is_full():
return _public_queue_snapshot()["full"]
def _public_queue_status_html():
snapshot = _public_queue_snapshot()
accent = "#b42318" if snapshot["full"] else "#1d7f4f"
label = "Queue full" if snapshot["full"] else "Queue open"
note = (
"Try again in a few minutes."
if snapshot["full"]
else "Generate stays available until all public slots are admitted."
)
return (
f"<div id='{QUEUE_STATUS_ELEM_ID}' style='border:1px solid #d8d8d8;border-left:4px solid {accent};"
"border-radius:6px;padding:10px 12px;margin:8px 0 12px;background:#fff;font-size:14px;line-height:1.4;'>"
f"<b>{label}</b> · Queue: {snapshot['active']} running / {snapshot['waiting']} waiting / "
f"{snapshot['free']} free of {snapshot['capacity']} slots<br>"
f"<span style='color:#666;'>{note}</span>"
"</div>"
)
def _queue_age_label(timestamp, now=None):
if not timestamp:
return "-"
now = time.time() if now is None else now
seconds = max(0, int(now - float(timestamp)))
if seconds < 60:
return f"{seconds}s"
minutes, seconds = divmod(seconds, 60)
if minutes < 60:
return f"{minutes}m {seconds:02d}s"
hours, minutes = divmod(minutes, 60)
return f"{hours}h {minutes:02d}m"
def _public_queue_admin_html():
snapshot = _public_queue_snapshot()
now = time.time()
rows = []
for entry in snapshot["entries"]:
state = html.escape(str(entry.get("state", "unknown")))
token = html.escape(str(entry.get("token", "")))
admitted = html.escape(_queue_age_label(entry.get("admitted_at"), now))
started = html.escape(_queue_age_label(entry.get("started_at"), now))
position = html.escape(str(entry.get("position", "-")))
rows.append(
"<tr>"
f"<td><span class='queue-state queue-state-{state}'>{state}</span></td>"
f"<td><code>{token}</code></td>"
f"<td>{position}</td>"
f"<td>{admitted}</td>"
f"<td>{started}</td>"
"</tr>"
)
if not rows:
rows.append("<tr><td colspan='5' class='queue-empty'>No admitted public jobs right now.</td></tr>")
return (
f"<div id='{QUEUE_ADMIN_ELEM_ID}' class='admin-queue-panel'>"
"<div class='admin-queue-header'>"
"<b>Admin queue</b>"
f"<span>{snapshot['active']} active · {snapshot['waiting']} waiting · "
f"{snapshot['free']} free / {snapshot['capacity']} slots</span>"
"</div>"
"<table class='admin-queue-table'>"
"<thead><tr><th>State</th><th>Token</th><th>Position</th><th>Admitted</th><th>Started</th></tr></thead>"
f"<tbody>{''.join(rows)}</tbody>"
"</table>"
f"<div class='admin-queue-note'>Refreshed every {QUEUE_ADMIN_TIMER_SECONDS}s from local admission state.</div>"
"</div>"
)
def _public_queue_admit():
global _queue_waiting, _queue_next_id
with _queue_lock:
if _queue_active + _queue_waiting >= PUBLIC_QUEUE_SIZE:
return None, f"Queue full — all {PUBLIC_QUEUE_SIZE} public slots are admitted. Try again in a few minutes."
_queue_next_id += 1
token = f"public-{int(time.time())}-{_queue_next_id}"
_queue_waiting += 1
_queue_tokens[token] = "waiting"
_queue_records[token] = {
"token": token,
"sequence": _queue_next_id,
"position": _queue_waiting,
"state": "waiting",
"admitted_at": time.time(),
"started_at": None,
}
position = _queue_waiting
jobs_ahead = max(0, _queue_active + position - 1)
noun = "job" if jobs_ahead == 1 else "jobs"
return token, f"Queue slot reserved. You are waiting behind {jobs_ahead} public {noun}."
def _public_queue_mark_started(token):
global _queue_active, _queue_waiting
if not token:
return False
with _queue_lock:
if _queue_tokens.get(token) != "waiting":
return False
_queue_tokens[token] = "active"
if token in _queue_records:
_queue_records[token]["state"] = "active"
_queue_records[token]["started_at"] = time.time()
_queue_waiting = max(0, _queue_waiting - 1)
_queue_active += 1
return True
def _public_queue_mark_finished(token):
global _queue_active, _queue_waiting
if not token:
return
with _queue_lock:
state = _queue_tokens.pop(token, None)
_queue_records.pop(token, None)
if state == "active":
_queue_active = max(0, _queue_active - 1)
elif state == "waiting":
_queue_waiting = max(0, _queue_waiting - 1)
def _public_queue_button_update():
if not _is_public_mode():
return gr.update(interactive=True)
return gr.update(interactive=not _public_queue_is_full())
def _queue_status_tick():
return _public_queue_status_html(), _public_queue_button_update()
def _queue_admin_tick():
return _public_queue_admin_html()
def _queue_initial_controls():
return _public_queue_status_html(), _public_queue_button_update(), _public_queue_admin_html()
def _admit_generate_click():
if not _is_public_mode():
return "", "Starting local generation.", _public_queue_status_html(), gr.update(interactive=True)
token, message = _public_queue_admit()
return token or "", message, _public_queue_status_html(), _public_queue_button_update()
def _build_prompt_payload(prompt_text, use_style, aesthetics, lighting, medium, color_palette,
use_composition, canvas, background, layout, elements_text):
prompt_text = (prompt_text or "").strip()
payload = {"high_level_description": prompt_text}
if use_style:
style = {}
if (aesthetics or "").strip():
style["aesthetics"] = aesthetics.strip()
if (lighting or "").strip():
style["lighting"] = lighting.strip()
if (medium or "").strip():
style["medium"] = medium.strip()
colors = [part.strip() for part in (color_palette or "").split(",") if part.strip()]
if colors:
style["color_palette"] = colors
if style:
payload["style_description"] = style
if use_composition:
composition = {}
if (canvas or "").strip():
composition["canvas"] = canvas.strip()
if (background or "").strip():
composition["background"] = background.strip()
if (layout or "").strip():
composition["layout"] = layout.strip()
elements = []
for raw in (elements_text or "").splitlines():
raw = raw.strip()
if not raw:
continue
if "|" in raw:
kind, desc = raw.split("|", 1)
kind = kind.strip() or "obj"
desc = desc.strip()
else:
kind, desc = "obj", raw
if desc:
elements.append({"type": kind, "desc": desc})
if elements:
composition["elements"] = elements
if composition:
payload["compositional_deconstruction"] = composition
if len(payload) == 1:
return json.dumps({"prompt": prompt_text})
return json.dumps(payload)
def _preset_choices(presets):
return [PRESET_PLACEHOLDER] + [label for label, _ in presets]
def _advanced_choices():
return [item["label"] for item in ADVANCED_RUN_PRESETS]
def _preset_value(presets, selected):
if selected == PRESET_PLACEHOLDER:
return ""
for label, value in presets:
if selected in (label, value):
return value
return selected or ""
def _advanced_preset_by_key(key):
for item in ADVANCED_RUN_PRESETS:
if key in (item["key"], item["label"]):
return item
return ADVANCED_RUN_PRESETS[0]
def _apply_text_preset(selected):
return _preset_value(PROMPT_PRESETS, selected)
def _apply_style_preset(selected, preset_name):
value = _preset_value(preset_name, selected)
return bool(value), value
def _apply_composition_preset(selected, preset_name):
value = _preset_value(preset_name, selected)
return bool(value), value
def _apply_aesthetics_preset(selected):
return _apply_style_preset(selected, AESTHETICS_PRESETS)
def _apply_lighting_preset(selected):
return _apply_style_preset(selected, LIGHTING_PRESETS)
def _apply_medium_preset(selected):
return _apply_style_preset(selected, MEDIUM_PRESETS)
def _apply_color_palette_preset(selected):
return _apply_style_preset(selected, COLOR_PALETTE_PRESETS)
def _apply_canvas_preset(selected):
return _apply_composition_preset(selected, CANVAS_PRESETS)
def _apply_background_preset(selected):
return _apply_composition_preset(selected, BACKGROUND_PRESETS)
def _apply_layout_preset(selected):
return _apply_composition_preset(selected, LAYOUT_PRESETS)
def _apply_elements_preset(selected):
return _apply_composition_preset(selected, ELEMENTS_PRESETS)
def _apply_advanced_preset(selected):
item = _advanced_preset_by_key(selected)
preset_name = PUBLIC_PRESET
width = int(item["width"])
height = int(item["height"])
steps = int(item["steps"])
if _is_public_mode():
width = _clamp_public_dimension(width, PUBLIC_MIN_WIDTH, PUBLIC_MAX_WIDTH)
height = _clamp_public_dimension(height, PUBLIC_MIN_HEIGHT, PUBLIC_MAX_HEIGHT)
steps = _clamp_public_steps(steps)
return int(item["seed"]), preset_name, width, height, steps
def _randomize_form():
prompt_text = random.choice(PROMPT_PRESETS)[1]
aesthetics = random.choice(AESTHETICS_PRESETS)[1]
lighting = random.choice(LIGHTING_PRESETS)[1]
medium = random.choice(MEDIUM_PRESETS)[1]
color_palette = random.choice(COLOR_PALETTE_PRESETS)[1]
canvas = random.choice(CANVAS_PRESETS)[1]
background = random.choice(BACKGROUND_PRESETS)[1]
layout = random.choice(LAYOUT_PRESETS)[1]
elements_text = random.choice(ELEMENTS_PRESETS)[1]
seed, preset_name, width, height, steps = _apply_advanced_preset(
random.choice(ADVANCED_RUN_PRESETS)["key"]
)
seed = random.randint(1, 999999)
return (
prompt_text,
seed,
preset_name,
width,
height,
steps,
True,
aesthetics,
lighting,
medium,
color_palette,
True,
canvas,
background,
layout,
elements_text,
)
def _assert_nf4_available():
try:
w = mx.random.normal((64, 64)).astype(mx.float16)
q = mx.quantize(w, bits=4, group_size=64, mode="nf4")
mx.eval(q[0])
except Exception as e:
raise RuntimeError(
"NF4 support is not active in the current MLX install. Reinstall the "
"NF4 fork last: pip install --force-reinstall --no-deps "
"git+https://github.com/lyonsno/mlx.git@nf4"
) from e
def _get_hf_token():
from huggingface_hub.utils import get_token
token = get_token()
if not token:
raise RuntimeError(
"Hugging Face token not found. Run `hf auth login` or set HF_TOKEN "
"after accepting the Ideogram 4 NF4 license."
)
return token
def _write_run_receipt(img, prompt, seed, width, height, preset, num_steps,
sampling_time, active_gb, sampling_peak_gb, total_peak_gb):
out_dir = os.path.join(os.path.dirname(__file__), "evidence", "live_runs")
os.makedirs(out_dir, exist_ok=True)
stamp = time.strftime("%Y%m%dT%H%M%S")
stem = f"{stamp}_{ROUTE_ID}_{int(width)}x{int(height)}_seed{int(seed)}"
image_path = os.path.join(out_dir, f"{stem}.png")
receipt_path = os.path.join(out_dir, f"{stem}.json")
img.save(image_path)
with open(image_path, "rb") as fp:
image_sha256 = hashlib.sha256(fp.read()).hexdigest()
receipt = {
"route": ROUTE_ID,
"model": MODEL_ID,
"model_revision": MODEL_REVISION,
"quant_format": QUANT_FORMAT,
"backend": BACKEND,
"not_routes": ["MFLUX", "GGUF/stable-diffusion.cpp", "PyTorch/MPS", "remote GPU"],
"host": os.uname().nodename,
"public_mode": _is_public_mode(),
"prompt": prompt,
"seed": int(seed),
"resolution": f"{int(width)}x{int(height)}",
"steps": int(num_steps),
"preset": preset,
"sampling_time_s": round(float(sampling_time), 2),
"seconds_per_step": round(float(sampling_time) / int(num_steps), 2),
"memory_active_gb": round(float(active_gb), 2),
"memory_sampling_peak_gb": round(float(sampling_peak_gb), 2),
"memory_total_peak_gb": round(float(total_peak_gb), 2),
"output": os.path.abspath(image_path),
"output_sha256": image_sha256,
}
with open(receipt_path, "w") as fp:
json.dump(receipt, fp, indent=2)
fp.write("\n")
return image_path, receipt_path, image_sha256
def _public_output_paths(seed, width, height):
out_dir = os.path.join(os.path.dirname(__file__), "evidence", "live_runs")
os.makedirs(out_dir, exist_ok=True)
stamp = time.strftime("%Y%m%dT%H%M%S")
stem = f"{stamp}_{ROUTE_ID}_{int(width)}x{int(height)}_seed{int(seed)}"
return os.path.join(out_dir, f"{stem}.png"), os.path.join(out_dir, f"{stem}.json")
def _append_request_log(event):
os.makedirs(os.path.dirname(REQUEST_LOG_PATH), exist_ok=True)
payload = {"ts": time.strftime("%Y-%m-%dT%H:%M:%S"), **event}
with open(REQUEST_LOG_PATH, "a") as fp:
fp.write(json.dumps(payload, sort_keys=True) + "\n")
def _load_gallery_manifest():
try:
with open(GALLERY_MANIFEST_PATH) as fp:
data = json.load(fp)
except FileNotFoundError:
data = {}
discovered = [_rel_path(path) for path in _discover_generated_images()]
promoted = list(dict.fromkeys(data.get("promoted", [])))
shown = list(dict.fromkeys(data.get("shown", [])))
hidden = list(dict.fromkeys(data.get("hidden", [])))
hidden = list(dict.fromkeys(hidden + [
rel for rel in discovered
if rel not in promoted and rel not in shown and rel not in hidden
]))
demoted = list(dict.fromkeys(data.get("demoted", [])))
demoted = list(dict.fromkeys(demoted + [
rel for rel in discovered
if rel not in promoted and rel not in demoted
]))
return {
"promoted": promoted,
"shown": shown,
"demoted": demoted,
"hidden": hidden,
}
def _save_gallery_manifest(data):
os.makedirs(os.path.dirname(GALLERY_MANIFEST_PATH), exist_ok=True)
with open(GALLERY_MANIFEST_PATH, "w") as fp:
json.dump(data, fp, indent=2)
fp.write("\n")
def _rel_path(path):
try:
return os.path.relpath(path, os.path.dirname(__file__))
except ValueError:
return path
def _image_caption(path):
rel = _rel_path(path)
receipt = path[:-4] + ".json" if path.endswith(".png") else ""
if receipt and os.path.exists(receipt):
try:
with open(receipt) as fp:
data = json.load(fp)
return f"{os.path.basename(path)} — {data.get('resolution', '?')} / {data.get('steps', '?')} steps / seed {data.get('seed', '?')}"
except Exception:
pass
return rel
def _image_short_caption(path):
receipt = path[:-4] + ".json" if path.endswith(".png") else ""
if receipt and os.path.exists(receipt):
try:
with open(receipt) as fp:
data = json.load(fp)
return f"{data.get('resolution', '?')} / {data.get('steps', '?')} steps / seed {data.get('seed', '?')}"
except Exception:
pass
name = os.path.basename(path)
return name if len(name) <= 34 else name[:31] + "..."
def _discover_generated_images():
seen = set()
items = []
for rel in PUBLIC_GALLERY_FILES:
path = os.path.join(os.path.dirname(__file__), rel)
if os.path.exists(path) and path not in seen:
seen.add(path)
items.append(path)
for pattern in [
os.path.join(os.path.dirname(__file__), "evidence", "live_runs", "*.png"),
os.path.join(os.path.dirname(__file__), "evidence", "matrix", "nf4_*.png"),
os.path.join(os.path.dirname(__file__), "evidence", "comparison", "nf4_*.png"),
os.path.join(os.path.dirname(__file__), "evidence", "nf4_*.png"),
]:
for path in sorted(glob.glob(pattern), reverse=True):
if path not in seen:
seen.add(path)
items.append(path)
return items
def _manifest_path_set(manifest, key):
return {
os.path.normpath(os.path.join(os.path.dirname(__file__), rel))
for rel in manifest.get(key, [])
}
def _visible_generated_images():
manifest = _load_gallery_manifest()
hidden = _manifest_path_set(manifest, "hidden")
return [path for path in _discover_generated_images() if os.path.normpath(path) not in hidden]
def _hidden_generated_images():
manifest = _load_gallery_manifest()
items = []
for rel in manifest.get("hidden", []):
path = os.path.normpath(os.path.join(os.path.dirname(__file__), rel))
if os.path.exists(path):
items.append(path)
return items
def _featured_gallery_paths():
manifest = _load_gallery_manifest()
demoted = _manifest_path_set(manifest, "demoted")
hidden = _manifest_path_set(manifest, "hidden")
promoted = []
for rel in manifest["promoted"]:
path = os.path.normpath(os.path.join(os.path.dirname(__file__), rel))
if os.path.exists(path) and path not in demoted and path not in hidden:
promoted.append(path)
if promoted:
return promoted
return []
def _file_url(path):
return "/gradio_api/file=" + urllib.parse.quote(os.path.abspath(path))
def _gallery_value(paths):
items = []
for path in paths:
if not os.path.exists(path):
continue
caption = html.escape(_image_caption(path))
url = _file_url(path)
items.append(
"<figure style='margin:0;min-width:0;'>"
f"<img src='{url}' alt='{caption}' "
"style='width:100%;aspect-ratio:1/1;object-fit:cover;border-radius:6px;border:1px solid #ddd;' />"
f"<figcaption style='font-size:11px;line-height:1.25;margin-top:4px;color:#555;overflow-wrap:anywhere;'>{caption}</figcaption>"
"</figure>"
)
if not items:
return "<div style='color:#666;font-size:13px;'>No generated images found yet.</div>"
return (
"<div style='display:grid;grid-template-columns:repeat(auto-fill,minmax(120px,1fr));"
"gap:10px;align-items:start;'>"
+ "".join(items)
+ "</div>"
)
def _featured_gallery_value(paths):
if not paths:
return "<div style='color:#666;font-size:13px;'>No promoted images yet.</div>"
return _gallery_value(paths)
def _gallery_bin_value(paths):
return [path for path in paths if os.path.exists(path)]
def _gallery_tile_html(path):
caption = html.escape(_image_short_caption(path))
url = _file_url(path)
return (
"<div style='width:100%;min-width:0;'>"
f"<img src='{url}' alt='{caption}' "
"style='width:100%;aspect-ratio:1/1;object-fit:cover;border-radius:6px;border:1px solid #ddd;' />"
"</div>"
)
def _gallery_dataset_samples(paths):
return [[_gallery_tile_html(path)] for path in paths if os.path.exists(path)]
def _gallery_dataset_labels(paths):
return ["" for path in paths if os.path.exists(path)]
def _gallery_dataset_update(paths):
return gr.update(
samples=_gallery_dataset_samples(paths),
sample_labels=_gallery_dataset_labels(paths),
value=None,
)
def _gallery_slot_paths(paths):
values = [path for path in paths[:GALLERY_SLOT_COUNT] if os.path.exists(path)]
return values + [None] * (GALLERY_SLOT_COUNT - len(values))
def _gallery_slot_html(path, selected=False):
if not path or not os.path.exists(path):
return ""
caption = html.escape(_image_short_caption(path))
url = _file_url(path)
selected_class = " selected" if selected else ""
border = "#ff6b1a" if selected else "#4a4b52"
shadow = "0 0 0 2px #ff6b1a" if selected else "none"
return (
f"<div class='gallery-slot{selected_class}' title='{caption}' "
"style='width:100%;height:112px;display:flex;align-items:center;justify-content:center;"
"padding:6px;border-radius:6px;background:#25262b;cursor:pointer;overflow:hidden;"
f"border:2px solid {border};box-shadow:{shadow};'>"
f"<img src='{url}' alt='{caption}' "
"style='max-width:100%;max-height:100%;object-fit:contain;display:block;' />"
"</div>"
)
def _gallery_slot_updates(paths, selected_rel=None):
return [
gr.update(
value=_gallery_slot_html(path, selected_rel and _rel_path(path) == selected_rel),
visible=bool(path),
)
for path in _gallery_slot_paths(paths)
]
def _selected_path_by_index(paths, index):
try:
index = int(index)
except Exception:
return None
if index < 0 or index >= len(paths):
return None
return _rel_path(paths[index])
def _selected_gallery_path(paths, evt):
index = _selected_gallery_index(evt)
if index is None or index < 0 or index >= len(paths):
return None
return _rel_path(paths[index])
def _selected_gallery_index(evt):
try:
index = evt.index[0] if isinstance(evt.index, (tuple, list)) else evt.index
return int(index)
except Exception:
return None
def _gallery_choices():
manifest = _load_gallery_manifest()
hidden = _manifest_path_set(manifest, "hidden")