This commit is contained in:
2026-11-13 00:57:30 +01:00
parent e7e3bcbbcb
commit 877f851160
7 changed files with 348 additions and 0 deletions

View File

@@ -7,6 +7,7 @@ das aktuelle Verzeichnis oder `--project <ordner>` (siehe `_bootstrap.py`).
| Werkzeug | Erzeugt | Modell | Projektdaten |
|---|---|---|---|
| `generate.py` / `adopt.py` / `cutout.py` | Sprites, Szenen, Karten | Flux.2 Klein (`workflows/`) | `PROMPTS_MODULE` |
| `adopt_scene.py` | Szene ohne Freistellen → `Sprites/<name>.jpg` (Cover-Zuschnitt) | – | `ASSETS_DIR` |
| `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` |

69
adopt_scene.py Normal file
View File

@@ -0,0 +1,69 @@
"""Take a generated scene (background, title art, splash) into the game WITHOUT cutting it out.
Finds the newest raw render for <name> in the project's output/, scales it (cover: fills the
target size, crops the overflow from the centre) and writes ASSETS_DIR/Sprites/<name>.jpg.
Sprites with a black backdrop go through adopt.py instead.
py -3.12 adopt_scene.py bg_title one scene, keeps the render size
py -3.12 adopt_scene.py bg_title bg_shop several
py -3.12 adopt_scene.py --size 1600x900 bg_title target size (cover + centre crop)
py -3.12 adopt_scene.py --quality 80 bg_title JPEG quality (default 85)
py -3.12 adopt_scene.py --png bg_title PNG instead of JPEG
"""
import glob
import os
import sys
from PIL import Image
import _bootstrap # project folder (config.py, lists) before every other module
import config
DEST = os.path.join(config.ASSETS_DIR, "Sprites")
def adopt_scene(name, size=None, quality=85, png=False):
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
img = Image.open(raws[-1]).convert("RGB")
if size:
tw, th = size
k = max(tw / img.width, th / img.height)
img = img.resize((max(tw, round(img.width * k)), max(th, round(img.height * k))), Image.LANCZOS)
left, top = (img.width - tw) // 2, (img.height - th) // 2
img = img.crop((left, top, left + tw, top + th))
os.makedirs(DEST, exist_ok=True)
out = os.path.join(DEST, name + (".png" if png else ".jpg"))
if png:
img.save(out, optimize=True)
else:
img.save(out, quality=quality, optimize=True, progressive=True)
print(f" {name}: {os.path.basename(raws[-1])} -> {out} ({img.width}x{img.height}, {os.path.getsize(out) // 1024} KB)")
return True
def main(argv):
size, quality, png, names = None, 85, False, []
i = 0
while i < len(argv):
a = argv[i]
if a == "--size":
w, h = argv[i + 1].lower().split("x"); size = (int(w), int(h)); i += 2; continue
if a == "--quality":
quality = int(argv[i + 1]); i += 2; continue
if a == "--png":
png = True
else:
names.append(a)
i += 1
if not names:
print(__doc__)
return 1
ok = all([adopt_scene(n, size, quality, png) for n in names])
return 0 if ok else 1
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))

187
comfy_check.py Normal file
View File

