Step1X-3D / app.py
theglobe1's picture
Upload app.py
71a028a verified
Raw History Blame Contribute Delete
5.5 kB
# Step1X-3D - SHAPE ONLY v2 for a NEW EMPTY Space (Uniboards, 2026-11-20). Upload only README.md, requirements.txt, app.py.
# step1x3d_geometry/ is fetched at start-up from the (paused, still readable) Space stepfun-ai/Step1X-3D, pinned commit.
# One photo -> mesh (GLB + STL) on a plain A10G (24 GB), not ZeroGPU.
# Removed from the original Space: the CUDA toolkit download, step1x3d_texture (SD/SDXL texturing), custom_rasterizer,
# nvdiffrast and the `spaces` decorator. Kept: step1x3d_geometry + stepfun-ai/Step1X-3D Geometry-Label-1300m (Apache-2.0).
# Background: removed HERE with BiRefNet-general (MIT). The pipeline's own default ("bria" = BRIA RMBG, non-commercial)
# is blocked: rembg.new_session refuses any bria model, and we always hand the pipeline a photo that already has a cut-out.
import os
import datetime
import numpy as np
import torch
import trimesh
import gradio as gr
import rembg
from PIL import Image
_new_session = rembg.new_session
def _safe_session(model_name="u2net", *a, **k):
if "bria" in str(model_name).lower():
raise RuntimeError("BRIA RMBG is non-commercial - blocked in this Space")
return _new_session(model_name, *a, **k)
rembg.new_session = _safe_session
import sys
from huggingface_hub import snapshot_download
CODE_DIR = snapshot_download(repo_id="stepfun-ai/Step1X-3D", repo_type="space",
revision="95bbafb61e724c72bef6be3a99804bfc6b0ca7ee",
allow_patterns=["step1x3d_geometry/*", "step1x3d_geometry/**"],
local_dir=os.path.join(os.path.dirname(os.path.abspath(__file__)), "step1x3d_src"))
sys.path.insert(0, CODE_DIR)
from step1x3d_geometry.models.pipelines.pipeline import Step1X3DGeometryPipeline
MAX_SEED = np.iinfo(np.int32).max
TMP_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "tmp")
os.makedirs(TMP_DIR, exist_ok=True)
pipeline = Step1X3DGeometryPipeline.from_pretrained("stepfun-ai/Step1X-3D", subfolder="Step1X-3D-Geometry-Label-1300m").to("cuda")
bg_session = _safe_session("birefnet-general", providers=["CPUExecutionProvider"])
def cut_out(img):
img = img.convert("RGBA")
if img.getextrema()[3][0] < 255: # already has a transparent background
return img
out = rembg.remove(img, session=bg_session).convert("RGBA")
if out.getextrema()[3][0] >= 255:
raise gr.Error("Could not separate the subject from the background - try a photo with a plainer background.")
return out
@torch.no_grad()
def generate(image, seed, steps, guidance, symmetry, edge_type, octree, target_faces):
if image is None:
raise gr.Error("Upload a photo first.")
seed = int(seed) if int(seed) >= 0 else int(np.random.randint(0, MAX_SEED))
cut = cut_out(image)
gen = torch.Generator(device="cuda").manual_seed(seed)
cut_path = os.path.join(TMP_DIR, f"cut_{seed}.png")
cut.save(cut_path)
out = pipeline(cut_path, label={"symmetry": symmetry, "edge_type": edge_type},
guidance_scale=float(guidance), num_inference_steps=int(steps), generator=gen,
octree_resolution=int(octree), max_facenum=int(target_faces) if int(target_faces) > 0 else 2000000,
do_reduce_face=int(target_faces) > 0)
mesh = out.mesh[0]
if not isinstance(mesh, trimesh.Trimesh):
mesh = trimesh.Trimesh(vertices=np.asarray(mesh.vertices), faces=np.asarray(mesh.faces))
stamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
folder = os.path.join(TMP_DIR, stamp)
os.makedirs(folder, exist_ok=True)
glb, stl = os.path.join(folder, f"step1x3d_{stamp}.glb"), os.path.join(folder, f"step1x3d_{stamp}.stl")
mesh.export(glb)
mesh.export(stl)
torch.cuda.empty_cache()
info = f"seed {seed}; faces {len(mesh.faces):,}; vertices {len(mesh.vertices):,}; watertight {mesh.is_watertight}"
return cut, glb, glb, stl, info
with gr.Blocks(title="Step1X-3D shape only") as demo:
gr.Markdown("# Step1X-3D - shape only\nOne photo (one subject) -> 3D mesh. Download GLB or STL.")
with gr.Row():
with gr.Column():
image_in = gr.Image(label="Photo", type="pil", image_mode="RGBA")
with gr.Accordion("Settings", open=False):
seed = gr.Number(label="Seed (-1 = random)", value=2025, precision=0)
steps = gr.Slider(10, 100, value=50, step=1, label="Sampling steps")
guidance = gr.Slider(1.0, 15.0, value=7.5, step=0.1, label="Guidance")
symmetry = gr.Radio(["x", "asymmetry"], value="asymmetry", label="Symmetry (x = mirror left/right)")
edge_type = gr.Radio(["sharp", "normal", "smooth"], value="normal", label="Edge type")
octree = gr.Slider(256, 512, value=384, step=64, label="Mesh resolution (octree)")
target_faces = gr.Slider(0, 2000000, value=0, step=10000, label="Target faces (0 = keep all)")
go = gr.Button("Generate", variant="primary")
with gr.Column():
cut_out_img = gr.Image(label="Cut-out used", type="pil")
model_out = gr.Model3D(label="Mesh")
glb_out = gr.File(label="Download GLB")
stl_out = gr.File(label="Download STL")
info_out = gr.Textbox(label="Info")
go.click(generate, [image_in, seed, steps, guidance, symmetry, edge_type, octree, target_faces],
[cut_out_img, model_out, glb_out, stl_out, info_out])
demo.queue(max_size=4).launch()