File size: 45,754 Bytes
a1c201e
 
 
 
 
 
 
 
 
 
 
 
96c23a5
9ffebcc
a1c201e
07c2379
 
 
96c23a5
9ffebcc
 
a1c201e
96c23a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1c201e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07c2379
 
 
 
 
 
 
 
a1c201e
 
 
 
07c2379
 
a1c201e
 
07c2379
 
 
 
 
 
 
 
 
 
 
 
 
 
b51a96f
 
 
 
 
 
 
07c2379
b51a96f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07c2379
 
96c23a5
a1c201e
 
 
 
 
 
9ffebcc
07c2379
a1c201e
07c2379
 
 
 
a1c201e
07c2379
b51a96f
 
 
 
07c2379
 
96c23a5
 
 
07c2379
 
 
 
 
 
 
 
 
 
 
a1c201e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ffebcc
 
a1c201e
 
9ffebcc
 
 
 
 
 
 
a1c201e
9ffebcc
 
 
a1c201e
 
9ffebcc
 
 
 
 
 
 
 
 
 
 
 
07c2379
 
 
 
 
 
 
 
 
 
 
 
 
9ffebcc
 
07c2379
96c23a5
a1c201e
 
 
 
96c23a5
a1c201e
 
 
07c2379
96c23a5
a1c201e
9ffebcc
a1c201e
 
9ffebcc
 
 
 
 
a1c201e
 
 
 
 
 
 
 
07c2379
 
96c23a5
a1c201e
07c2379
 
a1c201e
 
 
 
 
96c23a5
 
a1c201e
07c2379
a1c201e
 
 
 
 
 
 
 
 
 
 
 
07c2379
a1c201e
 
 
9ffebcc
 
 
96c23a5
a1c201e
 
 
9ffebcc
 
 
 
 
 
 
 
 
 
a1c201e
 
9ffebcc
 
a1c201e
 
 
df8a79c
9ffebcc
96c23a5
07c2379
a1c201e
9ffebcc
 
a1c201e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07c2379
a1c201e
 
 
 
 
 
 
 
9ffebcc
a1c201e
 
 
 
 
 
07c2379
a1c201e
07c2379
 
df0112c
 
 
32ceebc
07c2379
 
 
a1c201e
9ffebcc
a1c201e
07c2379
a1c201e
07c2379
 
 
 
9ffebcc
 
a1c201e
96c23a5
07c2379
96c23a5
 
07c2379
a1c201e
9ffebcc
 
a1c201e
 
 
 
07c2379
a1c201e
 
96c23a5
a1c201e
07c2379
a1c201e
 
 
 
 
 
 
 
07c2379
a1c201e
 
07c2379
 
32ceebc
a1c201e
 
 
07c2379
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1c201e
 
 
 
9ffebcc
 
a1c201e
9ffebcc
07c2379
9ffebcc
a1c201e
9ffebcc
a1c201e
 
96c23a5
a1c201e
9ffebcc
a1c201e
9ffebcc
a1c201e
9ffebcc
a1c201e
9ffebcc
07c2379
a1c201e
9ffebcc
 
a1c201e
 
9ffebcc
 
 
a1c201e
96c23a5
 
 
 
 
 
 
 
 
 
 
 
 
a1c201e
 
07c2379
a1c201e
 
 
96c23a5
 
b1f2278
a1c201e
9ffebcc
96c23a5
9ffebcc
a1c201e
 
9ffebcc
 
 
b1f2278
 
 
 
 
 
 
 
 
 
 
 
 
96c23a5
b1f2278
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ffebcc
 
 
07c2379
9ffebcc
07c2379
9ffebcc
 
 
a1c201e
 
 
 
 
 
 
9ffebcc
b1f2278
9ffebcc
 
07c2379
96c23a5
 
 
 
 
 
 
a1c201e
 
07c2379
a1c201e
b1f2278
a1c201e
b1f2278
a1c201e
 
07c2379
a1c201e
 
 
 
 
 
 
07c2379
a1c201e
 
 
 
 
 
 
 
 
 
 
07c2379
a1c201e
 
 
 
 
 
 
 
 
 
 
 
 
 
07c2379
96c23a5
 
07c2379
a1c201e
07c2379
a1c201e
07c2379
 
96c23a5
 
 
 
a1c201e
 
 
 
 
 
 
 
 
07c2379
a1c201e
 
 
 
 
b1f2278
 
 
a1c201e
 
 
b1f2278
a1c201e
 
b1f2278
a1c201e
 
b1f2278
 
 
 
 
 
a1c201e
 
 
 
b1f2278
a1c201e
b1f2278
 
 
a1c201e
 
b1f2278
 
a1c201e
 
 
 
 
 
 
 
 
95e1d19
 
 
 
 
 
 
 
 
 
 
 
07c2379
95e1d19
07c2379
95e1d19
07c2379
 
a1c201e
95e1d19
 
96c23a5
 
 
 
 
 
 
95e1d19
a1c201e
 
07c2379
 
 
 
 
b51a96f
07c2379
 
 
96c23a5
b51a96f
07c2379
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ffebcc
 
 
 
 
07c2379
 
9ffebcc
 
 
07c2379
 
9ffebcc
07c2379
9ffebcc
 
 
07c2379
9ffebcc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07c2379
9ffebcc
 
 
 
 
 
 
 
 
 
07c2379
9ffebcc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1c201e
 
 
 
 
 
 
 
 
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
"use strict";

const $ = (s) => document.querySelector(s);
const $$ = (s) => [...document.querySelectorAll(s)];
const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
const gb = (b) => (b >= 2 ** 30 ? `${(b / 2 ** 30).toFixed(1)} GB` : `${Math.max(1, Math.round(b / 2 ** 20))} MB`);
const store = {
  get(k, d) { try { return JSON.parse(localStorage.getItem(k)) ?? d; } catch { return d; } },
  set(k, v) { try { localStorage.setItem(k, JSON.stringify(v)); } catch {} },
};

const S = {
  cfg: null, cid: null, collections: [], rows: [], byId: new Map(), groups: new Map(), order: [], lic: new Map(),
  basket: new Set(), filtered: [], lastClicked: null, user: null, cats: new Set(), allLatents: false,
};
// file URL for a manifest path template like "objects/{id}/tile.webp"
const asset = (tmpl, id) => S.cfg.asset_base + tmpl.replace("{id}", encodeURIComponent(id));
const tileUrl = (id) => asset(S.cfg.paths.tile, id);
const variantWord = () => (S.cid === "gso" ? "colors" : S.cid === "thingi10k" ? "parts" : "versions");
const plural = (n, one, many = one + "s") => `${n.toLocaleString()} ${n === 1 ? one : many}`;
const pretty = (name) => name.replace(/_/g, " ");

