`;
// 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 trellis2-prep command.`);
if (rows.length && S.cfg.training_note) warn.push(esc(S.cfg.training_note));
$("#warnings").innerHTML = warn.map((w) => `
` : "");
// 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 ? "" : `
`);
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 (${strict.map((t) => esc(S.cfg.license_terms[t][0].toLowerCase())).join(", ")}) 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) =>
`
${esc(pretty(r.name))}
`).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 ${esc(done.repo_id)}. 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 + on any object to add it to your dataset.";
$("#sel-thumbs").innerHTML = rows.slice(-5).reverse().map((r) =>
``).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: ${esc(repo_id)}. 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]]) => `${esc(label)}`);
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 ? "" :
`Licenses carry over. A model trained on these objects is made from them: ` +
[terms.includes("by") && "credit the authors on its model card (ATTRIBUTION.md 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 ``;
}).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: `
Browse free 3D libraries, like {title} ({tagline}). Pick the objects you want and take them with
you, for a game, a render, 3D printing, or training an AI model.
Pick objects you like
Review your picks
Download them, or save them to Hugging Face
Takes 30 seconds. You can replay it any time from "How it works".
`,
next: "Show me around" },
{ target: "#lib-btn", title: "Choose a library",
body: "
Switch between 3D libraries here. Each one keeps its own selection, so you can come back to it.
When you're ready, open this to check your picks, choose file types and download 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.