Spaces:
Sleeping
Sleeping
Download process.py from Radiotomy/base-stage-ready: direct link, hf CLI and curl.
- Browser
- Download file 8.6 kB
-
https://huggingface.co/spaces/Radiotomy/base-stage-ready/resolve/main/process.py
- Command line
-
hf download hf://spaces/Radiotomy/base-stage-ready/process.py
-
curl -L -o process.py https://huggingface.co/spaces/Radiotomy/base-stage-ready/resolve/main/process.py
8.6 kB
| # Runs inside headless Blender: blender -b --python process.py -- in.glb out.glb report.json '{}' | |
| import bpy, sys, json, re, traceback | |
| from mathutils import Vector | |
| argv = sys.argv[sys.argv.index("--") + 1:] | |
| SRC, DST, REP = argv[0], argv[1], argv[2] | |
| OPTS = json.loads(argv[3] or "{}") | |
| report = {"blender": bpy.app.version_string, "warnings": []} | |
| def norm(n): | |
| n = n.lower().split(":")[-1] | |
| return re.sub(r"[^a-z0-9]", "", n) | |
| def side_names(base, side): | |
| s, l = ("left", "l") if side == "L" else ("right", "r") | |
| return [s + b for b in base] + [b + l for b in base] + [l + b for b in base] | |
| CORE = { | |
| "hips": ["hips", "pelvis"], "spine": ["spine", "spine01", "spine1"], "neck": ["neck", "neck01"], "head": ["head"], | |
| } | |
| for sd in ("L", "R"): | |
| CORE[f"arm_{sd}"] = side_names(["arm", "upperarm", "shoulder"], sd) | |
| CORE[f"forearm_{sd}"] = side_names(["forearm", "lowerarm"], sd) | |
| CORE[f"hand_{sd}"] = side_names(["hand"], sd) | |
| CORE[f"upleg_{sd}"] = side_names(["upleg", "thigh", "upperleg"], sd) | |
| CORE[f"leg_{sd}"] = side_names(["leg", "calf", "shin", "lowerleg", "knee"], sd) | |
| def reset(): | |
| bpy.ops.wm.read_factory_settings(use_empty=True) | |
| def mesh_objs(): | |
| return [o for o in bpy.context.scene.objects if o.type == "MESH"] | |
| def shape_names(): | |
| out = [] | |
| for o in mesh_objs(): | |
| if o.data.shape_keys: | |
| out += [k.name for k in o.data.shape_keys.key_blocks if k.name != "Basis"] | |
| return out | |
| def main(): | |
| reset() | |
| bpy.ops.import_scene.gltf(filepath=SRC) | |
| arms = [o for o in bpy.context.scene.objects if o.type == "ARMATURE"] | |
| meshes = mesh_objs() | |
| report["mesh"] = {"objects": len(meshes), "vertices": sum(len(o.data.vertices) for o in meshes)} | |
| if not arms: | |
| report["error"] = "No skeleton found. Rig the character first." | |
| return | |
| arm = max(arms, key=lambda a: len(a.data.bones)) | |
| bones = {norm(b.name): b.name for b in arm.data.bones} | |
| found, missing = {}, [] | |
| for key, cands in CORE.items(): | |
| hit = next((bones[c] for c in cands if c in bones), None) | |
| if hit: | |
| found[key] = hit | |
| else: | |
| missing.append(key) | |
| report["skeleton"] = {"compatible": not missing, "missing_bones": missing, "bone_count": len(arm.data.bones), "armature": arm.name} | |
| existing = shape_names() | |
| report["face"] = add_face(arm, found.get("head"), existing) if OPTS.get("face", True) else {"status": "skipped", "reason": "disabled"} | |
| report["hair"] = add_hair(arm, found.get("head"), bones) if OPTS.get("hair", True) else {"status": "skipped", "reason": "disabled"} | |
| bpy.ops.object.mode_set(mode="OBJECT") if bpy.context.object and bpy.context.object.mode != "OBJECT" else None | |
| bpy.ops.export_scene.gltf(filepath=DST, export_format="GLB", export_skins=True, export_morph=True, export_animations=True, export_apply=False) | |
| # Validate by re-importing the exported file into a clean scene. | |
| reset() | |
| bpy.ops.import_scene.gltf(filepath=DST) | |
| names = shape_names() | |
| a2 = [o for o in bpy.context.scene.objects if o.type == "ARMATURE"] | |
| report["validation"] = { | |
| "reimported": True, | |
| "bone_count": max((len(a.data.bones) for a in a2), default=0), | |
| "shape_keys": names[:40], | |
| "visemes": len([n for n in names if n.lower().startswith("viseme_")]), | |
| "arkit": len([n for n in names if n in ("jawOpen", "mouthClose", "mouthSmile", "eyeBlinkLeft", "eyeBlinkRight")]), | |
| "hair_bones": max((len([b for b in a.data.bones if "hair" in b.name.lower()]) for a in a2), default=0), | |
| } | |
| def head_verts(arm, head): | |
| """(object, [vertex indices], [world coords]) weighted mostly to the head bone.""" | |
| out = [] | |
| for o in mesh_objs(): | |
| if o.find_armature() != arm or head not in o.vertex_groups: | |
| continue | |
| gi = o.vertex_groups[head].index | |
| idx, co = [], [] | |
| for v in o.data.vertices: | |
| for g in v.groups: | |
| if g.group == gi and g.weight > 0.5: | |
| idx.append(v.index); co.append(o.matrix_world @ v.co) | |
| if idx: | |
| out.append((o, idx, co)) | |
| return out | |
| def add_face(arm, head, existing): | |
| if any(n in existing for n in ("jawOpen", "viseme_aa")): | |
| return {"status": "existing", "shape_keys": existing[:20]} | |
| if not head: | |
| return {"status": "skipped", "reason": "no head bone"} | |
| hv = head_verts(arm, head) | |
| allc = [c for _, _, cs in hv for c in cs] | |
| if len(allc) < 200: | |
| return {"status": "skipped", "reason": "head region could not be isolated from skin weights"} | |
| zs = [c.z for c in allc]; ys = [c.y for c in allc]; xs = [c.x for c in allc] | |
| zmin, zmax, ymin, ymax = min(zs), max(zs), min(ys), max(ys) | |
| xmid = (min(xs) + max(xs)) / 2 | |
| h, depth, width = zmax - zmin, ymax - ymin, max(xs) - min(xs) | |
| # Front faces -Y after glTF import. Mouth: lower 15-40% of head, front 30%, middle 45% of width. | |
| z0, z1, yf = zmin + 0.15 * h, zmin + 0.40 * h, ymin + 0.30 * depth | |
| picks = [] | |
| for o, idx, co in hv: | |
| sel = [(i, c) for i, c in zip(idx, co) if z0 <= c.z <= z1 and c.y <= yf and abs(c.x - xmid) <= 0.225 * width] | |
| if sel: | |
| picks.append((o, sel)) | |
| total = sum(len(s) for _, s in picks) | |
| if total < 20 or total > 8000: | |
| return {"status": "skipped", "reason": f"mouth region looked unreliable ({total} vertices)"} | |
| added = [] | |
| for o, sel in picks: | |
| if not o.data.shape_keys: | |
| o.shape_key_add(name="Basis", from_mix=False) | |
| inv = o.matrix_world.inverted().to_3x3() | |
| for name, amt in (("jawOpen", 0.06), ("viseme_aa", 0.05)): | |
| k = o.shape_key_add(name=name, from_mix=False) | |
| for i, c in sel: | |
| fall = 1.0 - (c.z - z0) / max(z1 - z0, 1e-6) # lower lip moves most | |
| k.data[i].co = o.data.vertices[i].co + inv @ Vector((0, 0, -amt * h * fall)) | |
| added.append(o.name) | |
| return {"status": "added", "confidence": "experimental", "shape_keys": ["jawOpen", "viseme_aa"], "vertices": total, "meshes": added} | |
| def add_hair(arm, head, bones): | |
| if any("hair" in k for k in bones): | |
| return {"status": "existing", "bone_total": len([k for k in bones if "hair" in k])} | |
| if not head: | |
| return {"status": "skipped", "reason": "no head bone"} | |
| targets = [] | |
| for o in mesh_objs(): | |
| if o.find_armature() != arm: | |
| continue | |
| if "hair" in o.name.lower(): | |
| targets.append((o, [v.index for v in o.data.vertices])) | |
| continue | |
| mats = [i for i, m in enumerate(o.data.materials) if m and "hair" in m.name.lower()] | |
| if mats: | |
| vs = {vi for p in o.data.polygons if p.material_index in mats for vi in p.vertices} | |
| targets.append((o, sorted(vs))) | |
| if not targets: | |
| return {"status": "skipped", "reason": "hair is not a separate mesh or material, so it can't be told apart from the head"} | |
| co = [o.matrix_world @ o.data.vertices[i].co for o, ids in targets for i in ids] | |
| top, bot = max(c.z for c in co), min(c.z for c in co) | |
| ymax = max(c.y for c in co) | |
| xmid = sum(c.x for c in co) / len(co) | |
| if top - bot < 1e-4: | |
| return {"status": "skipped", "reason": "hair region is flat"} | |
| names = ["hair_01", "hair_02", "hair_03"] | |
| inv = arm.matrix_world.inverted() | |
| bpy.context.view_layer.objects.active = arm | |
| bpy.ops.object.mode_set(mode="EDIT") | |
| eb = arm.data.edit_bones | |
| parent = eb[head] | |
| seg = (top - bot) / 3 | |
| for i, n in enumerate(names): | |
| b = eb.new(n) | |
| b.head = inv @ Vector((xmid, ymax * 0.9, top - seg * i)) | |
| b.tail = inv @ Vector((xmid, ymax * 0.9, top - seg * (i + 1))) | |
| b.parent = parent | |
| b.use_connect = i > 0 | |
| parent = b | |
| bpy.ops.object.mode_set(mode="OBJECT") | |
| for o, ids in targets: | |
| hg = o.vertex_groups.get(head) or o.vertex_groups.new(name=head) | |
| groups = [o.vertex_groups.get(n) or o.vertex_groups.new(name=n) for n in names] | |
| for i in ids: | |
| t = (top - (o.matrix_world @ o.data.vertices[i].co).z) / (top - bot) | |
| seg_i = min(2, int(t * 3)) | |
| w = min(0.85, 0.25 + t * 0.6) | |
| groups[seg_i].add([i], w, "REPLACE") | |
| hg.add([i], 1 - w, "REPLACE") | |
| return {"status": "added", "confidence": "experimental", "bones": names, "bone_total": 3, "vertices": sum(len(i) for _, i in targets)} | |
| try: | |
| main() | |
| except Exception as e: | |
| report["error"] = f"{e}" | |
| report["trace"] = traceback.format_exc()[-800:] | |
| with open(REP, "w") as f: | |
| json.dump(report, f) |