// ----------------------------------------------------------------- licenses
// Every row has a license id; /api/catalog explains each one (name, link, terms). A library is
// "mixed" when its objects don't all share one license (Thingi10K: each author chose their own).
const licOf = (r) => S.lic.get(r.license) || { id: r.license, name: r.license || S.cfg.license, url: S.cfg.license_url, terms: ["custom"] };
const mixed = () => S.cfg.licenses.length > 1;
const restrictive = (l) => l.terms.some((t) => S.cfg.restrictive_terms.includes(t));
const termChips = (l) => (l.terms.length ? l.terms : ["free"]).map((t) => {
  const [label, what] = S.cfg.license_terms[t] || ["Free to use", "No conditions: use it for anything, no credit needed."];
  return `<span class="term t-${t}" title="${esc(what)}">${esc(label)}</span>`;
}).join("");
const licLink = (l) => `<a href="${esc(l.url)}" target="_blank" rel="noopener">${esc(l.name)}</a>`;
// licenses of a set of rows, most common first: [{...license, count}]
function licensesOf(rows) {
  const n = new Map();
  rows.forEach((r) => n.set(r.license, (n.get(r.license) || 0) + 1));
  return [...n].sort((a, b) => b[1] - a[1]).map(([id, count]) => ({ ...licOf({ license: id }), count }));
}
const termsOf = (lics) => Object.keys(S.cfg.license_terms).filter((t) => lics.some((l) => l.terms.includes(t)));

// shown as soon as a library loads: what its license asks, or how the licenses split
function renderLicBar() {
  const lics = S.cfg.licenses;
  if (!mixed()) {
    const l = lics[0];
    const asks = l.terms.map((t) => S.cfg.license_terms[t][1]).join(" ") || "Use it for anything; no credit needed.";
    $("#lic-bar").innerHTML = `<b>License</b> ${licLink(l)} ${termChips(l)} <span class="hint">${esc(asks)}</span>`;
  } else {
    $("#lic-bar").innerHTML = `<b>Licenses vary per object</b> <span class="lic-chips">${lics.map((l) =>
      `<button class="chip lic${restrictive(l) ? " strict" : ""}" data-lic="${esc(l.id)}" aria-pressed="${$("#lic-filter").value === l.id}" title="${esc(l.terms.map((t) => S.cfg.license_terms[t][0]).join(", ") || "Free to use")}">${esc(l.name)} <span>${l.count.toLocaleString()}</span></button>`).join("")}</span>
      <span class="hint">${esc(S.cfg.license_note)} Each object shows its own; your dataset's step 1 sums them up.</span>`;
    $$("#lic-bar .chip").forEach((b) => b.addEventListener("click", () => {
      $("#lic-filter").value = $("#lic-filter").value === b.dataset.lic ? "" : b.dataset.lic;
      apply();
    }));
  }
}

