From e7e3bcbbcb22227e1031c104c0da60769c115a28 Mon Sep 17 00:00:00 2001 From: Michi Date: Wed, 11 Nov 2026 15:52:32 +0100 Subject: [PATCH] add generate_variants: reference-based variants (e.g. attack poses) with Flux.2 Klein Co-Authored-By: Claude Opus 5.5 --- README.md | 9 ++- generate_variants.py | 146 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 152 insertions(+), 3 deletions(-) create mode 100644 generate_variants.py diff --git a/README.md b/README.md index deeabfb..cefae50 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ das aktuelle Verzeichnis oder `--project ` (siehe `_bootstrap.py`). |---|---|---|---| | `generate.py` / `adopt.py` / `cutout.py` | Sprites, Szenen, Karten | Flux.2 Klein (`workflows/`) | `PROMPTS_MODULE` | | `generate_portraits.py` | alternde Portraits | Flux.2 Klein + ReferenceLatent | `PORTRAITS_MODULE` | +| `generate_variants.py` | Varianten einer Render (Pose, Zustand) mit derselben Figur | Flux.2 Klein + ReferenceLatent | `VARIANTS_MODULE` (Standard `variants`) | | `generate_vintage.py` | Vintage-Elemente (Luma-Key) | Flux.2 Klein | `VINTAGE_MODULE` | | `generate_video.py` / `adopt_video.py` | Clips, Loops | Wan 2.2 I2V | `VIDEO_MODULE` | | `generate_audio.py` / `adopt_audio.py` | Musik, Effekte | Stable Audio 3 | `AUDIO_MODULE` | @@ -24,10 +25,12 @@ Projekt-`config.py`: - `PROMPTS_MODULE` (Standard `prompts`), `AUDIO_MODULE`, optional `AUDIO_SUBDIR` (Standard `audio`) - für `adopt*` / Portraits / Vintage `ASSETS_DIR`, für Stimmen `LANG_DIR` und `CARDS_FILE` -Jedes Projekt hat einen Starter `gen.cmd` (Vorlage: ein beliebiges Projekt kopieren), z. B. `gen generate `. +Jedes Projekt hat einen Starter `gen.cmd`, z. B. `gen generate `. +Neues Projekt: Inhalt von [`template/`](template/) (`gen.cmd`, `config.py`, `prompts.py`, `audio.py`) +in den Generator-Ordner des Projekts kopieren und `config.py` anpassen. Stimmen laufen in der gemeinsamen Umgebung `.venv-tts` (torch 2.6 für Chatterbox, ~6 GB, nicht in git). Neu anlegen: `py -3.12 -m venv .venv-tts`, dann torch 2.6 cu124, `chatterbox-tts`, `faster-whisper`, `kokoro`. -Genutzt von: YourlifeisGame (`Spritegenerator\`), AquaNova, AquaNovaAndroid, Atlas Legends, -TinyWold, XP-Battleship (je `sprite-generator\`). +Genutzt von: YourlifeisGame, GladiatorIdle (je `Spritegenerator\`), AquaNova, AquaNovaAndroid, +Atlas Legends, Boulder Bound, TinyWold, XP-Battleship (je `sprite-generator\`). diff --git a/generate_variants.py b/generate_variants.py new file mode 100644 index 0000000..e7abfea --- /dev/null +++ b/generate_variants.py @@ -0,0 +1,146 @@ +""" +Variants of an existing render with Flux.2 Klein + ReferenceLatent: same character / object, +new pose, expression or state (e.g. a sprite's attack pose from its idle pose). + +Project module (config.VARIANTS_MODULE, default "variants"): + VARIANTS = [(name, ref_name, prompt)] ref_name = a PROMPTS name already rendered to output/ + STYLE = "..." optional suffix appended to every prompt + +Usage (from the project's generator folder, or with --project): + py -3.12 generate_variants.py every variant that has no render yet + py -3.12 generate_variants.py hero_attack one variant (re-rolls if it exists) + py -3.12 generate_variants.py --force re-roll all + +Output: output/_raw_NNNNN_.png (newest render of ref_name is the reference), +so adopt.py / cutout.py work on variants exactly like on normal renders. +""" +import glob +import importlib +import json +import os +import random +import sys +import time +import urllib.parse +import urllib.request +import uuid + +import _bootstrap # noqa: F401 (project folder first on sys.path) +import config + +_m = importlib.import_module(getattr(config, "VARIANTS_MODULE", "variants")) +VARIANTS = _m.VARIANTS +STYLE = getattr(_m, "STYLE", "") +OUT = config.OUTPUT_DIR +SIZE = getattr(_m, "SIZE", (1024, 1024)) + +UNET = getattr(config, "UNET_NAME", "flux-2-klein-4b-fp8.safetensors") +CLIP = getattr(config, "CLIP_NAME", "qwen_3_4b.safetensors") +CLIP_TYPE = getattr(config, "CLIP_TYPE", "flux2") +VAE = getattr(config, "VAE_NAME", "flux2-vae.safetensors") + + +def _post(path, payload): + req = urllib.request.Request(config.HOST + path, data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req) as r: + return json.loads(r.read().decode()) + + +def _get(path): + with urllib.request.urlopen(config.HOST + path) as r: + return json.loads(r.read().decode()) + + +def _upload(path): + boundary = uuid.uuid4().hex + name = "cg_variant_ref_" + os.path.basename(path) + body = (f"--{boundary}\r\nContent-Disposition: form-data; name=\"overwrite\"\r\n\r\ntrue\r\n" + f"--{boundary}\r\nContent-Disposition: form-data; name=\"image\"; filename=\"{name}\"\r\n" + f"Content-Type: image/png\r\n\r\n").encode() + open(path, "rb").read() + f"\r\n--{boundary}--\r\n".encode() + req = urllib.request.Request(config.HOST + "/upload/image", data=body, + headers={"Content-Type": f"multipart/form-data; boundary={boundary}"}) + with urllib.request.urlopen(req) as r: + return json.loads(r.read().decode())["name"] + + +def _graph(prompt, seed, prefix, ref_image): + w, h = SIZE + g = { + "1": {"class_type": "UNETLoader", "inputs": {"unet_name": UNET, "weight_dtype": "default"}}, + "2": {"class_type": "CLIPLoader", "inputs": {"clip_name": CLIP, "type": CLIP_TYPE, "device": "default"}}, + "3": {"class_type": "VAELoader", "inputs": {"vae_name": VAE}}, + "4": {"class_type": "CLIPTextEncode", "inputs": {"text": prompt, "clip": ["2", 0]}}, + "7": {"class_type": "KSamplerSelect", "inputs": {"sampler_name": "euler"}}, + "8": {"class_type": "Flux2Scheduler", "inputs": {"width": w, "height": h, "steps": 4}}, + "9": {"class_type": "RandomNoise", "inputs": {"noise_seed": seed}}, + "10": {"class_type": "EmptyFlux2LatentImage", "inputs": {"width": w, "height": h, "batch_size": 1}}, + "12": {"class_type": "VAEDecode", "inputs": {"samples": ["11", 0], "vae": ["3", 0]}}, + "13": {"class_type": "SaveImage", "inputs": {"images": ["12", 0], "filename_prefix": prefix}}, + "20": {"class_type": "LoadImage", "inputs": {"image": ref_image}}, + "21": {"class_type": "ImageScaleToTotalPixels", "inputs": {"image": ["20", 0], "upscale_method": "lanczos", + "megapixels": 1.0, "resolution_steps": 16}}, + "22": {"class_type": "VAEEncode", "inputs": {"pixels": ["21", 0], "vae": ["3", 0]}}, + "23": {"class_type": "ReferenceLatent", "inputs": {"conditioning": ["4", 0], "latent": ["22", 0]}}, + } + g["5"] = {"class_type": "ConditioningZeroOut", "inputs": {"conditioning": ["23", 0]}} + g["6"] = {"class_type": "CFGGuider", "inputs": {"model": ["1", 0], "positive": ["23", 0], + "negative": ["5", 0], "cfg": 1}} + g["11"] = {"class_type": "SamplerCustomAdvanced", "inputs": {"noise": ["9", 0], "guider": ["6", 0], + "sampler": ["7", 0], "sigmas": ["8", 0], + "latent_image": ["10", 0]}} + return g + + +def _newest(pattern): + files = sorted(glob.glob(os.path.join(OUT, pattern)), key=os.path.getmtime) + return files[-1] if files else None + + +def _next_index(name): + n = 0 + for f in glob.glob(os.path.join(OUT, f"{name}_raw_*.png")): + try: + n = max(n, int(os.path.basename(f).split("_raw_")[1].split("_")[0])) + except (IndexError, ValueError): + pass + return n + 1 + + +def run(name, ref_name, prompt): + ref = _newest(f"{ref_name}_raw_*.png") + if not ref: + print(f"[{name}] no render of reference '{ref_name}' in output/ - run generate first") + return False + full = f"{prompt}, {STYLE}" if STYLE else prompt + pid = _post("/prompt", {"prompt": _graph(full, random.randint(1, 2**31), "cg_variants/v", _upload(ref))})["prompt_id"] + while True: + time.sleep(1.0) + h = _get(f"/history/{pid}") + if pid in h: + st = h[pid].get("status", {}) + if st.get("status_str") == "error": + raise RuntimeError(json.dumps(st)[:1500]) + if st.get("completed"): + break + for node in h[pid]["outputs"].values(): + for info in node.get("images", []): + qs = urllib.parse.urlencode({"filename": info["filename"], "subfolder": info.get("subfolder", ""), + "type": info.get("type", "output")}) + dest = os.path.join(OUT, f"{name}_raw_{_next_index(name):05d}_.png") + urllib.request.urlretrieve(f"{config.HOST}/view?{qs}", dest) + print(f"[{name}] saved -> {dest} (ref {os.path.basename(ref)})", flush=True) + return True + return False + + +if __name__ == "__main__": + os.makedirs(OUT, exist_ok=True) + args = [a for a in sys.argv[1:] if not a.startswith("--") and not os.path.isdir(a)] + force = "--force" in sys.argv + for name, ref_name, prompt in VARIANTS: + if args and name not in args: + continue + if not args and not force and _newest(f"{name}_raw_*.png"): + continue + run(name, ref_name, prompt)