Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

CH48c: words to a sewn garment through SigLIP 2, trained with no captions. Each lean design is pictured from four sides (bake_batch.py PICTURES=1) and embedded with SigLIP 2 on the CPU (garment_embed.py); a small network learns the design's 122 settings as 196 slots (garment_params.py) from the picture embeddings, centred and with noise added, and is asked with a line's text embedding centred on a bank of garment lines (garment_model.py train, eval, make). words.sh makes each line a design, cuts it to SOMA, drapes and pictures it. First run on 86 designs: held out, the top's kind 0.66 against 0.44 most common, the bottom's 0.59 against 0.31; twelve lines of words 11 of 12, as many as the nearest picture, where a random design passes one or two; seven lines all valid patterns that hang right, six read as asked. sample_designs.py takes a given design (DESIGN, GID); sheet.py labels a garment asked in words with its words

shinyobjectz7d893bb612b5
diff --git a/docs/character.feature b/docs/character.feature
index fe95ad72..4e10258c 100644
--- a/docs/character.feature
+++ b/docs/character.feature
@@ -730,6 +730,27 @@ Feature: The character SDK as one system: SOMA bodies, Kimodo motion, generated
Then the training set holds sewn garments captioned by their settings and by what they look like
And worn hard pieces from CH49, each with its words, its picture and its 3D on SOMA
+ Scenario: CH48c. Words to a sewn garment through SigLIP 2, trained with no captions (first form of CH48)
+ # 11-15. The base weights are SigLIP 2 (siglip2-base-p16-256, already in raea's models, Apache-2.0), whose
+ # pictures and words share one space. Each lean design is pictured on the mannequin from four sides
+ # (bake_batch.py PICTURES=1, 0.3 s a design) and embedded on the CPU (garment_embed.py; Core ML's GPU computes
+ # SigLIP 2 wrong on this Mac); a small network (two layers of 512, garment_model.py) learns the design's 122
+ # settings as 196 slots (garment_params.py: numbers by their place in range, choices one-hot, the options
+ # being every value seen, since GarmentCode's own defaults fall outside its ranges) from the picture
+ # embeddings, centred on the pictures' mean, with noise added; asked in words, it is given the text
+ # embedding centred on a bank of garment lines' mean (the two kinds sit apart by a near-constant offset).
+ # So no caption is needed to train, and a line nobody wrote a caption for still lands near its pictures.
+ # First run, 86 designs: held-out pictures give the top's kind 0.66 (most common 0.44) and the bottom's
+ # 0.59 (0.31); the numbers are no better than their mean yet. Twelve lines of words with a check each
+ # ("trousers", "a pencil skirt", "a top with a hood", "a strapless top" ...): 11 of 12, as many as taking
+ # the nearest training picture's design, where a random design passes one or two; nonsense ("a bowl of
+ # soup") falls back to a fitted top and trousers. words.sh makes each line a design, cuts it to SOMA and
+ # drapes it, about 20 s and $0: seven of seven were valid patterns and hung right, six read as asked.
+ # Faults: "long-sleeved" comes out at the elbow, a turtleneck's collar collapses in the drape, unasked parts
+ # come along (trousers with a turtleneck), and "a long dress" is not known as a top joined to a skirt.
+ Then a line of words becomes a sewing pattern cut to SOMA and draped, with no caption written to train it
+ And its eval says how it compares with the nearest picture and with chance, on held-out designs and lines
+
Scenario: CH49. Worn hard pieces: helmets, hats, armour, visors (proposed)
# Patterns make only what is cut and sewn. A helmet, a hat, a breastplate or a visor is made the way the
# user first proposed for clothes and the creature flow makes animals: a picture of SOMA's mannequin
diff --git a/tools/garments/README.md b/tools/garments/README.md
index cc11b324..026a42fa 100644
--- a/tools/garments/README.md
+++ b/tools/garments/README.md
@@ -35,6 +35,22 @@ stretch, cloth inside the skin, and whether it stayed on).
- `render_pretty.py`: a garment to look at (EEVEE, fabric with sheen, soft studio light; `raea blender run`)
- `sheet.py`, `grid.py`, `snaps_view.py`: contact sheets, and the drape's snapshots (`SNAP=1`) over the body
+## Words to a garment: the first model (CH48c)
+
+SigLIP 2 (in raea's models) puts pictures and words in one space, so a small network trained on pictures of the
+draped designs answers lines of words, with no captions written. Needs `onnxruntime` and `tokenizers` in the venv.
+
+ LEAN=1 tools/garments/engine.sh DATA 300 101 # designs, draped
+ PICTURES=1 raea blender run tools/garments/bake_batch.py BODY.glb DATA/g*/ # four pictures each
+ $GARMENT_PY -I tools/garments/garment_embed.py DATA # DATA/embeds.npz
+ $GARMENT_PY -I tools/garments/garment_model.py train DATA MODEL.npz # seconds
+ $GARMENT_PY -I tools/garments/garment_model.py eval DATA MODEL.npz # held out, lines of words
+ tools/garments/words.sh MODEL.npz OUT "a pencil skirt" "a top with a hood" # designed, cut, draped, sheet
+
+- `garment_params.py`: a design's settings as one vector (numbers by place in range, choices one-hot) and back
+- `garment_embed.py`: SigLIP 2 picture and text embeddings, ONNX on the CPU (Core ML's GPU is wrong on this Mac)
+- `garment_model.py`: the network (embedding to settings), its training with noise so text lands, eval, `make`
+
## Worn hard pieces (CH49)
What can't be sewn (helmets, hats, armour, visors, hard-shell suits) is drawn on SOMA's mannequin by an image model,
diff --git a/tools/garments/bake_batch.py b/tools/garments/bake_batch.py
index 48fc8fd6..dfcfe78b 100644
--- a/tools/garments/bake_batch.py
+++ b/tools/garments/bake_batch.py
@@ -2,6 +2,8 @@
# The body loads once; per garment: seams welded, the cut as UVs, weights from the skin, skinned to SOMA's armature,
# exported as <name>.glb, and rendered on the mannequin from four sides (<name>_<view>.png).
# raea blender run bake_batch.py BODY.glb DIR... (each DIR holds one <name>.draped.npz)
+# PICTURES=1: the pictures alone, as JPEG (<name>_<view>.jpg), no weights or glb: what a lean design needs for training
+# (garment_embed.py reads them); a DIR that has them already is skipped.
import bpy, bmesh, sys, os, glob, json, zlib, time
import numpy as np
from mathutils import Vector
@@ -26,12 +28,15 @@ sc.display.shading.show_cavity = True; sc.render.resolution_x = 512; sc.render.r
cam = bpy.data.objects.new("cam", bpy.data.cameras.new("cam")); sc.collection.objects.link(cam); sc.camera = cam
cam.data.type = "ORTHO"; cam.data.ortho_scale = 2.0
VIEWS = {"front": (0, -4, 0.95), "threequarter": (2.8, -2.8, 0.95), "side": (4, 0, 0.95), "back": (0, 4, 0.95)}
+PICS = os.environ.get("PICTURES") == "1"
+if PICS: sc.render.image_settings.file_format = "JPEG"; sc.render.image_settings.quality = 88
for d in dirs:
t0 = time.time()
src = glob.glob(os.path.join(d, "*.draped.npz"))
if not src: print(f"bake: {d}: nothing draped", flush=True); continue
Z = np.load(src[0]); name = os.path.basename(src[0])[:-len(".draped.npz")]
+ if PICS and all(os.path.exists(os.path.join(d, f"{name}_{v}.jpg")) for v in VIEWS): continue
X = Z["X"].astype(float); X = np.c_[X[:, 0], -X[:, 2], X[:, 1]] # glTF (x, y, z) is Blender (x, -z, y)
me = bpy.data.meshes.new(name); me.from_pydata(X.tolist(), [], Z["F"].tolist()); me.update()
g = bpy.data.objects.new(name, me); sc.collection.objects.link(g)
@@ -49,14 +54,15 @@ for d in dirs:
# smooth: a flat-shaded mesh exports every triangle with its own three vertices (198,881 for 66,305), shading
# as facets ("pebbles") wherever it is drawn
me.polygons.foreach_set("use_smooth", [True] * len(me.polygons)); me.update()
- for vg in skin.vertex_groups: g.vertex_groups.new(name=vg.name)
- for o in bpy.data.objects: o.select_set(o is g)
- bpy.context.view_layer.objects.active = g
- dt = g.modifiers.new("weights", "DATA_TRANSFER"); dt.object = skin
- dt.use_vert_data = True; dt.data_types_verts = {"VGROUP_WEIGHTS"}; dt.vert_mapping = "POLYINTERP_NEAREST"
- dt.layers_vgroup_select_src = "ALL"; dt.layers_vgroup_select_dst = "NAME"
- bpy.ops.object.modifier_apply(modifier=dt.name)
- g.parent = arm; g.modifiers.new("skin", "ARMATURE").object = arm
+ if not PICS:
+ for vg in skin.vertex_groups: g.vertex_groups.new(name=vg.name)
+ for o in bpy.data.objects: o.select_set(o is g)
+ bpy.context.view_layer.objects.active = g
+ dt = g.modifiers.new("weights", "DATA_TRANSFER"); dt.object = skin
+ dt.use_vert_data = True; dt.data_types_verts = {"VGROUP_WEIGHTS"}; dt.vert_mapping = "POLYINTERP_NEAREST"
+ dt.layers_vgroup_select_src = "ALL"; dt.layers_vgroup_select_dst = "NAME"
+ bpy.ops.object.modifier_apply(modifier=dt.name)
+ g.parent = arm; g.modifiers.new("skin", "ARMATURE").object = arm
colour = PALETTE[zlib.crc32(name.encode()) % len(PALETTE)]
rgb = [int(colour[i:i + 2], 16) / 255 for i in (1, 3, 5)]
mat = bpy.data.materials.new(name); mat.use_nodes = True
@@ -64,14 +70,16 @@ for d in dirs:
bsdf.inputs["Base Color"].default_value = (*[x ** 2.2 for x in rgb], 1); bsdf.inputs["Roughness"].default_value = 0.9
mat.diffuse_color = (*[x ** 2.2 for x in rgb], 1)
me.materials.append(mat)
- for o in bpy.data.objects: o.select_set(o is g or o is arm)
- bpy.ops.export_scene.gltf(filepath=os.path.join(d, name + ".glb"), export_format="GLB", use_selection=True,
- export_animations=False, export_yup=True, export_skins=True)
+ if not PICS:
+ for o in bpy.data.objects: o.select_set(o is g or o is arm)
+ bpy.ops.export_scene.gltf(filepath=os.path.join(d, name + ".glb"), export_format="GLB", use_selection=True,
+ export_animations=False, export_yup=True, export_skins=True)
for view, loc in VIEWS.items():
cam.location = loc; cam.rotation_euler = (Vector((0, 0, 0.95)) - Vector(loc)).to_track_quat("-Z", "Y").to_euler()
- sc.render.filepath = os.path.join(d, f"{name}_{view}.png"); bpy.ops.render.render(write_still=True)
+ sc.render.filepath = os.path.join(d, f"{name}_{view}.{'jpg' if PICS else 'png'}"); bpy.ops.render.render(write_still=True)
welded = len(me.vertices)
- json.dump({"name": name, "colour": colour, "views": list(VIEWS), "vertices": welded},
- open(os.path.join(d, name + ".bake.json"), "w"))
+ if not PICS:
+ json.dump({"name": name, "colour": colour, "views": list(VIEWS), "vertices": welded},
+ open(os.path.join(d, name + ".bake.json"), "w"))
bpy.data.objects.remove(g); bpy.data.meshes.remove(me); bpy.data.materials.remove(mat)
print(f"bake: {name}: {len(X)} -> {welded} vertices, {colour}, {time.time() - t0:.1f} s", flush=True)
diff --git a/tools/garments/garment_embed.py b/tools/garments/garment_embed.py
new file mode 100644
index 00000000..c1b805b4
--- /dev/null
+++ b/tools/garments/garment_embed.py
@@ -0,0 +1,66 @@
+# SigLIP 2 (shipped in raea's models, siglip2-base-p16-256) for the garment model (docs/character.feature CH48c): each
+# design's pictures on the mannequin (bake_batch.py PICTURES=1) as image embeddings, and a line of words as a text
+# embedding in the same space. ONNX Runtime on the CPU: Core ML's GPU computes SigLIP 2 wrong on this Mac. The text is
+# lower-cased and padded to 64 tokens as raea's own index does (systems/index/src/text.rs).
+# python -I garment_embed.py OUT_DIR embeds every OUT_DIR/g*/<name>_<view>.jpg not yet in OUT_DIR/embeds.npz
+# python -I garment_embed.py --text "a long pencil skirt" ... prints each line's first values (a check)
+import glob, os, sys
+import numpy as np
+
+M = os.environ.get("SIGLIP_DIR", os.path.expanduser("~/.local/share/raea-models/siglip2-base-p16-256"))
+_s = {}
+
+
+def _session(name):
+ if name not in _s:
+ import onnxruntime as ort
+ o = ort.SessionOptions(); o.intra_op_num_threads = int(os.environ.get("SIGLIP_THREADS", "4"))
+ _s[name] = ort.InferenceSession(f"{M}/onnx/{name}.onnx", o, providers=["CPUExecutionProvider"])
+ return _s[name]
+
+
+def _unit(x):
+ return x / np.maximum(np.linalg.norm(x, axis=-1, keepdims=True), 1e-9)
+
+
+def image_embed(paths, batch=16):
+ """unit image embeddings (N, 768): each picture padded square with its own corner colour, then 256 px"""
+ from PIL import Image
+ out = []
+ for i in range(0, len(paths), batch):
+ px = []
+ for p in paths[i:i + batch]:
+ im = Image.open(p).convert("RGB"); w, h = im.size; s = max(w, h)
+ sq = Image.new("RGB", (s, s), im.getpixel((0, 0))); sq.paste(im, ((s - w) // 2, (s - h) // 2))
+ a = np.asarray(sq.resize((256, 256), Image.BILINEAR), np.float32) / 255.0
+ px.append(((a - 0.5) / 0.5).transpose(2, 0, 1))
+ out.append(_session("vision_model").run(["pooler_output"], {"pixel_values": np.stack(px)})[0])
+ return _unit(np.concatenate(out).astype(np.float32))
+
+
+def text_embed(lines):
+ """unit text embeddings (N, 768)"""
+ from tokenizers import Tokenizer
+ tok = Tokenizer.from_file(f"{M}/tokenizer.json"); pad = tok.token_to_id("<pad>") or 0
+ ids = np.full((len(lines), 64), pad, np.int64)
+ for i, s in enumerate(lines):
+ e = tok.encode(s.lower(), add_special_tokens=True).ids[:64]; ids[i, :len(e)] = e
+ return _unit(np.concatenate([_session("text_model").run(["pooler_output"], {"input_ids": ids[i:i + 32]})[0] for i in range(0, len(lines), 32)]).astype(np.float32))
+
+
+if __name__ == "__main__":
+ if sys.argv[1] == "--text":
+ for s, e in zip(sys.argv[2:], text_embed(sys.argv[2:])): print(f"{s!r}: {np.round(e[:4], 4)}")
+ sys.exit()
+ out = sys.argv[1]; path = f"{out}/embeds.npz"
+ have = dict(np.load(path)) if os.path.exists(path) else {"names": np.array([], str), "views": np.array([], str), "E": np.zeros((0, 768), np.float32)}
+ done = set(zip(have["names"].tolist(), have["views"].tolist()))
+ todo = []
+ for p in sorted(glob.glob(f"{out}/g*/*_*.jpg")):
+ n, v = os.path.basename(p)[:-4].rsplit("_", 1)
+ if (n, v) not in done and v != "pattern": todo.append((n, v, p))
+ if todo:
+ E = image_embed([p for _, _, p in todo])
+ have = {"names": np.r_[have["names"], [n for n, _, _ in todo]], "views": np.r_[have["views"], [v for _, v, _ in todo]], "E": np.r_[have["E"], E]}
+ np.savez(path, **have)
+ print(f"embed: {len(todo)} new pictures, {len(have['names'])} in {path}", flush=True)
diff --git a/tools/garments/garment_model.py b/tools/garments/garment_model.py
new file mode 100644
index 00000000..ffcde702
--- /dev/null
+++ b/tools/garments/garment_model.py
@@ -0,0 +1,163 @@
+# The garment model's first form (docs/character.feature CH48c): words to a GarmentCode design, through SigLIP 2's
+# shared space, trained with no captions. A small network learns each design's settings (garment_params.py) from
+# SigLIP 2 embeddings of its pictures on the mannequin; asked with words, it is given the words' text embedding instead.
+# The two kinds of embedding sit apart in SigLIP's space by a near-constant offset, so each is centred on its own kind's
+# mean (the pictures', and a bank of garment lines') and set to unit length, and noise is added to the pictures'
+# while training so the network answers for the neighbourhood of a picture, where a line's embedding lands (LAFITE).
+# python -I garment_model.py train DATA MODEL.npz DATA holds embeds.npz (garment_embed.py) and g*/design.yaml
+# python -I garment_model.py eval DATA MODEL.npz held-out designs from their pictures, and lines of words
+# python -I garment_model.py make MODEL.npz "words" OUT_DIR OUT_DIR/design.yaml, ready for GarmentCode
+import json, os, sys, zlib
+import numpy as np, yaml
+import mlx.core as mx, mlx.nn as nn, mlx.optimizers as optim
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from garment_params import Schema, _get
+from garment_embed import text_embed
+
+H, NOISE, STEPS = 512, float(os.environ.get("NOISE", "0.6")), int(os.environ.get("STEPS", "3000"))
+# lines a garment can be asked for: the text side's mean is taken over these and the designs' own captions
+BANK = ["a dress", "a skirt", "trousers", "a shirt", "a top", "a blouse", "a gown", "a long skirt", "a short skirt",
+ "a sleeveless dress", "a fitted top", "a loose shirt", "wide trousers", "a hooded top", "a turtleneck",
+ "a strapless dress", "a pleated skirt", "a pencil skirt", "a circle skirt", "a tiered skirt", "shorts"]
+# lines of words with what each must give (a value, a list of values that count, or a test), for eval
+PROBES = [
+ ("trousers", {"meta.bottom": "Pants"}),
+ ("a pair of trousers and a fitted shirt", {"meta.bottom": "Pants", "meta.upper": ["FittedShirt", "Shirt"]}),
+ ("a pencil skirt", {"meta.bottom": "PencilSkirt"}),
+ ("a full circle skirt", {"meta.bottom": ["SkirtCircle", "AsymmSkirtCircle"]}),
+ ("a tiered skirt with layers", {"meta.bottom": "SkirtLevels"}),
+ ("a skirt and no top", {"meta.upper": None, "meta.bottom": ["SkirtCircle", "AsymmSkirtCircle", "GodetSkirt", "Skirt2", "SkirtManyPanels", "PencilSkirt", "SkirtLevels"]}),
+ ("a top with a hood", {"collar.component.style": "Hood2Panels"}),
+ ("a turtleneck", {"collar.component.style": "Turtle"}),
+ ("a sleeveless top", {"sleeve.sleeveless": True}),
+ ("a long-sleeved shirt", {"sleeve.sleeveless": False, "sleeve.length": lambda v: v > 0.7}),
+ ("a strapless top", {"shirt.strapless": True}),
+ ("a long dress", {"meta.upper": ["FittedShirt", "Shirt"], "meta.bottom": ["SkirtCircle", "AsymmSkirtCircle", "GodetSkirt", "Skirt2", "SkirtManyPanels", "PencilSkirt", "SkirtLevels"]}),
+]
+
+
+def unit(x): return x / np.maximum(np.linalg.norm(x, axis=-1, keepdims=True), 1e-9)
+
+
+def load(data):
+ Z = np.load(f"{data}/embeds.npz")
+ names = sorted({str(n) for n in Z["names"]})
+ designs = {n: yaml.safe_load(open(f"{data}/{n}/design.yaml"))["design"] for n in names}
+ captions = [open(f"{data}/{n}/caption.txt").read().strip() for n in names if os.path.exists(f"{data}/{n}/caption.txt")]
+ return Z, names, designs, captions
+
+
+def held_out(name): return zlib.crc32(name.encode()) % 7 == 0
+
+
+class Net(nn.Module):
+ def __init__(self, width):
+ super().__init__()
+ self.l1, self.l2, self.out = nn.Linear(768, H), nn.Linear(H, H), nn.Linear(H, width)
+ self.drop = nn.Dropout(0.1)
+
+ def __call__(self, x):
+ return self.out(self.drop(nn.gelu(self.l2(self.drop(nn.gelu(self.l1(x)))))))
+
+
+def parts(schema):
+ """the vector's slots by how they are learned: numbers (squared error on a sigmoid), bools (cross entropy), choices"""
+ num = [f[3] for f in schema.fields if f[1] in ("float", "int")]
+ bol = [f[3] for f in schema.fields if f[1] == "bool"]
+ cho = [(f[3], f[4]) for f in schema.fields if f[1] in ("select", "select_null")]
+ return np.array(num), np.array(bol), cho
+
+
+def predict(net, schema, X):
+ z = np.array(net(mx.array(X)))
+ num, bol, cho = parts(schema); y = np.zeros_like(z)
+ y[:, num] = 1 / (1 + np.exp(-z[:, num])); y[:, bol] = (z[:, bol] > 0).astype(np.float32)
+ for a, w in cho: y[np.arange(len(z)), a + z[:, a:a + w].argmax(1)] = 1
+ return y
+
+
+def train(data, model_path):
+ Z, names, designs, captions = load(data)
+ schema = Schema.of([designs[n] for n in names])
+ keep = np.array([not held_out(str(n)) for n in Z["names"]])
+ mu_i = Z["E"][keep].mean(0); mu_t = text_embed(BANK + captions).mean(0)
+ X = unit(Z["E"][keep] - mu_i); Y = np.stack([schema.encode(designs[str(n)]) for n in Z["names"][keep]])
+ num, bol, cho = parts(schema)
+ net = Net(schema.width); opt = optim.AdamW(1e-3, weight_decay=1e-2)
+ numa, bola = mx.array(num), mx.array(bol)
+
+ def loss(net, x, y):
+ z = net(x)
+ l = mx.mean((mx.sigmoid(z[:, numa]) - y[:, numa]) ** 2) * 4
+ l = l + mx.mean(nn.losses.binary_cross_entropy(z[:, bola], y[:, bola], with_logits=True))
+ for a, w in cho: l = l + mx.mean(nn.losses.cross_entropy(z[:, a:a + w], mx.argmax(y[:, a:a + w], axis=1))) / len(cho) * 4
+ return l
+
+ step = nn.value_and_grad(net, loss); rng = np.random.default_rng(0)
+ for s in range(STEPS):
+ b = rng.integers(0, len(X), 128); e = rng.standard_normal((len(b), 768)).astype(np.float32)
+ x = unit(X[b] + NOISE * unit(e)) # a picture's neighbourhood, where a line's embedding lands
+ l, g = step(net, mx.array(x), mx.array(Y[b])); opt.update(net, g); mx.eval(net.parameters(), opt.state)
+ if s % 1000 == 0 or s == STEPS - 1: print(f"train: step {s} loss {float(l):.3f}", flush=True)
+ net.eval()
+ w = {k: np.array(v) for k, v in __import__("mlx.utils", fromlist=["tree_flatten"]).tree_flatten(net.parameters())}
+ np.savez(model_path, mu_i=mu_i, mu_t=mu_t, schema=schema.dump(), **{f"w:{k}": v for k, v in w.items()})
+ print(f"train: {len(names)} designs ({int(keep.sum())} pictures kept for training), {schema.width} slots -> {model_path}")
+
+
+def restore(model_path):
+ M = np.load(model_path)
+ schema = Schema.load(str(M["schema"]))
+ net = Net(schema.width); net.load_weights([(k[2:], mx.array(M[k])) for k in M.files if k.startswith("w:")]); net.eval()
+ return M, net, schema
+
+
+def ok(want, got):
+ if callable(want): return got is not None and want(got)
+ return got in want if isinstance(want, list) else got == want
+
+
+def evaluate(data, model_path):
+ Z, names, designs, captions = load(data)
+ M, net, schema = restore(model_path)
+ E, N = Z["E"], [str(n) for n in Z["names"]]
+ test = np.array([held_out(n) for n in N]); train_ = ~test
+ Xt = unit(E[test] - M["mu_i"]); P = predict(net, schema, Xt)
+ Yt = np.stack([schema.encode(designs[n]) for n in np.array(N)[test]])
+ Ytr = np.stack([schema.encode(designs[n]) for n in np.array(N)[train_]])
+ # the nearest training picture's design, for comparison
+ near = Ytr[(Xt @ unit(E[train_] - M["mu_i"]).T).argmax(1)]
+ print(f"eval: {int(test.sum())} held-out pictures of {len({n for n, t in zip(N, test) if t})} designs")
+ num, bol, cho = parts(schema)
+ for label, path in [("upper", "meta.upper"), ("bottom", "meta.bottom"), ("waistband", "meta.wb"), ("collar", "collar.component.style"), ("sleeveless", "sleeve.sleeveless")]:
+ f = next(f for f in schema.fields if ".".join(f[0]) == path); a, w = f[3], f[4]
+ acc = lambda Y: float((Y[:, a:a + w].argmax(1) == Yt[:, a:a + w].argmax(1)).mean()) if w > 1 else float((Y[:, a] == Yt[:, a]).mean())
+ base = np.bincount(Ytr[:, a:a + w].argmax(1), minlength=w).argmax() if w > 1 else round(float(Ytr[:, a].mean()))
+ prior = float((Yt[:, a:a + w].argmax(1) == base).mean()) if w > 1 else float((Yt[:, a] == base).mean())
+ print(f" {label:<11} model {acc(P):.2f} nearest picture {acc(near):.2f} most common {prior:.2f}")
+ mae = lambda Y: float(np.abs(Y[:, num] - Yt[:, num]).mean())
+ print(f" numbers model {mae(P):.3f} nearest picture {mae(near):.3f} mean {float(np.abs(Ytr[:, num].mean(0) - Yt[:, num]).mean()):.3f} (mean error, 0..1 of each range)")
+ T = unit(text_embed([p for p, _ in PROBES]) - M["mu_t"]); PT = predict(net, schema, T)
+ NT = Ytr[(T @ unit(E[train_] - M["mu_i"]).T).argmax(1)]
+ hits = {"model": 0, "nearest picture": 0}
+ for (words, want), pm, pn in zip(PROBES, PT, NT):
+ dm, dn = schema.decode(pm), schema.decode(pn)
+ r = {k: all(ok(w, _get(d, tuple(p.split(".")))["v"]) for p, w in want.items()) for k, d in (("model", dm), ("nearest picture", dn))}
+ for k in hits: hits[k] += r[k]
+ print(f" {words!r:<42} model {'yes' if r['model'] else 'no ':<3} nearest picture {'yes' if r['nearest picture'] else 'no'}")
+ print(f" lines of words: model {hits['model']} of {len(PROBES)}, nearest picture {hits['nearest picture']} of {len(PROBES)}")
+
+
+def make(model_path, words, out):
+ M, net, schema = restore(model_path)
+ d = schema.decode(predict(net, schema, unit(text_embed([words]) - M["mu_t"]))[0])
+ os.makedirs(out, exist_ok=True); yaml.safe_dump({"design": d}, open(f"{out}/design.yaml", "w"), sort_keys=False)
+ print(f"make: {words!r} -> {out}/design.yaml (upper {_get(d, ('meta', 'upper'))['v']}, bottom {_get(d, ('meta', 'bottom'))['v']})")
+
+
+if __name__ == "__main__":
+ cmd = sys.argv[1]
+ if cmd == "train": train(sys.argv[2], sys.argv[3])
+ elif cmd == "eval": evaluate(sys.argv[2], sys.argv[3])
+ elif cmd == "make": make(sys.argv[2], sys.argv[3], sys.argv[4])
+ else: raise SystemExit(__doc__)
diff --git a/tools/garments/garment_params.py b/tools/garments/garment_params.py
new file mode 100644
index 00000000..8f5c0837
--- /dev/null
+++ b/tools/garments/garment_params.py
@@ -0,0 +1,86 @@
+# A GarmentCode design's settings as one vector and back (docs/character.feature CH48c): the garment model's labels.
+# The schema is read from any design.yaml (every design holds the same tree): a float or int is its place in its range
+# (0..1), a bool is 0 or 1, a select is one-hot over its range, and a select_null has one more slot for "none".
+# from garment_params import Schema; s = Schema.of(design); x = s.encode(design); d = s.decode(x)
+import copy, json
+import numpy as np
+
+
+def _leaves(d, path=()):
+ for k, v in d.items():
+ if isinstance(v, dict) and "type" in v and "v" in v: yield path + (k,), v
+ elif isinstance(v, dict): yield from _leaves(v, path + (k,))
+
+
+def _get(d, path):
+ for k in path: d = d[k]
+ return d
+
+
+class Schema:
+ def __init__(self, fields, template):
+ self.fields, self.template = fields, template # fields: (path, kind, range, slot, width)
+ self.width = sum(f[4] for f in fields)
+
+ @staticmethod
+ def of(designs):
+ """from one design or several: a choice's options are every listed and every value seen (a design can hold
+ GarmentCode's default outside its own range, a front collar of CircleNeckHalf), a number's range takes in its
+ values"""
+ designs = designs if isinstance(designs, list) else [designs]
+ design = designs[0]
+ fields, at = [], 0
+ for path, leaf in _leaves(design):
+ kind, rng = leaf["type"], list(leaf["range"])
+ seen = [_get(d, path)["v"] for d in designs]
+ if kind in ("select", "select_null"):
+ for v in seen:
+ if v is not None and v not in rng: rng.append(v)
+ elif kind in ("float", "int"):
+ rng = [min([float(rng[0])] + [float(v) for v in seen]), max([float(rng[-1])] + [float(v) for v in seen])]
+ if kind in ("float", "int"): w = 1
+ elif kind == "bool": w = 1
+ elif kind == "select": w = len(rng)
+ elif kind == "select_null": w = len(rng) + 1
+ else: raise ValueError(f"{'.'.join(path)}: a setting of type {kind}")
+ fields.append((path, kind, rng, at, w)); at += w
+ return Schema(fields, copy.deepcopy(design))
+
+ def groups(self):
+ """slices of the vector by how each is learned: ('scalar', slot) or ('choice', slot, width)"""
+ return [("scalar", f[3]) if f[1] in ("float", "int", "bool") else ("choice", f[3], f[4]) for f in self.fields]
+
+ def encode(self, design):
+ x = np.zeros(self.width, np.float32)
+ for path, kind, rng, at, w in self.fields:
+ v = _get(design, path)["v"]
+ if kind in ("float", "int"):
+ lo, hi = float(rng[0]), float(rng[-1]); x[at] = 0.0 if hi == lo else np.clip((float(v) - lo) / (hi - lo), 0, 1)
+ elif kind == "bool": x[at] = 1.0 if v else 0.0
+ else: x[at + (rng.index(v) if v in rng else len(rng))] = 1.0
+ return x
+
+ def decode(self, x):
+ """a design from a vector: scalars clamped into range (ints rounded), each choice its highest slot"""
+ d = copy.deepcopy(self.template)
+ for path, kind, rng, at, w in self.fields:
+ leaf = _get(d, path)
+ if kind in ("float", "int"):
+ lo, hi = float(rng[0]), float(rng[-1]); v = lo + float(np.clip(x[at], 0, 1)) * (hi - lo)
+ leaf["v"] = int(round(v)) if kind == "int" else v
+ elif kind == "bool": leaf["v"] = bool(x[at] > 0.5)
+ else:
+ i = int(np.argmax(x[at:at + w])); leaf["v"] = rng[i] if i < len(rng) else None
+ return d
+
+ def dump(self):
+ return json.dumps({"fields": [[list(p), k, r, a, w] for p, k, r, a, w in self.fields], "template": self.template})
+
+ @staticmethod
+ def load(s):
+ j = json.loads(s)
+ return Schema([(tuple(p), k, r, a, w) for p, k, r, a, w in j["fields"]], j["template"])
+
+ def name(self, at):
+ for path, kind, rng, a, w in self.fields:
+ if a <= at < a + w: return ".".join(path)
diff --git a/tools/garments/sample_designs.py b/tools/garments/sample_designs.py
index cda44c04..5020cd9b 100644
--- a/tools/garments/sample_designs.py
+++ b/tools/garments/sample_designs.py
@@ -1,6 +1,7 @@
# The garment data engine's first step: random GarmentCode designs, cut to SOMA's measurements, each a folder with
# its design (the labels), a caption in words, the pattern and the flat pieces for the drape.
# python sample_designs.py GARMENTCODE_SRC SOMA.yaml OUT_DIR N [SEED]
+# DESIGN=design.yaml python sample_designs.py ... OUT_DIR 1 that design, not a random one (garment_model.py make)
# OUT_DIR/<id>/{design.yaml, caption.txt, <id>_specification.json, <id>.panels.json}
import sys, json, random, string, traceback
from pathlib import Path
@@ -43,11 +44,12 @@ def caption(d):
if wb: words.append("a gathered waistband" if v(d, "waistband", "waist") > 1.15 else "a waistband")
return ", ".join(words)
+GIVEN = __import__("os").environ.get("DESIGN")
made, tries = 0, 0
-while made < N and tries < N * 20:
+while made < N and tries < (1 if GIVEN else N * 20):
tries += 1
- d = sampler.randomize()
- gid = "g" + "".join(random.choices(string.ascii_lowercase + string.digits, k=8))
+ d = yaml.safe_load(open(GIVEN))["design"] if GIVEN else sampler.randomize()
+ gid = __import__("os").environ.get("GID") or "g" + "".join(random.choices(string.ascii_lowercase + string.digits, k=8))
folder = out / gid
try:
assert_param_combinations(d)
diff --git a/tools/garments/sheet.py b/tools/garments/sheet.py
index da8d8328..0a01627e 100644
--- a/tools/garments/sheet.py
+++ b/tools/garments/sheet.py
@@ -10,6 +10,8 @@ for d in dirs:
w, h = ims[0].size; row = Image.new("RGB", (w * len(ims), h + 36), "white")
for i, im in enumerate(ims): row.paste(im, (i * w, 36))
cap = open(os.path.join(d, "caption.txt")).read().strip() if os.path.exists(os.path.join(d, "caption.txt")) else ""
+ if os.path.exists(os.path.join(d, "words.txt")): # asked in words (words.sh): the words, then what was made
+ cap = f'asked "{open(os.path.join(d, "words.txt")).read().strip()}", made: {cap}'
rep = glob.glob(os.path.join(d, "*.drape.json")); r = __import__("json").load(open(rep[0])) if rep else {}
flag = "" if r.get("ok", True) else " [FAILED: " + ("slid" if not r.get("stayed", True) else "seams/inside") + "]"
ImageDraw.Draw(row).text((8, 10), f"{os.path.basename(d.rstrip('/'))}: {cap}{flag}", fill="red" if flag else "black")
diff --git a/tools/garments/words.sh b/tools/garments/words.sh
new file mode 100755
index 00000000..6fb1bd48
--- /dev/null
+++ b/tools/garments/words.sh
@@ -0,0 +1,28 @@
+#!/bin/bash
+# Words to garments on SOMA through the garment model (docs/character.feature CH48c): each line becomes a GarmentCode
+# design (garment_model.py make), cut to SOMA, draped on the GPU, baked and pictured, and one sheet of them all.
+# tools/garments/words.sh MODEL.npz OUT_DIR "a pencil skirt" "a top with a hood" ...
+# Needs what engine.sh needs (GARMENTCODE, GARMENT_PY, GARMENT_DATA). $0, about 20 s a line.
+set -euo pipefail
+T=$(cd "$(dirname "$0")" && pwd)
+GC=${GARMENTCODE:?a GarmentCode clone, see tools/garments/README.md}
+PY=${GARMENT_PY:?the venv python, see tools/garments/README.md}
+DATA=${GARMENT_DATA:-$HOME/.cache/raea-garments}
+BODY=${SOMA_BODY:-$HOME/.local/share/raea-models/soma/body/body.glb}
+MODEL=${1:?model}; OUT=${2:?out dir}; shift 2
+mkdir -p "$OUT"
+DIRS=()
+i=0
+for words in "$@"; do
+ i=$((i + 1)); n=w$(printf %02d $i); d=$OUT/$n
+ mkdir -p "$d"; printf '%s\n' "$words" > "$d/words.txt"
+ "$PY" -I "$T/garment_model.py" make "$MODEL" "$words" "$d" | grep -E "^make:"
+ (cd "$T" && DESIGN="$d/design.yaml" GID=$n "$PY" -I sample_designs.py "$GC" "$T/soma.yaml" "$OUT" 1 1) | grep -E "^sample: (w|rejected)" | cut -c1-160
+ [ -f "$d/$n.panels.json" ] || { echo "words: $n ($words): GarmentCode refused the design"; continue; }
+ log=$( (cd "$T" && "$PY" -I drape_mlx.py "$DATA/soma_sdf.npz" "$d/$n.panels.json" "$d" 150 -0.064 "$T/soma.yaml") 2>&1 ) && grep -E '^drape: \{' <<<"$log" | cut -c1-160 \
+ || echo "drape: $n failed: $(grep -vE '^\s*$' <<<"$log" | tail -1 | sed 's/Traceback/trace/')"
+ [ -f "$d/$n.draped.npz" ] && DIRS+=("$d")
+done
+[ ${#DIRS[@]} -gt 0 ] || exit 1
+raea blender run "$T/bake_batch.py" "$BODY" "${DIRS[@]}" 2>&1 | grep --line-buffered -E '^bake|Error|Traceback'
+"$PY" -I "$T/sheet.py" "$OUT/sheet.jpg" "${DIRS[@]}"