// ----------------------------------------------------------------- share links
// A subset is a bitset over the catalog sorted by object_id: ~180 chars for all 1,030 objects.
function encodeSubset() {
  const bytes = new Uint8Array(Math.ceil(S.order.length / 8));
  S.order.forEach((id, i) => { if (S.basket.has(id)) bytes[i >> 3] |= 1 << (i & 7); });
  let s = ""; bytes.forEach((b) => (s += String.fromCharCode(b)));
  return "s1." + btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
function decodeSubset(code) {
  if (!code.startsWith("s1.")) return null;
  const bin = atob(code.slice(3).replace(/-/g, "+").replace(/_/g, "/"));
  const ids = [];
  S.order.forEach((id, i) => { if ((bin.charCodeAt(i >> 3) || 0) & (1 << (i & 7))) ids.push(id); });
  return ids;
}
function shareUrl() {
  const base = S.cfg.app_url || location.origin + location.pathname;
  return `${base}#${S.cid}:${encodeSubset()}`;
}
// "#<collection>:s1.<bits>"; links made before collections existed are "#s1.<bits>" over GSO
function parseHash() {
  const h = location.hash.slice(1);
  if (!h) return {};
  const [cid, code] = h.includes(":") ? h.split(":", 2) : ["gso", h];
  return { cid, code };
}

// ----------------------------------------------------------------- boot
async function boot() {
  const [cols, me] = await Promise.all([
    fetch("/api/collections").then((r) => r.json()),
    fetch("/api/me").then((r) => r.json()).catch(() => ({ user: null })),
  ]);
  S.collections = cols.collections;
  S.user = me.user ? me : null;
  const known = (c) => S.collections.some((x) => x.id === c);
  const hash = parseHash();
  const cid = [hash.cid, store.get("collection", null), cols.default].find(known);
  bindFilters();
  bindBasket();
  bindTour();
  bindLibraries();
  renderAuth();
  await loadCollection(cid, hash.cid === cid ? hash.code : null);
  if (!store.get("tour_done", false)) setTimeout(() => startTour(0), 400);
}

// "Ready to train" status of a whole library, from /api/collections
function latentsStatus(c) {
  if (!c.latents) return { cls: "", text: "No TRELLIS.2 latents yet", title: "Not preprocessed for TRELLIS.2: training on these objects runs preprocessing first" };
  if (c.latents >= c.count) return { cls: " lat", text: "TRELLIS.2 latents: all objects", title: "Every object is already preprocessed for TRELLIS.2" };
  return { cls: " lat", text: `TRELLIS.2 latents: ${c.latents.toLocaleString()} of ${c.count.toLocaleString()}`, title: "Some objects are already preprocessed for TRELLIS.2" };
}

async function loadCollection(cid, code = null) {
  const summary = S.collections.find((c) => c.id === cid);
  const load = (S.loadSeq = (S.loadSeq || 0) + 1);
  $("#loading-msg").textContent = `Loading ${summary ? summary.title : "library"}…`;
  $("#loading").hidden = false;
  $(".browse").classList.add("busy");
  $(".browse").setAttribute("aria-busy", "true");
  let cfg;
  try {
    const r = await fetch(`/api/catalog?c=${encodeURIComponent(cid)}`);
    if (!r.ok) throw new Error(r.status);
    cfg = await r.json();
  } catch (e) {
    if (load === S.loadSeq) toast(`Couldn't load ${summary ? summary.title : "that library"}. Please try again.`);
    cfg = null;
  }
  if (load !== S.loadSeq) return;   // a newer switch is under way; it owns the spinner
  $("#loading").hidden = true;
  $(".browse").classList.remove("busy");
  $(".browse").removeAttribute("aria-busy");
  if (!cfg) return;
  S.cfg = cfg; S.cid = cid;
  S.rows = cfg.rows; S.byId = new Map(); S.groups = new Map();
  S.lic = new Map(cfg.licenses.map((l) => [l.id, l]));
  S.rows.forEach((r) => {
    S.byId.set(r.object_id, r);
    if (!S.groups.has(r.group)) S.groups.set(r.group, []);
    S.groups.get(r.group).push(r.object_id);
  });
  S.order = S.rows.map((r) => r.object_id).sort();
  S.allLatents = S.rows.every((r) => r.latents_repo);   // then the badge and filter carry no information
  store.set("collection", cid);

  const fromHash = code ? decodeSubset(code) : null;
  const legacy = cid === "gso" ? store.get("basket", []) : [];   // before collections, one GSO basket
  S.basket = new Set((fromHash ?? store.get(`basket:${cid}`, legacy)).filter((id) => S.byId.has(id)));
  if (fromHash) toast(`Loaded a shared selection of ${S.basket.size} objects from ${cfg.title}`);

  $("#lib-name").textContent = cfg.title;
  if (summary) {
    const st = latentsStatus(summary);
    Object.assign($("#lib-lat"), { className: `badge${st.cls}`, textContent: st.text, title: st.title, hidden: false });
  }
  $("#latents-group").hidden = S.allLatents;
  $("#size-group").hidden = !cfg.real_size;
  $("#license-group").hidden = !mixed();
  $("#lic-filter").innerHTML = `<option value="">Any license</option>` + cfg.licenses.map((l) => `<option value="${esc(l.id)}">${esc(l.name)} (${l.count.toLocaleString()})</option>`).join("");
  $("#commercial").checked = $("#lic-ack").checked = false;
  $("#sort option[value=size]").hidden = !cfg.real_size;
  if (!cfg.real_size && $("#sort").value === "size") $("#sort").value = "name";
  $("#objects-link").href = `https://huggingface.co/datasets/${cfg.objects_repo}`;
  $("#credit").textContent = cfg.credit;
  $("#q").placeholder = `Search ${S.rows.length.toLocaleString()} objects in ${cfg.title}…`;
  $("#q").value = $("#size-min").value = $("#size-max").value = "";
  ["#flat", "#watertight", "#one-per-group", "#latents"].forEach((sel) => ($(sel).checked = false));
  S.cats.clear();
  if (!$("#name").dataset.edited) $("#name").value = `my-${cid}-subset`;
  renderFacets();
  renderFormats();
  renderCats();
  apply();
  renderBasket();
}

function renderAuth() {
  const a = $("#auth");
  if (S.user) {
    a.innerHTML = `<img src="${esc(S.user.avatar)}" alt=""><span>${esc(S.user.user)}</span><a class="ghost small btn" href="/oauth/huggingface/logout">Sign out</a>`;
    $("#owner").innerHTML = [S.user.user, ...S.user.orgs].map((o) => `<option>${esc(o)}</option>`).join("");
  } else {
    a.innerHTML = `<a class="btn primary" href="/oauth/huggingface/login">Sign in with Hugging Face</a>`;
  }
  $("#hub-export").hidden = !S.user;
  $("#hub-login").hidden = !!S.user;
}

// ----------------------------------------------------------------- filters
const TOP_CATS = 7;   // more chips than this hide behind "More"

function renderCats() {
  const counts = {};
  S.rows.forEach((r) => { const c = r.category || "Other"; counts[c] = (counts[c] || 0) + 1; });
  const cats = Object.entries(counts).sort((a, b) => (a[0] === "Other") - (b[0] === "Other") || b[1] - a[1]);
  $("#cats").innerHTML = `<button class="chip" data-cat="" aria-pressed="true">All <span>${S.rows.length}</span></button>` +
    cats.map(([c, n], i) =>
      `<button class="chip${i >= TOP_CATS ? " extra" : ""}" data-cat="${esc(c)}" aria-pressed="false"${i >= TOP_CATS ? " hidden" : ""}>${esc(c)} <span>${n}</span></button>`).join("") +
    (cats.length > TOP_CATS ? `<button class="chip more" id="cats-more">+ ${cats.length - TOP_CATS} more</button>` : "");
  $$("#cats .chip[data-cat]").forEach((b) => b.addEventListener("click", () => {
    const c = b.dataset.cat;
    if (!c) S.cats.clear();
    else S.cats.has(c) ? S.cats.delete(c) : S.cats.add(c);
    syncCats();
    apply();
  }));
  $("#cats-more")?.addEventListener("click", (e) => {
    const open = e.currentTarget.dataset.open !== "1";
    e.currentTarget.dataset.open = open ? "1" : "";
    $$("#cats .chip.extra").forEach((b) => (b.hidden = !open && !S.cats.has(b.dataset.cat)));
    e.currentTarget.textContent = open ? "Fewer" : `+ ${$$("#cats .chip.extra").length} more`;
  });
}

function syncCats() {
  $$("#cats .chip[data-cat]").forEach((b) => b.setAttribute("aria-pressed", b.dataset.cat ? S.cats.has(b.dataset.cat) : !S.cats.size));
}

// facets beyond `category` (e.g. Smithsonian's museum) become dropdowns in the Filters panel
function renderFacets() {
  const extra = Object.entries(S.cfg.facets).filter(([k]) => k !== "category");
  $("#facet-extra").innerHTML = extra.map(([k, label]) => {
    const counts = {};
    S.rows.forEach((r) => { if (r[k]) counts[r[k]] = (counts[r[k]] || 0) + 1; });
    const opts = Object.entries(counts).sort((a, b) => b[1] - a[1]);
    return `<div class="mf-group"><h2>${esc(label)}</h2><select class="facet" data-facet="${esc(k)}">
      <option value="">Any</option>${opts.map(([v, n]) => `<option value="${esc(v)}">${esc(v)} (${n})</option>`).join("")}</select></div>`;
  }).join("");
  $$("#facet-extra select").forEach((sel) => sel.addEventListener("change", apply));
}

function advancedCount() {
  return [$("#size-min").value, $("#size-max").value].filter((v) => v !== "").length +
    ["#flat", "#watertight", "#one-per-group", "#latents"].filter((s) => $(s).checked).length +
    $$("#facet-extra select").filter((sel) => sel.value).length + ($("#lic-filter").value ? 1 : 0) + ($("#commercial").checked ? 1 : 0);
}

function bindFilters() {
  ["#q", "#size-min", "#size-max"].forEach((s) => $(s).addEventListener("input", apply));
  ["#flat", "#watertight", "#one-per-group", "#latents", "#sort", "#lic-filter", "#commercial"].forEach((s) => $(s).addEventListener("change", apply));
  $("#reset").addEventListener("click", () => {
    $("#q").value = $("#size-min").value = $("#size-max").value = "";
    ["#flat", "#watertight", "#one-per-group", "#latents"].forEach((s) => ($(s).checked = false));
    $$("#facet-extra select").forEach((sel) => (sel.value = ""));
    $("#lic-filter").value = ""; $("#commercial").checked = false;
    S.cats.clear();
    syncCats();
    apply();
  });
  $("#filters-btn").addEventListener("click", () => {
    const open = $("#more-filters").hidden;
    $("#more-filters").hidden = !open;
    $("#filters-btn").setAttribute("aria-expanded", open);
  });
  $("#add-all").addEventListener("click", () => { S.filtered.forEach((r) => S.basket.add(r.object_id)); changed(); });
  $("#remove-all").addEventListener("click", () => { S.filtered.forEach((r) => S.basket.delete(r.object_id)); changed(); });
}

function apply() {
  const q = $("#q").value.trim().toLowerCase().split(/\s+/).filter(Boolean);
  const lo = parseFloat($("#size-min").value), hi = parseFloat($("#size-max").value);
  const flat = $("#flat").checked, wt = $("#watertight").checked, lat = $("#latents").checked;
  const facets = $$("#facet-extra select").filter((sel) => sel.value).map((sel) => [sel.dataset.facet, sel.value]);
  const fields = S.cfg.search_fields;
  const lic = $("#lic-filter").value, commercial = $("#commercial").checked;
  let out = S.rows.filter((r) => {
    if (S.cats.size && !S.cats.has(r.category || "Other")) return false;
    if (facets.some(([k, v]) => r[k] !== v)) return false;
    if (!isNaN(lo) && r.max_dim_cm < lo) return false;
    if (!isNaN(hi) && r.max_dim_cm > hi) return false;
    if (flat && !(r.flatness < 0.25)) return false;
    if (wt && !r.is_watertight) return false;
    if (lat && !r.latents_repo) return false;
    if (lic && r.license !== lic) return false;
    if (commercial && licOf(r).terms.includes("nc")) return false;
    if (q.length) {
      const hay = fields.map((f) => r[f] ?? "").join(" ").toLowerCase();
      if (!q.every((t) => hay.includes(t))) return false;
    }
    return true;
  });
  if ($("#one-per-group").checked) {
    const seen = new Set();
    out = out.filter((r) => (seen.has(r.group) ? false : seen.add(r.group)));
  }
  const key = $("#sort").value;
  const cmp = {
    name: (a, b) => a.name.localeCompare(b.name),
    size: (a, b) => a.max_dim_cm - b.max_dim_cm,
    faces: (a, b) => (b.faces ?? 0) - (a.faces ?? 0),
    category: (a, b) => (a.category || "~").localeCompare(b.category || "~") || a.name.localeCompare(b.name),
  }[key];
  S.filtered = out.sort(cmp);
  const n = advancedCount();
  $("#filters-count").hidden = !n;
  $("#filters-count").textContent = n;
  renderLicBar();
  renderGrid();
}

function renderToolbar() {
  const n = S.filtered.length, all = S.filtered.length === S.rows.length;
  const inB = S.filtered.filter((r) => S.basket.has(r.object_id)).length;
  $("#count").textContent = all ? `${plural(n, "object")}` : `${plural(n, "object")} match`;
  $("#add-all").textContent = all ? `Add all ${n.toLocaleString()}` : `Add these ${n.toLocaleString()}`;
  $("#add-all").disabled = !n || inB === n;
  $("#remove-all").hidden = !inB;
  $("#remove-all").textContent = inB === n ? "Remove these" : `Remove ${inB} picked`;
}

// ----------------------------------------------------------------- grid
function renderGrid() {
  renderToolbar();
  $("#grid").innerHTML = S.filtered.length ? S.filtered.map((r, i) => {
    const sibs = S.groups.get(r.group).length;
    const inB = S.basket.has(r.object_id);
    return `<article class="tile${inB ? " in" : ""}" data-id="${esc(r.object_id)}" data-i="${i}">
      <button class="open" aria-label="View ${esc(pretty(r.name))} in 3D"><img loading="lazy" src="${tileUrl(r.object_id)}" alt="" onerror="this.style.visibility='hidden'"></button>
      <button class="add" aria-pressed="${inB}" aria-label="${inB ? "Remove from" : "Add to"} your dataset" title="${inB ? "Remove from" : "Add to"} your dataset">${inB ? "✓" : "+"}</button>
      <div class="badges">${sibs > 1 ? `<span class="badge" title="${sibs} ${variantWord()} of the same object">${sibs} ${variantWord()}</span>` : ""}${r.latents_repo && !S.allLatents ? `<span class="badge lat" title="Already preprocessed for TRELLIS.2">ready to train</span>` : ""}${mixed() ? `<span class="badge${restrictive(licOf(r)) ? " strict" : ""}" title="License: ${esc(licOf(r).terms.map((t) => S.cfg.license_terms[t][0]).join(", ") || "free to use")}">${esc(licOf(r).name.replace(/ \(.*\)$/, ""))}</span>` : ""}</div>
      <div class="cap"><span class="nm">${esc(pretty(r.name))}</span><span class="sub">${esc(r.category || "Other")}${S.cfg.real_size && r.max_dim_cm ? ` · ${Math.round(r.max_dim_cm)} cm` : ""}</span></div>
    </article>`;
  }).join("") : `<div class="empty"><b>No objects match.</b><span>Try another word, or <button class="link" id="empty-reset">clear the filters</button>.</span></div>`;
  $("#empty-reset")?.addEventListener("click", () => $("#reset").click());
}

$("#grid").addEventListener("click", (e) => {
  const tile = e.target.closest(".tile");
  if (!tile) return;
  const id = tile.dataset.id, i = +tile.dataset.i;
  if (e.target.closest(".add")) {
    if (e.shiftKey && S.lastClicked !== null) {
      const [a, b] = [Math.min(S.lastClicked, i), Math.max(S.lastClicked, i)];
      S.filtered.slice(a, b + 1).forEach((r) => S.basket.add(r.object_id));
    } else {
      S.basket.has(id) ? S.basket.delete(id) : S.basket.add(id);
    }
    S.lastClicked = i;
    changed();
  } else if (e.target.closest(".open")) {
    openDetail(id);
  }
});

function changed() {
  store.set(`basket:${S.cid}`, [...S.basket]);
  if (location.hash) history.replaceState(null, "", location.pathname);
  $$("#grid .tile").forEach((t) => {
    const inB = S.basket.has(t.dataset.id);
    t.classList.toggle("in", inB);
    const b = t.querySelector(".add");
    b.textContent = inB ? "✓" : "+";
    b.setAttribute("aria-pressed", inB);
  });
  renderToolbar();
  renderBasket();
  if ($("#detail").open) openDetail($("#detail").dataset.id);
}

// ----------------------------------------------------------------- detail
function openDetail(id) {
  const r = S.byId.get(id), d = $("#detail");
  d.dataset.id = id;
  const glb = asset(S.cfg.paths.preview_glb, id);
  if ($("#mv").getAttribute("src") !== glb) {
    // a library's own renders (OmniObject3D, ABO) go with its pictures; a few ABO objects have none
    const renders = r.extras_bytes > 0 ? (S.cfg.paths.files.renders || []).filter((p) => p.endsWith(".png")) : [];
    const thumbs = (S.cfg.paths.files.thumbnails || []).concat(renders)
      .map((t) => asset(t, id));
    $("#mv").setAttribute("src", glb);
    $("#mv").setAttribute("poster", thumbs[0] || tileUrl(id));
    $("#thumbs").innerHTML = thumbs.length > 1 ? thumbs.map((u, k) => `<img loading="lazy" src="${u}" alt="render ${k + 1}">`).join("") : "";
  }
  $("#d-name").textContent = pretty(r.name);
  $("#d-desc").textContent = r.description;
  const facetRows = Object.entries(S.cfg.facets).filter(([k]) => r[k]).map(([k, label]) => [label, r[k]]);
  const props = [
    ...facetRows, ...(r.brand ? [["Brand", r.brand]] : []),
    ...(S.cfg.real_size && r.size_x_cm ? [["Real size", `${r.size_x_cm} × ${r.size_y_cm} × ${r.size_z_cm} cm`]] : []),
    ...(r.faces ? [["Detail", `${r.faces.toLocaleString()} triangles${r.is_watertight ? ", closed mesh" : ""}`]] : []),
    ["Download size", `${gb(r.glb_bytes)} as GLB` + (S.cfg.formats.original ? `, ${gb(r.all_bytes - r.glb_bytes)} as original scan` : "")],
    ...(S.allLatents ? [] : [["TRELLIS.2", r.latents_repo ? "ready to train" : "needs preprocessing"]]),
    ["Object id", r.object_id],
  ];
  const l = licOf(r);
  $("#d-props").innerHTML = props.map(([k, v]) => `<dt>${esc(k)}</dt><dd>${esc(v)}</dd>`).join("") +
    `<dt>License</dt><dd>${licLink(l)} ${termChips(l)}</dd>` +
    (l.terms.includes("by") ? `<dt>Credit</dt><dd class="credit">${esc(r.credit || S.cfg.credit)}</dd>` : "") +
    (r.source_url ? `<dt>Source</dt><dd><a href="${esc(r.source_url)}" target="_blank" rel="noopener">original record ↗</a></dd>` : "");
  const inB = S.basket.has(id);
  $("#d-toggle").textContent = inB ? "✓ In your dataset (remove)" : "+ Add to my dataset";
  $("#d-toggle").className = inB ? "" : "primary";
  $("#d-toggle").onclick = () => { inB ? S.basket.delete(id) : S.basket.add(id); changed(); };
  const sibs = S.groups.get(r.group);
  $("#d-group").hidden = sibs.length < 2;
  const allIn = sibs.every((s) => S.basket.has(s));
  $("#d-group").textContent = allIn ? `Remove all ${sibs.length} ${variantWord()}` : `Add all ${sibs.length} ${variantWord()}`;
  $("#d-group").onclick = () => { sibs.forEach((s) => (allIn ? S.basket.delete(s) : S.basket.add(s))); changed(); };
  $("#d-siblings").innerHTML = sibs.length < 2 ? "" :
    `<h3>${S.cid === "gso" ? "Same shape, other colors" : S.cid === "thingi10k" ? "Other files of this design" : "Other versions of this object"}</h3><div>${sibs.map((s) => `<button class="sib${s === id ? " cur" : ""}${S.basket.has(s) ? " in" : ""}" data-id="${esc(s)}" title="${esc(pretty(S.byId.get(s).name))}"><img loading="lazy" src="${tileUrl(s)}" alt=""></button>`).join("")}</div>`;
  $$("#d-siblings .sib").forEach((b) => b.addEventListener("click", () => openDetail(b.dataset.id)));
  $("#d-cmd").textContent = `hf download ${S.cfg.objects_repo} --repo-type dataset --include "objects/${id}/*" --local-dir ${S.cid}`;
  if (!d.open) d.showModal();
}
$("#detail").addEventListener("click", (e) => { if (e.target === $("#detail")) $("#detail").close(); });

// ----------------------------------------------------------------- basket
function formats() { return $$("input[name=fmt]:checked").map((c) => c.value); }

function sizes(rows) {
  const sum = (f) => rows.reduce((a, r) => a + (f(r) || 0), 0);
  return {
    original: sum((r) => r.all_bytes - r.glb_bytes), glb: sum((r) => r.glb_bytes),
    preview: sum((r) => r.preview_glb_bytes), metadata: rows.length * 3000,
    thumbnails: rows.length * 70000 * (S.cfg.paths.files.thumbnails || []).length,
    renders: sum((r) => r.extras_bytes),
  };
}

// step 2's file cards come from the collection's manifest
function renderFormats() {
  const defaults = new Set(S.cfg.default_formats);
  $("#formats").innerHTML = Object.entries(S.cfg.formats).map(([f, [label, desc]]) =>
    `<label class="fmt"><input type="checkbox" name="fmt" value="${esc(f)}"${defaults.has(f) ? " checked" : ""}>
      <span class="fmt-text"><b>${esc(label)}${f === S.cfg.default_formats[0] ? " <em>recommended</em>" : ""}</b><small>${esc(desc)}</small></span>
      <span class="size" data-fmt="${esc(f)}"></span></label>`).join("");
}

// does an export with these formats carry the files trellis2-prep reads?
function hasPrepFiles(fmts) {
  const want = S.cfg.prep_include.map((g) => g.split("/").pop());
  return fmts.some((f) => (S.cfg.paths.files[f] || []).some((p) => want.includes(p.split("/").pop())));
}

function renderBasket() {
  const rows = [...S.basket].map((id) => S.byId.get(id)).sort((a, b) => a.name.localeCompare(b.name));
  const groups = new Set(rows.map((r) => r.group));
  const withLat = rows.filter((r) => r.latents_repo).length;
  const sz = sizes(rows);
  const total = formats().reduce((a, f) => a + sz[f], 0);
  $("#stats").innerHTML = `
    <div><b>${rows.length.toLocaleString()}</b><span>${rows.length === 1 ? "object" : "objects"}</span></div>
    <div><b>${groups.size.toLocaleString()}</b><span>distinct objects</span></div>
    <div><b>${rows.length ? gb(total) : "—"}</b><span>to download</span></div>`;

  // only matters to people training on it, so it sits in a collapsed "tips" section
  const warn = [];
  if (rows.length && groups.size < rows.length * 0.6)
    warn.push(`Only ${groups.size} distinct objects among ${rows.length}: many are ${variantWord()} of the same ${S.cid === "thingi10k" ? "design" : "object, which teach a shape model little"}.`);
  if (rows.length && groups.size < 40)
    warn.push(`Fairly small for training (the reference footwear run used about 180 objects). Expect overfitting; keep the step count low.`);
  const cats = {};
  rows.forEach((r) => { const c = r.category || "Other"; cats[c] = (cats[c] || 0) + 1; });
  if (Object.keys(cats).length > 3 && rows.length)
    warn.push(`Mixes ${Object.keys(cats).length} categories. A LoRA learns one coherent kind of object (and its usual pose) best.`);
  if (rows.length && withLat < rows.length)
    warn.push(`${plural(rows.length - withLat, "object")} still need TRELLIS.2 preprocessing; the dataset's README has the <code>trellis2-prep</code> command.`);
  if (rows.length && S.cfg.training_note) warn.push(esc(S.cfg.training_note));
  $("#warnings").innerHTML = warn.map((w) => `<p class="warn">${w}</p>`).join("");
  $("#tips-wrap").hidden = !warn.length;
  $("#tips-count").textContent = warn.length;

  const top = Object.entries(cats).sort((a, b) => b[1] - a[1]);
  $("#cat-bars").innerHTML = top.slice(0, 6).map(([c, n]) =>
    `<div class="bar-row"><span>${esc(c)}</span><div class="bar"><div style="width:${(100 * n) / rows.length}%"></div></div><em>${n}</em></div>`).join("") +
    (top.length > 6 ? `<p class="hint">+ ${top.length - 6} more categories</p>` : "");

  // what the picked objects' licenses ask, with a way out of the strict ones
  const lics = licensesOf(rows), strict = termsOf(lics).filter((t) => S.cfg.restrictive_terms.includes(t));
  $("#lic-box").innerHTML = !rows.length ? "" : `<h4>Licenses in your dataset</h4>` +
    lics.map((l) => `<div class="lic-row"><span>${licLink(l)} ${termChips(l)}</span><em>${l.count.toLocaleString()}</em>${lics.length > 1 ? `<button class="link" data-lic="${esc(l.id)}" title="Remove these ${l.count} objects from your dataset">Remove</button>` : "<i></i>"}</div>`).join("") +
    termsOf(lics).map((t) => `<p class="${S.cfg.restrictive_terms.includes(t) ? "warn" : "hint"}"><b>${esc(S.cfg.license_terms[t][0])}</b> (${plural(lics.filter((l) => l.terms.includes(t)).reduce((a, l) => a + l.count, 0), "object")}): ${esc(S.cfg.license_terms[t][1])}</p>`).join("") +
    (termsOf(lics).length ? "" : `<p class="hint">No conditions: use these objects for anything.</p>`);
  const sig = strict.join(",");
  if (S.ackSig !== sig) { S.ackSig = sig; $("#lic-ack").checked = false; }   // new terms need a new yes
  $("#lic-ack-wrap").hidden = !strict.length;
  $("#lic-ack-text").innerHTML = `I've read the license terms in step 1 (<b>${strict.map((t) => esc(S.cfg.license_terms[t][0].toLowerCase())).join(", ")}</b>) and will follow them.`;
  const licOk = !strict.length || $("#lic-ack").checked;
  S.licOk = licOk;

  $("#list-count").textContent = `(${rows.length})`;
  $("#basket-list").innerHTML = rows.map((r) =>
    `<li><img loading="lazy" src="${tileUrl(r.object_id)}" alt=""><span title="${esc(r.object_id)}">${esc(pretty(r.name))}</span><button class="x" data-id="${esc(r.object_id)}" aria-label="Remove ${esc(pretty(r.name))}">×</button></li>`).join("");

  $$(".size").forEach((s) => (s.textContent = rows.length ? gb(sz[s.dataset.fmt]) : ""));
  const tooBig = total > S.cfg.zip_max_bytes;
  $("#dl-zip").disabled = !rows.length || !formats().length || tooBig || !licOk;
  $("#dl-script").disabled = !rows.length || !formats().length || !licOk;
  renderExportButton(rows.length, total);
  $("#zip-note").textContent = !rows.length ? "Add objects to export them." :
    !formats().length ? "Pick at least one kind of file in step 2." :
    !licOk ? "Tick the license box above to continue." :
    tooBig ? `About ${gb(total)}: too big for a zip (limit ${gb(S.cfg.zip_max_bytes)}). Use the Python script or save to Hugging Face.` :
    `About ${gb(total)}.`;
  $("#repo-name").textContent = $("#name").value;
  renderSelbar(rows, groups.size);
}

// ---- Hub export guards: one dataset per selection, and only into a name that doesn't exist yet
const fnv = (str) => { let h = 0x811c9dc5; for (let i = 0; i < str.length; i++) { h ^= str.charCodeAt(i); h = Math.imul(h, 0x01000193); } return (h >>> 0).toString(16); };
const selectionSig = () => `${S.cid}:${S.basket.size}:${fnv([...S.basket].sort().join("\n"))}`;
const exportedFor = () => { const e = store.get(`exported:${S.cid}`, null); return e && e.sig === selectionSig() ? e : null; };
const repoId = () => `${$("#owner").value}/${$("#name").value}`;
S.name = { repo: null, available: null, reason: "" };
S.exporting = false;

function renderExportButton(n = S.basket.size, total = 0) {
  const done = exportedFor();
  $("#exported-note").hidden = !done;
  if (done) $("#exported-note").innerHTML = `This selection is already saved as <a href="${esc(done.url)}" target="_blank" rel="noopener">${esc(done.repo_id)}</a>. Change which objects are in it to create another dataset.`;
  const nameOk = S.name.repo === repoId() && S.name.available === true;
  $("#export").disabled = S.exporting || !S.user || !n || !formats().length || total > S.cfg.export_max_bytes || !!done || !nameOk || !S.licOk;
}

let nameTimer = null;
function checkName() {
  if (!S.user) return;
  const repo = repoId();
  if (!$("#name").value) { setNameStatus(repo, false, "Pick a name"); return; }
  setNameStatus(repo, null, "Checking the name…");
  clearTimeout(nameTimer);
  nameTimer = setTimeout(async () => {
    try {
      const r = await fetch(`/api/repo-available?repo_id=${encodeURIComponent(repo)}`);
      const b = await r.json();
      if (repo !== repoId()) return;   // the name changed while we were asking
      setNameStatus(repo, r.ok && b.available, r.ok ? (b.available ? `✓ ${repo} is available` : `✗ ${b.reason}. Choose another name.`) : (b.detail || "Couldn't check this name"));
    } catch { setNameStatus(repo, null, "Couldn't check this name"); }
  }, 350);
}

function setNameStatus(repo, available, text) {
  S.name = { repo, available, reason: text };
  const el = $("#name-status");
  el.textContent = text;
  el.className = "name-status" + (available === true ? " ok" : available === false ? " bad" : "");
  renderExportButton(S.basket.size, formats().reduce((a, f) => a + sizes([...S.basket].map((id) => S.byId.get(id)))[f], 0));
}

function renderSelbar(rows, shapes) {
  const n = rows.length;
  $("#sel-count").textContent = n ? `${plural(n, "object")} in your dataset` : "Nothing picked yet";
  $("#sel-sub").innerHTML = n ? `${plural(shapes, "distinct object")} · ${esc(S.cfg.title)}` : "Click <b>+</b> on any object to add it to your dataset.";
  $("#sel-thumbs").innerHTML = rows.slice(-5).reverse().map((r) =>
    `<img src="${tileUrl(r.object_id)}" alt="">`).join("");
  $("#review-btn").disabled = !n;
  $("#clear").hidden = !n;
  $("#selbar").classList.toggle("has", n > 0);
}

function bindBasket() {
  $("#basket-list").addEventListener("click", (e) => {
    const b = e.target.closest(".x");
    if (b) { S.basket.delete(b.dataset.id); changed(); }
  });
  $("#clear").addEventListener("click", () => { if (confirm("Remove every object from your dataset?")) { S.basket.clear(); changed(); } });
  $("#review-btn").addEventListener("click", () => { $("#drawer").showModal(); checkName(); });
  $("#drawer-close").addEventListener("click", () => $("#drawer").close());
  $("#drawer").addEventListener("click", (e) => { if (e.target === $("#drawer")) $("#drawer").close(); });
  $("#formats").addEventListener("change", renderBasket);
  $("#lic-ack").addEventListener("change", renderBasket);
  $("#lic-box").addEventListener("click", (e) => {
    const b = e.target.closest("button[data-lic]");
    if (!b) return;
    [...S.basket].forEach((id) => { if (S.byId.get(id).license === b.dataset.lic) S.basket.delete(id); });
    changed();
  });
  $("#name").addEventListener("input", () => {
    $("#name").value = $("#name").value.replace(/[^A-Za-z0-9._-]/g, "-");
    $("#name").dataset.edited = "1";
    renderBasket();
    checkName();
  });
  $("#owner").addEventListener("change", checkName);
  $("#dl-zip").addEventListener("click", () => {
    const f = $("#zip-form");
    f.payload.value = JSON.stringify({ collection: S.cid, ids: [...S.basket], formats: formats(), name: $("#name").value, share_url: shareUrl() });
    f.submit();
    toast("Your zip is being built and will download shortly");
  });
  $("#dl-script").addEventListener("click", () => {
    const ids = [...S.basket].sort();
    const py = scriptFor(ids, formats());
    const a = Object.assign(document.createElement("a"), {
      href: URL.createObjectURL(new Blob([py], { type: "text/x-python" })), download: "download_subset.py",
    });
    a.click();
    URL.revokeObjectURL(a.href);
  });
  $("#share").addEventListener("click", async () => {
    const url = shareUrl();
    try { await navigator.clipboard.writeText(url); toast("Link copied"); }
    catch { prompt("Copy this link", url); }
  });
  $("#import-btn").addEventListener("click", () => ($("#import-box").hidden = !$("#import-box").hidden));
  $("#import-go").addEventListener("click", () => {
    const shaToId = new Map(S.rows.map((r) => [r.prep_sha256, r.object_id]));
    const tokens = $("#import-text").value.split(/\s+/).filter((t) => t && !t.startsWith("#"));
    let n = 0;
    tokens.forEach((t) => {
      const id = S.byId.has(t) ? t : shaToId.get(t);
      if (id && !S.basket.has(id)) { S.basket.add(id); n++; }
    });
    toast(`Added ${n} objects`);
    $("#import-text").value = "";
    changed();
  });
  $("#export").addEventListener("click", startExport);
}

function scriptFor(ids, fmts) {
  const paths = Object.fromEntries(fmts.map((f) => [f, S.cfg.paths.files[f]]));
  const lics = licensesOf(ids.map((id) => S.byId.get(id))).map((l) =>
    `  ${String(l.count).padStart(5)}  ${l.name}: ${l.terms.map((t) => S.cfg.license_terms[t][0].toLowerCase()).join("; ") || "no conditions"}`).join("\n");
  return `"""Download ${ids.length} objects from ${S.cfg.title} (${S.cfg.objects_repo}).

    pip install huggingface_hub && python download_subset.py [out_dir]

Selection: ${shareUrl()}
${S.cfg.credit}

Licenses of these objects (each object's license and credit line: the \`license\` and \`credit\`
columns of ${S.cfg.objects_repo}'s catalog.parquet; keep the credits with anything you share):
${lics}
"""
import sys
from huggingface_hub import snapshot_download

IDS = ${JSON.stringify(ids, null, 1)}
FORMATS = ${JSON.stringify(paths, null, 1)}

patterns = [p.format(id=i) for i in IDS for paths in FORMATS.values() for p in paths]
out = snapshot_download("${S.cfg.objects_repo}", repo_type="dataset", allow_patterns=patterns,
                        local_dir=sys.argv[1] if len(sys.argv) > 1 else "${S.cid}_subset")
print("downloaded to", out)
`;
}

async function startExport() {
  const repo_id = repoId(), ids = [...S.basket], fmts = formats(), sig = selectionSig();
  S.exporting = true;
  renderExportButton();
  $("#export-status").hidden = false;
  $("#export-msg").textContent = "starting";
  $("#export-bar").style.width = "0%";
  const finish = () => { S.exporting = false; renderBasket(); };
  const res = await fetch("/api/export", {
    method: "POST", headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ collection: S.cid, ids, formats: fmts, repo_id, private: $("#private").checked, share_url: shareUrl() }),
  });
  const body = await res.json();
  if (!res.ok) {
    $("#export-msg").textContent = body.detail || "export failed";
    if (res.status === 409) setNameStatus(repo_id, false, `✗ ${body.detail}`);
    finish();
    return;
  }
  const poll = async () => {
    const st = await fetch(`/api/export/${body.job}`).then((r) => r.json());
    $("#export-bar").style.width = `${Math.round(st.progress * 100)}%`;
    if (st.status === "done") {
      store.set(`exported:${S.cid}`, { sig, repo_id, url: st.url });
      $("#export-msg").innerHTML = `Done: <a href="${esc(st.url)}" target="_blank" rel="noopener">${esc(repo_id)}</a>. Its card has the download and TRELLIS.2 training commands.`;
      setNameStatus(repo_id, false, `✗ ${repo_id} now holds this dataset`);
      showTrainLink({ repo_id, ids, formats: fmts });
      finish();
    } else if (st.status === "error") {
      $("#export-msg").textContent = st.message;
      finish();
      checkName();   // a failed export may have created the repo: re-check before allowing a retry
    } else {
      $("#export-msg").textContent = st.message;
      setTimeout(poll, 1500);
    }
  };
  poll();
}

