Spaces:
Running on Zero
Running on Zero
Deploy ARDY ZeroGPU Blender motion API
Browse files525 unmodified lines5265275285295305315325335345355365375385395405415422 unmodified lines54554654754854955055110 unmodified lines5625635645655665675685695705715725735745755761 unmodified line578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677471 unmodified lines11491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119323 unmodified lines12171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239525 unmodified linesrandomize_seed,None,)motion_tensor = torch.from_numpy(motion_np).to("cuda")out = _decode_motion("human", motion_tensor)r = RIGS["human"]skeleton = r["skeleton"]joint_names = list(skeleton.bone_order_names)parents = list(r["parents"])rest_positions = to_numpy(skeleton.neutral_joints)output_dir = Path(tempfile.mkdtemp(prefix="ardy_blender_"))npz_path = output_dir / "ardy_motion.npz"bvh_path = output_dir / "ardy_motion.bvh"metadata_path = output_dir / "metadata.json"np.savez_compressed(2 unmodified linesfps=np.asarray(r["fps"], dtype=np.float32),text=np.asarray(prompt),seed=np.asarray(seed, dtype=np.int64),rig=np.asarray("human"),joint_names=np.asarray(joint_names),parents=np.asarray(parents, dtype=np.int32),rest_positions=np.asarray(rest_positions, dtype=np.float32),10 unmodified linesmetadata_path.write_text(json.dumps({"model": "nvidia/ARDY-Core-RP-20FPS-Horizon40","rig": "human","prompt": prompt,"seed": seed,"fps": r["fps"],"frames": int(out["posed_joints"].shape[0]),"joints": joint_names,"parents": parents,"coordinate_system": "Y-up, metric","post_processing": False,},ensure_ascii=False,1 unmodified line),encoding="utf-8",)return str(bvh_path), str(npz_path), str(metadata_path), seed@spaces.GPUdef generate_timeline_motion(timeline: list[list[object]],diffusion_steps: int = NUM_BASE_STEPS,cfg_weight: float = 2.0,seed: int = 0,randomize_seed: bool = True,) -> tuple[str, str, str, int]:"""Generate sequential prompts as one autoregressively continuous motion."""from timeline_utils import normalize_timeliner = RIGS["human"]segments = normalize_timeline(timeline, fps=float(r["fps"]))motion_np = Noneresolved_seed = int(seed)for index, segment in enumerate(segments):start_frame = 0 if motion_np is None else int(motion_np.shape[1])_, resolved_seed, motion_np = _core_generate("human",segment["prompt"],segment["duration_seconds"],diffusion_steps,cfg_weight,resolved_seed,bool(randomize_seed) if index == 0 else False,motion_np,)end_frame = int(motion_np.shape[1])segment["start_frame"] = start_framesegment["end_frame"] = end_framesegment["duration_seconds"] = (end_frame - start_frame) / float(r["fps"])if motion_np is None:raise gr.Error("The timeline did not contain any motion segments.")motion_tensor = torch.from_numpy(motion_np).to("cuda")out = _decode_motion("human", motion_tensor)skeleton = r["skeleton"]joint_names = list(skeleton.bone_order_names)parents = list(r["parents"])rest_positions = to_numpy(skeleton.neutral_joints)output_dir = Path(tempfile.mkdtemp(prefix="ardy_timeline_"))npz_path = output_dir / "ardy_timeline_motion.npz"bvh_path = output_dir / "ardy_timeline_motion.bvh"metadata_path = output_dir / "timeline_metadata.json"timeline_json = json.dumps(segments, ensure_ascii=False)np.savez_compressed(npz_path,**out,fps=np.asarray(r["fps"], dtype=np.float32),text=np.asarray(timeline_json),seed=np.asarray(resolved_seed, dtype=np.int64),rig=np.asarray("human"),joint_names=np.asarray(joint_names),parents=np.asarray(parents, dtype=np.int32),rest_positions=np.asarray(rest_positions, dtype=np.float32),)write_bvh(bvh_path,joint_names=joint_names,parents=parents,rest_positions=rest_positions,local_rot_mats=out["local_rot_mats"],root_positions=out["root_positions"],fps=r["fps"],)metadata_path.write_text(json.dumps({"model": "nvidia/ARDY-Core-RP-20FPS-Horizon40","rig": "human","seed": resolved_seed,"fps": r["fps"],"frames": int(out["posed_joints"].shape[0]),"duration_seconds": float(out["posed_joints"].shape[0]) / float(r["fps"]),"segments": segments,"joints": joint_names,"parents": parents,"coordinate_system": "Y-up, metric","generation_mode": "autoregressive timeline","post_processing": False,},ensure_ascii=False,indent=2,),encoding="utf-8",)return str(bvh_path), str(npz_path), str(metadata_path), resolved_seed# -----------------------------------------------------------------------------471 unmodified lineswith gr.Accordion("Blender export", open=False):gr.Markdown("Generate the human rig as **BVH**, full-fidelity **NPZ**, and ""JSON metadata. Import the BVH directly in Blender.")export_blender = gr.Button("Generate Blender files", variant="secondary")with gr.Row():bvh_file = gr.File(label="Blender BVH")npz_file = gr.File(label="ARDY NPZ")metadata_file = gr.File(label="Metadata")with gr.Accordion("Continuous action timeline", open=True):gr.Markdown("Add one short instruction per row. ARDY carries the previous pose and ""root trajectory into the next row, producing one continuous motion. ""Each segment is 2–4 seconds (the model's generation window is 2 seconds), ""and the combined duration may not exceed 8 seconds.")timeline_input = gr.Dataframe(headers=["Action prompt", "Duration (seconds)"],datatype=["str", "number"],type="array",row_count=(4, "dynamic"),col_count=(2, "fixed"),value=[["Walk forward two steps.", 2.0],["Turn around smoothly.", 2.0],["Wave the right hand.", 2.0],["Sit down on the ground.", 2.0],],label="Action segments",)generate_timeline = gr.Button("Generate continuous timeline",variant="primary",)with gr.Row():timeline_bvh = gr.File(label="Continuous Blender BVH")timeline_npz = gr.File(label="Continuous ARDY NPZ")timeline_metadata = gr.File(label="Timeline metadata")gr.Examples(examples=EXAMPLES,inputs=[prompt, rig, duration],23 unmodified linescont.click(fn=ui_continue, inputs=_gen_inputs + [seq_state],outputs=[player, seed, seq_state], api_name=False)export_blender.click(fn=generate_blender_motion,inputs=[prompt, duration, diffusion_steps, cfg_weight, seed, randomize_seed],outputs=[bvh_file, npz_file, metadata_file, seed],api_name=False,)generate_timeline.click(fn=generate_timeline_motion,inputs=[timeline_input, diffusion_steps, cfg_weight, seed, randomize_seed],outputs=[timeline_bvh, timeline_npz, timeline_metadata, seed],api_name=False,concurrency_limit=1,)# Clean single-shot endpoint for the HTTP API / MCP tool (no session state).gr.api(generate_motion, api_name="generate")gr.api(generate_blender_motion, api_name="generate_blender")gr.api(generate_timeline_motion, api_name="generate_timeline")demo.queue()525 unmodified lines5265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615622 unmodified lines56556656756856957057110 unmodified lines5825835845855865875885895905915925935945955965975985996006016026036041 unmodified line606607608609610611612613614615616617618619620621622623471 unmodified lines109510961097109810991100110111021103110411051106110711081109111023 unmodified lines113411351136113711381139114011411142114311441145114611471148525 unmodified linesrandomize_seed,None,)return _export_motion_files("human", motion_np, prompt, seed)def _export_motion_files(rig: str,motion_np: np.ndarray,prompt: str,seed: int,) -> tuple[str, str, str, int]:"""Decode an accumulated ARDY sequence and write Blender export files."""rig_key = _normalize_rig(rig)if motion_np is None:raise gr.Error("Generate a motion first, then use Continue to extend it before exporting.")motion_np = np.asarray(motion_np)if motion_np.ndim != 3 or motion_np.shape[0] != 1 or motion_np.shape[1] < 1:raise gr.Error(f"Invalid ARDY sequence state: shape={motion_np.shape}")motion_tensor = torch.from_numpy(motion_np).to("cuda")out = _decode_motion(rig_key, motion_tensor)r = RIGS[rig_key]skeleton = r["skeleton"]joint_names = list(skeleton.bone_order_names)parents = list(r["parents"])rest_positions = to_numpy(skeleton.neutral_joints)output_dir = Path(tempfile.mkdtemp(prefix="ardy_blender_"))npz_path = output_dir / f"ardy_{rig_key}_motion.npz"bvh_path = output_dir / f"ardy_{rig_key}_motion.bvh"metadata_path = output_dir / "metadata.json"np.savez_compressed(2 unmodified linesfps=np.asarray(r["fps"], dtype=np.float32),text=np.asarray(prompt),seed=np.asarray(seed, dtype=np.int64),rig=np.asarray(rig_key),joint_names=np.asarray(joint_names),parents=np.asarray(parents, dtype=np.int32),rest_positions=np.asarray(rest_positions, dtype=np.float32),10 unmodified linesmetadata_path.write_text(json.dumps({"model": ("nvidia/ARDY-Core-RP-20FPS-Horizon40"if rig_key == "human"else "nvidia/ARDY-G1-RP-25FPS-Horizon52"),"rig": rig_key,"latest_prompt": prompt,"seed": int(seed),"fps": r["fps"],"frames": int(out["posed_joints"].shape[0]),"duration_seconds": (float(out["posed_joints"].shape[0]) / float(r["fps"])),"joints": joint_names,"parents": parents,"coordinate_system": "Y-up, metric","source": "current accumulated Generate/Continue sequence","post_processing": False,},ensure_ascii=False,1 unmodified line),encoding="utf-8",)return str(bvh_path), str(npz_path), str(metadata_path), int(seed)@spaces.GPUdef export_current_sequence(state: object,rig: str = DEFAULT_RIG,prompt: str = "",seed: int = 0,) -> tuple[str, str, str, int]:"""Export the complete sequence currently held by Generate/Continue."""return _export_motion_files(rig, state, prompt, seed)# -----------------------------------------------------------------------------471 unmodified lineswith gr.Accordion("Blender export", open=False):gr.Markdown("Export the **complete motion currently in the player**, including ""every segment added with **Continue ▸**, as Blender **BVH**, ""full-fidelity **NPZ**, and JSON metadata.")export_blender = gr.Button("Export current sequence", variant="secondary")with gr.Row():bvh_file = gr.File(label="Blender BVH")npz_file = gr.File(label="ARDY NPZ")metadata_file = gr.File(label="Metadata")gr.Examples(examples=EXAMPLES,inputs=[prompt, rig, duration],23 unmodified linescont.click(fn=ui_continue, inputs=_gen_inputs + [seq_state],outputs=[player, seed, seq_state], api_name=False)export_blender.click(fn=export_current_sequence,inputs=[seq_state, rig, prompt, seed],outputs=[bvh_file, npz_file, metadata_file, seed],api_name=False,)# Clean single-shot endpoint for the HTTP API / MCP tool (no session state).gr.api(generate_motion, api_name="generate")gr.api(generate_blender_motion, api_name="generate_blender")demo.queue()
app.py+50-141