CoolFace
Apppublic

AFindex/TRELLIS.2

sourceHugging Facemitupdated 9mo agoView on Hugging Face
0likes
app.py687 linesDownload Raw Back to root
1import gradio as gr2from gradio_client import Client, handle_file3import spaces4 5import os6os.environ["OPENCV_IO_ENABLE_OPENEXR"] = '1'7os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"8os.environ["ATTN_BACKEND"] = "flash_attn_3"9os.environ["FLEX_GEMM_AUTOTUNE_CACHE_PATH"] = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'autotune_cache.json')10os.environ["FLEX_GEMM_AUTOTUNER_VERBOSE"] = '1'11from datetime import datetime12import shutil13import cv214from typing import *15import torch16import numpy as np17from PIL import Image18import base6419import io20import tempfile21from trellis2.modules.sparse import SparseTensor22from trellis2.pipelines import Trellis2ImageTo3DPipeline23from trellis2.renderers import EnvMap24from trellis2.utils import render_utils25import o_voxel26 27 28MAX_SEED = np.iinfo(np.int32).max29TMP_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tmp')30MODES = [31    {"name": "Normal", "icon": "assets/app/normal.png", "render_key": "normal"},32    {"name": "Clay render", "icon": "assets/app/clay.png", "render_key": "clay"},33    {"name": "Base color", "icon": "assets/app/basecolor.png", "render_key": "base_color"},34    {"name": "HDRI forest", "icon": "assets/app/hdri_forest.png", "render_key": "shaded_forest"},35    {"name": "HDRI sunset", "icon": "assets/app/hdri_sunset.png", "render_key": "shaded_sunset"},36    {"name": "HDRI courtyard", "icon": "assets/app/hdri_courtyard.png", "render_key": "shaded_courtyard"},37]38STEPS = 839DEFAULT_MODE = 340DEFAULT_STEP = 341 42 43css = """44/* Overwrite Gradio Default Style */45.stepper-wrapper {46    padding: 0;47}48 49.stepper-container {50    padding: 0;51    align-items: center;52}53 54.step-button {55    flex-direction: row;56}57 58.step-connector {59    transform: none;60}61 62.step-number {63    width: 16px;64    height: 16px;65}66 67.step-label {68    position: relative;69    bottom: 0;70}71 72.wrap.center.full {73    inset: 0;74    height: 100%;75}76 77.wrap.center.full.translucent {78    background: var(--block-background-fill);79}80 81.meta-text-center {82    display: block !important;83    position: absolute !important;84    top: unset !important;85    bottom: 0 !important;86    right: 0 !important;87    transform: unset !important;88}89 90/* Previewer */91.previewer-container {92    position: relative;93    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;94    width: 100%;95    height: 722px;96    margin: 0 auto;97    padding: 20px;98    display: flex;99    flex-direction: column;100    align-items: center;101    justify-content: center;102}103 104.previewer-container .tips-icon {105    position: absolute;106    right: 10px;107    top: 10px;108    z-index: 10;109    border-radius: 10px;110    color: #fff;111    background-color: var(--color-accent);112    padding: 3px 6px;113    user-select: none;114}115 116.previewer-container .tips-text {117    position: absolute;118    right: 10px;119    top: 50px;120    color: #fff;121    background-color: var(--color-accent);122    border-radius: 10px;123    padding: 6px;124    text-align: left;125    max-width: 300px;126    z-index: 10;127    transition: all 0.3s;128    opacity: 0%;129    user-select: none;130}131 132.previewer-container .tips-text p {133    font-size: 14px;134    line-height: 1.2;135}136 137.tips-icon:hover + .tips-text { 138    display: block;139    opacity: 100%;140}141 142/* Row 1: Display Modes */143.previewer-container .mode-row {144    width: 100%;145    display: flex;146    gap: 8px;147    justify-content: center;148    margin-bottom: 20px;149    flex-wrap: wrap;150}151.previewer-container .mode-btn {152    width: 24px;153    height: 24px;154    border-radius: 50%;155    cursor: pointer;156    opacity: 0.5;157    transition: all 0.2s;158    border: 2px solid #ddd;159    object-fit: cover;160}161.previewer-container .mode-btn:hover { opacity: 0.9; transform: scale(1.1); }162.previewer-container .mode-btn.active {163    opacity: 1;164    border-color: var(--color-accent);165    transform: scale(1.1);166}167 168/* Row 2: Display Image */169.previewer-container .display-row {170    margin-bottom: 20px;171    min-height: 400px;172    width: 100%;173    flex-grow: 1;174    display: flex;175    justify-content: center;176    align-items: center;177}178.previewer-container .previewer-main-image {179    max-width: 100%;180    max-height: 100%;181    flex-grow: 1;182    object-fit: contain;183    display: none;184}185.previewer-container .previewer-main-image.visible {186    display: block;187}188 189/* Row 3: Custom HTML Slider */190.previewer-container .slider-row {191    width: 100%;192    display: flex;193    flex-direction: column;194    align-items: center;195    gap: 10px;196    padding: 0 10px;197}198 199.previewer-container input[type=range] {200    -webkit-appearance: none;201    width: 100%;202    max-width: 400px;203    background: transparent;204}205.previewer-container input[type=range]::-webkit-slider-runnable-track {206    width: 100%;207    height: 8px;208    cursor: pointer;209    background: #ddd;210    border-radius: 5px;211}212.previewer-container input[type=range]::-webkit-slider-thumb {213    height: 20px;214    width: 20px;215    border-radius: 50%;216    background: var(--color-accent);217    cursor: pointer;218    -webkit-appearance: none;219    margin-top: -6px;220    box-shadow: 0 2px 5px rgba(0,0,0,0.2);221    transition: transform 0.1s;222}223.previewer-container input[type=range]::-webkit-slider-thumb:hover {224    transform: scale(1.2);225}226 227/* Overwrite Previewer Block Style */228.gradio-container .padded:has(.previewer-container) {229    padding: 0 !important;230}231 232.gradio-container:has(.previewer-container) [data-testid="block-label"] {233    position: absolute;234    top: 0;235    left: 0;236}237"""238 239 240head = """241<script>242    function refreshView(mode, step) {243        // 1. Find current mode and step244        const allImgs = document.querySelectorAll('.previewer-main-image');245        for (let i = 0; i < allImgs.length; i++) {246            const img = allImgs[i];247            if (img.classList.contains('visible')) {248                const id = img.id;249                const [_, m, s] = id.split('-');250                if (mode === -1) mode = parseInt(m.slice(1));251                if (step === -1) step = parseInt(s.slice(1));252                break;253            }254        }255        256        // 2. Hide ALL images257        // We select all elements with class 'previewer-main-image'258        allImgs.forEach(img => img.classList.remove('visible'));259 260        // 3. Construct the specific ID for the current state261        // Format: view-m{mode}-s{step}262        const targetId = 'view-m' + mode + '-s' + step;263        const targetImg = document.getElementById(targetId);264 265        // 4. Show ONLY the target266        if (targetImg) {267            targetImg.classList.add('visible');268        }269 270        // 5. Update Button Highlights271        const allBtns = document.querySelectorAll('.mode-btn');272        allBtns.forEach((btn, idx) => {273            if (idx === mode) btn.classList.add('active');274            else btn.classList.remove('active');275        });276    }277    278    // --- Action: Switch Mode ---279    function selectMode(mode) {280        refreshView(mode, -1);281    }282    283    // --- Action: Slider Change ---284    function onSliderChange(val) {285        refreshView(-1, parseInt(val));286    }287</script>288"""289 290 291empty_html = f"""292<div class="previewer-container">293    <svg style=" opacity: .5; height: var(--size-5); color: var(--body-text-color);"294    xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="feather feather-image"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><circle cx="8.5" cy="8.5" r="1.5"></circle><polyline points="21 15 16 10 5 21"></polyline></svg>295</div>296"""297 298 299def image_to_base64(image):300    buffered = io.BytesIO()301    image = image.convert("RGB")302    image.save(buffered, format="jpeg", quality=85)303    img_str = base64.b64encode(buffered.getvalue()).decode()304    return f"data:image/jpeg;base64,{img_str}"305 306 307def start_session(req: gr.Request):308    user_dir = os.path.join(TMP_DIR, str(req.session_hash))309    os.makedirs(user_dir, exist_ok=True)310    311    312def end_session(req: gr.Request):313    user_dir = os.path.join(TMP_DIR, str(req.session_hash))314    shutil.rmtree(user_dir)315    316 317def remove_background(input: Image.Image) -> Image.Image:318    with tempfile.NamedTemporaryFile(suffix='.png') as f:319        input = input.convert('RGB')320        input.save(f.name)321        output = rmbg_client.predict(handle_file(f.name), api_name="/image")[0][0]322        output = Image.open(output)323        return output324 325 326def preprocess_image(input: Image.Image) -> Image.Image:327    """328    Preprocess the input image.329    """330    # if has alpha channel, use it directly; otherwise, remove background331    has_alpha = False332    if input.mode == 'RGBA':333        alpha = np.array(input)[:, :, 3]334        if not np.all(alpha == 255):335            has_alpha = True336    max_size = max(input.size)337    scale = min(1, 1024 / max_size)338    if scale < 1:339        input = input.resize((int(input.width * scale), int(input.height * scale)), Image.Resampling.LANCZOS)340    if has_alpha:341        output = input342    else:343        output = remove_background(input)344    output_np = np.array(output)345    alpha = output_np[:, :, 3]346    bbox = np.argwhere(alpha > 0.8 * 255)347    bbox = np.min(bbox[:, 1]), np.min(bbox[:, 0]), np.max(bbox[:, 1]), np.max(bbox[:, 0])348    center = (bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2349    size = max(bbox[2] - bbox[0], bbox[3] - bbox[1])350    size = int(size * 1)351    bbox = center[0] - size // 2, center[1] - size // 2, center[0] + size // 2, center[1] + size // 2352    output = output.crop(bbox)  # type: ignore353    output = np.array(output).astype(np.float32) / 255354    output = output[:, :, :3] * output[:, :, 3:4]355    output = Image.fromarray((output * 255).astype(np.uint8))356    return output357 358 359def pack_state(latents: Tuple[SparseTensor, SparseTensor, int]) -> dict:360    shape_slat, tex_slat, res = latents361    return {362        'shape_slat_feats': shape_slat.feats.cpu().numpy(),363        'tex_slat_feats': tex_slat.feats.cpu().numpy(),364        'coords': shape_slat.coords.cpu().numpy(),365        'res': res,366    }367    368    369def unpack_state(state: dict) -> Tuple[SparseTensor, SparseTensor, int]:370    shape_slat = SparseTensor(371        feats=torch.from_numpy(state['shape_slat_feats']).cuda(),372        coords=torch.from_numpy(state['coords']).cuda(),373    )374    tex_slat = shape_slat.replace(torch.from_numpy(state['tex_slat_feats']).cuda())375    return shape_slat, tex_slat, state['res']376 377 378def get_seed(randomize_seed: bool, seed: int) -> int:379    """380    Get the random seed.381    """382    return np.random.randint(0, MAX_SEED) if randomize_seed else seed383 384 385@spaces.GPU(duration=120)386def image_to_3d(387    image: Image.Image,388    seed: int,389    resolution: str,390    ss_guidance_strength: float,391    ss_guidance_rescale: float,392    ss_sampling_steps: int,393    ss_rescale_t: float,394    shape_slat_guidance_strength: float,395    shape_slat_guidance_rescale: float,396    shape_slat_sampling_steps: int,397    shape_slat_rescale_t: float,398    tex_slat_guidance_strength: float,399    tex_slat_guidance_rescale: float,400    tex_slat_sampling_steps: int,401    tex_slat_rescale_t: float,402    req: gr.Request,403    progress=gr.Progress(track_tqdm=True),404) -> str:405    # --- Sampling ---406    outputs, latents = pipeline.run(407        image,408        seed=seed,409        preprocess_image=False,410        sparse_structure_sampler_params={411            "steps": ss_sampling_steps,412            "guidance_strength": ss_guidance_strength,413            "guidance_rescale": ss_guidance_rescale,414            "rescale_t": ss_rescale_t,415        },416        shape_slat_sampler_params={417            "steps": shape_slat_sampling_steps,418            "guidance_strength": shape_slat_guidance_strength,419            "guidance_rescale": shape_slat_guidance_rescale,420            "rescale_t": shape_slat_rescale_t,421        },422        tex_slat_sampler_params={423            "steps": tex_slat_sampling_steps,424            "guidance_strength": tex_slat_guidance_strength,425            "guidance_rescale": tex_slat_guidance_rescale,426            "rescale_t": tex_slat_rescale_t,427        },428        pipeline_type={429            "512": "512",430            "1024": "1024_cascade",431            "1536": "1536_cascade",432        }[resolution],433        return_latent=True,434    )435    mesh = outputs[0]436    mesh.simplify(16777216) # nvdiffrast limit437    images = render_utils.render_snapshot(mesh, resolution=1024, r=2, fov=36, nviews=STEPS, envmap=envmap)438    state = pack_state(latents)439    torch.cuda.empty_cache()440    441    # --- HTML Construction ---442    # The Stack of 48 Images443    images_html = ""444    for m_idx, mode in enumerate(MODES):445        for s_idx in range(STEPS):446            # ID Naming Convention: view-m{mode}-s{step}447            unique_id = f"view-m{m_idx}-s{s_idx}"448            449            # Logic: Only Mode 0, Step 0 is visible initially450            is_visible = (m_idx == DEFAULT_MODE and s_idx == DEFAULT_STEP)451            vis_class = "visible" if is_visible else ""452            453            # Image Source454            img_base64 = image_to_base64(Image.fromarray(images[mode['render_key']][s_idx]))455            456            # Render the Tag457            images_html += f"""458                <img id="{unique_id}" 459                     class="previewer-main-image {vis_class}" 460                     src="{img_base64}" 461                     loading="eager">462            """463    464    # Button Row HTML465    btns_html = ""466    for idx, mode in enumerate(MODES):        467        active_class = "active" if idx == DEFAULT_MODE else ""468        # Note: onclick calls the JS function defined in Head469        btns_html += f"""470            <img src="{mode['icon_base64']}" 471                 class="mode-btn {active_class}" 472                 onclick="selectMode({idx})"473                 title="{mode['name']}">474        """475    476    # Assemble the full component477    full_html = f"""478    <div class="previewer-container">479        <div class="tips-wrapper">480            <div class="tips-icon">šŸ’”Tips</div>481            <div class="tips-text">482                <p>ā— <b>Render Mode</b> - Click on the circular buttons to switch between different render modes.</p>483                <p>ā— <b>View Angle</b> - Drag the slider to change the view angle.</p>484            </div>485        </div>486        487        <!-- Row 1: Viewport containing 48 static <img> tags -->488        <div class="display-row">489            {images_html}490        </div>491        492        <!-- Row 2 -->493        <div class="mode-row" id="btn-group">494            {btns_html}495        </div>496 497        <!-- Row 3: Slider -->498        <div class="slider-row">499            <input type="range" id="custom-slider" min="0" max="{STEPS - 1}" value="{DEFAULT_STEP}" step="1" oninput="onSliderChange(this.value)">500        </div>501    </div>502    """503    504    return state, full_html505 506 507@spaces.GPU(duration=120)508def extract_glb(509    state: dict,510    decimation_target: int,511    texture_size: int,512    req: gr.Request,513    progress=gr.Progress(track_tqdm=True),514) -> Tuple[str, str]:515    """516    Extract a GLB file from the 3D model.517 518    Args:519        state (dict): The state of the generated 3D model.520        decimation_target (int): The target face count for decimation.521        texture_size (int): The texture resolution.522 523    Returns:524        str: The path to the extracted GLB file.525    """526    user_dir = os.path.join(TMP_DIR, str(req.session_hash))527    shape_slat, tex_slat, res = unpack_state(state)528    mesh = pipeline.decode_latent(shape_slat, tex_slat, res)[0]529    mesh.simplify(16777216)530    glb = o_voxel.postprocess.to_glb(531        vertices=mesh.vertices,532        faces=mesh.faces,533        attr_volume=mesh.attrs,534        coords=mesh.coords,535        attr_layout=pipeline.pbr_attr_layout,536        grid_size=res,537        aabb=[[-0.5, -0.5, -0.5], [0.5, 0.5, 0.5]],538        decimation_target=decimation_target,539        texture_size=texture_size,540        remesh=True,541        remesh_band=1,542        remesh_project=0,543        use_tqdm=True,544    )545    now = datetime.now()546    timestamp = now.strftime("%Y-%m-%dT%H%M%S") + f".{now.microsecond // 1000:03d}"547    os.makedirs(user_dir, exist_ok=True)548    glb_path = os.path.join(user_dir, f'sample_{timestamp}.glb')549    glb.export(glb_path, extension_webp=True)550    torch.cuda.empty_cache()551    return glb_path, glb_path552 553 554with gr.Blocks(delete_cache=(600, 600)) as demo:555    gr.Markdown("""556    ## Image to 3D Asset with [TRELLIS.2](https://microsoft.github.io/TRELLIS.2)557    * Upload an image (preferably with an alpha-masked foreground object) and click Generate to create a 3D asset.558    * Click Extract GLB to export and download the generated GLB file if you're satisfied with the result. Otherwise, try another time.559    """)560    561    with gr.Row():562        with gr.Column(scale=1, min_width=360):563            image_prompt = gr.Image(label="Image Prompt", format="png", image_mode="RGBA", type="pil", height=400)564            565            resolution = gr.Radio(["512", "1024", "1536"], label="Resolution", value="1024")566            seed = gr.Slider(0, MAX_SEED, label="Seed", value=0, step=1)567            randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)568            decimation_target = gr.Slider(100000, 500000, label="Decimation Target", value=300000, step=10000)569            texture_size = gr.Slider(1024, 4096, label="Texture Size", value=2048, step=1024)570            571            generate_btn = gr.Button("Generate")572                573            with gr.Accordion(label="Advanced Settings", open=False):                574                gr.Markdown("Stage 1: Sparse Structure Generation")575                with gr.Row():576                    ss_guidance_strength = gr.Slider(1.0, 10.0, label="Guidance Strength", value=7.5, step=0.1)577                    ss_guidance_rescale = gr.Slider(0.0, 1.0, label="Guidance Rescale", value=0.7, step=0.01)578                    ss_sampling_steps = gr.Slider(1, 50, label="Sampling Steps", value=12, step=1)579                    ss_rescale_t = gr.Slider(1.0, 6.0, label="Rescale T", value=5.0, step=0.1)580                gr.Markdown("Stage 2: Shape Generation")581                with gr.Row():582                    shape_slat_guidance_strength = gr.Slider(1.0, 10.0, label="Guidance Strength", value=7.5, step=0.1)583                    shape_slat_guidance_rescale = gr.Slider(0.0, 1.0, label="Guidance Rescale", value=0.5, step=0.01)584                    shape_slat_sampling_steps = gr.Slider(1, 50, label="Sampling Steps", value=12, step=1)585                    shape_slat_rescale_t = gr.Slider(1.0, 6.0, label="Rescale T", value=3.0, step=0.1)586                gr.Markdown("Stage 3: Material Generation")587                with gr.Row():588                    tex_slat_guidance_strength = gr.Slider(1.0, 10.0, label="Guidance Strength", value=1.0, step=0.1)589                    tex_slat_guidance_rescale = gr.Slider(0.0, 1.0, label="Guidance Rescale", value=0.0, step=0.01)590                    tex_slat_sampling_steps = gr.Slider(1, 50, label="Sampling Steps", value=12, step=1)591                    tex_slat_rescale_t = gr.Slider(1.0, 6.0, label="Rescale T", value=3.0, step=0.1)                592 593        with gr.Column(scale=10):594            with gr.Walkthrough(selected=0) as walkthrough:595                with gr.Step("Preview", id=0):596                    preview_output = gr.HTML(empty_html, label="3D Asset Preview", show_label=True, container=True)597                    extract_btn = gr.Button("Extract GLB")598                with gr.Step("Extract", id=1):599                    glb_output = gr.Model3D(label="Extracted GLB", height=724, show_label=True, display_mode="solid", clear_color=(0.25, 0.25, 0.25, 1.0))600                    download_btn = gr.DownloadButton(label="Download GLB")601            gr.Markdown("*We are actively working on improving the speed of GLB extraction. Currently, it may take half a minute or more and face count is limited.*")602                    603        with gr.Column(scale=1, min_width=172):604            examples = gr.Examples(605                examples=[606                    f'assets/example_image/{image}'607                    for image in os.listdir("assets/example_image")608                ],609                inputs=[image_prompt],610                fn=preprocess_image,611                outputs=[image_prompt],612                run_on_click=True,613                examples_per_page=18,614            )615                    616    output_buf = gr.State()617    618 619    # Handlers620    demo.load(start_session)621    demo.unload(end_session)622    623    image_prompt.upload(624        preprocess_image,625        inputs=[image_prompt],626        outputs=[image_prompt],627    )628 629    generate_btn.click(630        get_seed,631        inputs=[randomize_seed, seed],632        outputs=[seed],633    ).then(634        lambda: gr.Walkthrough(selected=0), outputs=walkthrough635    ).then(636        image_to_3d,637        inputs=[638            image_prompt, seed, resolution,639            ss_guidance_strength, ss_guidance_rescale, ss_sampling_steps, ss_rescale_t,640            shape_slat_guidance_strength, shape_slat_guidance_rescale, shape_slat_sampling_steps, shape_slat_rescale_t,641            tex_slat_guidance_strength, tex_slat_guidance_rescale, tex_slat_sampling_steps, tex_slat_rescale_t,642        ],643        outputs=[output_buf, preview_output],644    )645    646    extract_btn.click(647        lambda: gr.Walkthrough(selected=1), outputs=walkthrough648    ).then(649        extract_glb,650        inputs=[output_buf, decimation_target, texture_size],651        outputs=[glb_output, download_btn],652    )653        654 655# Launch the Gradio app656if __name__ == "__main__":657    os.makedirs(TMP_DIR, exist_ok=True)658 659    # Construct ui components660    btn_img_base64_strs = {}661    for i in range(len(MODES)):662        icon = Image.open(MODES[i]['icon'])663        MODES[i]['icon_base64'] = image_to_base64(icon)664 665    rmbg_client = Client("briaai/BRIA-RMBG-2.0")666    pipeline = Trellis2ImageTo3DPipeline.from_pretrained('microsoft/TRELLIS.2-4B')667    pipeline.rembg_model = None668    pipeline.low_vram = False669    pipeline.cuda()670    671    envmap = {672        'forest': EnvMap(torch.tensor(673            cv2.cvtColor(cv2.imread('assets/hdri/forest.exr', cv2.IMREAD_UNCHANGED), cv2.COLOR_BGR2RGB),674            dtype=torch.float32, device='cuda'675        )),676        'sunset': EnvMap(torch.tensor(677            cv2.cvtColor(cv2.imread('assets/hdri/sunset.exr', cv2.IMREAD_UNCHANGED), cv2.COLOR_BGR2RGB),678            dtype=torch.float32, device='cuda'679        )),680        'courtyard': EnvMap(torch.tensor(681            cv2.cvtColor(cv2.imread('assets/hdri/courtyard.exr', cv2.IMREAD_UNCHANGED), cv2.COLOR_BGR2RGB),682            dtype=torch.float32, device='cuda'683        )),684    }685    686    demo.launch(css=css, head=head)687