// ----------------------------------------------------------------- training
// Training happens in the trainer Space (it asks for the "jobs" permission; this Space never does).
// The link prefills it: straight from existing latents when subset training is on, otherwise the
// exported OBJs for preprocessing. Never latents without a subset, which would train on everything.
function showTrainLink(exported) {
  const rows = exported.ids.map((id) => S.byId.get(id));
  const latents = rows.every((r) => r.latents_repo) && new Set(rows.map((r) => r.latents_repo)).size === 1 ? rows[0].latents_repo : null;
  const name = exported.repo_id.split("/")[1];
  const q = new URLSearchParams({ name });
  let note;
  if (latents && S.cfg.subset_enabled) {
    q.set("latents", latents); q.set("subset", exported.repo_id);
    note = "Every object is already preprocessed, so training starts right away.";
  } else if (hasPrepFiles(exported.formats)) {
    q.set("meshes", exported.repo_id); q.set("include", S.cfg.prep_include.join(" "));
    note = "The trainer will preprocess your objects first, then train.";
  } else {
    const need = Object.entries(S.cfg.formats).filter(([f]) => hasPrepFiles([f])).map(([, [label]]) => `<b>${esc(label)}</b>`);
    note = `Tip: include ${need.join(" or ")} in step 2 so the trainer can preprocess your objects; this export has none.`;
  }
  $("#train-go").href = `${S.cfg.trainer_url}?${q}`;
  $("#train-note").innerHTML = note;
  const terms = termsOf(licensesOf(rows));
  $("#train-lic").innerHTML = !terms.length ? "" :
    `<b>Licenses carry over.</b> A model trained on these objects is made from them: ` +
    [terms.includes("by") && "credit the authors on its model card (<code>ATTRIBUTION.md</code> in your dataset lists them)",
     terms.includes("nc") && "keep it non-commercial",
     (terms.includes("sa") || terms.includes("copyleft")) && "check whether share-alike applies before you publish it",
     terms.includes("custom") && "follow the source's usage rules"].filter(Boolean).join("; ") + ".";
  $("#train-link").hidden = false;
}

