"""Image to 3D model, through the same local ComfyUI the sprites come from. Usage: python generate_mesh.py [name] [--octree=256] a PNG on disk - a clean render of one object, ideally on a plain or transparent background. What the sprite generator already produces, in other words. [name] what the GLB is called. Defaults to the image's own stem. --no-square send the image as it is (otherwise it is padded to a white square first, see `square`) Hunyuan3D v2 turns one picture into geometry: image -> CLIP vision -> a diffusion pass in a 3D latent -> voxels -> a mesh, saved as a GLB. It produces *shape only*. There is no texture, no material and no vertex colour, which matters when deciding what to do with the result - see the note in the TinyWorld GLB loader. Results land in the project's OUTPUT_DIR. The workflow is workflows/Image to 3D - Hunyuan3D.json in the API format the rest of this tool uses. Written out from the UI export in the same folder, because ComfyUI's /prompt endpoint takes the API format and the editor saves the other one. """ import json import os import random import sys import time import urllib.parse import urllib.request import uuid import _bootstrap # Projektordner (config.py, Listen) vor allen anderen Modulen import config CHECKPOINT = "hunyuan3d-dit-v2-0-fp16.safetensors" WORKFLOW = "Image to 3D - Hunyuan3D.json" def post_json(url, payload): data = json.dumps(payload).encode("utf-8") req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"}) with urllib.request.urlopen(req) as resp: return json.loads(resp.read().decode("utf-8")) def get_json(url): with urllib.request.urlopen(url) as resp: return json.loads(resp.read().decode("utf-8")) def upload_image(path): """Puts the file in ComfyUI's input folder and answers with its name there. Multipart by hand: this tool has no third-party dependencies and one boundary is cheaper than adding requests to the setup instructions. """ name = os.path.basename(path) boundary = uuid.uuid4().hex with open(path, "rb") as handle: blob = handle.read() parts = [] parts.append(f"--{boundary}\r\n".encode()) parts.append( f'Content-Disposition: form-data; name="image"; filename="{name}"\r\n'.encode()) parts.append(b"Content-Type: image/png\r\n\r\n") parts.append(blob) parts.append(f"\r\n--{boundary}\r\n".encode()) parts.append(b'Content-Disposition: form-data; name="overwrite"\r\n\r\n') parts.append(b"true") parts.append(f"\r\n--{boundary}--\r\n".encode()) body = b"".join(parts) req = urllib.request.Request( f"{config.HOST}/upload/image", data=body, headers={"Content-Type": f"multipart/form-data; boundary={boundary}"}) with urllib.request.urlopen(req) as resp: answer = json.loads(resp.read().decode("utf-8")) return answer.get("name", name) def square(path, margin=0.08): """Pads the picture to a square, object centred, on white. CLIPVisionEncode crops the centre square, so a portrait image lost its top and bottom (a gladiator's helmet and feet) and the shape came out squashed. Hunyuan3D was trained on objects filling ~85 % of a white square; with an alpha channel the transparent part becomes white too. """ from PIL import Image im = Image.open(path) if im.mode == "RGBA": bbox = im.getchannel("A").point(lambda a: 255 if a > 40 else 0).getbbox() or (0, 0) + im.size im = im.crop(bbox) flat = Image.new("RGB", im.size, (255, 255, 255)) flat.paste(im, mask=im.getchannel("A")) im = flat else: im = im.convert("RGB") side = round(max(im.size) / (1 - 2 * margin)) out = Image.new("RGB", (side, side), (255, 255, 255)) out.paste(im, ((side - im.width) // 2, (side - im.height) // 2)) dest = os.path.join(config.OUTPUT_DIR, "_mesh_input_" + os.path.splitext(os.path.basename(path))[0] + ".png") out.save(dest) return dest def build(image_name, name, seed, octree): path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "workflows", WORKFLOW) with open(path, "r", encoding="utf-8") as handle: text = handle.read() text = text.replace("{{CHECKPOINT}}", CHECKPOINT) text = text.replace("{{IMAGE}}", image_name.replace("\\", "\\\\").replace('"', '\\"')) text = text.replace("{{NAME}}", name) text = text.replace("{{SEED}}", str(seed)) text = text.replace("{{OCTREE}}", str(octree)) return json.loads(text) def queue_and_wait(name, workflow, timeout=1200): result = post_json(f"{config.HOST}/prompt", {"prompt": workflow}) if "error" in result: print(f"[{name}] SUBMIT ERROR: {json.dumps(result)[:800]}") return [] pid = result["prompt_id"] print(f"[{name}] queued as {pid}") start = time.time() while time.time() - start < timeout: history = get_json(f"{config.HOST}/history/{pid}") if pid in history: entry = history[pid] status = entry.get("status", {}) files = [] for node_out in entry.get("outputs", {}).values(): # SaveGLB reports under "3d" on some builds and "result" on # others; both carry the same {filename, subfolder, type}. for key in ("3d", "result", "images", "gltf"): for item in node_out.get(key, []) or []: if isinstance(item, dict) and "filename" in item: files.append(item) if files: return files if status.get("status_str") == "error": for kind, data in status.get("messages", []): if kind == "execution_error": print(f"[{name}] ERROR in {data.get('node_type')}: " f"{data.get('exception_message')}") return [] print(f"[{name}] ERROR: {json.dumps(status)[:600]}") return [] if status.get("completed"): print(f"[{name}] finished with nothing to download: " f"{json.dumps(entry)[:600]}") return [] time.sleep(3) print(f"[{name}] TIMEOUT") return [] def download(info, dest_dir): query = urllib.parse.urlencode({ "filename": info["filename"], "subfolder": info.get("subfolder", ""), "type": info.get("type", "output"), }) with urllib.request.urlopen(f"{config.HOST}/view?{query}") as resp: blob = resp.read() dest = os.path.join(dest_dir, os.path.basename(info["filename"])) with open(dest, "wb") as handle: handle.write(blob) return dest def main(): args = [a for a in sys.argv[1:] if not a.startswith("--")] flags = [a for a in sys.argv[1:] if a.startswith("--")] if not args: print(__doc__) return 1 source = args[0] if not os.path.isfile(source): print(f"no such image: {source}") return 1 name = args[1] if len(args) > 1 else os.path.splitext(os.path.basename(source))[0] octree = 256 for flag in flags: if flag.startswith("--octree="): octree = int(flag.split("=", 1)[1]) os.makedirs(config.OUTPUT_DIR, exist_ok=True) uploaded = upload_image(source if "--no-square" in flags else square(source)) print(f"[{name}] uploaded {uploaded}") workflow = build(uploaded, name, random.randint(1, 2 ** 32 - 1), octree) files = queue_and_wait(name, workflow) if not files: print(f"[{name}] FAILED") return 1 for info in files: print(f"[{name}] saved -> {download(info, config.OUTPUT_DIR)}") return 0 if __name__ == "__main__": raise SystemExit(main())