@@ -0,0 +1,187 @@
"""ComfyUI check: inventory, workflow validation, recent errors - short output for the
comfyui-workflow-expert skill (so nothing has to be read by hand).
py -3.12 comfy_check.py inventory: server/GPU, custom nodes, models, ComfyGen workflows
py -3.12 comfy_check.py --full same, every model file name
py -3.12 comfy_check.py <workflow.json> validate: format, missing nodes, missing/unknown models,
broken links, placeholders, sampler/size summary
py -3.12 comfy_check.py --log [N] last errors from ComfyUI's log (default 40 lines context)
Workflow files may be ComfyGen templates ({{SEED}} etc., also unquoted) - they are filled with dummies
before parsing. With the server running, node types and model names are checked against /object_info
(exactly what causes "value not in list" / "node does not exist" errors).
"""
import json
import os
import re
import sys
import urllib.request
COMFY = r"D:\ComfyUI\ComfyUI"
MODELS = os.path.join(COMFY, "models")
HOST = "http://127.0.0.1:8188"
HERE = os.path.dirname(os.path.abspath(__file__))
MODEL_EXT = (".safetensors", ".ckpt", ".pt", ".pth", ".gguf", ".bin", ".onnx", ".sft")
def get(path, timeout=3):
try:
with urllib.request.urlopen(HOST + path, timeout=timeout) as r:
return json.loads(r.read().decode("utf-8"))
except Exception:
return None
def model_index():
idx = {}
if not os.path.isdir(MODELS):
return idx
for folder in os.listdir(MODELS):
base = os.path.join(MODELS, folder)
if not os.path.isdir(base):
continue
for dp, _, fs in os.walk(base):
for f in fs:
if f.lower().endswith(MODEL_EXT):
rel = os.path.relpath(os.path.join(dp, f), base)
idx.setdefault(folder, []).append(rel)
return idx
def inventory(full):
out = []
st = get("/system_stats")
if st:
dev = st.get("devices", [{}])[0]
out.append(f"Server: läuft, ComfyUI {st.get('system', {}).get('comfyui_version', '?')}, "
f"{re.sub(r'^cuda:\d+\s*|\s*:.*$', '', dev.get('name', '?'))} "
f"VRAM {dev.get('vram_total', 0) / 2**30:.0f} GB (frei {dev.get('vram_free', 0) / 2**30:.1f} GB)")
else:
out.append("Server: aus (start: D:\\ComfyUI → .venv\\Scripts\\python.exe -s ComfyUI\\main.py)")
cn = os.path.join(COMFY, "custom_nodes")
packs = sorted(d for d in os.listdir(cn) if os.path.isdir(os.path.join(cn, d)) and not d.startswith((".", "_")) and d != "__pycache__") if os.path.isdir(cn) else []
out.append(f"Custom-Node-Pakete ({len(packs)}): " + ", ".join(packs))
idx = model_index()
out.append("Modelle:")
for folder in sorted(idx, key=str.lower):
names = sorted(idx[folder], key=str.lower)
shown = names if full or len(names) <= 6 else names[:6] + [f"+{len(names) - 6}"]
out.append(f" {folder} ({len(names)}): " + ", ".join(shown))
wf = os.path.join(HERE, "workflows")
if os.path.isdir(wf):
rows = []
for f in sorted(os.listdir(wf)):
if f.endswith(".json"):
fmt, data, _ = load_workflow(os.path.join(wf, f))
rows.append(f"{f} [{fmt}]")
out.append("ComfyGen-Workflows: " + " · ".join(rows))
print("\n".join(out))
def load_workflow(path):
text = open(path, encoding="utf-8-sig").read()
placeholders = sorted(set(re.findall(r"\{\{([A-Z0-9_]+)\}\}", text)))
# unquoted placeholders (numbers) -> 0, quoted ones stay strings
filled = re.sub(r'(?<!")\{\{[A-Z0-9_]+\}\}(?!")', "0", text)
try:
data = json.loads(filled)
except json.JSONDecodeError as e:
return f"kaputtes JSON ({e.msg}, Zeile {e.lineno})", None, placeholders
if isinstance(data, dict) and "nodes" in data and "links" in data:
return "UI", data, placeholders
if isinstance(data, dict) and all(isinstance(v, dict) and "class_type" in v for v in data.values()):
return "API", data, placeholders
return "unbekannt", data, placeholders
def options_for(info, ctype, inp):
spec = (info or {}).get(ctype, {}).get("input", {})
for group in ("required", "optional"):
v = spec.get(group, {}).get(inp)
if v and isinstance(v[0], list):
return v[0]
if v and v[0] == "COMBO" and len(v) > 1 and isinstance(v[1], dict):
return v[1].get("options")
return None
def validate(path):
fmt, data, ph = load_workflow(path)
out = [f"{os.path.basename(path)}: Format {fmt}" + (f", Platzhalter: {', '.join(ph)}" if ph else "")]
if data is None or fmt == "unbekannt":
print("\n".join(out)); return
info = get("/object_info", timeout=15)
if not info:
out.append("(Server aus – Node-Typen und Modellnamen nur gegen Dateien geprüft)")
idx = model_index()
all_models = {os.path.basename(m).lower() for ms in idx.values() for m in ms}
problems, summary = [], []
if fmt == "UI":
nodes = [(str(n.get("id")), n.get("type"), n.get("widgets_values") or []) for n in data["nodes"]]
out.append(f"{len(nodes)} Nodes, {len(data['links'])} Verbindungen – für ComfyGen/API: im Editor „Export (API)“ speichern")
for nid, ctype, widgets in nodes:
if ctype in ("Note", "MarkdownNote", "Reroute", "PrimitiveNode"):
continue
if info and ctype not in info:
problems.append(f"Node {nid} „{ctype}“ unbekannt (Custom Node fehlt/deaktiviert)")
for w in widgets if isinstance(widgets, list) else []:
if isinstance(w, str) and w.lower().endswith(MODEL_EXT) and "{{" not in w and os.path.basename(w).lower() not in all_models:
problems.append(f"Node {nid} ({ctype}): Modell fehlt: {w}")
else:
ids = set(data)
for nid, n in data.items():
ctype, inputs = n["class_type"], n.get("inputs", {})
if info and ctype not in info:
problems.append(f"Node {nid} „{ctype}“ unbekannt (Custom Node fehlt/deaktiviert)")
for k, v in inputs.items():
if isinstance(v, list) and len(v) == 2 and isinstance(v[1], int) and isinstance(v[0], str):
if v[0] not in ids:
problems.append(f"Node {nid}.{k} zeigt auf fehlenden Node {v[0]}")
continue
if isinstance(v, str) and "{{" not in v:
opts = options_for(info, ctype, k) if info else None
if opts is not None and v not in opts and (v.lower().endswith(MODEL_EXT) or k.endswith("_name") or k in ("model", "ckpt_name")):
problems.append(f"Node {nid} ({ctype}).{k} = „{v}“ nicht in der Liste des Servers")
elif opts is None and v.lower().endswith(MODEL_EXT) and os.path.basename(v).lower() not in all_models:
problems.append(f"Node {nid} ({ctype}).{k}: Modell fehlt: {v}")
if "sampler" in ctype.lower() or ctype in ("KSampler", "KSamplerAdvanced"):
keys = ("steps", "cfg", "sampler_name", "scheduler", "denoise")
vals = ", ".join(f"{k}={inputs[k]}" for k in keys if k in inputs and not isinstance(inputs[k], list))
if vals:
summary.append(f"{ctype}#{nid}: {vals}")
if ctype in ("Flux2Scheduler", "BasicScheduler", "CFGGuider", "ModelSamplingAuraFlow", "ModelSamplingFlux"):
vals = ", ".join(f"{k}={v}" for k, v in inputs.items() if not isinstance(v, list) and k in ("steps", "cfg", "shift", "scheduler", "denoise"))
if vals:
summary.append(f"{ctype}#{nid}: {vals}")
if "Latent" in ctype and "width" in inputs:
summary.append(f"{ctype}#{nid}: {inputs.get('width')}x{inputs.get('height')} batch {inputs.get('batch_size', 1)}")
if ctype in ("SaveImage", "SaveAudio", "SaveAudioMP3", "SaveGLB", "VHS_VideoCombine", "SaveVideo", "SaveAnimatedWEBP"):
summary.append(f"{ctype}#{nid}: prefix {inputs.get('filename_prefix', '?')}")
out.append(f"{len(data)} Nodes: " + ", ".join(sorted({n['class_type'] for n in data.values()})))
out += ["- " + s for s in summary]
out += ["PROBLEM " + p for p in problems] or ["Keine Probleme gefunden."]
print("\n".join(out))
def show_log(n):
log = os.path.join(COMFY, "user", "comfyui.log")
if not os.path.exists(log):
print("kein Log:", log); return
lines = open(log, encoding="utf-8", errors="replace").read().splitlines()
hits = [i for i, l in enumerate(lines) if re.search(r"Traceback|Error|Exception|out of memory|not in list|does not exist|Prompt outputs failed", l)]
if not hits:
print(f"Keine Fehler in {log} ({len(lines)} Zeilen)."); return
start = max(0, hits[-1] - n // 2)
print(f"{len(hits)} Fehlerzeilen in {log}; letzte Stelle (Zeile {hits[-1] + 1}):")
print("\n".join(lines[start:hits[-1] + n // 2]))
if __name__ == "__main__":
a = sys.argv[1:]
if not a or a == ["--full"]:
inventory("--full" in a)
elif a[0] == "--log":
show_log(int(a[1]) if len(a) > 1 else 40)
else:
validate(a[0])

11
template/audio.py Normal file
View File

@@ -0,0 +1,11 @@
"""Musik und Effekte für generate_audio.py (Stable Audio). Mindestlänge 1 s.
CLIPS = [(name, prompt, sekunden, negative)]
"""
NEG_MUSIC = "vocals, singing, speech, harsh noise, distortion, abrupt ending, low quality"
NEG_SFX = "music, melody, vocals, speech, reverb tail, background ambience, low quality"
CLIPS = [
("sfx_click", "short soft UI button click", 1, NEG_SFX),
("music_menu", "calm looping menu music, light synth pads", 30, NEG_MUSIC),
]

38
template/config.py Normal file
View File

@@ -0,0 +1,38 @@
"""Projekt-Konfiguration für die ComfyGen-Werkzeuge. Diesen Ordner (template/) in das neue
Projekt kopieren, z. B. als <Projekt>\\sprite-generator\\, und die Pfade unten anpassen."""
import os
HERE = os.path.dirname(os.path.abspath(__file__))
# ComfyUI-Server (lokal).
HOST = "http://127.0.0.1:8188"
# Workflow aus ComfyGen\workflows\ – Flux.2 Klein ist der empfohlene Standard.
WORKFLOW_FILE = "Text to Image - Flux Klein.json"
UNET_NAME = "flux-2-klein-4b-fp8.safetensors"
CLIP_NAME = "qwen_3_4b.safetensors"
CLIP_TYPE = "flux2"
VAE_NAME = "flux2-vae.safetensors"
CHECKPOINT = "" # nur für workflows/default.json (SDXL o. ä.)
# Roh-Ergebnisse (nicht in git).
OUTPUT_DIR = os.path.join(HERE, "output")
# Wird genutzt, wenn ein Prompt keinen eigenen Negativ-Prompt hat.
NEGATIVE_PROMPT = "text, watermark, signature, blurry, low quality, extra limbs"
# Ziel für adopt*.py (schreibt nach ASSETS_DIR\Sprites, \Audio, \Video).
PROJECT_ROOT = os.path.join(HERE, "..")
ASSETS_DIR = os.path.join(PROJECT_ROOT, "Assets")
# Listen-Module in diesem Ordner.
PROMPTS_MODULE = "prompts"
AUDIO_MODULE = "audio"
# Optional, nur wenn gebraucht:
# AUDIO_SUBDIR = "audio"
# VIDEO_MODULE = "video"
# PORTRAITS_MODULE = "portraits"
# VINTAGE_MODULE = "vintage"
# VOICE_MODULE = "voice"
# LANG_DIR = os.path.join(PROJECT_ROOT, "Languages")
# CARDS_FILE = os.path.join(PROJECT_ROOT, "cards.json")

24
template/gen.cmd Normal file
View File

@@ -0,0 +1,24 @@
@echo off
rem Starts a tool from D:\Oculusquest\Projekt\_Tools\ComfyGen for this project.
rem gen list the tools
rem gen generate <name> image from prompts.py
rem gen adopt <name> cut out + copy into ASSETS_DIR\Sprites
rem gen generate_audio <name> music / sfx from the audio list
set TOOLS=D:\Oculusquest\Projekt\_Tools\ComfyGen
rem shift below also moves %0, so remember this folder first
set HERE=%~dp0
set SCRIPT=%~1
if "%SCRIPT%"=="" (
echo Tools:& dir /b "%TOOLS%\*.py" | findstr /v /b "_"
exit /b 0
)
shift
set PY=py -3.12
if /i "%SCRIPT%"=="generate_voice" set PY="%TOOLS%\.venv-tts\Scripts\python.exe"
if /i "%SCRIPT%"=="make_voice_refs" set PY="%TOOLS%\.venv-tts\Scripts\python.exe"
set PYTHONIOENCODING=utf-8
pushd "%HERE%"
%PY% "%TOOLS%\%SCRIPT%.py" %1 %2 %3 %4 %5 %6 %7 %8 %9
set RC=%ERRORLEVEL%
popd
exit /b %RC%

18
template/prompts.py Normal file
View File

@@ -0,0 +1,18 @@
"""Was generate.py erzeugt.
PROMPTS = [(name, positive)] oder [(name, positive, negative)]
SIZES = {name: (breite, höhe)} optional, sonst Größe des Workflows (1024x1024)
Immer "plain solid black background" verlangen, nie "transparent": cutout.py/adopt.py
stellen den schwarzen Hintergrund deterministisch frei.
"""
_STYLE = (
"game sprite, clean outline, bold colours, soft shading, "
"centred single subject, plain solid black background"
)
PROMPTS = [
("example_coin", f"a shiny gold coin, {_STYLE}"),
]
SIZES = {}