commit e3d21e55c903d085c1f5c13bc584437d1a622018 Author: Michi Date: Fri Oct 2 09:41:31 2026 +0200 ComfyGen: shared generator tools (images, portraits, vintage, video, audio, voice) Moved from YourlifeisGame/Spritegenerator; projects are found via _bootstrap.py (cwd or --project) and provide config.py plus list modules. Co-Authored-By: Claude Opus 5.5 (1M context) diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0fe8306 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.venv-tts/ +__pycache__/ +*.pyc diff --git a/README.md b/README.md new file mode 100644 index 0000000..5230045 --- /dev/null +++ b/README.md @@ -0,0 +1,23 @@ +# ComfyGen – gemeinsame Generator-Werkzeuge + +Erzeugt Bilder, Videos, Klänge und Stimmen für Spiele lokal über ComfyUI (127.0.0.1:8188). +Ein **Projekt** ist ein Ordner mit `config.py` und Listen-Modulen; die Werkzeuge finden es über +das aktuelle Verzeichnis oder `--project ` (siehe `_bootstrap.py`). + +| Werkzeug | Erzeugt | Modell | Projektdaten | +|---|---|---|---| +| `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_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` | +| `generate_voice.py` | Erzählstimme mit Whisper-Prüfung | Chatterbox (+ Kokoro-Referenzen) | `VOICE_MODULE`, `LANG_DIR`, `CARDS_FILE` | +| `make_voice_refs.py` | Referenzstimmen in `voice_refs/` | Kokoro | – | + +Benötigte Pfade in der Projekt-`config.py`: `OUTPUT_DIR`, `ASSETS_DIR`, für Stimmen `LANG_DIR`, `CARDS_FILE`. + +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`. + +Projekte, die schon umgestellt sind: YourlifeisGame. Ältere Projekte (AquaNova, TinyWold, …) haben noch +eigene Kopien in ihrem `sprite-generator` und können einzeln umziehen. diff --git a/_bootstrap.py b/_bootstrap.py new file mode 100644 index 0000000..e96a1c4 --- /dev/null +++ b/_bootstrap.py @@ -0,0 +1,21 @@ +""" +Projektordner finden, bevor ein ComfyGen-Werkzeug etwas importiert. + +Ein Projekt ist ein Ordner mit config.py (Pfade, Modelle) und den Listen des Spiels +(prompts_*.py, audio_*.py, video_*.py, portraits_*.py, vintage_*.py, voice_*.py). +Gesucht wird: --project , sonst das aktuelle Verzeichnis. +""" +import os +import sys + +TOOLS_DIR = os.path.dirname(os.path.abspath(__file__)) +PROJECT_DIR = os.getcwd() +if "--project" in sys.argv: + i = sys.argv.index("--project") + PROJECT_DIR = os.path.abspath(sys.argv[i + 1]) + del sys.argv[i:i + 2] +if not os.path.isfile(os.path.join(PROJECT_DIR, "config.py")): + sys.exit(f"ComfyGen: kein Projekt in {PROJECT_DIR} (dort fehlt config.py). " + f"Im Generator-Ordner des Projekts starten oder --project angeben.") +if PROJECT_DIR not in sys.path: + sys.path.insert(0, PROJECT_DIR) diff --git a/adopt.py b/adopt.py new file mode 100644 index 0000000..a622528 --- /dev/null +++ b/adopt.py @@ -0,0 +1,85 @@ +"""Take a generated sprite into the game. + +Finds the newest raw render for , keys out the black backdrop +(cutout.py), trims the transparent margin, pads to a square and scales to +SIZE px, then writes ../Assets/Sprites/.png. The game draws sprites with +PictureBoxSizeMode.Zoom, so square keeps every icon the same visual size. + + py -3.12 adopt.py stat_health one sprite + py -3.12 adopt.py stat_health life_baby several + py -3.12 adopt.py --all every name in the prompt list +""" +import glob +import importlib +import os +import sys + +from PIL import Image + +import _bootstrap # Projektordner (config.py, Listen) vor allen anderen Modulen +import config +from cutout import cutout + +HERE = os.path.dirname(os.path.abspath(__file__)) +DEST = os.path.join(config.ASSETS_DIR, "Sprites") +SIZE = 128 +MARGIN = 0.04 # share of the side left free around the icon +ALPHA_THRESHOLD = 8 + + +def adopt(name): + raws = sorted(glob.glob(os.path.join(config.OUTPUT_DIR, f"{name}_raw_*.png")), + key=os.path.getmtime) + if not raws: + print(f" {name}: no raw render in output/, skipped") + return False + + image = cutout(raws[-1]) + box = image.getchannel("A").point(lambda v: 255 if v > ALPHA_THRESHOLD else 0).getbbox() + if box is None: + print(f" {name}: fully transparent after cutout, skipped") + return False + image = image.crop(box) + + side = int(max(image.size) * (1 + 2 * MARGIN)) + square = Image.new("RGBA", (side, side), (0, 0, 0, 0)) + square.paste(image, ((side - image.width) // 2, (side - image.height) // 2)) + square = square.resize((SIZE, SIZE), Image.LANCZOS) + + os.makedirs(DEST, exist_ok=True) + dest = os.path.join(DEST, f"{name}.png") + square.save(dest, optimize=True) + print(f" {name:18s} {os.path.basename(raws[-1])} -> Assets/Sprites/{name}.png") + return True + + +def adopt_backdrop(name, width=1920, height=1080): + """Full-screen picture: no cutout, cover-crop to 16:9, saved as JPEG.""" + raws = sorted(glob.glob(os.path.join(config.OUTPUT_DIR, f"{name}_raw_*.png")), + key=os.path.getmtime) + if not raws: + print(f" {name}: no raw render in output/, skipped") + return False + image = Image.open(raws[-1]).convert("RGB") + scale = max(width / image.width, height / image.height) + image = image.resize((round(image.width * scale), round(image.height * scale)), Image.LANCZOS) + left, top = (image.width - width) // 2, (image.height - height) // 2 + image = image.crop((left, top, left + width, top + height)) + dest = os.path.join(DEST, f"{name}.jpg") + image.save(dest, quality=88, optimize=True) + print(f" {name:18s} {os.path.basename(raws[-1])} -> Assets/Sprites/{name}.jpg") + return True + + +if __name__ == "__main__": + args = sys.argv[1:] + if not args: + print(__doc__) + sys.exit(1) + if args[0] == "--backdrop": + sys.exit(0 if all(adopt_backdrop(n) for n in args[1:]) else 1) + if args == ["--all"]: + prompts = importlib.import_module(getattr(config, "PROMPTS_MODULE", "prompts_life")) + args = [p[0] for p in prompts.PROMPTS] + ok = sum(adopt(n) for n in args) + print(f"{ok}/{len(args)} adopted") diff --git a/adopt_audio.py b/adopt_audio.py new file mode 100644 index 0000000..3818cde --- /dev/null +++ b/adopt_audio.py @@ -0,0 +1,88 @@ +"""Take generated audio into the game: ../Assets/Audio/.mp3. + +Per clip: newest roll from output/audio, trailing silence cut (Stable Audio +pads every short clip to its full length), soft fades on music so a loop seam +is a dip rather than a click, then one gain to a peak that depends on the kind +of sound - a button click must sit well under an event chime, and both under +the music never. + + py -3.12 adopt_audio.py sfx_click one clip + py -3.12 adopt_audio.py --all every clip in the list +""" +import glob +import importlib +import os +import re +import subprocess +import sys + +import _bootstrap # Projektordner (config.py, Listen) vor allen anderen Modulen +import config + +HERE = os.path.dirname(os.path.abspath(__file__)) +SRC = os.path.join(config.OUTPUT_DIR, "audio") +DEST = os.path.join(config.ASSETS_DIR, "Audio") + +QUIET = {"sfx_click": -14.0, "sfx_tick": -16.0, "sfx_pop": -10.0, + "sfx_tip": -10.0, "sfx_choice": -9.0} +MUSIC_PEAK = -4.0 +SFX_PEAK = -4.0 + + +def peak_of(path, filters=""): + args = ["ffmpeg", "-hide_banner", "-i", path] + af = (filters + "," if filters else "") + "volumedetect" + run = subprocess.run(args + ["-af", af, "-f", "null", "-"], capture_output=True, text=True) + hit = re.search(r"max_volume:\s*(-?[\d.]+) dB", run.stderr) + return float(hit.group(1)) if hit else None + + +def duration_of(path): + run = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", + "-of", "default=nw=1:nk=1", path], capture_output=True, text=True) + return float(run.stdout.strip() or 0) + + +def adopt(name): + rolls = sorted(glob.glob(os.path.join(SRC, f"{name}_*.mp3")), key=os.path.getmtime) + rolls = [r for r in rolls if not r.endswith("_levelled.mp3")] + if not rolls: + print(f" {name}: no roll in output/audio, skipped") + return False + src = rolls[-1] + + if name.startswith("music_"): + length = duration_of(src) + shape = f"afade=t=in:d=1.5,afade=t=out:st={max(0.0, length - 2.5):.2f}:d=2.5" + target = MUSIC_PEAK + else: + # cut the silent tail: reverse, drop leading silence, reverse back + shape = ("areverse,silenceremove=start_periods=1:start_threshold=-50dB:start_silence=0.05," + "areverse") + target = QUIET.get(name, SFX_PEAK) + + top = peak_of(src, shape) + if top is None: + print(f" {name}: could not be measured, skipped") + return False + gain = target - top + + os.makedirs(DEST, exist_ok=True) + dest = os.path.join(DEST, f"{name}.mp3") + subprocess.run(["ffmpeg", "-hide_banner", "-loglevel", "error", "-y", "-i", src, + "-af", f"{shape},volume={gain:.2f}dB", "-ar", "44100", + "-codec:a", "libmp3lame", "-q:a", "3", dest], check=True) + print(f" {name:16s} {os.path.basename(src)} peak {top:6.1f} -> {target:5.1f} dB" + f" {duration_of(dest):5.1f}s") + return True + + +if __name__ == "__main__": + args = sys.argv[1:] + if not args: + print(__doc__) + sys.exit(1) + if args == ["--all"]: + args = [c[0] for c in importlib.import_module(config.AUDIO_MODULE).CLIPS] + ok = sum(adopt(n) for n in args) + print(f"{ok}/{len(args)} adopted") diff --git a/adopt_video.py b/adopt_video.py new file mode 100644 index 0000000..0e00bec --- /dev/null +++ b/adopt_video.py @@ -0,0 +1,103 @@ +""" +Copies rendered intro clips (output/video//frame_*.png) into the game as +Assets/Video/_NN.jpg. The vignette the intro used to paint over the stills +is baked in here, so the game only has to scale one small frame per tick. + +Wan renders 49 frames (~3 s at 16 fps) but a chapter lasts 5 s, so one in-between +frame is synthesised for every pair via bidirectional optical flow (OpenCV +Farneback): 97 frames, ~19 fps on screen instead of a choppy ~10. + +Sidebar scenes (scene_*) are a slow loop in the game's left column instead: no +vignette and no in-between frames, but the same darkening towards the bottom the +still image had (MainForm.SceneBitmap), so it blends into the dark column. + +Usage: + py -3.12 adopt_video.py every clip that has frames + py -3.12 adopt_video.py story_old just one +""" +import glob +import os +import sys + +import cv2 +import numpy as np +from PIL import Image, ImageDraw, ImageFilter + +import _bootstrap # Projektordner (config.py, Listen) vor allen anderen Modulen +import config + +SRC = os.path.join(config.OUTPUT_DIR, "video") +DEST = os.path.join(config.ASSETS_DIR, "Video") +QUALITY = 80 + + +def vignette(size): + """Same shape as IntroForm.BuildScene: ellipse, clear centre, 170/255 black at the edge.""" + w, h = size + k = 4 # draw at 1/4 size, blur, scale up: smooth radial falloff + m = Image.new("L", (w // k, h // k), 170) + d = ImageDraw.Draw(m) + d.ellipse((-w * 0.2 / k, -h * 0.3 / k, w * 1.2 / k, h * 1.3 / k), fill=0) + m = m.filter(ImageFilter.GaussianBlur(w / k * 0.12)).resize((w, h), Image.BILINEAR) + return m + + +def bottom_shade(size): + """Top clear → bottom 120/255 of (10,12,26), like MainForm.SceneBitmap.""" + w, h = size + return Image.linear_gradient("L").resize((w, h)).point(lambda v: v * 120 // 255) + + +def _warp(img, flow): + h, w = flow.shape[:2] + gx, gy = np.meshgrid(np.arange(w, dtype=np.float32), np.arange(h, dtype=np.float32)) + return cv2.remap(img, gx + flow[..., 0], gy + flow[..., 1], cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE) + + +def midframe(a, b): + """Frame halfway between a and b (RGB uint8 arrays).""" + ga, gb = cv2.cvtColor(a, cv2.COLOR_RGB2GRAY), cv2.cvtColor(b, cv2.COLOR_RGB2GRAY) + args = (None, 0.5, 4, 21, 3, 5, 1.1, 0) + fab = cv2.calcOpticalFlowFarneback(ga, gb, *args) + fba = cv2.calcOpticalFlowFarneback(gb, ga, *args) + # the pixel at x in the middle frame came from x - fab/2 in a and x - fba/2 in b + wa = _warp(a, -0.5 * fab) + wb = _warp(b, -0.5 * fba) + return cv2.addWeighted(wa, 0.5, wb, 0.5, 0) + + +def interpolate(frames): + out = [] + for a, b in zip(frames, frames[1:]): + out += [a, midframe(a, b)] + return out + [frames[-1]] + + +def adopt(name): + frames = sorted(glob.glob(os.path.join(SRC, name, "frame_*.png"))) + if not frames: + print(f"{name}: no frames"); return + os.makedirs(DEST, exist_ok=True) + for old in glob.glob(os.path.join(DEST, f"{name}_*.jpg")): + os.remove(old) + raw = [np.asarray(Image.open(f).convert("RGB")) for f in frames] + scene = name.startswith("scene_") + if not scene: + raw = interpolate(raw) + size = (raw[0].shape[1], raw[0].shape[0]) + mask = bottom_shade(size) if scene else vignette(size) + black = Image.new("RGB", size, (10, 12, 26) if scene else (0, 0, 0)) + total = 0 + for i, arr in enumerate(raw): + im = Image.composite(black, Image.fromarray(arr), mask) + p = os.path.join(DEST, f"{name}_{i:02d}.jpg") + im.save(p, quality=QUALITY, optimize=True) + total += os.path.getsize(p) + print(f"{name}: {len(frames)} -> {len(raw)} frames, {total / 1e6:.1f} MB") + + +if __name__ == "__main__": + names = sys.argv[1:] or sorted(os.listdir(SRC)) + for n in names: + if os.path.isdir(os.path.join(SRC, n)): + adopt(n) diff --git a/cutout.py b/cutout.py new file mode 100644 index 0000000..bd4673b --- /dev/null +++ b/cutout.py @@ -0,0 +1,110 @@ +""" +Deterministic background removal for the generator's raw renders -- +a replacement for the "Image Rembg (Remove Background)" node in the +ComfyUI workflow (see generate.py), which is an AI matting model and +sometimes badly mis-segments stylized/glowing game-art: leaves the backdrop +solid instead of transparent, eats holes into light-colored subjects, etc. +(e.g. output/ship_phantom_cutout_00001_.png shipped with its black backdrop +still fully opaque). + +Every raw render sits on a plain solid black backdrop by design (see the +"plain solid black background" suffix in prompts.py, added specifically so +the background can be keyed out reliably) -- so instead of trusting a model +to guess the subject silhouette, this flood-fills the near-black region +connected to the image border (the backdrop, and only the backdrop -- a +sprite's own interior black shading isn't connected to the border) and +clears it to alpha 0, feathering a soft edge for glow/anti-aliasing that +fades into black rather than cutting it off hard. + +Usage: + python cutout.py # every *_raw_*.png in output/ + python cutout.py ship_phantom # only output/ship_phantom_raw_*.png + python cutout.py aq_menu_lock --holes + +`--holes` also clears black the subject *encloses*: the inside of a padlock's +shackle, the middle of an anchor's ring, the gap under a rock arch. The flood +fill only reaches black that touches the frame's edge, so those stayed opaque - +a black blob drawn over whatever the sprite stands on. Opt-in rather than the +default because a large deliberately-black detail (a cave mouth, a big pupil) +is indistinguishable from a hole by colour alone; say so per sprite. +""" +import _bootstrap # Projektordner (config.py, Listen) vor allen anderen Modulen +import config +import glob +import os +import sys + +import numpy as np +from PIL import Image +from scipy import ndimage + +OUT_DIR = config.OUTPUT_DIR + +BLACK_THRESHOLD = 20 # max(R,G,B) below this = definitely background +FEATHER_RANGE = 40 # brightness range over which the edge ring fades in + +# An enclosed black region at least this share of the frame is a hole the +# background shows through, not a detail. A pupil on a 1024 render is a few +# hundred pixels; the inside of a padlock's shackle is tens of thousands. +HOLE_SHARE = 0.0015 + + +def cutout(path, holes=False, share=HOLE_SHARE): + im = Image.open(path).convert("RGBA") + arr = np.asarray(im).astype(np.int16) + rgb = arr[:, :, :3] + brightness = rgb.max(axis=2) + + near_black = brightness <= BLACK_THRESHOLD + labels, _ = ndimage.label(near_black, structure=np.ones((3, 3))) # 8-connected + border_labels = set(labels[0, :]) | set(labels[-1, :]) | set(labels[:, 0]) | set(labels[:, -1]) + border_labels.discard(0) + background = np.isin(labels, list(border_labels)) + + if holes: + # Every near-black region, counted in one pass, and the large ones that + # do not touch the edge added to the background. Sizes by bincount + # rather than a mask per label: a render has thousands of tiny dark + # specks and one comparison over the whole frame each is minutes. + sizes = np.bincount(labels.ravel()) + least = share * near_black.size + enclosed = [label for label in np.nonzero(sizes >= least)[0] + if label != 0 and label not in border_labels] + if enclosed: + background |= np.isin(labels, enclosed) + + alpha = arr[:, :, 3].copy() + alpha[background] = 0 + + # feather the ring of foreground pixels touching the backdrop, so a + # glowing edge that anti-aliases into black doesn't get a hard fringe + dilated = ndimage.binary_dilation(background, iterations=1) + edge_ring = dilated & ~background + feather = np.clip((brightness - BLACK_THRESHOLD) / FEATHER_RANGE * 255, 0, 255).astype(np.uint8) + alpha[edge_ring] = np.minimum(alpha[edge_ring], feather[edge_ring]) + + out = arr.copy() + out[:, :, 3] = alpha + return Image.fromarray(out.astype(np.uint8), "RGBA") + + +if __name__ == "__main__": + # Flags apart from the name, so `--holes` works on either side of it. + flags = {arg for arg in sys.argv[1:] if arg.startswith("--")} + names = [arg for arg in sys.argv[1:] if not arg.startswith("--")] + only = names[0] if names else None + # `--holes=0.006` raises the bar for one sprite whose pupil is bigger than + # HOLE_SHARE: the seahorse's eye went transparent with its tail's loop. + sized = [flag for flag in flags if flag.startswith("--holes=")] + holes = "--holes" in flags or bool(sized) + share = float(sized[0].split("=", 1)[1]) if sized else HOLE_SHARE + + pattern = f"{only}_raw_*.png" if only else "*_raw_*.png" + raws = sorted(glob.glob(os.path.join(OUT_DIR, pattern))) + if not raws: + print(f"No raw renders found matching {pattern} in {OUT_DIR}") + sys.exit(1) + for raw_path in raws: + dest = raw_path.replace("_raw_", "_cutout_") + cutout(raw_path, holes=holes, share=share).save(dest) + print(f"-> {dest}" + (" (enclosed holes cleared)" if holes else "")) diff --git a/generate.py b/generate.py new file mode 100644 index 0000000..6051f42 --- /dev/null +++ b/generate.py @@ -0,0 +1,159 @@ +""" +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) diff --git a/generate_audio.py b/generate_audio.py new file mode 100644 index 0000000..8f3e58e --- /dev/null +++ b/generate_audio.py @@ -0,0 +1,122 @@ +# Music + SFX generation via ComfyUI's Stable Audio pipeline (checkpoint +# stable_audio_3_medium_base.safetensors). Same server as generate.py. +# Results land in output/audio/. Usage: +# python generate_audio.py # everything in audio_life.py +# python generate_audio.py sfx_click # single entry +import json +import os +import random +import sys +import time +import urllib.parse +import urllib.request + +import _bootstrap # Projektordner (config.py, Listen) vor allen anderen Modulen +import config + +HOST = "http://127.0.0.1:8188" +OUT_DIR = os.path.join(config.OUTPUT_DIR, "audio") +CLIP_NAME = "t5gemma_b_b_ul2.safetensors" + +import importlib + + +# Die Clip-Liste dieses Spiels: (name, prompt, seconds, negative) — siehe audio_life.py +CLIPS = importlib.import_module(getattr(config, "AUDIO_MODULE", "audio_life")).CLIPS + + +def build_graph(name, positive, negative, seconds, seed): + return { + "1": {"class_type": "CheckpointLoaderSimple", + "inputs": {"ckpt_name": "stable_audio_3_medium_base.safetensors"}}, + "1c": {"class_type": "CLIPLoader", + "inputs": {"clip_name": CLIP_NAME, "type": "stable_audio"}}, + "2": {"class_type": "CLIPTextEncode", + "inputs": {"text": positive, "clip": ["1c", 0]}}, + "3": {"class_type": "CLIPTextEncode", + "inputs": {"text": negative, "clip": ["1c", 0]}}, + "4": {"class_type": "ConditioningStableAudio", + "inputs": {"positive": ["2", 0], "negative": ["3", 0], + "seconds_start": 0.0, "seconds_total": seconds}}, + "5": {"class_type": "EmptyLatentAudio", + "inputs": {"seconds": seconds, "batch_size": 1}}, + "6": {"class_type": "KSampler", + "inputs": {"model": ["1", 0], "positive": ["4", 0], "negative": ["4", 1], + "latent_image": ["5", 0], "seed": seed, "steps": 50, + "cfg": 5.0, "sampler_name": "dpmpp_3m_sde", + "scheduler": "exponential", "denoise": 1.0}}, + "7": {"class_type": "VAEDecodeAudio", + "inputs": {"samples": ["6", 0], "vae": ["1", 2]}}, + "8": {"class_type": "SaveAudioMP3", + "inputs": {"audio": ["7", 0], "filename_prefix": f"audio/{name}", + "quality": "320k"}}, + } + + +def submit(graph): + req = urllib.request.Request( + f"{HOST}/prompt", + data=json.dumps({"prompt": graph}).encode(), + headers={"Content-Type": "application/json"}) + try: + with urllib.request.urlopen(req) as res: + return json.load(res)["prompt_id"] + except urllib.error.HTTPError as error: + # ComfyUI answers a bad graph with 400 and a body naming the node and + # the field it did not like. Without printing it, every mistake in here + # looks the same: "HTTP Error 400: Bad Request" and nothing to go on. + body = error.read().decode("utf-8", "replace") + print(f" rejected by ComfyUI: {body[:2000]}", flush=True) + raise + + +def wait_for(prompt_id, timeout=900): + start = time.time() + while time.time() - start < timeout: + with urllib.request.urlopen(f"{HOST}/history/{prompt_id}") as res: + hist = json.load(res) + if prompt_id in hist: + entry = hist[prompt_id] + status = entry.get("status", {}) + if status.get("status_str") == "error": + for m in status.get("messages", []): + if m[0] == "execution_error": + raise RuntimeError(f"{m[1].get('node_type')}: {m[1].get('exception_message', '')[:400]}") + raise RuntimeError("execution error") + if status.get("completed") or entry.get("outputs"): + return entry["outputs"] + time.sleep(3) + raise TimeoutError(prompt_id) + + +def download(outputs): + os.makedirs(OUT_DIR, exist_ok=True) + saved = [] + for node_output in outputs.values(): + for audio in node_output.get("audio", []): + params = urllib.parse.urlencode({ + "filename": audio["filename"], + "subfolder": audio.get("subfolder", ""), + "type": audio.get("type", "output"), + }) + dest = os.path.join(OUT_DIR, audio["filename"].split("/")[-1]) + with urllib.request.urlopen(f"{HOST}/view?{params}") as res, open(dest, "wb") as f: + f.write(res.read()) + saved.append(dest) + return saved + + +if __name__ == "__main__": + only = set(sys.argv[1:]) + for name, positive, seconds, negative in CLIPS: + if only and name not in only: + continue + seed = random.randint(0, 2**32 - 1) + print(f"[{name}] queueing ({seconds:.0f}s, seed {seed})...", flush=True) + pid = submit(build_graph(name, positive, negative, seconds, seed)) + outputs = wait_for(pid) + for path in download(outputs): + print(f"[{name}] saved -> {path}", flush=True) + + + diff --git a/generate_portraits.py b/generate_portraits.py new file mode 100644 index 0000000..ebee8e1 --- /dev/null +++ b/generate_portraits.py @@ -0,0 +1,169 @@ +""" +Player portraits that age through a life: 3 genders x 3 looks x 6 age stages. + +For every identity the adult portrait is painted first (Flux.2 Klein, text to image); +the other stages are edits of that adult picture (Flux.2 Klein with ReferenceLatent), +so it stays recognisably the same face from baby to old age. + + py -3.12 generate_portraits.py everything (skips what exists) + py -3.12 generate_portraits.py m1 one identity (all stages) + py -3.12 generate_portraits.py m1 --force redo it + py -3.12 generate_portraits.py --adopt copy into ../Assets/Sprites (512x512 jpg) + py -3.12 generate_portraits.py --sheet out.jpg contact sheet for checking + +Files: output/portraits/_.png -> Assets/Sprites/portrait___.jpg +""" +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 + +HERE = os.path.dirname(os.path.abspath(__file__)) +OUT = os.path.join(config.OUTPUT_DIR, "portraits") +DEST = os.path.join(config.ASSETS_DIR, "Sprites") + +UNET, CLIP, CLIP_TYPE, VAE = "flux-2-klein-4b-fp8.safetensors", "qwen_3_4b.safetensors", "flux2", "flux2-vae.safetensors" + +# Projektdaten (Stil, Looks, Altersstufen) aus dem Projekt: config.PORTRAITS_MODULE +import importlib as _il +_d = _il.import_module(getattr(config, "PORTRAITS_MODULE", "portraits_life")) +STYLE, LOOKS, STAGES, ORDER = _d.STYLE, _d.LOOKS, _d.STAGES, _d.ORDER + + +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 = "yl_portrait_" + 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=None): + 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": 1024, "height": 1024, "steps": 4}}, + "9": {"class_type": "RandomNoise", "inputs": {"noise_seed": seed}}, + "10": {"class_type": "EmptyFlux2LatentImage", "inputs": {"width": 1024, "height": 1024, "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}}, + } + pos = ["4", 0] + if ref_image: + g["20"] = {"class_type": "LoadImage", "inputs": {"image": ref_image}} + g["21"] = {"class_type": "ImageScaleToTotalPixels", "inputs": {"image": ["20", 0], "upscale_method": "lanczos", "megapixels": 1.0, "resolution_steps": 16}} + g["22"] = {"class_type": "VAEEncode", "inputs": {"pixels": ["21", 0], "vae": ["3", 0]}} + g["23"] = {"class_type": "ReferenceLatent", "inputs": {"conditioning": ["4", 0], "latent": ["22", 0]}} + pos = ["23", 0] + g["5"] = {"class_type": "ConditioningZeroOut", "inputs": {"conditioning": pos}} + g["6"] = {"class_type": "CFGGuider", "inputs": {"model": ["1", 0], "positive": pos, "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 run(prompt, dest, ref=None): + seed = random.randint(1, 2**31) + ref_name = upload(ref) if ref else None + pid = post("/prompt", {"prompt": graph(prompt, seed, "yl_portraits/p", ref_name)})["prompt_id"] + while True: + time.sleep(1.5) + 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")}) + urllib.request.urlretrieve(f"{config.HOST}/view?{qs}", dest) + return + + +def make(ident, force=False): + os.makedirs(OUT, exist_ok=True) + adult = os.path.join(OUT, f"{ident}_adult.png") + for stage in ORDER: + dest = os.path.join(OUT, f"{ident}_{stage}.png") + if os.path.exists(dest) and (not force or (stage == "adult" and KEEP_ADULT)): + continue + t0 = time.time() + if stage == "adult": + run(f"{LOOKS[ident]}, a mature adult about thirty-five years old with an adult face" + f"{', light stubble' if ident.startswith('m') else ''}, {STYLE}", dest) + else: + # die Beschreibung der Person ausdrücklich mitgeben: ohne sie wurde dunkle Haut bei + # Baby/Kind/Teen oft hell — es muss über das ganze Leben dieselbe Person bleiben + run(f"the same person from the reference image {STAGES[stage]}. The person is {LOOKS[ident]}. " + f"Keep exactly the same skin tone and ethnicity, the same face, the same eye colour and the same " + f"hair colour and texture, same clothing colours, same pose and framing, {STYLE}", + dest, ref=adult) + print(f"{ident} {stage:6s} {time.time() - t0:5.1f} s", flush=True) + + +def adopt(): + from PIL import Image + for ident in LOOKS: + g, look = ident[0], ident[1] + for stage in ORDER: + src = os.path.join(OUT, f"{ident}_{stage}.png") + if not os.path.exists(src): + continue + Image.open(src).convert("RGB").resize((512, 512), Image.LANCZOS).save( + os.path.join(DEST, f"portrait_{g}_{look}_{stage}.jpg"), quality=88, optimize=True) + print("adopted") + + +def sheet(path): + from PIL import Image, ImageDraw + c = 180 + im = Image.new("RGB", (c * len(ORDER), (c + 16) * len(LOOKS)), (24, 26, 40)) + d = ImageDraw.Draw(im) + for r, ident in enumerate(LOOKS): + for k, stage in enumerate(ORDER): + f = os.path.join(OUT, f"{ident}_{stage}.png") + if os.path.exists(f): + im.paste(Image.open(f).convert("RGB").resize((c, c)), (k * c, r * (c + 16))) + d.text((k * c + 4, r * (c + 16) + c + 2), f"{ident} {stage}", fill=(220, 220, 230)) + im.save(path, quality=88) + + +KEEP_ADULT = "--keep-adult" in sys.argv # --force, aber das Erwachsenenbild (Referenz) behalten + +if __name__ == "__main__": + a = sys.argv[1:] + if "--adopt" in a: + adopt() + elif "--sheet" in a: + sheet(a[a.index("--sheet") + 1]) + else: + ids = [x for x in a if x in LOOKS] or list(LOOKS) + for ident in ids: + make(ident, force="--force" in a) diff --git a/generate_video.py b/generate_video.py new file mode 100644 index 0000000..156a41c --- /dev/null +++ b/generate_video.py @@ -0,0 +1,139 @@ +""" +Animate the intro story stills with Wan 2.2 I2V (A14B, high+low noise experts) +plus the lightx2v step-distill LoRA, on a local ComfyUI server. + +Usage: + py -3.12 generate_video.py [ ...] e.g. story_old + py -3.12 generate_video.py --all + +Frames land in output/video//frame_XXXX.png plus a preview.gif. +""" +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 + +ROOT = os.path.dirname(os.path.abspath(__file__)) +SPRITES = os.path.join(config.ASSETS_DIR, "Sprites") +OUT = os.path.join(config.OUTPUT_DIR, "video") + +WIDTH, HEIGHT = 832, 480 # 16:9-ish 480p, what Wan 14B handles on 12 GB +LENGTH = 49 # frames at 16 fps -> ~3 s +STEPS, SPLIT = 8, 4 # high-noise expert 0..4, low-noise expert 4..8 +SHIFT = 5.0 + +# Projektdaten (Stil, Negativ-Prompt, Bewegungen, Größen) aus dem Projekt: config.VIDEO_MODULE +import importlib as _il +_d = _il.import_module(getattr(config, "VIDEO_MODULE", "video_life")) +STYLE, NEGATIVE, MOTION, SIZE = _d.STYLE, _d.NEGATIVE, _d.MOTION, _d.SIZE + + +def post(path, payload): + req = urllib.request.Request(config.HOST + path, data=json.dumps(payload).encode("utf-8"), + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req) as r: + return json.loads(r.read().decode("utf-8")) + + +def get(path): + with urllib.request.urlopen(config.HOST + path) as r: + return json.loads(r.read().decode("utf-8")) + + +def upload(path, width=WIDTH, height=HEIGHT): + """Uploads the still cover-cropped to width x height so the video starts exactly on it.""" + from PIL import Image + im = Image.open(path).convert("RGB") + s = max(width / im.width, height / im.height) + im = im.resize((round(im.width * s), round(im.height * s)), Image.LANCZOS) + l, t = (im.width - width) // 2, (im.height - height) // 2 + im = im.crop((l, t, l + width, t + height)) + tmp = os.path.join(OUT, "_upload.png") + im.save(tmp) + boundary = uuid.uuid4().hex + name = "yl_" + os.path.basename(path).rsplit(".", 1)[0] + ".png" + 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(tmp, "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("utf-8"))["name"] + + +def workflow(image_name, prompt, seed, prefix, width=WIDTH, height=HEIGHT): + lora = "Wan21_I2V_14B_lightx2v_cfg_step_distill_lora_rank64.safetensors" + return { + "1": {"class_type": "UNETLoader", "inputs": {"unet_name": "Wan2_2-I2V-A14B-HIGH_fp8_e5m2_scaled_KJ.safetensors", "weight_dtype": "default"}}, + "2": {"class_type": "UNETLoader", "inputs": {"unet_name": "Wan2_2-I2V-A14B-LOW_fp8_e5m2_scaled_KJ.safetensors", "weight_dtype": "default"}}, + "3": {"class_type": "LoraLoaderModelOnly", "inputs": {"model": ["1", 0], "lora_name": lora, "strength_model": 3.0}}, + "4": {"class_type": "LoraLoaderModelOnly", "inputs": {"model": ["2", 0], "lora_name": lora, "strength_model": 1.5}}, + "5": {"class_type": "ModelSamplingSD3", "inputs": {"model": ["3", 0], "shift": SHIFT}}, + "6": {"class_type": "ModelSamplingSD3", "inputs": {"model": ["4", 0], "shift": SHIFT}}, + "7": {"class_type": "CLIPLoader", "inputs": {"clip_name": "umt5_xxl_fp16.safetensors", "type": "wan"}}, + "8": {"class_type": "CLIPTextEncode", "inputs": {"clip": ["7", 0], "text": f"{prompt}, {STYLE}"}}, + "9": {"class_type": "CLIPTextEncode", "inputs": {"clip": ["7", 0], "text": NEGATIVE}}, + "10": {"class_type": "VAELoader", "inputs": {"vae_name": "wan_2.1_vae.safetensors"}}, + "11": {"class_type": "LoadImage", "inputs": {"image": image_name}}, + "12": {"class_type": "WanImageToVideo", "inputs": {"positive": ["8", 0], "negative": ["9", 0], "vae": ["10", 0], + "width": width, "height": height, "length": LENGTH, + "batch_size": 1, "start_image": ["11", 0]}}, + "13": {"class_type": "KSamplerAdvanced", "inputs": {"model": ["5", 0], "add_noise": "enable", "noise_seed": seed, + "steps": STEPS, "cfg": 1.0, "sampler_name": "euler", "scheduler": "simple", + "positive": ["12", 0], "negative": ["12", 1], "latent_image": ["12", 2], + "start_at_step": 0, "end_at_step": SPLIT, "return_with_leftover_noise": "enable"}}, + "14": {"class_type": "KSamplerAdvanced", "inputs": {"model": ["6", 0], "add_noise": "disable", "noise_seed": seed, + "steps": STEPS, "cfg": 1.0, "sampler_name": "euler", "scheduler": "simple", + "positive": ["12", 0], "negative": ["12", 1], "latent_image": ["13", 0], + "start_at_step": SPLIT, "end_at_step": 10000, "return_with_leftover_noise": "disable"}}, + "15": {"class_type": "VAEDecode", "inputs": {"samples": ["14", 0], "vae": ["10", 0]}}, + "16": {"class_type": "SaveImage", "inputs": {"images": ["15", 0], "filename_prefix": prefix}}, + } + + +def run(name): + src = os.path.join(SPRITES, name + ".jpg") + dest = os.path.join(OUT, name) + os.makedirs(dest, exist_ok=True) + w, h = SIZE.get(name, (WIDTH, HEIGHT)) + img = upload(src, w, h) + seed = random.randint(1, 2**31) + pid = post("/prompt", {"prompt": workflow(img, MOTION[name], seed, f"yl_video/{name}", w, h)})["prompt_id"] + t0 = time.time() + print(f"{name}: queued (seed {seed})", flush=True) + while True: + time.sleep(5) + h = get(f"/history/{pid}") + if pid in h: + st = h[pid].get("status", {}) + if st.get("status_str") == "error": + print(json.dumps(st, indent=1)[:3000]); return False + if st.get("completed"): + break + print(f"{name}: done in {time.time() - t0:.0f} s", flush=True) + from PIL import Image + frames = [] + for node in h[pid]["outputs"].values(): + for i, info in enumerate(node.get("images", [])): + qs = urllib.parse.urlencode({"filename": info["filename"], "subfolder": info.get("subfolder", ""), "type": info.get("type", "output")}) + p = os.path.join(dest, f"frame_{i:04d}.png") + urllib.request.urlretrieve(f"{config.HOST}/view?{qs}", p) + frames.append(Image.open(p).convert("RGB")) + if frames: + frames[0].save(os.path.join(dest, "preview.gif"), save_all=True, append_images=frames[1:], duration=62, loop=0) + print(f"{name}: {len(frames)} frames -> {dest}") + return True + + +if __name__ == "__main__": + os.makedirs(OUT, exist_ok=True) + names = [n for n in MOTION if n.startswith("story_")] if "--all" in sys.argv else [a for a in sys.argv[1:] if not a.startswith("--")] + for n in names: + run(n) diff --git a/generate_vintage.py b/generate_vintage.py new file mode 100644 index 0000000..a5a9140 --- /dev/null +++ b/generate_vintage.py @@ -0,0 +1,109 @@ +""" +Vintage family tree assets (Flux.2 Klein via ComfyUI). + + py -3.12 generate_vintage.py generate all (keeps existing) + py -3.12 generate_vintage.py frame --force + py -3.12 generate_vintage.py --adopt copy to ../Assets/Sprites (keyed PNGs, parchment JPG) + py -3.12 generate_vintage.py --sheet x.jpg + +Frame, seal and ribbon are painted on pure black; --adopt turns black into transparency +(luma key), so the inside of the oval frame is see-through as well. +""" +import os +import sys + +import generate_portraits as gp # gleiche ComfyUI-Anbindung (upload/run/graph) +import _bootstrap # Projektordner (config.py, Listen) vor allen anderen Modulen +import config + +OUT = os.path.join(config.OUTPUT_DIR, "vintage") +DEST = os.path.join(config.ASSETS_DIR, "Sprites") + +# Motive aus dem Projekt: config.VINTAGE_MODULE +import importlib as _il +ITEMS = _il.import_module(getattr(config, "VINTAGE_MODULE", "vintage_life")).ITEMS + + +def generate(name, force=False): + os.makedirs(OUT, exist_ok=True) + dest = os.path.join(OUT, name + ".png") + if os.path.exists(dest) and not force: + return + prompt, w, h, _ = ITEMS[name] + g = gp.graph(prompt, __import__("random").randint(1, 2**31), "yl_vintage/" + name) + g["8"]["inputs"].update(width=w, height=h) + g["10"]["inputs"].update(width=w, height=h) + pid = gp.post("/prompt", {"prompt": g})["prompt_id"] + import time, json, urllib.parse, urllib.request + while True: + time.sleep(1.5) + hist = gp.get(f"/history/{pid}") + if pid in hist: + st = hist[pid].get("status", {}) + if st.get("status_str") == "error": + raise RuntimeError(json.dumps(st)[:1500]) + if st.get("completed"): + break + for node in hist[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")}) + urllib.request.urlretrieve(f"{config.HOST}/view?{qs}", dest) + print(name, "ok", flush=True) + + +def luma_key(img): + """Schwarz → durchsichtig, weicher Übergang; Farben bleiben.""" + import numpy as np + from PIL import Image + a = np.asarray(img.convert("RGB")).astype("float32") + lum = a.max(axis=2) + alpha = np.clip((lum - 18) * 5.0, 0, 255) + rgba = np.dstack([a, alpha]).astype("uint8") + out = Image.fromarray(rgba, "RGBA") + return out.crop(out.getbbox() or (0, 0, out.width, out.height)) + + +def adopt(): + from PIL import Image + for name, (_, w, h, keyed) in ITEMS.items(): + src = os.path.join(OUT, name + ".png") + if not os.path.exists(src): + continue + im = Image.open(src) + if keyed: + im = luma_key(im) + im.thumbnail((640, 640), Image.LANCZOS) + im.save(os.path.join(DEST, name + ".png"), optimize=True) + else: + # weißen Rand um das Pergament abschneiden + mx, my = int(im.width * 0.035), int(im.height * 0.05) + im.convert("RGB").crop((mx, my, im.width - mx, im.height - my)).resize((1920, 1080), Image.LANCZOS).save(os.path.join(DEST, name + ".jpg"), quality=88, optimize=True) + print("adopted") + + +def sheet(path): + from PIL import Image + tiles = [] + for name in ITEMS: + f = os.path.join(OUT, name + ".png") + if os.path.exists(f): + im = Image.open(f).convert("RGB") + im.thumbnail((420, 300)) + tiles.append(im) + W = sum(t.width for t in tiles) + 10 * len(tiles) + sh = Image.new("RGB", (W, 300), (60, 60, 70)) + x = 0 + for t in tiles: + sh.paste(t, (x, 0)); x += t.width + 10 + sh.save(path, quality=88) + + +if __name__ == "__main__": + a = sys.argv[1:] + if "--adopt" in a: + adopt() + elif "--sheet" in a: + sheet(a[a.index("--sheet") + 1]) + else: + for n in [x for x in a if x in ITEMS] or list(ITEMS): + generate(n, force="--force" in a) diff --git a/generate_voice.py b/generate_voice.py new file mode 100644 index 0000000..d9f0461 --- /dev/null +++ b/generate_voice.py @@ -0,0 +1,166 @@ +""" +Narrator voice for the intro, generated locally with Chatterbox Multilingual. + +Runs in its own venv (Chatterbox pins torch 2.6), see .venv-tts: + .venv-tts\\Scripts\\python.exe generate_voice.py all languages + .venv-tts\\Scripts\\python.exe generate_voice.py de one language + .venv-tts\\Scripts\\python.exe generate_voice.py de intro.line1 one line + +Texts come straight from ../Languages/.json. Each line is rendered to +output/voice//.wav, then trimmed, loudness-normalised and written as +../Assets/Audio/voice__.mp3 (embedded in the exe). + + .venv-tts\\Scripts\\python.exe generate_voice.py --cards [de] [--skip-existing] + every event card ("Title. Body") + +Female and male narrator alternate (voice_refs/, made by make_voice_refs.py); +Chatterbox clones the reference timbre into every language. + +Chatterbox sometimes keeps babbling after the sentence or swallows words, so every +take is transcribed with Whisper and only accepted when the words match and the +length is plausible and the pitch fits the wanted voice; otherwise the next seed +is tried (best take wins). +""" +import _bootstrap # Projektordner (config.py, Listen) vor allen anderen Modulen +import config +import difflib +import re +import json +import os +import subprocess +import sys + +import librosa +import numpy as np +import torch +import torchaudio as ta +from chatterbox.mtl_tts import ChatterboxMultilingualTTS +from faster_whisper import WhisperModel + +HERE = os.path.dirname(os.path.abspath(__file__)) +LANG_DIR = config.LANG_DIR +AUDIO_DIR = os.path.join(config.ASSETS_DIR, "Audio") +RAW_DIR = os.path.join(config.OUTPUT_DIR, "voice") + +# Welche Texte gesprochen werden, kommt aus dem Projekt: config.VOICE_MODULE +import importlib as _il +_d = _il.import_module(getattr(config, "VOICE_MODULE", "voice_life")) +LANGS, KEYS, VOICE_OF = _d.LANGS, _d.KEYS, _d.VOICE_OF +REFS = os.path.join(HERE, "voice_refs") + +# calm storyteller: little exaggeration, low cfg = slower, more relaxed pacing +EXAGGERATION = 0.4 +CFG_WEIGHT = 0.5 # Englisch; andere Sprachen 0, sonst färbt der englische Akzent der Referenz ab +TEMPERATURE = 0.7 +SEED = int(os.environ.get("VOICE_SEED", 7)) # anderer Startwert für einen Satz: set VOICE_SEED=100 +TRIES = 12 +MIN_MATCH = 0.98 # buchstabenweise; 0,97 ließ noch "Entschiedung" durch +CHARS_PER_SEC = 8.0 # slower than this = babbling / long pauses + +SPOKEN = _d.SPOKEN + +# trim silence at both ends, gentle fade, broadcast-ish loudness +FILTER = ("silenceremove=start_periods=1:start_threshold=-45dB:start_silence=0.05," + "areverse,silenceremove=start_periods=1:start_threshold=-45dB:start_silence=0.1,areverse," + "afade=t=in:d=0.03,loudnorm=I=-18:TP=-2:LRA=7") + + +def mp3_name(lang, key): + return f"voice_{lang}_{key.replace('.', '_')}.mp3" + + +def norm(t): + # buchstabenweise, ohne Leerzeichen: "Weg teilst" == "wegteilst" + return re.sub(r"[^\w]+", "", t.lower().replace("ß", "ss")) + + +def match(a, b): + return difflib.SequenceMatcher(None, norm(a), norm(b)).ratio() + + +def pitch_ok(wav, sr, voice): + """Grobe Geschlechtsprüfung über die mittlere Tonhöhe (Frau ~165+ Hz, Mann ~150- Hz).""" + y = librosa.resample(wav, orig_sr=sr, target_sr=16000) + f0, voiced, _ = librosa.pyin(y, fmin=60, fmax=400, sr=16000) + f0 = f0[voiced] + if len(f0) == 0: + return False, 0.0 + med = float(np.median(f0)) + return (med >= 160 if voice == "female" else med <= 155), med + + +def card_ids(): + """Karten-Ids in der Reihenfolge von EventCardSystem.cs (für den Stimmenwechsel).""" + src = open(config.CARDS_FILE, encoding="utf-8-sig").read() + return re.findall(r'^\s+new\("([a-z_0-9]+)", "', src, re.M) + + +def items_for(texts, args): + """(key, Untertitel-Text, Stimme) — Intro-Sätze oder alle Karten.""" + if "--cards" in args: + ids = [a[5:] for a in args if a.startswith("card.")] or card_ids() + order = card_ids() + out = [] + for cid in ids: + title, body = texts[f"card.{cid}.title"], texts[f"card.{cid}.body"] + text = f"{title.rstrip('.!?…')}. {body}" + out.append((f"card.{cid}", text, "female" if order.index(cid) % 2 == 0 else "male")) + return out + if "--album" in args: + keys = [k for k in texts if k.startswith("album.voice.")] + only = [a for a in args if a.startswith("album.voice.")] # einzelne Sätze neu erzeugen + return [(k, texts[k], "female" if i % 2 == 0 else "male") for i, k in enumerate(keys) if not only or k in only] + keys = [a for a in args if a in KEYS] or KEYS + return [(k, texts[k], VOICE_OF[k]) for k in keys] + + +def main(): + args = sys.argv[1:] + langs = [a for a in args if a in LANGS] or LANGS + skip = "--skip-existing" in args + min_match = 0.95 if "--cards" in args else MIN_MATCH # Album-Sätze sind kurz → streng # lange Texte: Whisper weicht minimal ab + device = "cuda" if torch.cuda.is_available() else "cpu" + model = ChatterboxMultilingualTTS.from_pretrained(device=device) + whisper = WhisperModel("small", device="cpu", compute_type="int8") + for lang in langs: + texts = json.load(open(os.path.join(LANG_DIR, f"{lang}.json"), encoding="utf-8")) + os.makedirs(os.path.join(RAW_DIR, lang), exist_ok=True) + for key, text, voice in items_for(texts, args): + dest = os.path.join(AUDIO_DIR, mp3_name(lang, key)) + if skip and os.path.exists(dest): + continue + raw = os.path.join(RAW_DIR, lang, key + ".wav") + tmp = os.path.join(RAW_DIR, lang, key + ".try.wav") + max_len = max(3.2, len(text) / CHARS_PER_SEC) # kurze Sätze brauchen mit Pausen ~3 s + best = (-1.0, None, "") + for attempt in range(TRIES): + torch.manual_seed(SEED + attempt) + wav = model.generate(SPOKEN.get((lang, key), text), language_id=lang, + audio_prompt_path=os.path.join(REFS, f"{voice}.wav"), + exaggeration=EXAGGERATION, temperature=TEMPERATURE, + cfg_weight=CFG_WEIGHT if lang == "en" else 0.0) + ta.save(tmp, wav, model.sr) + dur = wav.shape[-1] / model.sr + # direkt als 16-kHz-Array (Whisper' eigener Datei-Loader verträgt die av-Version nicht) + pcm = ta.functional.resample(wav.cpu(), model.sr, 16000)[0].numpy().astype("float32") + segs, _ = whisper.transcribe(pcm, language=lang, beam_size=5) + heard = " ".join(sg.text for sg in segs).strip() + good_pitch, f0 = pitch_ok(wav[0].cpu().numpy(), model.sr, voice) + score = match(text, heard) - (0.5 if dur > max_len else 0) - (0.5 if not good_pitch else 0) + print(f" try {attempt}: {voice} {f0:3.0f} Hz {dur:4.1f} s match {score:.2f} '{heard}'", flush=True) + if score > best[0]: + best = (score, dur, heard) + os.replace(tmp, raw) + if score >= min_match: + break + if os.path.exists(tmp): + os.remove(tmp) + if best[0] < min_match: + print(f"!! {lang} {key}: best take only {best[0]:.2f}", flush=True) + subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-i", raw, "-af", FILTER, + "-ac", "1", "-ar", "44100", "-b:a", "96k", dest], check=True) + print(f"{lang} {key:14s} {voice:6s} {best[1]:4.1f} s match {best[0]:.2f} {text}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/make_voice_refs.py b/make_voice_refs.py new file mode 100644 index 0000000..24642b0 --- /dev/null +++ b/make_voice_refs.py @@ -0,0 +1,41 @@ +""" +Reference voices for the narrator (generate_voice.py clones them with Chatterbox). + +Kokoro has clearly female / male English voices; a ~12 s calm sample of each is +enough for Chatterbox to take over the timbre in every language. + + .venv-tts\\Scripts\\python.exe make_voice_refs.py +writes voice_refs/female.wav and voice_refs/male.wav +""" +import _bootstrap # Projektordner (config.py, Listen) vor allen anderen Modulen +import config +import os + +import numpy as np +import soundfile as sf +from kokoro import KPipeline + +HERE = os.path.dirname(os.path.abspath(__file__)) +OUT = os.path.join(HERE, "voice_refs") + +TEXT = ("Once upon a time, in a quiet little town by the sea, a child was born. " + "The years went by like seasons, slowly and then all at once. " + "There were first steps, first friends, and a first love, " + "and every single day added another page to the story.") + +VOICES = {"female": "af_heart", "male": "am_michael"} + + +def main(): + os.makedirs(OUT, exist_ok=True) + pipe = KPipeline(lang_code="a") + for name, voice in VOICES.items(): + chunks = [audio for _, _, audio in pipe(TEXT, voice=voice, speed=0.9)] + audio = np.concatenate([c.numpy() if hasattr(c, "numpy") else c for c in chunks]) + path = os.path.join(OUT, f"{name}.wav") + sf.write(path, audio, 24000) + print(f"{name}: {voice}, {len(audio) / 24000:.1f} s -> {path}") + + +if __name__ == "__main__": + main() diff --git a/voice_refs/female.wav b/voice_refs/female.wav new file mode 100644 index 0000000..25e19a5 Binary files /dev/null and b/voice_refs/female.wav differ diff --git a/voice_refs/male.wav b/voice_refs/male.wav new file mode 100644 index 0000000..4bafe24 Binary files /dev/null and b/voice_refs/male.wav differ diff --git a/workflows/3d modell.json b/workflows/3d modell.json new file mode 100644 index 0000000..717aa10 --- /dev/null +++ b/workflows/3d modell.json @@ -0,0 +1 @@ +{"id":"4125c6df-9bca-430d-8e85-7cff9cc592d4","revision":0,"last_node_id":18,"last_link_id":22,"nodes":[{"id":1,"type":"ImageOnlyCheckpointLoader","pos":[450,-600],"size":[342.5625,127.328125],"flags":{},"order":0,"mode":0,"inputs":[{"localized_name":"ckpt_name","name":"ckpt_name","type":"COMBO","widget":{"name":"ckpt_name"},"link":null}],"outputs":[{"localized_name":"MODEL","name":"MODEL","type":"MODEL","links":[16]},{"localized_name":"CLIP_VISION","name":"CLIP_VISION","type":"CLIP_VISION","links":[20]},{"localized_name":"VAE","name":"VAE","type":"VAE","links":[18]}],"properties":{"Node name for S&R":"ImageOnlyCheckpointLoader","cnr_id":"comfy-core","ver":"0.3.59","models":[{"name":"hunyuan_3d_v2.1.safetensors","url":"https://huggingface.co/Comfy-Org/hunyuan3D_2.1_repackaged/resolve/main/hunyuan_3d_v2.1.safetensors","directory":"checkpoints"}]},"widgets_values":["hunyuan3d-dit-v2-0-fp16.safetensors"]},{"id":2,"type":"LoadImage","pos":[480,-390],"size":[274.0625,339.328125],"flags":{},"order":1,"mode":0,"inputs":[{"localized_name":"image","name":"image","type":"COMBO","widget":{"name":"image"},"link":null},{"localized_name":"choose file to upload","name":"upload","type":"IMAGEUPLOAD","widget":{"name":"upload"},"link":null}],"outputs":[{"localized_name":"IMAGE","name":"IMAGE","type":"IMAGE","links":[21]},{"localized_name":"MASK","name":"MASK","type":"MASK","links":null}],"properties":{"Node name for S&R":"LoadImage","cnr_id":"comfy-core","ver":"0.3.59"},"widgets_values":["tw_build_fishing_boat_raw_00001_.png","image"]},{"id":3,"type":"ModelSamplingAuraFlow","pos":[840,-600],"size":[270,79.328125],"flags":{},"order":4,"mode":0,"inputs":[{"localized_name":"model","name":"model","type":"MODEL","link":16},{"localized_name":"shift","name":"shift","type":"FLOAT","widget":{"name":"shift"},"link":null}],"outputs":[{"localized_name":"MODEL","name":"MODEL","type":"MODEL","links":[19]}],"properties":{"Node name for S&R":"ModelSamplingAuraFlow","cnr_id":"comfy-core","ver":"0.3.59"},"widgets_values":[1]},{"id":7,"type":"KSampler","pos":[1150,-600],"size":[270,311.328125],"flags":{},"order":7,"mode":0,"inputs":[{"localized_name":"model","name":"model","type":"MODEL","link":19},{"localized_name":"positive","name":"positive","type":"CONDITIONING","link":5},{"localized_name":"negative","name":"negative","type":"CONDITIONING","link":6},{"localized_name":"latent_image","name":"latent_image","type":"LATENT","link":7},{"localized_name":"seed","name":"seed","type":"INT","widget":{"name":"seed"},"link":null},{"localized_name":"steps","name":"steps","type":"INT","widget":{"name":"steps"},"link":null},{"localized_name":"cfg","name":"cfg","type":"FLOAT","widget":{"name":"cfg"},"link":null},{"localized_name":"sampler_name","name":"sampler_name","type":"COMBO","widget":{"name":"sampler_name"},"link":null},{"localized_name":"scheduler","name":"scheduler","type":"COMBO","widget":{"name":"scheduler"},"link":null},{"localized_name":"denoise","name":"denoise","type":"FLOAT","widget":{"name":"denoise"},"link":null}],"outputs":[{"localized_name":"LATENT","name":"LATENT","type":"LATENT","links":[8]}],"properties":{"Node name for S&R":"KSampler","cnr_id":"comfy-core","ver":"0.3.59"},"widgets_values":[754725286487164,"randomize",30,5,"euler","normal",1]},{"id":10,"type":"SaveGLB","pos":[1460,-600],"size":[810,820],"flags":{},"order":10,"mode":0,"inputs":[{"localized_name":"mesh","name":"mesh","type":"MESH,FILE_3D_GLB,FILE_3D_GLTF,FILE_3D_OBJ,FILE_3D_FBX,FILE_3D_STL,FILE_3D_USDZ,FILE_3D_PLY,FILE_3D_SPLAT,FILE_3D_SPZ,FILE_3D_KSPLAT,FILE_3D_SPLAT_ANY,FILE_3D_POINT_CLOUD_ANY,FILE_3D","link":11},{"localized_name":"filename_prefix","name":"filename_prefix","type":"STRING","widget":{"name":"filename_prefix"},"link":null},{"localized_name":"image","name":"image","type":"PREVIEW_3D","widget":{"name":"image"},"link":null}],"outputs":[],"properties":{"Node name for S&R":"SaveGLB","cnr_id":"comfy-core","ver":"0.3.59","Camera Info":{"position":{"x":9.120136087242537,"y":2.293737356159448,"z":9.219634231216268},"target":{"x":0,"y":2.5,"z":0},"zoom":1,"cameraType":"perspective"},"Last Time Model File":"mesh/ComfyUI_00005_.glb","Last Time Model Folder":"output","Scene Config":{"showGrid":true,"backgroundColor":"#282828","backgroundImage":"","backgroundRenderMode":"tiled","models":[{"position":{"x":0,"y":0,"z":0},"quaternion":{"x":0,"y":0,"z":0,"w":1},"scale":{"x":1,"y":1,"z":1}}]},"Camera Config":{"cameraType":"perspective","fov":35,"state":{"position":{"x":2.594467159354075,"y":0.5285688460173493,"z":-5.266725404481917},"target":{"x":0.003979921340942383,"y":0.004029184579849243,"z":0.008415281772613524},"zoom":1,"cameraType":"perspective"}},"Light Config":{"intensity":3,"hdri":{"enabled":false,"hdriPath":"","showAsBackground":false,"intensity":1}}},"widgets_values":["mesh/ComfyUI",""]},{"id":8,"type":"VAEDecodeHunyuan3D","pos":[1150,-290],"size":[270,103.328125],"flags":{},"order":8,"mode":0,"inputs":[{"localized_name":"samples","name":"samples","type":"LATENT","link":8},{"localized_name":"vae","name":"vae","type":"VAE","link":18},{"localized_name":"num_chunks","name":"num_chunks","type":"INT","widget":{"name":"num_chunks"},"link":null},{"localized_name":"octree_resolution","name":"octree_resolution","type":"INT","widget":{"name":"octree_resolution"},"link":null}],"outputs":[{"localized_name":"VOXEL","name":"VOXEL","type":"VOXEL","links":[10]}],"properties":{"Node name for S&R":"VAEDecodeHunyuan3D","cnr_id":"comfy-core","ver":"0.3.59"},"widgets_values":[8000,256]},{"id":9,"type":"VoxelToMesh","pos":[1150,-130],"size":[270,111.328125],"flags":{},"order":9,"mode":0,"inputs":[{"localized_name":"voxel","name":"voxel","type":"VOXEL","link":10},{"localized_name":"algorithm","name":"algorithm","type":"COMBO","widget":{"name":"algorithm"},"link":null},{"localized_name":"threshold","name":"threshold","type":"FLOAT","widget":{"name":"threshold"},"link":null}],"outputs":[{"localized_name":"MESH","name":"MESH","type":"MESH","links":[11]}],"properties":{"Node name for S&R":"VoxelToMesh","cnr_id":"comfy-core","ver":"0.3.59"},"widgets_values":["surface net",0.6]},{"id":13,"type":"CLIPVisionEncode","pos":[840,-500],"size":[270,103.328125],"flags":{},"order":5,"mode":0,"inputs":[{"localized_name":"clip_vision","name":"clip_vision","type":"CLIP_VISION","link":20},{"localized_name":"image","name":"image","type":"IMAGE","link":21},{"localized_name":"crop","name":"crop","type":"COMBO","widget":{"name":"crop"},"link":null}],"outputs":[{"localized_name":"CLIP_VISION_OUTPUT","name":"CLIP_VISION_OUTPUT","type":"CLIP_VISION_OUTPUT","links":[22]}],"properties":{"Node name for S&R":"CLIPVisionEncode","cnr_id":"comfy-core","ver":"0.3.59"},"widgets_values":["center"]},{"id":6,"type":"Hunyuan3Dv2Conditioning","pos":[900,-370],"size":[225,71.328125],"flags":{},"order":6,"mode":0,"inputs":[{"localized_name":"clip_vision_output","name":"clip_vision_output","type":"CLIP_VISION_OUTPUT","link":22}],"outputs":[{"localized_name":"positive","name":"positive","type":"CONDITIONING","links":[5]},{"localized_name":"negative","name":"negative","type":"CONDITIONING","links":[6]}],"properties":{"Node name for S&R":"Hunyuan3Dv2Conditioning","cnr_id":"comfy-core","ver":"0.3.59"},"widgets_values":[]},{"id":4,"type":"EmptyLatentHunyuan3Dv2","pos":[840,-270],"size":[270,111.328125],"flags":{},"order":2,"mode":0,"inputs":[{"localized_name":"resolution","name":"resolution","type":"INT","widget":{"name":"resolution"},"link":null},{"localized_name":"batch_size","name":"batch_size","type":"INT","widget":{"name":"batch_size"},"link":null}],"outputs":[{"localized_name":"LATENT","name":"LATENT","type":"LATENT","links":[7]}],"properties":{"Node name for S&R":"EmptyLatentHunyuan3Dv2","cnr_id":"comfy-core","ver":"0.3.59"},"widgets_values":[4096,1]},{"id":15,"type":"MarkdownNote","pos":[40,-640],"size":[370,324.21875],"flags":{},"order":3,"mode":0,"inputs":[],"outputs":[],"properties":{},"widgets_values":["\n## Model link\n\n**checkpoints**\n\n- [hunyuan_3d_v2.1.safetensors](https://huggingface.co/Comfy-Org/hunyuan3D_2.1_repackaged/resolve/main/hunyuan_3d_v2.1.safetensors)\n\n\nModel Storage Location\n\n```\n📂 ComfyUI/\n├── 📂 models/\n│ └── 📂 checkpoints/\n│ └── hunyuan_3d_v2.1.safetensors\n```\n"],"color":"#222","bgcolor":"#000"}],"links":[[5,6,0,7,1,"CONDITIONING"],[6,6,1,7,2,"CONDITIONING"],[7,4,0,7,3,"LATENT"],[8,7,0,8,0,"LATENT"],[10,8,0,9,0,"VOXEL"],[11,9,0,10,0,"MESH"],[16,1,0,3,0,"MODEL"],[18,1,2,8,1,"VAE"],[19,3,0,7,0,"MODEL"],[20,1,1,13,0,"CLIP_VISION"],[21,2,0,13,1,"IMAGE"],[22,13,0,6,0,"CLIP_VISION_OUTPUT"]],"groups":[{"id":1,"title":"Step 1 - Load model","bounding":[440,-670,356.3746337890625,183.60000610351562],"color":"#3f789e","flags":{}},{"id":2,"title":"Step 2 - Upload image here","bounding":[440,-470,350,410],"color":"#3f789e","flags":{}}],"config":{},"extra":{"ds":{"scale":1.135786666666667,"offset":[-368.05996431254744,752.472786863973]},"frontendVersion":"1.27.10","VHS_latentpreview":false,"VHS_latentpreviewrate":0,"VHS_MetadataImage":true,"VHS_KeepIntermediate":true},"version":0.4} \ No newline at end of file diff --git a/workflows/Image to 3D - Hunyuan3D.json b/workflows/Image to 3D - Hunyuan3D.json new file mode 100644 index 0000000..2818466 --- /dev/null +++ b/workflows/Image to 3D - Hunyuan3D.json @@ -0,0 +1,81 @@ +{ + "1": { + "class_type": "ImageOnlyCheckpointLoader", + "inputs": { + "ckpt_name": "{{CHECKPOINT}}" + } + }, + "2": { + "class_type": "LoadImage", + "inputs": { + "image": "{{IMAGE}}" + } + }, + "3": { + "class_type": "ModelSamplingAuraFlow", + "inputs": { + "model": ["1", 0], + "shift": 1.0 + } + }, + "13": { + "class_type": "CLIPVisionEncode", + "inputs": { + "clip_vision": ["1", 1], + "image": ["2", 0], + "crop": "center" + } + }, + "6": { + "class_type": "Hunyuan3Dv2Conditioning", + "inputs": { + "clip_vision_output": ["13", 0] + } + }, + "4": { + "class_type": "EmptyLatentHunyuan3Dv2", + "inputs": { + "resolution": 4096, + "batch_size": 1 + } + }, + "7": { + "class_type": "KSampler", + "inputs": { + "model": ["3", 0], + "positive": ["6", 0], + "negative": ["6", 1], + "latent_image": ["4", 0], + "seed": {{SEED}}, + "steps": 30, + "cfg": 5.0, + "sampler_name": "euler", + "scheduler": "normal", + "denoise": 1.0 + } + }, + "8": { + "class_type": "VAEDecodeHunyuan3D", + "inputs": { + "samples": ["7", 0], + "vae": ["1", 2], + "num_chunks": 8000, + "octree_resolution": {{OCTREE}} + } + }, + "9": { + "class_type": "VoxelToMesh", + "inputs": { + "voxel": ["8", 0], + "algorithm": "surface net", + "threshold": 0.6 + } + }, + "10": { + "class_type": "SaveGLB", + "inputs": { + "mesh": ["9", 0], + "filename_prefix": "{{NAME}}" + } + } +} diff --git a/workflows/Text to Image - Flux Klein.json b/workflows/Text to Image - Flux Klein.json new file mode 100644 index 0000000..386ffba --- /dev/null +++ b/workflows/Text to Image - Flux Klein.json @@ -0,0 +1,24 @@ +{ + "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": "{{POSITIVE}}", "clip": ["2", 0]}}, + "5": {"class_type": "ConditioningZeroOut", "inputs": {"conditioning": ["4", 0]}}, + "6": {"class_type": "CFGGuider", "inputs": {"model": ["1", 0], "positive": ["4", 0], "negative": ["5", 0], "cfg": 1}}, + "7": {"class_type": "KSamplerSelect", "inputs": {"sampler_name": "euler"}}, + "8": {"class_type": "Flux2Scheduler", "inputs": {"width": 1024, "height": 1024, "steps": 4}}, + "9": {"class_type": "RandomNoise", "inputs": {"noise_seed": {{SEED}}}}, + "10": {"class_type": "EmptyFlux2LatentImage", "inputs": {"width": 1024, "height": 1024, "batch_size": 1}}, + "11": {"class_type": "SamplerCustomAdvanced", "inputs": { + "noise": ["9", 0], "guider": ["6", 0], "sampler": ["7", 0], "sigmas": ["8", 0], "latent_image": ["10", 0] + }}, + "12": {"class_type": "VAEDecode", "inputs": {"samples": ["11", 0], "vae": ["3", 0]}}, + "13": {"class_type": "SaveImage", "inputs": {"images": ["12", 0], "filename_prefix": "{{NAME}}_raw"}}, + "14": {"class_type": "Image Rembg (Remove Background)", "inputs": { + "images": ["12", 0], "transparency": true, "model": "isnet-general-use", + "post_processing": true, "only_mask": false, "alpha_matting": false, + "alpha_matting_foreground_threshold": 240, "alpha_matting_background_threshold": 10, + "alpha_matting_erode_size": 10, "background_color": "none" + }}, + "15": {"class_type": "SaveImage", "inputs": {"images": ["14", 0], "filename_prefix": "{{NAME}}_cutout"}} +} diff --git a/workflows/Text to Image - Game.json b/workflows/Text to Image - Game.json new file mode 100644 index 0000000..f2bbcc3 --- /dev/null +++ b/workflows/Text to Image - Game.json @@ -0,0 +1,22 @@ +{ + "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": "{{POSITIVE}}", "clip": ["2", 0]}}, + "5": {"class_type": "CLIPTextEncode", "inputs": {"text": "{{NEGATIVE}}", "clip": ["2", 0]}}, + "6": {"class_type": "EmptySD3LatentImage", "inputs": {"width": 1024, "height": 1024, "batch_size": 1}}, + "7": {"class_type": "ModelSamplingAuraFlow", "inputs": {"model": ["1", 0], "shift": 3}}, + "8": {"class_type": "KSampler", "inputs": { + "model": ["7", 0], "positive": ["4", 0], "negative": ["5", 0], "latent_image": ["6", 0], + "seed": {{SEED}}, "steps": 8, "cfg": 1, "sampler_name": "dpm_2", "scheduler": "karras", "denoise": 1 + }}, + "9": {"class_type": "VAEDecode", "inputs": {"samples": ["8", 0], "vae": ["3", 0]}}, + "10": {"class_type": "SaveImage", "inputs": {"images": ["9", 0], "filename_prefix": "{{NAME}}_raw"}}, + "11": {"class_type": "Image Rembg (Remove Background)", "inputs": { + "images": ["9", 0], "transparency": true, "model": "isnet-general-use", + "post_processing": true, "only_mask": false, "alpha_matting": false, + "alpha_matting_foreground_threshold": 240, "alpha_matting_background_threshold": 10, + "alpha_matting_erode_size": 10, "background_color": "none" + }}, + "12": {"class_type": "SaveImage", "inputs": {"images": ["11", 0], "filename_prefix": "{{NAME}}_cutout"}} +} diff --git a/workflows/default.json b/workflows/default.json new file mode 100644 index 0000000..baa4b33 --- /dev/null +++ b/workflows/default.json @@ -0,0 +1,19 @@ +{ + "1": {"class_type": "CheckpointLoaderSimple", "inputs": {"ckpt_name": "{{CHECKPOINT}}"}}, + "2": {"class_type": "CLIPTextEncode", "inputs": {"text": "{{POSITIVE}}", "clip": ["1", 1]}}, + "3": {"class_type": "CLIPTextEncode", "inputs": {"text": "{{NEGATIVE}}", "clip": ["1", 1]}}, + "4": {"class_type": "EmptyLatentImage", "inputs": {"width": 1024, "height": 1024, "batch_size": 1}}, + "5": {"class_type": "KSampler", "inputs": { + "model": ["1", 0], "positive": ["2", 0], "negative": ["3", 0], "latent_image": ["4", 0], + "seed": {{SEED}}, "steps": 32, "cfg": 6.5, "sampler_name": "dpmpp_2m", "scheduler": "karras", "denoise": 1.0 + }}, + "6": {"class_type": "VAEDecode", "inputs": {"samples": ["5", 0], "vae": ["1", 2]}}, + "7": {"class_type": "SaveImage", "inputs": {"images": ["6", 0], "filename_prefix": "{{NAME}}_raw"}}, + "8": {"class_type": "Image Rembg (Remove Background)", "inputs": { + "images": ["6", 0], "transparency": true, "model": "isnet-general-use", + "post_processing": true, "only_mask": false, "alpha_matting": false, + "alpha_matting_foreground_threshold": 240, "alpha_matting_background_threshold": 10, + "alpha_matting_erode_size": 10, "background_color": "none" + }}, + "9": {"class_type": "SaveImage", "inputs": {"images": ["8", 0], "filename_prefix": "{{NAME}}_cutout"}} +}