Download scripts/model.py from CharlieDreemur/Recreate-AAA: direct link, hf CLI and curl.
- Browser
- Download file 6.18 kB
-
https://huggingface.co/CharlieDreemur/Recreate-AAA/resolve/main/scripts/model.py
- Command line
-
hf download hf://CharlieDreemur/Recreate-AAA/scripts/model.py
-
curl -L -o model.py https://huggingface.co/CharlieDreemur/Recreate-AAA/resolve/main/scripts/model.py
6.18 kB
| """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()) | |