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) <noreply@anthropic.com>
170 lines
7.9 KiB
Python
170 lines
7.9 KiB
Python
"""
|
|
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/<g><look>_<stage>.png -> Assets/Sprites/portrait_<g>_<look>_<stage>.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)
|