import tempfile
import gradio as gr
from gradio.inputs import Image, Radio
from gradio.outputs import Image3D
from gltflib import GLTF, FileResource

avocado = GLTF.load('./Avocado.glb')
cube = GLTF.load("./AnimatedCube/AnimatedCube.gltf")

def load_mesh(im: str, choose: str):
    print(im)
    # let's first clone the source model
    model = (avocado if choose == "avocado" else cube).clone()
    resource = FileResource(im.name)
    model.resources.append(resource)
    # let's do surgery
    if choose != "avocado":
        model.model.images[0].uri = im.name
    with tempfile.NamedTemporaryFile(suffix=".glb", delete=False) as file:
        model.export(file.name)
        return file.name

iface = gr.Interface(
    fn=load_mesh,
    description="draw on a canvas, get a 3D model",
    inputs=[
        Image(source="canvas", type="file", label="canvas"),
        Radio(choices=["cube", "avocado"], default="cube"),
    ],
    outputs=Image3D(),
    live=True,
)

if __name__ == "__main__":
    iface.launch()