File size: 2,886 Bytes
2d77bd6
 
 
 
 
 
 
 
 
 
 
9feba35
 
2d77bd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9feba35
2d77bd6
 
 
 
 
9feba35
 
2d77bd6
 
 
 
 
 
 
9feba35
 
2d77bd6
 
 
 
 
 
 
 
 
 
 
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
# /// script
# requires-python = ">=3.10"
# dependencies = ["pillow"]
# ///
"""Make the web previews for the scenes listed in tools/scenes.json.

For each scene, downloads scenes/<scene>/<scene>.glb and preview.png from the gated
dataset (read only; needs HF_TOKEN from an account with access), shrinks the GLB with
Blender (tools/blender_scene_glb.py) into previews/scenes/<scene>.glb, and writes a
960 px thumbnail to previews/thumbs/<id>.webp.

Run from the Space folder:  HF_TOKEN=$(hf auth token) uv run tools/make_scene_previews.py [scene ...]
(no names: every scene; a scene's max_texture in scenes.json overrides --max-texture)
"""

import argparse
import json
import os
import subprocess
import sys
import tempfile
import urllib.request

from PIL import Image

HF = "https://huggingface.co"
HERE = os.path.dirname(os.path.abspath(__file__))


def download(url, dest):
    headers = {"Authorization": f"Bearer {os.environ['HF_TOKEN']}"} if os.environ.get("HF_TOKEN") else {}
    with urllib.request.urlopen(urllib.request.Request(url, headers=headers), timeout=600) as r, open(dest, "wb") as f:
        while chunk := r.read(1 << 20):
            f.write(chunk)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--blender", default="/Applications/Blender.app/Contents/MacOS/Blender")
    ap.add_argument("--max-texture", type=int, default=2048)
    ap.add_argument("scenes", nargs="*", help="only these scenes (folder names); default all")
    args = ap.parse_args()
    cfg = json.load(open(os.path.join(HERE, "scenes.json")))
    os.makedirs("previews/scenes", exist_ok=True)
    os.makedirs("previews/thumbs", exist_ok=True)
    for s in cfg["scenes"]:
        if args.scenes and s["scene"] not in args.scenes:
            continue
        base = f"{HF}/datasets/{cfg['dataset']}/resolve/main/scenes/{s['scene']}"
        with tempfile.TemporaryDirectory() as tmp:
            glb, png = os.path.join(tmp, "in.glb"), os.path.join(tmp, "preview.png")
            download(f"{base}/{s['scene']}.glb", glb)
            download(f"{base}/preview.png", png)
            out = f"previews/scenes/{s['scene']}.glb"
            run = subprocess.run([args.blender, "-b", "--factory-startup", "--python",
                                  os.path.join(HERE, "blender_scene_glb.py"), "--", glb, out,
                                  str(s.get("max_texture", args.max_texture))],
                                 capture_output=True, text=True)
            if "SCENE_OK" not in run.stdout:
                sys.exit(f"{s['scene']}: Blender failed\n{(run.stdout + run.stderr)[-800:]}")
            img = Image.open(png).convert("RGB")
            img.thumbnail((960, 960))
            img.save(f"previews/thumbs/{s['id']}.webp", quality=88)
        print(f"{s['name']}: {os.path.getsize(out) / 1e6:.1f} MB GLB", file=sys.stderr)


if __name__ == "__main__":
    main()