suvadityamuk's picture
suvadityamuk HF Staff
Update GSO subset builder
32ceebc verified
Raw History Blame Contribute Delete
15.5 kB
"""Turn a list of object ids from a 3D collection into files: a streamed zip, or a dataset repo on the Hub.
Both read from a collection repo (gso_browser/collection3d/format.py) through a
`fetch(path, dest_dir) -> local_path` callable (Hub download in the Space, a local copy in dev).
File layouts, formats, prep globs and credit lines come from the collection's manifest (`man`).
"""
from __future__ import annotations
import io
import json
import os
import random
import re
import shutil
import tempfile
import zipfile
from collections import Counter
from typing import Callable, Iterable, Iterator
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
import licenses
COMPRESSIBLE = (".obj", ".mtl", ".json", ".txt", ".md", ".py", ".csv")
Fetch = Callable[[str, str], "str | None"]
def key_column(rows: pd.DataFrame) -> str:
"""The latents key: `prep_sha256` in the collection format, `obj_sha256` in older GSO catalogs."""
return "prep_sha256" if "prep_sha256" in rows else "obj_sha256"
def object_paths(ids: Iterable[str], formats: Iterable[str], man: dict) -> list[str]:
files = man["paths"]["files"]
return [p.format(id=i) for i in ids for f in formats for p in files[f]]
def estimate_bytes(rows: pd.DataFrame, formats: Iterable[str], man: dict) -> int:
files = man["paths"]["files"]
n = pd.Series(1, index=rows.index)
per = {"glb": rows.glb_bytes, "preview": rows.preview_glb_bytes,
"original": (rows.all_bytes - rows.glb_bytes) if "original" in files else 0 * n,
"thumbnails": n * 70_000 * len(files.get("thumbnails", [])), "metadata": n * 3_000,
"renders": rows.extras_bytes.fillna(0) if "extras_bytes" in rows else 0 * n}
return int(sum(per[f].sum() for f in formats))
def holdout_split(rows: pd.DataFrame, frac: float = 0.05, seed: int = 0) -> list[str]:
"""Group-aware held-out split: make_holdout.py's shuffle, keyed on the catalog's `group`.
Each collection's `group` puts variants of one physical object together (GSO: name rules refined
by shape; Smithsonian: museum record; NASA: subject), so they differ from make_holdout's name-only
key. Whole groups are taken in a seeded shuffle until ~frac of objects are held out. Returns latents
keys. Needs >= 2 groups.
"""
groups: dict[str, list[str]] = {}
for sha, group in zip(rows[key_column(rows)], rows.group):
groups.setdefault(group, []).append(sha)
if len(groups) < 2:
return []
keys = sorted(groups)
random.Random(seed).shuffle(keys)
target = max(1, round(len(rows) * frac))
held: list[str] = []
for key in keys:
if len(held) >= target:
break
held.extend(groups[key])
return sorted(held)
def subset_txt(rows: pd.DataFrame, man: dict) -> str:
"""`trellis2-train --subset` reads the first token of each line; the id is for people."""
lines = [f"# sha256 of {man['prep_include'][0].replace('*', '<id>')} (the TRELLIS.2 latents key) object_id"]
lines += [f"{sha} {oid}" for sha, oid in zip(rows[key_column(rows)], rows.object_id)]
return "\n".join(lines) + "\n"
def download_script(man: dict, rows: pd.DataFrame, formats: list[str]) -> str:
files = {f: man["paths"]["files"][f] for f in formats}
ids = list(rows.object_id)
lics = "\n".join(f" {l['count']:>5} {l['name']}: {licenses.terms_text(l)}" for l in licenses.breakdown(rows, man))
return f'''"""Download {len(ids)} objects from {man["title"]} ({man["objects_repo"]}).
pip install huggingface_hub && python download_subset.py [out_dir]
{man["credit"]}
Licenses of these objects (the license and credit line of each one is in catalog.parquet
and ATTRIBUTION.md of the subset; keep the credits with anything you share):
{lics}
"""
import sys
from huggingface_hub import snapshot_download
IDS = {json.dumps(ids, indent=1)}
FORMATS = {json.dumps(files, indent=1)}
patterns = [p.format(id=i) for i in IDS for paths in FORMATS.values() for p in paths]
out = snapshot_download("{man["objects_repo"]}", repo_type="dataset", allow_patterns=patterns,
local_dir=sys.argv[1] if len(sys.argv) > 1 else "3d_subset")
print("downloaded to", out)
'''
def _brief(paths: list[str]) -> list[str]:
"""Paths for a card's file table, with a run of numbered files (renders/000.png, 001.png, ...) as one entry."""
numbered = [p for p in paths if re.search(r"/\d+\.\w+$", p)]
if len(numbered) < 3:
return paths
first, last = numbered[0], numbered[-1]
run = f"{first.rsplit('/', 1)[0]}/{first.rsplit('/', 1)[1].split('.')[0]}…{last.rsplit('/', 1)[1]}"
return [run] + [p for p in paths if p not in numbered]
def card(repo_id: str, rows: pd.DataFrame, formats: list[str], man: dict, space_url: str,
share_url: str, latents_repo: str | None, n_latents: int, n_holdout: int) -> str:
cats = Counter(c or "uncategorized" for c in rows.category).most_common()
cat_table = "\n".join(f"| {c} | {n} |" for c, n in cats)
files = man["paths"]["files"]
layout = [f"| {', '.join(f'`{p}`'.replace('{id}', '<id>') for p in _brief(files[f]))} | {man['formats'][f][1]} |" for f in formats]
layout.append("| `catalog.parquet` | one row per object: metadata, geometry stats, license, variant group |")
layout.append("| `ATTRIBUTION.md` | the credit line and license of every object |")
layout.append("| `subset.txt` | `<sha256> <object_id>` per line; `trellis2-train --subset` reads it |")
if n_holdout:
layout.append("| `holdout.txt` | group-aware held-out split (sha256), used by `trellis2-train --subset` |")
layout_table = "\n".join(layout)
include = " ".join(f'"{g}"' for g in man["prep_include"])
prep_files = {p for g in man["prep_include"] for f, ps in files.items() for p in ps if p.endswith(g.rsplit("/", 1)[-1])}
has_prep_files = any(p in prep_files for f in formats for p in files[f])
user = repo_id.split("/")[0]
name = repo_id.split("/")[1]
trellis = []
if latents_repo and n_latents:
trellis.append(f"""{n_latents} of the {len(rows)} objects already have TRELLIS.2 latents in
[`{latents_repo}`](https://huggingface.co/datasets/{latents_repo}), so you can train straight away
on that part (run the same command with `--config shape` for the shape flow):
```bash
hf jobs run -d --flavor a100-large --timeout 12h --secrets HF_TOKEN \\
cr.hf.co/suvadityamuk/trellis2-finetuning-train:latest \\
trellis2-train \\
--config ss \\
--latents {latents_repo} \\
--subset {repo_id} \\
--push-to {user}/{name}-trellis2-lora \\
--trackio-space {user}/trellis2-trackio \\
--private --trackio-private
```
""")
if n_latents < len(rows):
if has_prep_files:
trellis.append(f"""To encode {'the rest' if n_latents else 'them'} yourself, preprocess this repo, then train on the result
(drop `--subset` and point `--latents` at the new repo):
```bash
hf jobs run -d --flavor a100-large --timeout 6h --secrets HF_TOKEN \\
cr.hf.co/suvadityamuk/trellis2-finetuning-prep:latest \\
trellis2-prep \\
--meshes {repo_id} \\
--meshes-include {include} \\
--push-to {user}/{name}-trellis2-latents \\
--private
```
""")
else:
trellis.append("To encode the objects without latents, re-export with the files TRELLIS.2 preprocesses "
f"({', '.join(man['prep_include'])}) and run `trellis2-prep` on it.")
if man.get("training_note"):
trellis.append(f"> {man['training_note']}\n")
trellis_md = "\n".join(trellis)
license_tag = licenses.hub_tag(rows, man)
license_note = f"\n{man['license_note']}\n" if man.get("license_note") else ""
return f"""---
license: {license_tag}
pretty_name: {name}
tags:
- 3d
- mesh
- 3d-subset-builder
source_datasets:
- {man["objects_repo"]}
configs:
- config_name: default
data_files: catalog.parquet
---
# {name}
A subset of **{len(rows)} objects from [{man["title"]}](https://huggingface.co/datasets/{man["objects_repo"]})**
({rows.group.nunique()} distinct objects once variants are grouped), built with the
[3D subset builder]({space_url}). [Open this subset in the builder]({share_url}) to edit or fork it.
| category | objects |
|---|---|
{cat_table}
## Files
| path | what |
|---|---|
{layout_table}
```python
from huggingface_hub import snapshot_download
snapshot_download("{repo_id}", repo_type="dataset", local_dir="{name}")
```
## Fine-tune TRELLIS.2 on it
{trellis_md}
See the [TRELLIS.2 LoRA write-up](https://huggingface.co/suvadityamuk/trellis-2-finetune-gso) for
flavors, configs and evaluation.
## License and attribution
{man["credit"]}
{licenses.summary_md(rows, man)}
{license_note}
`ATTRIBUTION.md` has the credit line and license of every object, and `catalog.parquet` has them as
`credit` and `license` columns: keep them with the objects and with anything you publish that was made
from them, including a model trained on them if a license here asks for that. Files are copied unmodified from
[`{man["objects_repo"]}`](https://huggingface.co/datasets/{man["objects_repo"]}) (previews are derived).
This summary is not legal advice; the linked license texts apply.
"""
# ---------------------------------------------------------------------------- zip
class _Sink(io.RawIOBase):
"""Write-only, unseekable buffer: zipfile then streams entries with data descriptors."""
def __init__(self) -> None:
self.buf = bytearray()
self.pos = 0
def writable(self) -> bool:
return True
def write(self, b) -> int:
self.buf += b
self.pos += len(b)
return len(b)
def tell(self) -> int:
return self.pos
def take(self) -> bytes:
out = bytes(self.buf)
self.buf.clear()
return out
def zip_stream(paths: list[str], fetch: Fetch, extras: dict[str, str | bytes], root: str) -> Iterator[bytes]:
"""Yield a zip of `paths` (fetched one at a time, deleted after) plus in-memory `extras`."""
sink = _Sink()
tmp = tempfile.mkdtemp(prefix="gso_zip_")
try:
with zipfile.ZipFile(sink, "w") as zf:
for arc, text in extras.items():
zf.writestr(f"{root}/{arc}", text, compress_type=zipfile.ZIP_DEFLATED)
yield sink.take()
for path in paths:
local = fetch(path, tmp)
if local is None:
continue
info = zipfile.ZipInfo(f"{root}/{path}", date_time=(2020, 9, 18, 0, 0, 0))
info.compress_type = zipfile.ZIP_DEFLATED if path.endswith(COMPRESSIBLE) else zipfile.ZIP_STORED
info.external_attr = 0o644 << 16
with zf.open(info, "w", force_zip64=True) as dst, open(local, "rb") as src:
while chunk := src.read(1 << 20):
dst.write(chunk)
if len(sink.buf) > 4 << 20:
yield sink.take()
if local.startswith(tmp):
os.remove(local)
yield sink.take()
yield sink.take()
finally:
shutil.rmtree(tmp, ignore_errors=True)
# ---------------------------------------------------------------------------- hub
def export_to_hub(token: str, repo_id: str, private: bool, rows: pd.DataFrame, formats: list[str],
extras: dict[str, str], fetch: Fetch, progress: Callable[[str, float], None], man: dict,
objects_per_commit: int = 100) -> str:
"""Create repo_id with the user's token and upload the subset in batches of objects."""
from huggingface_hub import CommitOperationAdd, HfApi
api = HfApi(token=token)
url = api.create_repo(repo_id, repo_type="dataset", private=private, exist_ok=False) # never overwrite
ids = list(rows.object_id)
batches = [ids[i:i + objects_per_commit] for i in range(0, len(ids), objects_per_commit)] if formats else []
for b, batch in enumerate(batches):
tmp = tempfile.mkdtemp(prefix="gso_export_")
try:
ops = []
paths = object_paths(batch, formats, man)
for k, path in enumerate(paths):
local = fetch(path, tmp)
if local is not None:
ops.append(CommitOperationAdd(path_in_repo=path, path_or_fileobj=local))
progress(f"downloading batch {b + 1}/{len(batches)} ({k + 1}/{len(paths)} files)",
(b + 0.5 * (k + 1) / len(paths)) / (len(batches) + 1))
progress(f"uploading batch {b + 1}/{len(batches)}", (b + 0.75) / (len(batches) + 1))
api.create_commit(repo_id, ops, repo_type="dataset",
commit_message=f"Add objects {b * objects_per_commit + 1}-"
f"{b * objects_per_commit + len(batch)}")
finally:
shutil.rmtree(tmp, ignore_errors=True)
progress("writing catalog and card", len(batches) / (len(batches) + 1))
ops = [CommitOperationAdd(path_in_repo=k, path_or_fileobj=v if isinstance(v, bytes) else v.encode())
for k, v in extras.items()]
api.create_commit(repo_id, ops, repo_type="dataset", commit_message="Add catalog, manifest and card")
progress("done", 1.0)
return str(url)
def catalog_bytes(rows: pd.DataFrame, formats: list[str], man: dict, hub_repo: str | None = None) -> bytes:
"""The export's catalog. With hub_repo, its `mesh` column holds `hf://datasets/<repo>@main/...`
paths: the dataset viewer leaves repo-relative Mesh paths empty ("Not supported"). A zip keeps
relative paths, which `datasets` resolves next to the parquet on disk."""
files = man["paths"]["files"]
out = rows.drop(columns=[c for c in ("latents_repo", "mesh") if c in rows]).copy()
for fmt, col in (("glb", "glb_path"), ("original", "obj_path"), ("preview", "preview_glb_path")):
if fmt in formats and fmt in files:
out[col] = [files[fmt][0].format(id=i) for i in out.object_id]
table = pa.Table.from_pandas(out, preserve_index=False).replace_schema_metadata(None)
mesh = out.get("glb_path", out.get("preview_glb_path")) # whichever GLB the export carries
if mesh is not None:
base = f"hf://datasets/{hub_repo}@main/" if hub_repo else ""
table = with_mesh_column(table, [base + p for p in mesh])
buf = io.BytesIO()
pq.write_table(table, buf)
return buf.getvalue()
_DTYPES = {"double": "float64", "float": "float32", "halffloat": "float16"}
def with_mesh_column(table: pa.Table, paths: list, name: str = "mesh", index: int = 1) -> pa.Table:
"""Insert a `datasets.Mesh` column of GLB paths, so the Hub's dataset viewer renders each row in 3D
(a Parquet-backed dataset only shows meshes through a typed column like this). For the viewer the
paths must be absolute `hf://datasets/<repo>@<rev>/<path>`; relative ones render as "Not supported"."""
mesh = pa.struct([("bytes", pa.binary()), ("path", pa.string())])
cells = [None if p is None else {"bytes": None, "path": p} for p in paths]
table = table.add_column(index, name, pa.array(cells, type=mesh))
features = {f.name: {"_type": "Mesh"} if f.name == name else
{"dtype": _DTYPES.get(str(f.type), str(f.type)), "_type": "Value"} for f in table.schema}
return table.replace_schema_metadata({"huggingface": json.dumps({"info": {"features": features}})})