// ----------------------------------------------------------------- libraries
function bindLibraries() {
  $("#lib-btn").addEventListener("click", () => {
    $("#libs-list").innerHTML = S.collections.map((c) => {
      const picked = store.get(`basket:${c.id}`, c.id === "gso" ? store.get("basket", []) : []).length;
      const st = latentsStatus(c);
      return `<button class="lib${c.id === S.cid ? " cur" : ""}" data-id="${esc(c.id)}">
        <img src="${esc(c.asset_base + c.tile.replace("{id}", encodeURIComponent(c.sample)))}" alt="">
        <span><b>${esc(c.title)}</b><small>${esc(c.tagline)}</small>
        <small class="hint">${c.count.toLocaleString()} objects · ${esc(c.license)}${c.license_terms.includes("nc") ? " · some non-commercial" : ""}${picked ? ` · ${picked} picked` : ""}</small>
        <small><i class="badge${st.cls}" title="${esc(st.title)}">${esc(st.text)}</i></small></span></button>`;
    }).join("");
    $("#libs").showModal();
  });
  $("#libs-list").addEventListener("click", async (e) => {
    const b = e.target.closest(".lib");
    if (!b) return;
    $("#libs").close();
    if (b.dataset.id !== S.cid) {
      if (location.hash) history.replaceState(null, "", location.pathname);
      await loadCollection(b.dataset.id);
      window.scrollTo({ top: 0 });
    }
  });
  $("#libs").addEventListener("click", (e) => { if (e.target === $("#libs")) $("#libs").close(); });
}

