-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmake_axis_grid_viewer.py
More file actions
978 lines (871 loc) · 34.1 KB
/
make_axis_grid_viewer.py
File metadata and controls
978 lines (871 loc) · 34.1 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
#!/usr/bin/env python3
# make_axis_grid_viewer.py
# Viewer generator for ComfyUI dimensioned image sets.
# Supports: single image, 1D grid (X or Y axis), 2D grid (X & Y axes).
# Lazy-load only: images are never embedded; relative URLs are used.
#
# Updates in this version:
# - Eliminate redraw flicker: keep grid structure stable and update <img> src in-place where possible.
# - Grid and background fully respect theme colors.
# - Unique axis choices per picklist; disable slider when set to X or Y.
# - Uniform 10px grid spacing; min image size 256px; horizontal scroll when too many X items.
# - Single-image mode auto-fits in viewport without scrolling.
import json
import re
import argparse
from pathlib import Path
import sys
from string import Template
import os
def parse_args():
p = argparse.ArgumentParser(
description="ComfyUI ND image viewer with axis grids (lazy-load only)."
)
p.add_argument(
"--images",
dest="image_dir",
default=None,
help="Path to folder of PNGs (default: <base>/params/images).",
)
p.add_argument(
"--workflow",
dest="workflow",
default=None,
help="Path to ComfyUI workflow JSON (default: <base>/simple_image1.json).",
)
p.add_argument(
"-o",
"--output",
dest="output",
default=None,
help="Path to output HTML (default: <images>/0000_axis_grid_viewer.html).",
)
p.add_argument(
"--base",
dest="basepath",
default=".",
help="Base directory for resolving relative paths (default: current directory).",
)
p.add_argument(
"legacy_args",
nargs="*",
help=argparse.SUPPRESS,
)
return p.parse_args()
def strip_counter(token: str) -> str:
m = re.match(r"^(.*?)(_+\d+_?)$", token)
if m and m.group(1):
return m.group(1)
return token
def parse_dimension_segment(seg: str):
parts = seg.split("-")
if len(parts) != 3:
return None
node_str, prop, val_token = parts
if not node_str.isdigit():
return None
node_id = int(node_str)
if not re.fullmatch(r"[A-Za-z0-9_]+", prop or ""):
return None
val_token = strip_counter(val_token)
dotted = val_token.replace("_", ".")
try:
vnum = float(dotted)
return node_id, prop, vnum, val_token, dotted # key, display
except ValueError:
if not re.fullmatch(r"[A-Za-z0-9_]+", val_token or ""):
return None
return node_id, prop, None, val_token, val_token
def parse_filename(fname: str):
stem = Path(fname).stem
segs = stem.split("--")
dims = []
for seg in segs:
p = parse_dimension_segment(seg)
if p is None:
return None
dims.append(p)
return dims
def load_node_titles(workflow_path: Path):
with open(workflow_path, "r", encoding="utf-8") as f:
wf = json.load(f)
titles = {}
def pick_title(node):
return (node.get("title")
or node.get("label")
or node.get("type")
or "Node %s" % node.get("id", "?"))
if isinstance(wf, dict) and "nodes" in wf:
nodes = wf["nodes"]
it = nodes.values() if isinstance(nodes, dict) else nodes
for node in it:
titles[int(node["id"])] = pick_title(node)
return titles
if isinstance(wf, list):
for node in wf:
titles[int(node["id"])] = pick_title(node)
return titles
raise ValueError("Unrecognized workflow JSON format.")
def relpath_for_html(target: Path, base: Path) -> str:
"""
Return a POSIX-style relative path from base -> target for embedding in HTML/JSON.
"""
rel = os.path.relpath(target, base)
return rel.replace("\\", "/")
def main():
args = parse_args()
basepath = Path(args.basepath).resolve()
if not basepath.is_dir():
sys.exit(f"Base path not found: {basepath}")
legacy = list(args.legacy_args or [])
image_arg = args.image_dir
workflow_arg = args.workflow
output_arg = args.output
if legacy:
if image_arg is None and len(legacy) >= 1:
image_arg = legacy[0]
if workflow_arg is None and len(legacy) >= 2:
workflow_arg = legacy[1]
if output_arg is None and len(legacy) >= 3:
output_arg = legacy[2]
if len(legacy) > 3:
sys.exit("Too many positional arguments supplied.")
def resolve_path(path_value, default_path):
if path_value is None:
return default_path
p = Path(path_value)
if not p.is_absolute():
p = basepath / p
return p
img_dir = resolve_path(image_arg, basepath / "params" / "images").resolve()
wf_path = resolve_path(workflow_arg, basepath / "simple_image1.json").resolve()
out_html = resolve_path(output_arg, img_dir / "0000_axis_grid_viewer.html").resolve()
out_base = out_html.parent
out_base.mkdir(parents=True, exist_ok=True)
if not img_dir.is_dir():
sys.exit(f"Image directory not found: {img_dir}")
if not wf_path.is_file():
sys.exit(f"Workflow JSON not found: {wf_path}")
node_titles = load_node_titles(wf_path)
images = []
dim_signature = None
dim_count = None
dim_info = []
for f in sorted(img_dir.glob("*.png")):
parsed = parse_filename(f.name)
if not parsed:
continue
if dim_count is None:
dim_count = len(parsed)
dim_info = [{'keys': {}, 'all_numeric': True} for _ in range(dim_count)]
dim_signature = [(d[0], d[1]) for d in parsed]
elif len(parsed) != dim_count:
raise ValueError(f"Inconsistent dimension count in {f.name}")
this_sig = [(d[0], d[1]) for d in parsed]
if this_sig != dim_signature:
raise ValueError(f"Dimension signature mismatch in {f.name}")
value_keys = []
for i,(nid,prop,vnum,vkey,vdisp) in enumerate(parsed):
if vnum is None:
dim_info[i]['all_numeric'] = False
dim_info[i]['keys'].setdefault(vkey, {'num': vnum, 'disp': vdisp})
value_keys.append(vkey)
images.append((tuple(value_keys), f.name))
if not images:
sys.exit("No valid images found.")
dim_values = []
for i in range(dim_count):
items = dim_info[i]['keys']
if dim_info[i]['all_numeric']:
order = sorted(items.keys(), key=lambda k: (items[k]['num'], k))
else:
order = sorted(items.keys())
dim_values.append([{'k': k, 'd': items[k]['disp']} for k in order])
poster_lookup = {"|".join(vals): fname for vals, fname in images}
dim_labels = []
max_label = 0
for (nid, prop) in dim_signature:
title = node_titles.get(nid, f"Node {nid}")
label = f"{title}:{nid}:{prop}"
dim_labels.append(label)
max_label = max(max_label, len(label))
label_em = max(8.0, min(60.0, max_label * 0.62))
# Also detect optional MP4s and pair via the same parsed key
videos_by_key = {}
for f in sorted(img_dir.glob("*.mp4")):
parsed = parse_filename(f.name)
if not parsed:
continue
this_sig = [(d[0], d[1]) for d in parsed]
if this_sig != dim_signature:
continue
value_keys = []
for (nid, prop, vnum, vkey, vdisp) in parsed:
value_keys.append(vkey)
videos_by_key["|".join(value_keys)] = f.name
poster_urls = {
fname: relpath_for_html(img_dir / fname, out_base)
for _, fname in images
}
video_urls = {
fname: relpath_for_html(img_dir / fname, out_base)
for fname in videos_by_key.values()
}
meta = dict(
dim_values=dim_values,
poster_lookup=poster_lookup,
video_lookup=videos_by_key,
dim_labels=dim_labels,
label_em=label_em,
lazy=True,
poster_urls=poster_urls,
video_urls=video_urls
)
html = Template("""<!DOCTYPE html>
<html lang=\"en\">
<head>
<meta charset="UTF-8">
<title>ComfyParamVisualizer</title>
<style>
:root { --bg:#fff; --fg:#111; --muted:#666; --border:#cfcfcf; --accent:#7a7afe; --label-font:0.85rem; }
:root[data-theme="dark"]{ --bg:#0d0f13; --fg:#e5e7eb; --muted:#9aa0a6; --border:#2a2f3a; --accent:#7aa2ff; --label-font:0.85rem; }
body{margin:0;font-family:sans-serif;background:var(--bg);color:var(--fg);}
.container{width:auto;max-width:none;margin:12px auto;padding:0 12px;box-sizing:border-box;}
.header{display:flex;justify-content:space-between;align-items:center;margin-bottom:6px;}
h1{margin:0;font-size:1.05rem;font-weight:600;}
.meta{font-size:0.85rem;color:var(--muted);margin-bottom:8px;}
.toggle{border:1px solid var(--border);background:transparent;color:var(--fg);
border-radius:8px;padding:4px 8px;cursor:pointer;}\r\n/* Scale control */\r\n.controls{display:flex;align-items:center;gap:10px;}\r\n.scale-wrap{display:flex;align-items:center;gap:6px;color:var(--muted);font-size:0.9rem;}\r\n.scale-wrap input[type=range]{width:180px;}
#sliders{border:1px solid var(--border);border-radius:8px;padding:8px 10px 2px 10px;
background:rgba(127,127,127,0.03);}
.slider-row{display:grid;grid-template-columns:auto ${label_em}em 1fr 110px;
align-items:center;gap:10px;margin:10px 0;}
.label-col{justify-self:end;text-align:right;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
.slider-wrap{display:flex;flex-direction:column;align-items:center;gap:2px;}
.value-bubble{font-size:0.85rem;color:var(--muted);}
/* Theme-aware form controls */
.axis-wrap{display:flex;gap:6px;align-items:center;justify-content:flex-end;}
.axis-wrap select{
padding:2px 6px;
border:1px solid var(--border);
border-radius:6px;
background:var(--bg);
color:var(--fg);
}
.axis-wrap option{ background:var(--bg); color:var(--fg); }
input[type=checkbox]{
width:16px;height:16px;
accent-color: var(--accent);
background: var(--bg);
}
/* Grid */
#gridWrap{
margin-top:10px;border:1px solid var(--border);border-radius:8px;padding:8px;
overflow-x:auto; overflow-y:auto; width:auto;
box-sizing:border-box;
background:var(--bg); /* respect theme */
}
#grid{
display:grid;
gap:10px;
align-items:start;
justify-items:center; /* center items in their tracks */
justify-content:center; /* center the grid as a whole */
grid-auto-rows:auto;
background:var(--bg); /* respect theme */
}
.repaint{ transform: translateZ(0.0001px); }
.hdr{font-size:var(--label-font);color:var(--muted);text-align:center;padding:2px 4px;
white-space:normal;hyphens:auto;overflow-wrap:anywhere;word-break:normal;
line-height:1.1;background:var(--bg);align-self:center;}
.yhdr{writing-mode:vertical-rl;text-orientation:mixed;align-self:center;justify-self:end;font-size:var(--label-font);
text-align:center;padding:0 2px;hyphens:auto;overflow-wrap:anywhere;word-break:normal;
transform: rotate(180deg); transform-origin: center; max-inline-size: 8ch;}
.cell{display:flex;flex-direction:column;align-items:center;gap:4px;background:var(--bg);}
.cell .vwrap{position:relative; display:inline-block; min-height:10px;}
.cell a{display:block;border:1px solid var(--border);width:auto;}
.cell img{
display:block;
width:auto;
height:auto;
object-fit:contain;
background:#000;
max-width:none;
}
/* Removed play overlay; click or shift-click behavior handled in JS */
.footer{display:none;}
input[type=range]{height:26px;background:transparent;}
input[type=range]::-webkit-slider-runnable-track{height:6px;background:rgba(127,127,127,0.35);border-radius:6px;}
input[type=range]::-webkit-slider-thumb{
-webkit-appearance:none;appearance:none;width:20px;height:20px;border-radius:50%;
background:var(--accent);border:1px solid rgba(0,0,0,0.25);margin-top:-7px;
}
input[type=range]:hover::-webkit-slider-thumb{width:22px;height:22px;margin-top:-8px;}
input[type=range]::-moz-range-track{height:6px;background:rgba(127,127,127,0.35);border-radius:6px;}
input[type=range]::-moz-range-thumb{
width:20px;height:20px;border-radius:50%;background:var(--accent);
border:1px solid rgba(0,0,0,0.25);
}</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>ComfyParamVisualizer</h1>
<div class="controls">
<button id="themeToggle" class="toggle" type="button">Theme</button>
<button id="redrawBtn" class="toggle" type="button">Redraw</button>
<div class="scale-wrap">
<label for="scaleSlider">Size:</label>
<input id="scaleSlider" type="range" min="1" max="200" value="100" />
<span id="scaleValue">100%</span>
</div>
</div>
</div>
<div class="meta">
</div>
<div id="sliders"></div>
<div id="gridWrap">
<div id="grid"></div>
<div class="footer" id="gridHint"></div>
</div>
</div>
<script>
(function(){
const saved=localStorage.getItem("viewer_theme");
if(saved==="dark"||( !saved && window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches)){
document.documentElement.setAttribute("data-theme","dark");
}
document.getElementById("themeToggle").onclick=function(){
const cur=document.documentElement.getAttribute("data-theme");
if(cur==="dark"){document.documentElement.removeAttribute("data-theme");localStorage.setItem("viewer_theme","light");}
else{document.documentElement.setAttribute("data-theme","dark");localStorage.setItem("viewer_theme","dark");}
};
})();
const data=${meta_json};
const dims=data.dim_values.length;
const curIdx=new Array(dims).fill(0);
const locked=new Array(dims).fill(false);
const axis=new Array(dims).fill("none"); // "none" | "x" | "y"
const slidersRoot=document.getElementById("sliders");
const gridWrap=document.getElementById("gridWrap");
const gridRoot=document.getElementById("grid");
const gridHint=document.getElementById("gridHint");
const sliderEls=[];
const lockEls=[];
const axisSelEls=[];
// Track current grid structure to avoid teardown/rebuild (reduces flicker)
let curStruct = { mode:"", xLen:0, yLen:0 };
let imageCells = []; // Array of <img> elements in row-major order (no headers)
// ---- Lazy loader via IntersectionObserver (robust for large grids) ----
let io = null;
const PRELOAD_MARGIN = 600; // px ahead of viewport
function setupLazyLoader(){
if(io) return;
io = new IntersectionObserver((entries)=>{
for(const e of entries){
const wrap = e.target;
const im = wrap.querySelector('img');
if(!im) continue;
// Treat as eligible if intersecting or within preload margin relative to gridWrap
const r = e.boundingClientRect;
const rootR = e.rootBounds || gridWrap.getBoundingClientRect();
const nearView = (r.top < rootR.bottom + PRELOAD_MARGIN) && (r.bottom > rootR.top - PRELOAD_MARGIN);
if((e.isIntersecting || nearView) && im.dataset && im.dataset.src && !im.getAttribute('src')){
im.decoding = "async";
im.src = im.dataset.src;
}
// Stop observing once this cycle has an active src and it's loaded
if(im.getAttribute('src') && im.complete && im.naturalWidth>0){ io.unobserve(wrap); }
}
}, { root:gridWrap, rootMargin: PRELOAD_MARGIN+"px", threshold: 0 });
}
function observeForLoad(im){
setupLazyLoader();
const wrap = getWrapper(im);
if(wrap){ io.observe(wrap); }
}
function isNearViewport(el){
if(!el) return false;
const r = el.getBoundingClientRect();
const R = gridWrap.getBoundingClientRect();
const m = PRELOAD_MARGIN;
return (r.top < R.bottom + m) &&
(r.bottom > R.top - m) &&
(r.left < R.right + m) &&
(r.right > R.left - m);
}
function getWrapper(im){
// Observe the outer cell for consistent geometry regardless of image size
// structure: .cell > .vwrap > a > img
return im?.parentElement?.parentElement?.parentElement || null;
}
function kickVisibleLoads(){
// Ensure any visible-but-unloaded images get their src set now
for(const im of imageCells){
if(!im) continue;
if(im.getAttribute('src')) continue;
const ds = im.dataset?.src;
if(!ds) continue;
const wrap = getWrapper(im);
if(isNearViewport(wrap)){
// Small async to let layout settle before setting src
requestAnimationFrame(()=>{ im.decoding = 'async'; im.src = ds; });
}
}
}
function forceRedraw(){
const xDim = axis.indexOf('x');
const hasX = xDim !== -1;
const xLen = hasX ? data.dim_values[xDim].length : 1;
for(const im of imageCells){
if(!im) continue;
const wrap = getWrapper(im);
const visible = isNearViewport(wrap);
const isBlankLoaded = !!im.getAttribute('src') && im.complete && (im.naturalWidth===0 || im.naturalHeight===0);
const needs = (!im.getAttribute('src') && visible) || isBlankLoaded;
if(needs){
const url = im.dataset?.src || im.getAttribute('src');
if(!url) { observeForLoad(im); continue; }
// reload by clearing src then restoring next frame
im.removeAttribute('src');
im.dataset.loaded='';
im.onload = () => {
if(!natW || !natH){ natW = im.naturalWidth || im.width; natH = im.naturalHeight || im.height; }
if(hasX && scaleMode==='auto'){ computeAutoScale(xLen); }
applyScaleToImages();
};
requestAnimationFrame(()=>{ im.decoding='async'; im.src = url; });
} else if(!im.getAttribute('src') && im.dataset?.src) {
observeForLoad(im);
}
}
kickVisibleLoads();
// Force a repaint of the grid container to resolve rare paint stalls
function forceRepaint(el){ if(!el) return; el.classList.add('repaint'); el.getBoundingClientRect(); requestAnimationFrame(()=>{ el.classList.remove('repaint'); }); }
forceRepaint(gridRoot);
forceRepaint(gridWrap);
}
function applyGridColumnWidths(hasX, hasY, xLen){
// Make the first column size to its content (y labels), independent of image scale
if(hasX && hasY){ gridRoot.style.gridTemplateColumns = "max-content " + Array(xLen).fill("auto").join(" "); }
else if(hasX){ gridRoot.style.gridTemplateColumns = "max-content " + Array(xLen).fill("auto").join(" "); }
else if(hasY){ gridRoot.style.gridTemplateColumns = "max-content auto"; }
else { gridRoot.style.gridTemplateColumns = "auto"; }
}// ---- Global scaling state ----
let natW = 0, natH = 0; // natural dimensions (assumed uniform across images)
let autoScale = 1; // computed to fit X columns within viewport width (<=1)
let userScalePct = 100; // 1..200
let scaleMode = 'auto'; // 'auto' or 'user'
const gapPx = 10; // matches CSS grid gap
const scaleSlider = document.getElementById('scaleSlider');
const scaleValue = document.getElementById('scaleValue');
const redrawBtn = document.getElementById('redrawBtn');
scaleSlider.addEventListener('input', () => {
userScalePct = Math.max(1, Math.min(200, parseInt(scaleSlider.value || '100', 10)));
scaleMode = 'user';
scaleValue.textContent = userScalePct + '%';
applyScaleToImages();
// Keep Y header column width fixed when scaling
const xDim = axis.indexOf('x');
const yDim = axis.indexOf('y');
const hasX = xDim !== -1;
if(hasX){ applyGridColumnWidths(true, (yDim!==-1), data.dim_values[xDim].length); }
});
// Manual redraw button: reload visible or blank images immediately
redrawBtn.addEventListener('click', () => { forceRedraw(); });
function effectiveScale(){
return (scaleMode === 'auto') ? autoScale : (userScalePct/100);
}
function computeAutoScale(xCount){
// Compute based on available width inside gridWrap (no horizontal scroll), cap at 1.0
const wrap = document.getElementById('gridWrap');
const wrapW = Math.max(1, wrap.clientWidth - 2*8); // minus padding approx
// Estimate side header width (two autos in XY/X modes)
let sideHdr = 0;
const anyHdr = wrap.querySelector('.yhdr');
if(anyHdr){ sideHdr = Math.ceil(anyHdr.getBoundingClientRect().width); }
// Available for image columns (subtract left and right headers if present)
const colArea = Math.max(1, wrapW - sideHdr*2 - gapPx*(xCount+1));
if (natW <= 0) { autoScale = 1; return; }
const needed = xCount * natW;
// Apply a small safety margin (2%) to avoid horizontal scrollbar
const s = Math.max(0.01, Math.min(1, (colArea / needed) * 0.98));
autoScale = s;
if (scaleMode === 'auto'){
const pct = Math.max(1, Math.round(s*100));
scaleSlider.value = String(pct);
scaleValue.textContent = pct + '%';
}
}
function applyScaleToImages(){
const s = effectiveScale();
if (natW>0){
const w = Math.max(1, Math.floor(natW * s));
for(const im of imageCells){ im.style.width = w + 'px'; }
syncVideoSizes();
}
// Adapt label font size to scale: 0.70rem..1.0rem range
const minRem = 0.70, maxRem = 1.00;
const rem = Math.max(minRem, Math.min(maxRem, 0.70 + 0.30 * s));
document.documentElement.style.setProperty('--label-font', rem.toFixed(3) + 'rem');
}
function sliderWidth(n){return Math.min(680,Math.max(140,140+(n-2)*36));}
function buildUI(){
for(let i=0;i<dims;i++){
const row=document.createElement("div");row.className="slider-row";
const lock=document.createElement("input");lock.type="checkbox";
lock.onchange=()=>{locked[i]=lock.checked;updateDisabledState(i);};
row.appendChild(lock);
lockEls.push(lock);
const label=document.createElement("div");label.className="label-col";label.textContent=data.dim_labels[i];
row.appendChild(label);
const wrap=document.createElement("div");wrap.className="slider-wrap";
const bubble=document.createElement("div");bubble.className="value-bubble";bubble.textContent=data.dim_values[i][0].d;
const slider=document.createElement("input");slider.type="range";
slider.min=0;slider.max=data.dim_values[i].length-1;slider.step=1;slider.value=0;
slider.style.width=sliderWidth(data.dim_values[i].length)+"px";
slider.oninput=()=>{curIdx[i]=+slider.value;bubble.textContent=data.dim_values[i][curIdx[i]].d;renderGrid();};
wrap.appendChild(bubble);wrap.appendChild(slider);
row.appendChild(wrap);
sliderEls.push(slider);
const axisWrap=document.createElement("div");axisWrap.className="axis-wrap";
const axisSel=document.createElement("select");
["none","x","y"].forEach(v=>axisSel.add(new Option(v,v)));
axisSel.value="none";
axisSel.onchange=()=>{setAxis(i, axisSel.value);};
axisWrap.appendChild(axisSel);
row.appendChild(axisWrap);
axisSelEls.push(axisSel);
slidersRoot.appendChild(row);
updateDisabledState(i);
}
syncAxisOptions();
}
function updateDisabledState(i){
const shouldDisable = locked[i] || axis[i] !== "none";
sliderEls[i].disabled = shouldDisable;
}
function syncAxisOptions(){
const xOwner = axis.indexOf("x");
const yOwner = axis.indexOf("y");
for(let j=0;j<axisSelEls.length;j++){
const sel = axisSelEls[j];
for(let k=0;k<sel.options.length;k++){
const opt = sel.options[k];
if(opt.value==="x"){
opt.disabled = (xOwner !== -1 && j !== xOwner);
} else if(opt.value==="y"){
opt.disabled = (yOwner !== -1 && j !== yOwner);
} else {
opt.disabled = false;
}
}
}
}
function setAxis(i, v){
axis[i]=v;
updateDisabledState(i);
syncAxisOptions();
// Axes change may alter structure; rebuild if needed
curStruct.mode=""; // force structure recompute
renderGrid();
}
function keyFrom(idxOverride){
const arr=[];
for(let d=0; d<dims; d++){
const i = (idxOverride && Object.prototype.hasOwnProperty.call(idxOverride, d)) ? idxOverride[d] : curIdx[d];
arr.push(data.dim_values[d][i].k);
}
return arr.join("|");
}
function fnameFor(idxOverride){
const k = keyFrom(idxOverride);
return data.poster_lookup[k];
}
function ensureStructure(hasX, hasY, xLen, yLen){
let desiredMode = "single";
if(hasX && hasY) desiredMode="xy";
else if(hasX) desiredMode="x";
else if(hasY) desiredMode="y";
if(curStruct.mode===desiredMode && curStruct.xLen===xLen && curStruct.yLen===yLen){
return; // no structural change; reuse DOM
}
// rebuild structure
gridRoot.innerHTML="";
imageCells = [];
curStruct = { mode:desiredMode, xLen:xLen, yLen:yLen };
if(desiredMode==="xy"){
gridRoot.style.gridTemplateColumns = "auto " + Array(xLen).fill("auto").join(" ");
const makeHdr=(txt, cls)=>{ const d=document.createElement("div"); d.className="hdr "+(cls||""); d.textContent=txt; return d; };
gridRoot.appendChild(makeHdr("", "yhdr"));
for(let cx=0; cx<xLen; cx++){ gridRoot.appendChild(makeHdr(data.dim_values[axis.indexOf("x")][cx].d, "")); }
for(let ry=0; ry<yLen; ry++){
gridRoot.appendChild(makeHdr(data.dim_values[axis.indexOf("y")][ry].d, "yhdr"));
for(let cx=0; cx<xLen; cx++){
const img = makeImgCell();
imageCells.push(img);
gridRoot.appendChild(img.parentElement.parentElement);
}
}
} else if(desiredMode==="x"){
gridRoot.style.gridTemplateColumns = "auto " + Array(xLen).fill("auto").join(" ");
const makeHdr=(txt, cls)=>{ const d=document.createElement("div"); d.className="hdr "+(cls||""); d.textContent=txt; return d; };
gridRoot.appendChild(makeHdr("", "yhdr"));
for(let cx=0; cx<xLen; cx++){ gridRoot.appendChild(makeHdr(data.dim_values[axis.indexOf("x")][cx].d, "")); }
// Add an empty Y-header cell for the image row so images align under X headers
gridRoot.appendChild(makeHdr("", "yhdr"));
for(let cx=0; cx<xLen; cx++){
const img = makeImgCell();
imageCells.push(img);
gridRoot.appendChild(img.parentElement.parentElement);
}
} else if(desiredMode==="y"){
gridRoot.style.gridTemplateColumns = "auto auto";
const makeHdr=(txt, cls)=>{ const d=document.createElement("div"); d.className="hdr "+(cls||""); d.textContent=txt; return d; };
for(let ry=0; ry<yLen; ry++){
gridRoot.appendChild(makeHdr(data.dim_values[axis.indexOf("y")][ry].d, "yhdr"));
const img = makeImgCell();
imageCells.push(img);
gridRoot.appendChild(img.parentElement.parentElement);
}
} else {
gridRoot.style.gridTemplateColumns = "auto";
const img = makeImgCell();
imageCells.push(img);
gridRoot.appendChild(img.parentElement.parentElement);
}
}
function makeImgCell(){
const cell=document.createElement("div");cell.className="cell";
const vwrap=document.createElement("div");vwrap.className="vwrap";
const a=document.createElement("a");a.target="_blank";a.rel="noopener noreferrer";
const im=new Image();
// We'll set src with an IntersectionObserver when near viewport
im.loading="lazy"; im.alt="";
a.appendChild(im);
vwrap.appendChild(a);
cell.appendChild(vwrap);
// Click behavior: normal click plays inline; Shift+click opens video in new tab
im.addEventListener('click', (e)=>{
if(im.dataset.hasvid==='1'){
e.preventDefault();
const k = im.dataset.key;
const vf = data.video_lookup[k];
const vurl = vf ? data.video_urls[vf] : null;
if(!vurl) return;
if(e.shiftKey){
window.open(vurl, '_blank', 'noopener,noreferrer');
} else {
launchVideoInCell(im);
}
}
});
// Observe for lazy loading
observeForLoad(im);
// return image element so caller can update src without rebuilding
return im;
}
function desiredFilenames(hasX, hasY, xDim, yDim, xLen, yLen){
const list=[];
if(hasX && hasY){
for(let ry=0; ry<yLen; ry++){
for(let cx=0; cx<xLen; cx++){
const override={}; override[xDim]=cx; override[yDim]=ry;
list.push(fnameFor(override));
}
}
} else if(hasX){
for(let cx=0; cx<xLen; cx++){
const override={}; override[xDim]=cx;
list.push(fnameFor(override));
}
} else if(hasY){
for(let ry=0; ry<yLen; ry++){
const override={}; override[yDim]=ry;
list.push(fnameFor(override));
}
} else {
list.push(fnameFor(null));
}
return list;
}
function renderGrid(){
const xDim = axis.indexOf("x");
const yDim = axis.indexOf("y");
const hasX = xDim !== -1;
const hasY = yDim !== -1;
const xLen = hasX ? data.dim_values[xDim].length : 1;
const yLen = hasY ? data.dim_values[yDim].length : 1;
ensureStructure(hasX, hasY, xLen, yLen);
applyGridColumnWidths(hasX, hasY, xLen);
if(hasX && natW>0){ computeAutoScale(xLen); applyScaleToImages(); }
// Update images in-place (no grid teardown -> minimal flicker)
const names = desiredFilenames(hasX, hasY, xDim, yDim, xLen, yLen);
for(let i=0;i<imageCells.length;i++){
const im = imageCells[i];
const fname = names[i];
const a = im.parentElement;
const vwrap = a.parentElement;
const overlay = null;
if(!fname){
// missing: blank this cell
if(im.dataset.loaded!=="missing"){
im.removeAttribute("src");
im.dataset.loaded="missing";
a.removeAttribute("href");
}
continue;
}
// Stop video if key changes or on update
stopVideoForCell(im, true);
const k = keyForCellIndex(i, hasX, hasY, xDim, yDim);
im.dataset.key = k;
const hasVid = !!data.video_lookup[k];
im.dataset.hasvid = hasVid ? '1' : '';
// overlay removed
const url = data.poster_urls[fname];
if(a.href !== url){
a.href = url;
}
// Queue load via IntersectionObserver. Avoid immediate src assignment for huge grids.
if(im.dataset.src !== url){ im.dataset.src = url; }
// if src differs from new url, clear it and allow IO to load when near
if(im.getAttribute('src') !== url){
const wrapEl = getWrapper(im);
if(isNearViewport(wrapEl)){
// If already near viewport, load immediately for responsiveness
im.decoding = "async";
im.onload = () => { if (!natW || !natH){ natW = im.naturalWidth || im.width; natH = im.naturalHeight || im.height; } if (hasX && scaleMode==='auto'){ computeAutoScale(xLen); } applyScaleToImages(); im.dataset.loaded='ok'; };
im.src = url;
} else {
im.removeAttribute('src');
im.onload = () => { if (!natW || !natH){ natW = im.naturalWidth || im.width; natH = im.naturalHeight || im.height; } if (hasX && scaleMode==='auto'){ computeAutoScale(xLen); } applyScaleToImages(); im.dataset.loaded='ok'; };
// Re-observe every time we defer loading (may have been unobserved before)
observeForLoad(im);
}
}
}
// Single-image fit
if(!hasX && !hasY){
fitSingleImage();
window.addEventListener("resize", fitSingleImage);
}
// After structural/URL updates, make sure visible cells actually load
requestAnimationFrame(()=>setTimeout(kickVisibleLoads, 0));
}
function fitSingleImage(){
const img = gridRoot.querySelector(".cell img");
if(!img) return;
const rect = gridWrap.getBoundingClientRect();
const availableH = Math.max(100, window.innerHeight - rect.top - 24);
const nw = img.naturalWidth || img.width;
const nh = img.naturalHeight || img.height;
const s = Math.min(1, availableH/nh);
img.style.width = Math.floor(nw*s) + "px";
img.style.maxHeight = availableH + "px";
// keep video (if any) in sync
const vwrap = img.parentElement?.parentElement;
const vid = vwrap ? vwrap.querySelector('video') : null;
if(vid){
const rect2 = img.getBoundingClientRect();
vid.style.width = Math.max(1, Math.floor(rect2.width)) + 'px';
vid.style.height = Math.max(1, Math.floor(rect2.height)) + 'px';
}
}
// Recompute scales and keep Y header column fixed on resize in grid modes
window.addEventListener("resize", () => {
const xDim = axis.indexOf("x");
const yDim = axis.indexOf("y");
const hasX = xDim !== -1;
const hasY = yDim !== -1;
if(hasX && natW>0){
computeAutoScale(data.dim_values[xDim].length);
applyScaleToImages();
applyGridColumnWidths(hasX, hasY, data.dim_values[xDim].length);
}
kickVisibleLoads();
});
// Also kick loads while scrolling inside the grid container
gridWrap.addEventListener('scroll', () => { kickVisibleLoads(); });
buildUI();
renderGrid();
// Helpers for video per-cell
function keyForCellIndex(idx, hasX, hasY, xDim, yDim){
if(hasX && hasY){
const xLen = data.dim_values[xDim].length;
const cx = idx % xLen;
const ry = Math.floor(idx / xLen);
const override={}; override[xDim]=cx; override[yDim]=ry;
return keyFrom(override);
} else if(hasX){
const override={}; override[xDim]=idx; return keyFrom(override);
} else if(hasY){
const override={}; override[yDim]=idx; return keyFrom(override);
} else {
return keyFrom(null);
}
}
function launchVideoInCell(im){
const a = im.parentElement;
const vwrap = a.parentElement;
if(vwrap.querySelector('video')) return;
const k = im.dataset.key;
const vf = data.video_lookup[k];
if(!vf) return;
const vurl = data.video_urls[vf];
const pf = data.poster_lookup[k];
const purl = pf ? data.poster_urls[pf] : '';
const vid = document.createElement('video');
vid.controls = true; vid.autoplay = true; vid.playsInline = true; vid.poster = purl;
vid.src = vurl; vid.style.display='block'; vid.style.background='#000';
const rect = im.getBoundingClientRect();
vid.style.width = Math.max(1, Math.floor(rect.width)) + 'px';
vid.style.height = Math.max(1, Math.floor(rect.height)) + 'px';
im.style.display='none';
vwrap.insertBefore(vid, a);
// Update link to point to video while playing
a.href = vurl;
const onEnd = ()=>{ stopVideoForCell(im, true); };
vid.addEventListener('ended', onEnd);
}
function stopVideoForCell(im, restoreLink){
const a = im.parentElement;
const vwrap = a.parentElement;
const vid = vwrap.querySelector('video');
if(!vid) return;
try{ vid.pause(); }catch(e){}
try{ vid.removeAttribute('src'); vid.load?.(); }catch(e){}
try{ vid.remove(); }catch(e){}
im.style.display='block';
if(restoreLink){
const pf = im.dataset.key ? data.poster_lookup[im.dataset.key] : null;
if(pf){ a.href = data.poster_urls[pf]; }
}
}
// Keep video width in sync when scaling
function syncVideoSizes(){
const cells = gridRoot.querySelectorAll('.cell');
for(const cell of cells){
const vwrap = cell.querySelector('.vwrap');
if(!vwrap) continue;
const vid = vwrap.querySelector('video');
const im = vwrap.querySelector('img');
if(vid && im){
const rect = im.getBoundingClientRect();
vid.style.width = Math.max(1, Math.floor(rect.width)) + 'px';
vid.style.height = Math.max(1, Math.floor(rect.height)) + 'px';
}
}
}
</script>
</body>
</html>
""").substitute(
label_em=f"{label_em:.1f}",
meta_json=json.dumps(meta)
)
out_html.write_text(html, encoding="utf-8")
print("Generated HTML:", out_html)
print("Note: Viewer uses lazy-load only. Keep the PNGs in place so the HTML can load them.")
if __name__ == "__main__":
main()