Compare commits
10 Commits
53e83ad096
...
877f851160
| Author | SHA1 | Date | |
|---|---|---|---|
| 877f851160 | |||
| e7e3bcbbcb | |||
| dab37de87a | |||
| 0890bf025f | |||
| fa2d0592fd | |||
| 953ec56630 | |||
| f5fdd4a6d4 | |||
| 31768ca41c | |||
| 052a56bc11 | |||
| 3b39dbce0b |
10
README.md
10
README.md
@@ -7,7 +7,9 @@ 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` |
|
||||
| `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 +26,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 <name>`.
|
||||
Jedes Projekt hat einen Starter `gen.cmd`, z. B. `gen generate <name>`.
|
||||
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\`).
|
||||
|
||||
13
adopt.py
13
adopt.py
@@ -9,6 +9,8 @@ PictureBoxSizeMode.Zoom, so square keeps every icon the same visual size.
|
||||
py -3.12 adopt.py stat_health life_baby several
|
||||
py -3.12 adopt.py --all every name in the prompt list
|
||||
py -3.12 adopt.py --size 512 hero larger square (default 128)
|
||||
py -3.12 adopt.py --holes archer also clear enclosed black (see cutout.py)
|
||||
py -3.12 adopt.py --ai hero dark parts decided by a matting model (rembg)
|
||||
"""
|
||||
import glob
|
||||
import importlib
|
||||
@@ -19,7 +21,7 @@ from PIL import Image
|
||||
|
||||
import _bootstrap # Projektordner (config.py, Listen) vor allen anderen Modulen
|
||||
import config
|
||||
from cutout import cutout
|
||||
from cutout import cutout, cutout_ai
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
DEST = os.path.join(config.ASSETS_DIR, "Sprites")
|
||||
@@ -28,7 +30,7 @@ MARGIN = 0.04 # share of the side left free around the icon
|
||||
ALPHA_THRESHOLD = 8
|
||||
|
||||
|
||||
def adopt(name, size=None):
|
||||
def adopt(name, size=None, holes=False, ai=False):
|
||||
size = size or SIZE
|
||||
raws = sorted(glob.glob(os.path.join(config.OUTPUT_DIR, f"{name}_raw_*.png")),
|
||||
key=os.path.getmtime)
|
||||
@@ -36,7 +38,7 @@ def adopt(name, size=None):
|
||||
print(f" {name}: no raw render in output/, skipped")
|
||||
return False
|
||||
|
||||
image = cutout(raws[-1])
|
||||
image = cutout_ai(raws[-1]) if ai else cutout(raws[-1], holes=holes)
|
||||
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")
|
||||
@@ -76,6 +78,9 @@ def adopt_backdrop(name, width=1920, height=1080):
|
||||
if __name__ == "__main__":
|
||||
args = sys.argv[1:]
|
||||
size = None
|
||||
holes = "--holes" in args
|
||||
ai = "--ai" in args
|
||||
args = [a for a in args if a not in ("--holes", "--ai")]
|
||||
if len(args) >= 2 and args[0] == "--size":
|
||||
size = int(args[1])
|
||||
args = args[2:]
|
||||
@@ -87,5 +92,5 @@ if __name__ == "__main__":
|
||||
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, size) for n in args)
|
||||
ok = sum(adopt(n, size, holes, ai) for n in args)
|
||||
print(f"{ok}/{len(args)} adopted")
|
||||
|
||||
69
adopt_scene.py
Normal file
69
adopt_scene.py
Normal 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:]))
|
||||
@@ -11,11 +11,17 @@ 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.
|
||||
|
||||
Optional per clip, ADOPT = {name: {"tween": bool, "shade": 0..255, "frames": n}} in the
|
||||
project's VIDEO_MODULE: tween=False keeps the 49 raw frames (slow loops, half the size), shade
|
||||
darkens every frame by that alpha of black (to match a dimmed backdrop in the game), frames
|
||||
keeps only the first n raw frames (cut a clip before it goes wrong).
|
||||
|
||||
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 importlib
|
||||
import os
|
||||
import sys
|
||||
|
||||
@@ -26,6 +32,7 @@ from PIL import Image, ImageDraw, ImageFilter
|
||||
import _bootstrap # Projektordner (config.py, Listen) vor allen anderen Modulen
|
||||
import config
|
||||
|
||||
ADOPT = getattr(importlib.import_module(getattr(config, "VIDEO_MODULE", "video_life")), "ADOPT", {})
|
||||
SRC = os.path.join(config.OUTPUT_DIR, "video")
|
||||
DEST = os.path.join(config.ASSETS_DIR, "Video")
|
||||
QUALITY = 80
|
||||
@@ -80,9 +87,10 @@ def adopt(name):
|
||||
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]
|
||||
opts = ADOPT.get(name, {})
|
||||
raw = [np.asarray(Image.open(f).convert("RGB")) for f in frames[:opts.get("frames", len(frames))]]
|
||||
scene = name.startswith("scene_")
|
||||
if not scene:
|
||||
if opts.get("tween", not scene):
|
||||
raw = interpolate(raw)
|
||||
size = (raw[0].shape[1], raw[0].shape[0])
|
||||
mask = bottom_shade(size) if scene else vignette(size)
|
||||
@@ -90,6 +98,8 @@ def adopt(name):
|
||||
total = 0
|
||||
for i, arr in enumerate(raw):
|
||||
im = Image.composite(black, Image.fromarray(arr), mask)
|
||||
if opts.get("shade"):
|
||||
im = Image.composite(Image.new("RGB", size, (0, 0, 0)), im, Image.new("L", size, opts["shade"]))
|
||||
p = os.path.join(DEST, f"{name}_{i:02d}.jpg")
|
||||
im.save(p, quality=QUALITY, optimize=True)
|
||||
total += os.path.getsize(p)
|
||||
|
||||
187
comfy_check.py
Normal file
187
comfy_check.py
Normal 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])
|
||||
22
cutout.py
22
cutout.py
@@ -88,6 +88,28 @@ def cutout(path, holes=False, share=HOLE_SHARE):
|
||||
return Image.fromarray(out.astype(np.uint8), "RGBA")
|
||||
|
||||
|
||||
_SESSION = None
|
||||
|
||||
|
||||
def cutout_ai(path, model="isnet-general-use"):
|
||||
"""Wie cutout(), aber fast schwarze Stellen entscheidet ein Freistell-Modell (rembg):
|
||||
dunkle Haut, dunkler Stoff oder Haare bleiben Figur, eingeschlossene Lücken (zwischen Arm
|
||||
und Körper, im Lasso) werden Hintergrund. Helle Bildteile behalten die genaue Kante."""
|
||||
global _SESSION
|
||||
from rembg import new_session, remove
|
||||
if _SESSION is None:
|
||||
_SESSION = new_session(model)
|
||||
base = cutout(path) # Kante und helle Teile
|
||||
arr = np.asarray(base).copy()
|
||||
rgb = arr[:, :, :3].astype(np.int16)
|
||||
brightness = rgb.max(axis=2)
|
||||
mask = np.asarray(remove(Image.open(path).convert("RGB"), session=_SESSION, only_mask=True).convert("L"))
|
||||
dark = ndimage.binary_dilation(brightness <= BLACK_THRESHOLD + 25, iterations=2)
|
||||
# dunkle Bereiche: Deckkraft vom Modell (weich), sonst unverändert
|
||||
arr[:, :, 3] = np.where(dark, mask, arr[:, :, 3]).astype(np.uint8)
|
||||
return Image.fromarray(arr, "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("--")}
|
||||
|
||||
@@ -7,6 +7,8 @@ Usage:
|
||||
or transparent background. What the sprite generator already
|
||||
produces, in other words.
|
||||
[name] what the GLB is called. Defaults to the image's own stem.
|
||||
--no-square send the image as it is (otherwise it is padded to a white
|
||||
square first, see `square`)
|
||||
|
||||
Hunyuan3D v2 turns one picture into geometry: image -> CLIP vision -> a
|
||||
diffusion pass in a 3D latent -> voxels -> a mesh, saved as a GLB. It produces
|
||||
@@ -78,6 +80,32 @@ def upload_image(path):
|
||||
return answer.get("name", name)
|
||||
|
||||
|
||||
def square(path, margin=0.08):
|
||||
"""Pads the picture to a square, object centred, on white.
|
||||
|
||||
CLIPVisionEncode crops the centre square, so a portrait image lost its top
|
||||
and bottom (a gladiator's helmet and feet) and the shape came out squashed.
|
||||
Hunyuan3D was trained on objects filling ~85 % of a white square; with an
|
||||
alpha channel the transparent part becomes white too.
|
||||
"""
|
||||
from PIL import Image
|
||||
im = Image.open(path)
|
||||
if im.mode == "RGBA":
|
||||
bbox = im.getchannel("A").point(lambda a: 255 if a > 40 else 0).getbbox() or (0, 0) + im.size
|
||||
im = im.crop(bbox)
|
||||
flat = Image.new("RGB", im.size, (255, 255, 255))
|
||||
flat.paste(im, mask=im.getchannel("A"))
|
||||
im = flat
|
||||
else:
|
||||
im = im.convert("RGB")
|
||||
side = round(max(im.size) / (1 - 2 * margin))
|
||||
out = Image.new("RGB", (side, side), (255, 255, 255))
|
||||
out.paste(im, ((side - im.width) // 2, (side - im.height) // 2))
|
||||
dest = os.path.join(config.OUTPUT_DIR, "_mesh_input_" + os.path.splitext(os.path.basename(path))[0] + ".png")
|
||||
out.save(dest)
|
||||
return dest
|
||||
|
||||
|
||||
def build(image_name, name, seed, octree):
|
||||
path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "workflows", WORKFLOW)
|
||||
with open(path, "r", encoding="utf-8") as handle:
|
||||
@@ -164,7 +192,7 @@ def main():
|
||||
octree = int(flag.split("=", 1)[1])
|
||||
|
||||
os.makedirs(config.OUTPUT_DIR, exist_ok=True)
|
||||
uploaded = upload_image(source)
|
||||
uploaded = upload_image(source if "--no-square" in flags else square(source))
|
||||
print(f"[{name}] uploaded {uploaded}")
|
||||
|
||||
workflow = build(uploaded, name, random.randint(1, 2 ** 32 - 1), octree)
|
||||
|
||||
146
generate_variants.py
Normal file
146
generate_variants.py
Normal file
@@ -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/<name>_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)
|
||||
91
make_tileable.py
Normal file
91
make_tileable.py
Normal file
@@ -0,0 +1,91 @@
|
||||
"""Make a generated render tile seamlessly (textures for 3D floors, walls, cloth).
|
||||
|
||||
Takes the newest raw render for <name> from the project's output/ folder, cross-blends it
|
||||
with a copy shifted by half its size (so the seams move into the middle and fade out),
|
||||
scales it and writes ../Assets/Sprites/<name>.jpg (or .png with --png).
|
||||
|
||||
py -3.12 make_tileable.py tex_sand both directions (floors)
|
||||
py -3.12 make_tileable.py --x tex_wall_stone only left/right (walls, friezes)
|
||||
py -3.12 make_tileable.py --size 1024x512 tex_wall output size (default: render size)
|
||||
py -3.12 make_tileable.py --blend 0.3 tex_sand width of the fade (share of the side, default 0.25)
|
||||
|
||||
Works on any image: make_tileable.py --file in.png out.jpg [--x] [--size WxH]
|
||||
"""
|
||||
import glob
|
||||
import os
|
||||
import sys
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
|
||||
def tileable(img, x_only=False, blend=0.25):
|
||||
"""Seamless version of img: interior of the original, edges taken from the half-shifted copy."""
|
||||
a = np.asarray(img.convert("RGB"), dtype=np.float32)
|
||||
h, w, _ = a.shape
|
||||
b = np.roll(a, (0 if x_only else h // 2, w // 2), axis=(0, 1))
|
||||
|
||||
def ramp(n):
|
||||
# 0 at the edge, 1 after blend*n pixels, smooth in between
|
||||
d = np.minimum(np.arange(n), np.arange(n)[::-1]) / max(1.0, blend * n)
|
||||
d = np.clip(d, 0, 1)
|
||||
return d * d * (3 - 2 * d)
|
||||
|
||||
wx = ramp(w)[None, :]
|
||||
wy = np.ones((h, 1)) if x_only else ramp(h)[:, None]
|
||||
k = (wx * wy)[..., None]
|
||||
out = a * k + b * (1 - k)
|
||||
return Image.fromarray(np.clip(out, 0, 255).astype(np.uint8))
|
||||
|
||||
|
||||
def save(img, dest, size=None):
|
||||
if size:
|
||||
img = img.resize(size, Image.LANCZOS)
|
||||
os.makedirs(os.path.dirname(dest), exist_ok=True)
|
||||
if dest.lower().endswith(".png"):
|
||||
img.save(dest, optimize=True)
|
||||
else:
|
||||
img.save(dest, quality=90)
|
||||
print(f" -> {dest} {img.size[0]}x{img.size[1]}")
|
||||
|
||||
|
||||
def main(args):
|
||||
x_only = "--x" in args
|
||||
png = "--png" in args
|
||||
size, blend, files = None, 0.25, False
|
||||
names = []
|
||||
i = 0
|
||||
while i < len(args):
|
||||
a = args[i]
|
||||
if a == "--size":
|
||||
w, h = args[i + 1].lower().split("x"); size = (int(w), int(h)); i += 2; continue
|
||||
if a == "--blend":
|
||||
blend = float(args[i + 1]); i += 2; continue
|
||||
if a == "--file":
|
||||
files = True
|
||||
elif not a.startswith("--"):
|
||||
names.append(a)
|
||||
i += 1
|
||||
if files:
|
||||
if len(names) != 2:
|
||||
print(__doc__); return 1
|
||||
save(tileable(Image.open(names[0]), x_only, blend), names[1], size)
|
||||
return 0
|
||||
if not names:
|
||||
print(__doc__); return 1
|
||||
|
||||
import _bootstrap # noqa: F401 Projektordner (config.py) zuerst
|
||||
import config
|
||||
ok = True
|
||||
for name in names:
|
||||
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"); ok = False; continue
|
||||
dest = os.path.join(config.ASSETS_DIR, "Sprites", name + (".png" if png else ".jpg"))
|
||||
print(f" {name}: {os.path.basename(raws[-1])}")
|
||||
save(tileable(Image.open(raws[-1]), x_only, blend), dest, size)
|
||||
return 0 if ok else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
@@ -5,7 +5,8 @@ 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
|
||||
writes voice_refs/female.wav, voice_refs/male.wav and voice_refs/warrior.wav
|
||||
(warrior: very deep, rough battle voice – Kokoro bm_lewis, −3 semitones, soft saturation)
|
||||
"""
|
||||
import _bootstrap # Projektordner (config.py, Listen) vor allen anderen Modulen
|
||||
import config
|
||||
@@ -25,6 +26,21 @@ TEXT = ("Once upon a time, in a quiet little town by the sea, a child was born.
|
||||
|
||||
VOICES = {"female": "af_heart", "male": "am_michael"}
|
||||
|
||||
WARRIOR_TEXT = ("Hear me, sons of Rome! I have bled in this sand for years. I have broken chains and broken men. "
|
||||
"Tonight I fight, and tomorrow I will be free!")
|
||||
|
||||
|
||||
def warrior():
|
||||
import librosa
|
||||
audio = np.concatenate([a.numpy() if hasattr(a, "numpy") else a
|
||||
for _, _, a in KPipeline(lang_code="b")(WARRIOR_TEXT, voice="bm_lewis", speed=0.88)])
|
||||
deep = librosa.effects.pitch_shift(audio.astype(np.float32), sr=24000, n_steps=-3)
|
||||
deep = deep / (np.abs(deep).max() + 1e-6)
|
||||
rough = np.tanh(deep * 2.6) / np.tanh(2.6) * 0.6 + deep * 0.4
|
||||
path = os.path.join(OUT, "warrior.wav")
|
||||
sf.write(path, rough * 0.9, 24000)
|
||||
print(f"warrior: bm_lewis deep/rough, {len(audio) / 24000:.1f} s -> {path}")
|
||||
|
||||
|
||||
def main():
|
||||
os.makedirs(OUT, exist_ok=True)
|
||||
@@ -35,6 +51,7 @@ def main():
|
||||
path = os.path.join(OUT, f"{name}.wav")
|
||||
sf.write(path, audio, 24000)
|
||||
print(f"{name}: {voice}, {len(audio) / 24000:.1f} s -> {path}")
|
||||
warrior()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
276
paint_mesh.py
Normal file
276
paint_mesh.py
Normal file
@@ -0,0 +1,276 @@
|
||||
"""Gives a Hunyuan3D shape its colours back, from the pictures it was made from.
|
||||
|
||||
gen paint_mesh <shape.glb> <front.png> [--back=<back.png>] [--back-mirrored]
|
||||
[--name=hero] [--faces=30000] [--height=180] [--smooth=12]
|
||||
|
||||
Hunyuan3D (generate_mesh) returns shape only. This tool:
|
||||
|
||||
* **cleans** the shape: keeps the big parts (the raw mesh has tens of thousands
|
||||
of crumbs), decimates to `--faces` with quadric simplification (smooth, not
|
||||
faceted like mesh_prep), and turns all faces outwards;
|
||||
* **lines up** every view with the shape: the mesh's silhouette is fitted to the
|
||||
picture's silhouette (bounding box first, then a small search for the best
|
||||
overlap), so a view does not have to match pixel for pixel;
|
||||
* **projects** the colours: each vertex takes the colour of the pixel it lands on
|
||||
in each view where it is visible (z-buffer, so the shield does not paint the
|
||||
arm behind it), weighted by how squarely it faces that view; whatever no view
|
||||
sees is filled from its neighbours;
|
||||
* **writes** `<name>_painted.glb` (vertex colours, smooth normals),
|
||||
`<name>_mixamo.obj` (same shape without colour, feet on the ground, facing +Z,
|
||||
`--height` units tall: what mixamo.com wants for auto-rigging) and
|
||||
`<name>_painted.png` (front, three-quarter, side and back preview).
|
||||
|
||||
Views are orthographic: the front picture looks from +Z (the side Hunyuan puts
|
||||
the picture's subject on), the back picture from -Z. A back view drawn as a
|
||||
mirror image (shield on the same side as in the front view - image models do
|
||||
that) needs `--back-mirrored`. Pictures may be RGBA, or RGB on black (then
|
||||
cutout_ai finds the figure). Magenta and every other colour pass through as
|
||||
they are, so a game can still recolour team colours.
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
|
||||
import numpy as np
|
||||
import trimesh
|
||||
from PIL import Image
|
||||
from scipy import ndimage, sparse
|
||||
|
||||
import _bootstrap # noqa: F401 Projektordner (config.py) vor allen anderen Modulen
|
||||
import config
|
||||
|
||||
|
||||
# ── shape ────────────────────────────────────────────────────────────────
|
||||
|
||||
def clean(path, faces, smooth=12):
|
||||
mesh = trimesh.load(path, force="mesh")
|
||||
parts = mesh.split(only_watertight=False)
|
||||
big = max(len(p.faces) for p in parts)
|
||||
keep = [p for p in parts if len(p.faces) >= big * 0.02]
|
||||
mesh = trimesh.util.concatenate(keep)
|
||||
print(f"shape: {len(parts)} parts, kept {len(keep)} -> {len(mesh.faces)} faces")
|
||||
if smooth:
|
||||
# surface net leaves a grainy, stair-stepped skin; Taubin smooths it without shrinking
|
||||
trimesh.smoothing.filter_taubin(mesh, iterations=smooth)
|
||||
if len(mesh.faces) > faces:
|
||||
mesh = mesh.simplify_quadric_decimation(face_count=faces)
|
||||
mesh.merge_vertices()
|
||||
mesh.remove_unreferenced_vertices()
|
||||
trimesh.repair.fix_winding(mesh)
|
||||
trimesh.repair.fix_inversion(mesh, multibody=True)
|
||||
print(f"shape: {len(mesh.vertices)} vertices, {len(mesh.faces)} faces")
|
||||
return mesh
|
||||
|
||||
|
||||
# ── views ────────────────────────────────────────────────────────────────
|
||||
|
||||
def load_view(path, mirrored=False):
|
||||
"""RGB (float 0..1) and mask (bool) of a picture; holes in the mask filled."""
|
||||
im = Image.open(path)
|
||||
if im.mode == "RGBA":
|
||||
rgba = np.asarray(im)
|
||||
else:
|
||||
from cutout import cutout_ai
|
||||
cut = np.asarray(cutout_ai(path))
|
||||
rgba = np.dstack([np.asarray(im.convert("RGB")), cut[:, :, 3]])
|
||||
if mirrored:
|
||||
rgba = rgba[:, ::-1]
|
||||
rgb = rgba[:, :, :3].astype(np.float32) / 255
|
||||
mask = ndimage.binary_fill_holes(rgba[:, :, 3] > 100)
|
||||
return rgb, mask
|
||||
|
||||
|
||||
def robust_box(mask):
|
||||
cols = np.nonzero(mask.sum(0) > 3)[0]
|
||||
rows = np.nonzero(mask.sum(1) > 3)[0]
|
||||
return cols.min(), cols.max(), rows.min(), rows.max()
|
||||
|
||||
|
||||
def project(points, sign):
|
||||
"""Orthographic view from +Z (sign 1) or -Z (sign -1): image x, image y (up) and depth toward the camera."""
|
||||
return points[:, 0] * sign, points[:, 1], points[:, 2] * sign
|
||||
|
||||
|
||||
def fit(samples, sign, mask):
|
||||
"""Scale/offset that put the mesh's silhouette on the picture's: (sx, sy, tx, ty), pixel = x*sx+tx, row = ty-y*sy."""
|
||||
h, w = mask.shape
|
||||
x, y, _ = project(samples, sign)
|
||||
c0, c1, r0, r1 = robust_box(mask)
|
||||
sx = (c1 - c0) / max(np.ptp(x), 1e-6)
|
||||
sy = (r1 - r0) / max(np.ptp(y), 1e-6)
|
||||
p = np.array([sx, sy, c0 - x.min() * sx, r0 + y.max() * sy])
|
||||
|
||||
small = 4 # search on a quarter-size grid
|
||||
target = mask[::small, ::small]
|
||||
sh, sw = target.shape
|
||||
|
||||
def score(q):
|
||||
u = ((x * q[0] + q[2]) / small).astype(np.int32)
|
||||
v = ((q[3] - y * q[1]) / small).astype(np.int32)
|
||||
ok = (u >= 0) & (u < sw) & (v >= 0) & (v < sh)
|
||||
sil = np.zeros((sh, sw), bool)
|
||||
sil[v[ok], u[ok]] = True
|
||||
sil = ndimage.binary_closing(sil, iterations=1)
|
||||
return (sil & target).sum() / max((sil | target).sum(), 1)
|
||||
|
||||
best = score(p)
|
||||
for step in (0.04, 0.02, 0.01, 0.005):
|
||||
improved = True
|
||||
while improved:
|
||||
improved = False
|
||||
for i in range(4):
|
||||
for d in (-1, 1):
|
||||
q = p.copy()
|
||||
q[i] += d * step * (p[i] if i < 2 else (w if i == 2 else h))
|
||||
s = score(q)
|
||||
if s > best + 1e-4:
|
||||
best, p, improved = s, q, True
|
||||
print(f" fit: overlap {best:.3f}")
|
||||
return p
|
||||
|
||||
|
||||
def zbuffer(samples, sign, p, shape, scale=2):
|
||||
"""Nearest depth per (scale x smaller) pixel, from dense surface samples."""
|
||||
h, w = shape[0] // scale, shape[1] // scale
|
||||
x, y, z = project(samples, sign)
|
||||
u = ((x * p[0] + p[2]) / scale).astype(np.int64)
|
||||
v = ((p[3] - y * p[1]) / scale).astype(np.int64)
|
||||
ok = (u >= 0) & (u < w) & (v >= 0) & (v < h)
|
||||
buf = np.full(h * w, -np.inf)
|
||||
np.maximum.at(buf, v[ok] * w + u[ok], z[ok])
|
||||
return buf.reshape(h, w), scale
|
||||
|
||||
|
||||
def sample_view(verts, normals, sign, view, samples, tol):
|
||||
rgb, mask = view
|
||||
p = fit(samples, sign, mask)
|
||||
zb, sc = zbuffer(samples, sign, p, mask.shape)
|
||||
x, y, z = project(verts, sign)
|
||||
u = x * p[0] + p[2]
|
||||
v = p[3] - y * p[1]
|
||||
h, w = mask.shape
|
||||
ui = np.clip(u.round().astype(int), 0, w - 1)
|
||||
vi = np.clip(v.round().astype(int), 0, h - 1)
|
||||
inside = (u >= 0) & (u < w) & (v >= 0) & (v < h) & mask[vi, ui]
|
||||
# visible: no surface noticeably nearer the camera in the 3x3 around it
|
||||
near = ndimage.maximum_filter(zb, size=3)
|
||||
zi = near[np.clip(vi // sc, 0, zb.shape[0] - 1), np.clip(ui // sc, 0, zb.shape[1] - 1)]
|
||||
visible = z >= zi - tol
|
||||
facing = np.clip(normals[:, 2] * sign, 0, 1)
|
||||
weight = np.where(inside & visible, facing ** 1.5, 0.0)
|
||||
# bilinear colour
|
||||
u0 = np.clip(np.floor(u).astype(int), 0, w - 2); v0 = np.clip(np.floor(v).astype(int), 0, h - 2)
|
||||
fu = np.clip(u - u0, 0, 1)[:, None]; fv = np.clip(v - v0, 0, 1)[:, None]
|
||||
col = (rgb[v0, u0] * (1 - fu) * (1 - fv) + rgb[v0, u0 + 1] * fu * (1 - fv)
|
||||
+ rgb[v0 + 1, u0] * (1 - fu) * fv + rgb[v0 + 1, u0 + 1] * fu * fv)
|
||||
print(f" {int((weight > 0).sum())} of {len(verts)} vertices coloured")
|
||||
return col, weight
|
||||
|
||||
|
||||
def fill(mesh, colours, known):
|
||||
"""Unknown vertices take the mean of their known neighbours, repeatedly."""
|
||||
edges = mesh.edges_unique
|
||||
n = len(mesh.vertices)
|
||||
adj = sparse.coo_matrix((np.ones(len(edges) * 2), (np.r_[edges[:, 0], edges[:, 1]], np.r_[edges[:, 1], edges[:, 0]])),
|
||||
shape=(n, n)).tocsr()
|
||||
known = known.copy()
|
||||
for _ in range(400):
|
||||
if known.all():
|
||||
break
|
||||
k = known.astype(np.float64)
|
||||
s = adj @ (colours * k[:, None])
|
||||
c = adj @ k
|
||||
grow = (~known) & (c > 0)
|
||||
if not grow.any():
|
||||
break
|
||||
colours[grow] = s[grow] / c[grow, None]
|
||||
known |= grow
|
||||
return colours
|
||||
|
||||
|
||||
# ── preview ──────────────────────────────────────────────────────────────
|
||||
|
||||
def preview(mesh, colours, path, size=600):
|
||||
pts, fi = trimesh.sample.sample_surface(mesh, 900_000)
|
||||
bary = trimesh.triangles.points_to_barycentric(mesh.triangles[fi], pts)
|
||||
col = (colours[mesh.faces[fi]] * bary[:, :, None]).sum(1)
|
||||
nrm = mesh.face_normals[fi]
|
||||
lo, hi = mesh.bounds
|
||||
scale = (size - 40) / (hi[1] - lo[1])
|
||||
tiles = []
|
||||
for yaw in (0, -35, -90, 180):
|
||||
a = np.radians(yaw)
|
||||
rot = np.array([[np.cos(a), 0, np.sin(a)], [0, 1, 0], [-np.sin(a), 0, np.cos(a)]])
|
||||
p = (pts - (lo + hi) / 2) @ rot.T
|
||||
n = nrm @ rot.T
|
||||
light = 0.45 + 0.55 * np.clip(n @ np.array([0.3, 0.5, 0.81]), 0, 1)
|
||||
u = (p[:, 0] * scale + size / 2).astype(int)
|
||||
v = (size / 2 - p[:, 1] * scale).astype(int)
|
||||
ok = (u >= 0) & (u < size) & (v >= 0) & (v < size)
|
||||
order = np.argsort(p[ok, 2])
|
||||
img = np.full((size, size, 3), 40, np.float32)
|
||||
img[v[ok][order], u[ok][order]] = (col[ok] * light[ok, None])[order] * 255
|
||||
tiles.append(img)
|
||||
Image.fromarray(np.hstack(tiles).clip(0, 255).astype(np.uint8)).save(path)
|
||||
|
||||
|
||||
# ── main ─────────────────────────────────────────────────────────────────
|
||||
|
||||
def main():
|
||||
args = [a for a in sys.argv[1:] if not a.startswith("--")]
|
||||
flags = {a.split("=", 1)[0]: (a.split("=", 1)[1] if "=" in a else True) for a in sys.argv[1:] if a.startswith("--")}
|
||||
if len(args) < 2:
|
||||
print(__doc__)
|
||||
return 1
|
||||
name = flags.get("--name") or os.path.splitext(os.path.basename(args[0]))[0]
|
||||
out = config.OUTPUT_DIR
|
||||
os.makedirs(out, exist_ok=True)
|
||||
|
||||
mesh = clean(args[0], int(flags.get("--faces", 30000)), int(flags.get("--smooth", 12)))
|
||||
verts = np.asarray(mesh.vertices)
|
||||
normals = np.asarray(mesh.vertex_normals)
|
||||
samples, _ = trimesh.sample.sample_surface(mesh, 600_000)
|
||||
tol = np.ptp(verts[:, 1]) * 0.012
|
||||
|
||||
total = np.zeros((len(verts), 3)); weight = np.zeros(len(verts))
|
||||
views = [("front", args[1], 1, False)]
|
||||
if flags.get("--back"):
|
||||
views.append(("back", flags["--back"], -1, bool(flags.get("--back-mirrored"))))
|
||||
for label, path, sign, mirrored in views:
|
||||
print(f"{label}: {path}")
|
||||
col, w = sample_view(verts, normals, sign, load_view(path, mirrored), samples, tol)
|
||||
total += col * w[:, None]; weight += w
|
||||
known = weight > 0.02
|
||||
colours = np.where(known[:, None], total / np.maximum(weight, 1e-9)[:, None], 0.5)
|
||||
colours = fill(mesh, colours, known)
|
||||
|
||||
# standing on the ground, centred, --height tall (same transform for both files)
|
||||
lo, hi = mesh.bounds
|
||||
scale = float(flags.get("--height", 180)) / (hi[1] - lo[1])
|
||||
mesh.apply_translation([-(lo[0] + hi[0]) / 2, -lo[1], -(lo[2] + hi[2]) / 2])
|
||||
mesh.apply_scale(scale)
|
||||
|
||||
painted = mesh.copy()
|
||||
painted.visual = trimesh.visual.ColorVisuals(painted, vertex_colors=(np.c_[colours, np.ones(len(colours))] * 255).astype(np.uint8))
|
||||
glb = os.path.join(out, f"{name}_painted.glb")
|
||||
with open(glb, "wb") as f:
|
||||
f.write(trimesh.exchange.gltf.export_glb(painted, include_normals=True))
|
||||
# Punkte + Farben schlicht binär (fbx2gim überträgt sie auf die Mixamo-Figur; Assimp liest die
|
||||
# Farben aus der GLB nicht zuverlässig): int Anzahl, je Punkt 3 float + 4 byte RGBA
|
||||
pcol = os.path.join(out, f"{name}_painted.pcol")
|
||||
rgba = (np.c_[np.clip(colours, 0, 1), np.ones(len(colours))] * 255).round().astype(np.uint8)
|
||||
rec = np.zeros(len(colours), dtype=[("p", "<f4", 3), ("c", "u1", 4)])
|
||||
rec["p"] = mesh.vertices; rec["c"] = rgba
|
||||
with open(pcol, "wb") as f:
|
||||
f.write(np.int32(len(rec)).tobytes()); f.write(rec.tobytes())
|
||||
obj = os.path.join(out, f"{name}_mixamo.obj")
|
||||
plain = trimesh.Trimesh(mesh.vertices, mesh.faces, process=False)
|
||||
with open(obj, "w", encoding="utf-8") as f:
|
||||
f.write(trimesh.exchange.obj.export_obj(plain, include_normals=True, include_color=False, include_texture=False))
|
||||
png = os.path.join(out, f"{name}_painted.png")
|
||||
preview(mesh, colours, png)
|
||||
print(f"-> {glb}\n-> {pcol}\n-> {obj}\n-> {png}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
11
template/audio.py
Normal file
11
template/audio.py
Normal 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
38
template/config.py
Normal 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
24
template/gen.cmd
Normal 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
18
template/prompts.py
Normal 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 = {}
|
||||
BIN
voice_refs/warrior.wav
Normal file
BIN
voice_refs/warrior.wav
Normal file
Binary file not shown.
Reference in New Issue
Block a user