// ----------------------------------------------------------------- first-timer tour
// A welcome card, then coach marks that spotlight each part of the page. Shown once
// (remembered in localStorage); "How it works" replays it.
const TOUR = [
  { title: "Welcome! Build your own 3D dataset",
    body: `<p>Browse free 3D libraries, like <b>{title}</b> ({tagline}). Pick the objects you want and take them with
           you, for a game, a render, 3D printing, or training an AI model.</p>
           <ol class="tour-steps"><li><b>Pick</b> objects you like</li><li><b>Review</b> your picks</li><li><b>Download</b> them, or save them to Hugging Face</li></ol>
           <p class="hint">Takes 30 seconds. You can replay it any time from "How it works".</p>`,
    next: "Show me around" },
  { target: "#lib-btn", title: "Choose a library",
    body: "<p>Switch between 3D libraries here. Each one keeps its own selection, so you can come back to it.</p>" },
  { target: "#find", title: "Find objects",
    body: "<p>Type what you're after, or tap a category. <b>Filters</b> has more options, like shape and size.</p>" },
  { target: "#grid .tile", title: "Look, then pick",
    body: "<p>Click a picture to <b>spin the object in 3D</b>. Click <b>+</b> to add it to your dataset.</p><p class=\"hint\">Tip: shift-click + to add a whole row at once.</p>" },
  { target: "#add-all", title: "Or grab them all",
    body: "<p>Adds every object matching your search in one click: pick a category, then add them all.</p>" },
  { target: "#selbar", title: "Your dataset lives here",
    body: "<p>Everything you pick collects in this bar, and it's remembered if you come back later.</p>" },
  { target: "#review-btn", title: "Get your files",
    body: "<p>When you're ready, open this to <b>check your picks, choose file types and download</b> a zip. Signed in, you can also save it as a dataset on your Hugging Face account, and even train a TRELLIS.2 model on it.</p>",
    next: "Start exploring" },
];
let tourAt = -1;

