Spaces:
Sleeping
Sleeping
| import os | |
| import streamlit as st | |
| import tempfile | |
| import trimesh | |
| import pymeshlab | |
| import cadquery as cq | |
| from pathlib import Path | |
| import subprocess | |
| # Ensure FreeCAD is in the system path | |
| os.environ["PATH"] += r";C:\Program Files\FreeCAD 0.21\bin" | |
| # Set title | |
| st.title("3D Model Converter") | |
| # Supported formats | |
| input_formats = ["obj", "stl", "ply", "glb", "gltf", "off", "3ds", "fbx", "dae", "stp", "skp"] | |
| output_formats = ["obj", "stl", "ply", "glb", "gltf", "off", "3ds", "fbx", "dae"] | |
| # Upload file | |
| uploaded_file = st.file_uploader("Upload a 3D model file", type=input_formats) | |
| if uploaded_file: | |
| file_ext = uploaded_file.name.split(".")[-1].lower() | |
| # Select output format | |
| output_format = st.selectbox("Select output format", [fmt for fmt in output_formats if fmt != file_ext]) | |
| # Process and convert | |
| if st.button("Convert"): | |
| with tempfile.TemporaryDirectory() as temp_dir: | |
| input_path = os.path.join(temp_dir, uploaded_file.name) | |
| output_path = os.path.join(temp_dir, f"converted.{output_format}") | |
| # Save uploaded file | |
| with open(input_path, "wb") as f: | |
| f.write(uploaded_file.read()) | |
| try: | |
| if file_ext == "stp": | |
| temp_stl_path = os.path.join(temp_dir, "temp.stl") # Temporary STL file | |
| # Convert STEP to STL using FreeCAD | |
| freecad_script = f""" | |
| import FreeCAD | |
| import Part | |
| import Mesh | |
| doc = FreeCAD.newDocument() | |
| shape = Part.Shape() | |
| shape.read("{input_path}") | |
| Mesh.export([shape], "{temp_stl_path}") | |
| """ | |
| script_path = os.path.join(temp_dir, "convert_stp.py") | |
| with open(script_path, "w") as f: | |
| f.write(freecad_script) | |
| subprocess.run(["freecadcmd", script_path], check=True) | |
| if output_format == "stl": | |
| output_path = temp_stl_path | |
| else: | |
| mesh = trimesh.load(temp_stl_path) # Convert STL to other formats | |
| mesh.export(output_path) | |
| elif file_ext in ["obj", "stl", "ply", "off"]: | |
| mesh = trimesh.load(input_path) | |
| mesh.export(output_path) | |
| else: | |
| ms = pymeshlab.MeshSet() | |
| ms.load_new_mesh(input_path) | |
| ms.save_current_mesh(output_path, binary=True) | |
| # Provide download link | |
| with open(output_path, "rb") as f: | |
| st.download_button(label="Download Converted File", data=f, file_name=f"converted.{output_format}") | |
| except Exception as e: | |
| st.error(f"Conversion failed: {e}") # Show error if conversion fails | |