File size: 1,131 Bytes
1b294d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import trimesh
import tempfile
import atexit
import shutil
import pathlib
import gradio as gr


def cleanup_temp_directories():
    print("Deleting temporary files")
    for temp_dir in temp_directories:
        try:
            shutil.rmtree(temp_dir)
        except FileNotFoundError:
            print(f"Could not delete directory {temp_dir}")


def stl2glb(glb_file):
    temp_dir = pathlib.Path(tempfile.mkdtemp())
    temp_directories.append(temp_dir)

    mesh = trimesh.load(glb_file)
    glb = trimesh.exchange.gltf.export_glb(mesh)

    output_file = (temp_dir / glb_file).with_suffix(".glb")
    with open(output_file, "wb") as f:
        f.write(glb)

    return str(output_file)


if __name__ == "__main__":
    temp_directories = []
    atexit.register(cleanup_temp_directories)

    demo = gr.Interface(
        fn=stl2glb,
        inputs=gr.Model3D(label="STL File"),
        outputs=gr.Model3D(label="GLB File"),
        examples=["space_shuttle.stl"],
        title="STL2GLB Converter",
        description="Convert a .stl file to a .glb file",
        analytics_enabled=False,
    )
    demo.launch(share=False)