File size: 6,175 Bytes
966b234
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""A model of something in a recording, made from a picture of it (or from words) by Tripo.

    uv run python -m scripts.model BUILD NAME (--picture FILE | --text "what it is") [--rig [--clips idle walk run ...]]

For what a reconstruction cannot be: a thing that has to be seen from all sides, move its limbs, be picked up or
driven. FILE is a picture inside BUILD (a cut-out with transparency, or a crop). Without ``--rig`` the model is
made from the picture as it is: a prop, a weapon, a vehicle. With it the picture is first redrawn standing in a
T-pose, still holding what it holds (a figure caught in the middle of a move cannot be given a skeleton), then
modelled and rigged with Mixamo's bone names; ``--clips`` adds Tripo's own motions (idle, walk, run, dive, climb, jump, slash, shoot, hurt,
fall, turn), walk and run on the spot. Everything lands in BUILD/assets/tripo/NAME/ and what was made is printed
as JSON: {"model": the file for a page (GLTFLoader reads it), "clips": {name: file}, "credits": spent on this
build so far}. Made again with the same NAME, what is already there is kept and only the missing is paid for.
About 30 credits a model, 60 with a skeleton, 10 a clip. $TRIPO_API_KEY, or the file bench_builder.tripo_tools
names. The model is a guess from one picture: right from where the picture was taken, invented elsewhere, and
in whatever size and facing Tripo gave it: measure it where it is used.
"""

from __future__ import annotations

import argparse
import json
import sys
import time
from pathlib import Path

STANDING = ("the same character as in the reference picture, whole body in frame, standing upright in a T-pose seen from the front, legs slightly "
            "apart, arms straight out to the sides, still holding in the same hands whatever it holds in the reference picture (a weapon, a shield), "
            "plain light grey background, even studio light; keep its build, proportions, clothing, armour and colours exactly")


def ready() -> bool:
    from bench_builder import tripo_tools

    try:
        return tripo_tools.tripo_configured()
    except Exception:
        return False


def make(build: Path, name: str, picture: Path | None = None, text: str = "", rig: bool = False, clips: tuple[str, ...] = ()) -> dict:
    """The model, its clips and the credits spent; raises bench_builder.tripo_tools.TripoError where Tripo refuses."""
    from PIL import Image, ImageStat

    from bench_builder import tripo_tools

    service = tripo_tools.TripoService(build / ".splat", build); folder = build / "assets" / "tripo" / name; folder.mkdir(parents=True, exist_ok=True)

    def finished(started: dict, minutes: float = 15) -> dict:
        until = time.time() + 60 * minutes
        while True:
            got = service.wait([started["task_id"]], 240)["tasks"][started["task_id"]]
            if got["status"] == "success":
                return got | {"task_id": started["task_id"]}
            if got["status"] not in ("queued", "running") or time.time() > until:
                raise tripo_tools.TripoError(f"{got['status']} {got.get('error', '')}".strip())

    kind = "rig" if rig else "model"
    if (folder / f"{kind}.task.json").is_file() and (folder / f"{kind}.glb").is_file():
        made = json.loads((folder / f"{kind}.task.json").read_text())
    else:
        source = {"prompt": text}
        if picture is not None:
            # As a model maker wants a picture: the whole thing, square, on a plain ground, large, and not dark.
            cut = Image.open(picture).convert("RGBA"); side = round(1.2 * max(cut.size))
            ground = Image.new("RGBA", (side, side), (200, 200, 200, 255)); ground.alpha_composite(cut, ((side - cut.width) // 2, (side - cut.height) // 2))
            dark = ImageStat.Stat(cut.convert("L"), cut.getchannel("A")).mean[0]; shown = ground.convert("RGB").resize((1024, 1024), Image.LANCZOS)
            if dark < 90:
                shown = shown.point(lambda v: min(255, round(v * min(3.0, 110 / max(dark, 1)))))
            shown.save(folder / "reference.png"); source = {"image_path": f"assets/tripo/{name}/reference.png"}
            if rig:
                source = {"image_task_id": finished(service.concept_image(name, STANDING, f"assets/tripo/{name}/reference.png", ""))["task_id"]}
        made = finished(service.generate_model(name, **source))
        if rig:
            if not (finished(service.rig_check(made["task_id"])).get("output") or {}).get("riggable"):
                raise tripo_tools.TripoError("its model cannot be given a skeleton")
            made = finished(service.rig(name, made["task_id"]))
    for task in [service.animate(name, made["task_id"], clip, in_place=clip in ("walk", "run")) for clip in clips if not (folder / f"anim-{clip}.glb").is_file()]:
        finished(task)
    try:
        web = service.optimize(f"assets/tripo/{name}/{kind}.glb")["output"]
    except Exception:                                        # as it came, then: larger, and still a model
        web = f"assets/tripo/{name}/{kind}.glb"
    return {"model": web, "clips": {clip: f"assets/tripo/{name}/anim-{clip}.glb" for clip in clips if (folder / f"anim-{clip}.glb").is_file()},
            "credits": round(service.committed_credits())}


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("build", type=Path); parser.add_argument("name")
    parser.add_argument("--picture", type=Path); parser.add_argument("--text", default="")
    parser.add_argument("--rig", action="store_true"); parser.add_argument("--clips", nargs="*", default=[])
    args = parser.parse_args(argv)
    if (args.picture is None) == (not args.text):
        parser.error("give --picture or --text, one of them")
    if not ready():
        print("no Tripo key ($TRIPO_API_KEY)", file=sys.stderr); return 1
    build = args.build.resolve()
    print(json.dumps(make(build, args.name, (build / args.picture) if args.picture and not args.picture.is_absolute() else args.picture, args.text, args.rig, tuple(args.clips))))
    return 0


if __name__ == "__main__":
    sys.exit(main())