function bindTour() {
  $("#help-btn").addEventListener("click", () => startTour(0));
  $("#tour-next").addEventListener("click", () => (tourAt + 1 < TOUR.length ? showTourStep(tourAt + 1) : endTour()));
  $("#tour-back").addEventListener("click", () => showTourStep(tourAt - 1));
  $("#tour-skip").addEventListener("click", endTour);
  document.addEventListener("keydown", (e) => {
    if (tourAt < 0) return;
    if (e.key === "Escape") endTour();
    if (e.key === "ArrowRight") $("#tour-next").click();
    if (e.key === "ArrowLeft" && tourAt > 0) $("#tour-back").click();
  });
  window.addEventListener("resize", () => tourAt >= 0 && placeTour());
  window.addEventListener("scroll", () => tourAt >= 0 && placeTour(), { passive: true });
}

function startTour(i) {
  ["#drawer", "#detail", "#libs"].forEach((d) => $(d).open && $(d).close());
  $("#tour").hidden = false;
  document.body.classList.add("touring");
  showTourStep(i);
}

function showTourStep(i) {
  tourAt = i;
  const s = TOUR[i];
  $("#tour-step").textContent = i ? `Step ${i} of ${TOUR.length - 1}` : "";
  $("#tour-title").textContent = s.title;
  $("#tour-body").innerHTML = s.body.replace("{title}", esc(S.cfg.title)).replace("{tagline}", esc(S.cfg.tagline));
  $("#tour-back").hidden = i === 0;
  $("#tour-skip").textContent = i === 0 ? "No thanks" : "Skip tour";
  $("#tour-next").textContent = s.next || "Next";
  const el = s.target && document.querySelector(s.target);
  if (el) el.scrollIntoView({ block: "center", behavior: "instant" });
  placeTour();
  $("#tour-next").focus();
}

