""" Atlas Legends sprite generator - talks directly to a local ComfyUI server. Usage: python generate.py generate every prompt in prompts_life.py python generate.py generate just one prompt by name python generate.py --list-models list installed checkpoints Setup: - Pick a checkpoint and workflow in config.py. - Add prompts to PROMPTS in prompts_life.py (name, positive_prompt) tuples. - Drop additional workflow templates into workflows/ - see README.md for the {{PLACEHOLDER}} convention they need to follow. Each run saves two PNGs per prompt into output/: "_raw_*" (untouched render) and "_cutout_*" (background removed via the workflow's Rembg node). If a cutout comes out wrong -- Rembg is an AI matting model and sometimes mis-segments stylized/glowing art -- run `cutout.py ` instead of re-rolling; it flood-fills the raw render's near-black backdrop deterministically. Review the results, then copy whichever ones you want into the game's assets/icons/... folders by hand. """ import importlib import json import os import random import sys import time import urllib.request import urllib.parse import _bootstrap # Projektordner (config.py, Listen) vor allen anderen Modulen import config prompts = importlib.import_module(getattr(config, "PROMPTS_MODULE", "prompts_life")) def load_workflow_template(): path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "workflows", config.WORKFLOW_FILE) with open(path, "r", encoding="utf-8") as f: return f.read() def escape_json_string(text): return text.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n") def build_workflow(name, positive_prompt, negative_prompt, seed): text = load_workflow_template() text = text.replace("{{CHECKPOINT}}", escape_json_string(getattr(config, "CHECKPOINT", ""))) text = text.replace("{{UNET}}", escape_json_string(getattr(config, "UNET_NAME", ""))) text = text.replace("{{CLIP}}", escape_json_string(getattr(config, "CLIP_NAME", ""))) text = text.replace("{{CLIP2}}", escape_json_string(getattr(config, "CLIP_NAME2", ""))) text = text.replace("{{CLIP_TYPE}}", escape_json_string(getattr(config, "CLIP_TYPE", ""))) text = text.replace("{{VAE}}", escape_json_string(getattr(config, "VAE_NAME", ""))) text = text.replace("{{POSITIVE}}", escape_json_string(positive_prompt)) text = text.replace("{{NEGATIVE}}", escape_json_string(negative_prompt)) text = text.replace("{{NAME}}", escape_json_string(name)) text = text.replace("{{SEED}}", str(seed)) return json.loads(text) 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 download_image(img_info, dest_dir): qs = urllib.parse.urlencode({ "filename": img_info["filename"], "subfolder": img_info.get("subfolder", ""), "type": img_info.get("type", "output"), }) url = f"{config.HOST}/view?{qs}" with urllib.request.urlopen(url) as resp: data = resp.read() dest = os.path.join(dest_dir, img_info["filename"]) with open(dest, "wb") as f: f.write(data) return dest def queue_and_wait(name, wf, timeout=600): result = post_json(f"{config.HOST}/prompt", {"prompt": wf}) if "error" in result: print(f"[{name}] SUBMIT ERROR: {result}") return [] pid = result["prompt_id"] print(f"[{name}] queued as {pid}") start = time.time() while time.time() - start < timeout: hist = get_json(f"{config.HOST}/history/{pid}") if pid in hist: entry = hist[pid] status = entry.get("status", {}) outputs = entry.get("outputs", {}) images = [img for node_out in outputs.values() for img in node_out.get("images", [])] if images: return images if status.get("status_str") == "error": for msg_type, msg_data in status.get("messages", []): if msg_type == "execution_error": print(f"[{name}] ERROR in {msg_data.get('node_type')}: {msg_data.get('exception_message')}") return [] print(f"[{name}] ERROR (no details): {json.dumps(status)[:500]}") return [] if status.get("completed"): print(f"[{name}] completed but no images in outputs: {json.dumps(entry)[:500]}") return [] time.sleep(2) print(f"[{name}] TIMEOUT") return [] def list_models(): data = get_json(f"{config.HOST}/object_info/CheckpointLoaderSimple") names = data["CheckpointLoaderSimple"]["input"]["required"]["ckpt_name"][0] print("Installed checkpoints:") for n in names: marker = " <- current (config.py)" if n == config.CHECKPOINT else "" print(f" {n}{marker}") def run_one(name, positive_prompt, negative_prompt=None): os.makedirs(config.OUTPUT_DIR, exist_ok=True) seed = random.randint(1, 2**32 - 1) wf = build_workflow(name, positive_prompt, negative_prompt or config.NEGATIVE_PROMPT, seed) images = queue_and_wait(name, wf) if not images: print(f"[{name}] FAILED") return for img_info in images: dest = download_image(img_info, config.OUTPUT_DIR) print(f"[{name}] saved -> {dest}") if __name__ == "__main__": arg = sys.argv[1] if len(sys.argv) > 1 else None if arg == "--list-models": list_models() sys.exit(0) everything = list(prompts.PROMPTS) + list(getattr(prompts, "BACKDROPS", [])) todo = [p for p in everything if (p[0] == arg if arg else p in prompts.PROMPTS)] if not todo: print(f"No prompt named '{arg}' in prompts_life.py" if arg else "prompts_life.py has no PROMPTS entries.") sys.exit(1) for entry in todo: name, positive = entry[0], entry[1] negative = entry[2] if len(entry) > 2 else None run_one(name, positive, negative)