File size: 3,722 Bytes
30aba9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
"""
SAM 3D Objects MCP Server
Image + Mask β†’ 3D Object (PLY)
"""
import os
import sys
import subprocess
import tempfile
import uuid
from pathlib import Path

import gradio as gr
import numpy as np
import spaces
from huggingface_hub import snapshot_download, login
from PIL import Image

# Login with HF_TOKEN if available
if os.environ.get("HF_TOKEN"):
    login(token=os.environ.get("HF_TOKEN"))

# Clone sam-3d-objects repo if not exists
SAM3D_PATH = Path("/home/user/app/sam-3d-objects")
if not SAM3D_PATH.exists():
    print("Cloning sam-3d-objects repository...")
    subprocess.run([
        "git", "clone",
        "https://github.com/facebookresearch/sam-3d-objects.git",
        str(SAM3D_PATH)
    ], check=True)
    sys.path.insert(0, str(SAM3D_PATH))

# Add to path
sys.path.insert(0, str(SAM3D_PATH))

# Global model
MODEL = None


def load_model():
    """Load SAM 3D Objects model"""
    global MODEL

    if MODEL is not None:
        return MODEL

    import torch
    print("Loading SAM 3D Objects model...")

    # Download checkpoint
    checkpoint_dir = snapshot_download(
        repo_id="facebook/sam-3d-objects",
        token=os.environ.get("HF_TOKEN")
    )

    from sam_3d_objects import Sam3dObjects

    device = "cuda" if torch.cuda.is_available() else "cpu"

    MODEL = Sam3dObjects.from_pretrained(checkpoint_dir, device=device)

    print("βœ“ Model loaded")
    return MODEL


@spaces.GPU(duration=120)
def reconstruct_object(image: np.ndarray, mask: np.ndarray) -> tuple:
    """
    Reconstruct 3D object from image and mask.

    Args:
        image: Input RGB image
        mask: Binary mask indicating object region

    Returns:
        tuple: (ply_path, status)
    """
    if image is None:
        return None, "❌ No image provided"
    if mask is None:
        return None, "❌ No mask provided"

    try:
        import torch
        import trimesh
        model = load_model()

        # Process image
        if isinstance(image, Image.Image):
            image = np.array(image)

        # Process mask
        if isinstance(mask, Image.Image):
            mask = np.array(mask)

        # Convert mask to binary if needed
        if len(mask.shape) == 3:
            mask = mask[:, :, 0]
        mask = (mask > 127).astype(np.uint8)

        # Run inference
        outputs = model.predict(image, mask)

        if outputs is None:
            return None, "⚠️ Reconstruction failed"

        # Export as PLY
        output_dir = tempfile.mkdtemp()
        ply_path = f"{output_dir}/object_{uuid.uuid4().hex[:8]}.ply"

        # Save gaussian splat as PLY
        outputs.save_ply(ply_path)

        return ply_path, "βœ“ Object reconstructed"

    except Exception as e:
        import traceback
        traceback.print_exc()
        return None, f"❌ Error: {e}"


# Gradio Interface
with gr.Blocks(title="SAM 3D Objects MCP") as demo:
    gr.Markdown("# πŸ“¦ SAM 3D Objects MCP Server\n**Image + Mask β†’ 3D Object (PLY)**")

    with gr.Row():
        with gr.Column():
            input_image = gr.Image(label="Input Image", type="numpy")
            input_mask = gr.Image(label="Object Mask", type="numpy")
            btn = gr.Button("🎯 Reconstruct", variant="primary")

        with gr.Column():
            output_file = gr.File(label="3D Object (PLY)")
            status = gr.Textbox(label="Status")

    btn.click(reconstruct_object, inputs=[input_image, input_mask], outputs=[output_file, status])

    gr.Markdown("""
    ---
    ### MCP Server
    ```json
    {"mcpServers": {"sam3d-objects": {"command": "npx", "args": ["mcp-remote", "URL/gradio_api/mcp/sse"]}}}
    ```
    """)


if __name__ == "__main__":
    demo.launch(mcp_server=True)