function placeTour() {
  const s = TOUR[tourAt], card = $("#tour-card"), spot = $("#tour-spot");
  const el = s.target && document.querySelector(s.target);
  card.classList.toggle("center", !el);
  spot.hidden = !el;
  if (!el) { card.style.left = card.style.top = ""; return; }
  const r = el.getBoundingClientRect(), pad = 6;
  Object.assign(spot.style, { left: `${r.left - pad}px`, top: `${r.top - pad}px`, width: `${r.width + 2 * pad}px`, height: `${r.height + 2 * pad}px` });
  const cw = card.offsetWidth, ch = card.offsetHeight, vw = innerWidth, vh = innerHeight, gap = 14;
  const below = r.bottom + gap + ch < vh;
  const top = below ? r.bottom + gap : Math.max(gap, r.top - gap - ch);
  const left = Math.min(Math.max(gap, r.left + r.width / 2 - cw / 2), vw - cw - gap);
  Object.assign(card.style, { left: `${left}px`, top: `${top}px` });
}

function endTour() {
  tourAt = -1;
  $("#tour").hidden = true;
  document.body.classList.remove("touring");
  store.set("tour_done", true);
}

function toast(msg) {
  const t = $("#toast");
  t.textContent = msg;
  t.hidden = false;
  clearTimeout(toast.h);
  toast.h = setTimeout(() => (t.hidden = true), 3000);
}

boot().catch((e) => { $("#grid").innerHTML = `<p class="warn">Could not load the catalog: ${esc(e.message)}</p>`; });