Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -9,32 +9,9 @@ import json
|
|
| 9 |
import atexit
|
| 10 |
import glob
|
| 11 |
|
| 12 |
-
def process_cad_file(file):
|
| 13 |
-
# Check if the file exists and is not empty
|
| 14 |
-
if not os.path.exists(file.name):
|
| 15 |
-
raise ValueError("Uploaded file is missing or does not exist.")
|
| 16 |
-
if os.path.getsize(file.name) == 0:
|
| 17 |
-
raise ValueError("Uploaded file is empty.")
|
| 18 |
-
|
| 19 |
-
# Validate file format
|
| 20 |
-
file_extension = os.path.splitext(file.name)[-1].lower()
|
| 21 |
-
if file_extension not in [".stp", ".step", ".iges", ".igs"]:
|
| 22 |
-
raise ValueError(f"Unsupported file format: {file_extension}")
|
| 23 |
-
|
| 24 |
-
# Process the valid CAD file
|
| 25 |
-
try:
|
| 26 |
-
if file_extension in [".stp", ".step"]:
|
| 27 |
-
return cq.importers.importStep(file.name)
|
| 28 |
-
elif file_extension in [".iges", ".igs"]:
|
| 29 |
-
return cq.importers.importStep(file.name) # Same handler for now
|
| 30 |
-
else:
|
| 31 |
-
raise ValueError("Invalid file type detected during processing.")
|
| 32 |
-
except Exception as e:
|
| 33 |
-
raise RuntimeError(f"Error processing the CAD file: {str(e)}")
|
| 34 |
-
|
| 35 |
# Cleanup function to remove temporary files
|
| 36 |
def cleanup_temp_files():
|
| 37 |
-
temp_files = glob.glob("
|
| 38 |
for temp_file in temp_files:
|
| 39 |
try:
|
| 40 |
os.remove(temp_file)
|
|
@@ -43,84 +20,71 @@ def cleanup_temp_files():
|
|
| 43 |
|
| 44 |
atexit.register(cleanup_temp_files)
|
| 45 |
|
| 46 |
-
#
|
| 47 |
def generate_2d_view(file):
|
| 48 |
try:
|
| 49 |
-
# Process CAD file
|
| 50 |
model = process_cad_file(file)
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
svg_content = model.toSvg()
|
| 54 |
-
svg_path = "/tmp/2d_view.svg"
|
| 55 |
-
with open(svg_path, "w") as svg_file:
|
| 56 |
-
svg_file.write(svg_content)
|
| 57 |
-
|
| 58 |
-
print(f"2D View successfully generated: {svg_path}")
|
| 59 |
-
return svg_path
|
| 60 |
except Exception as e:
|
| 61 |
-
|
| 62 |
-
print(error_message) # Log error details
|
| 63 |
-
return error_message
|
| 64 |
-
|
| 65 |
|
| 66 |
-
# Generate 3D View
|
| 67 |
def generate_3d_view(file):
|
| 68 |
try:
|
| 69 |
-
# Import CAD file
|
| 70 |
model = cq.importers.importStep(file.name)
|
| 71 |
|
| 72 |
-
# Extract solids
|
| 73 |
-
solids = model.solids()
|
| 74 |
if not solids:
|
| 75 |
raise ValueError("No solids found in the CAD model.")
|
| 76 |
|
| 77 |
-
#
|
| 78 |
-
|
| 79 |
-
faces = []
|
| 80 |
for solid in solids:
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
mesh.export(obj_path)
|
| 88 |
|
| 89 |
-
|
| 90 |
-
|
|
|
|
|
|
|
| 91 |
except Exception as e:
|
| 92 |
-
|
| 93 |
-
print(error_message) # Log error details
|
| 94 |
-
return error_message
|
| 95 |
|
| 96 |
|
| 97 |
-
|
|
|
|
| 98 |
def generate_views(file):
|
| 99 |
try:
|
| 100 |
-
two_d_view = generate_2d_view(file)
|
| 101 |
-
three_d_view = generate_3d_view(file)
|
| 102 |
-
|
| 103 |
-
# Check if 3D generation was successful
|
| 104 |
-
if "Error" in three_d_view:
|
| 105 |
-
return two_d_view, {"error": True, "message": three_d_view}
|
| 106 |
-
else:
|
| 107 |
-
return two_d_view, {"error": False, "message": "3D view generated successfully!"}
|
| 108 |
except Exception as e:
|
| 109 |
-
return f"Error: {str(e)}",
|
| 110 |
|
| 111 |
-
#
|
| 112 |
def process_cad_file(file):
|
| 113 |
file_extension = os.path.splitext(file.name)[-1].lower()
|
| 114 |
if file_extension in [".stp", ".step"]:
|
| 115 |
-
|
| 116 |
elif file_extension in [".iges", ".igs"]:
|
| 117 |
-
|
| 118 |
elif file_extension == ".sldprt":
|
| 119 |
-
raise NotImplementedError("SLDPRT support is not implemented.")
|
| 120 |
elif file_extension == ".dwg":
|
| 121 |
-
raise NotImplementedError("DWG support is not implemented.")
|
| 122 |
else:
|
| 123 |
raise ValueError(f"Unsupported file format: {file_extension}")
|
|
|
|
| 124 |
|
| 125 |
# APDL script generation
|
| 126 |
def generate_apdl_script(file, press_force, material_json):
|
|
@@ -129,14 +93,17 @@ def generate_apdl_script(file, press_force, material_json):
|
|
| 129 |
elastic_modulus = material.get("elastic_modulus", 2e11)
|
| 130 |
poisson = material.get("poisson", 0.3)
|
| 131 |
|
|
|
|
|
|
|
| 132 |
model = process_cad_file(file)
|
| 133 |
-
|
|
|
|
| 134 |
exporters.export(model, stl_file)
|
| 135 |
|
| 136 |
apdl_script = f"""\n
|
| 137 |
/PREP7
|
| 138 |
! Importing Geometry
|
| 139 |
-
/import, '{
|
| 140 |
! Material Properties
|
| 141 |
MP, EX, 1, {elastic_modulus}
|
| 142 |
MP, PRXY, 1, {poisson}
|
|
@@ -149,14 +116,15 @@ SOLVE
|
|
| 149 |
*GET, stress, NODE, 0, S, MAX
|
| 150 |
/EXIT, SAVE
|
| 151 |
"""
|
| 152 |
-
apdl_file_path = "
|
| 153 |
with open(apdl_file_path, "w") as apdl_file:
|
| 154 |
apdl_file.write(apdl_script)
|
|
|
|
| 155 |
return apdl_script, apdl_file_path
|
| 156 |
except Exception as e:
|
| 157 |
-
return f"Error
|
| 158 |
|
| 159 |
-
#
|
| 160 |
def find_free_port(start_port, end_port):
|
| 161 |
for port in range(start_port, end_port + 1):
|
| 162 |
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
|
@@ -164,7 +132,7 @@ def find_free_port(start_port, end_port):
|
|
| 164 |
return port
|
| 165 |
raise OSError(f"No available ports in range {start_port}-{end_port}")
|
| 166 |
|
| 167 |
-
#
|
| 168 |
def main():
|
| 169 |
with gr.Blocks() as app:
|
| 170 |
gr.Markdown("# Press Tool Design and APDL Script Generator")
|
|
@@ -176,11 +144,8 @@ def main():
|
|
| 176 |
)
|
| 177 |
|
| 178 |
with gr.Row():
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
two_d_output = gr.Image(label="2D View", type="filepath") # Use 'filepath' to display image from a file path
|
| 182 |
-
|
| 183 |
-
three_d_output = gr.Label(label="3D View Status") # 3D as Label
|
| 184 |
generate_views_btn = gr.Button("Generate 2D & 3D Views")
|
| 185 |
|
| 186 |
with gr.Row():
|
|
@@ -195,14 +160,19 @@ def main():
|
|
| 195 |
download_button = gr.File(label="Download Script")
|
| 196 |
generate_apdl_btn = gr.Button("Generate APDL Script")
|
| 197 |
|
| 198 |
-
# Visualization
|
| 199 |
generate_views_btn.click(
|
| 200 |
fn=generate_views,
|
| 201 |
inputs=step_input,
|
| 202 |
outputs=[two_d_output, three_d_output]
|
| 203 |
)
|
| 204 |
|
| 205 |
-
# APDL Script
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
generate_apdl_btn.click(
|
| 207 |
fn=generate_apdl_script,
|
| 208 |
inputs=[step_input, force_input, material_input],
|
|
@@ -213,8 +183,9 @@ def main():
|
|
| 213 |
if __name__ == "__main__":
|
| 214 |
app = main()
|
| 215 |
try:
|
| 216 |
-
|
|
|
|
|
|
|
| 217 |
app.launch(server_port=port, debug=True)
|
| 218 |
except Exception as e:
|
| 219 |
-
print(f"Failed to launch: {str(e)}")
|
| 220 |
-
|
|
|
|
| 9 |
import atexit
|
| 10 |
import glob
|
| 11 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
# Cleanup function to remove temporary files
|
| 13 |
def cleanup_temp_files():
|
| 14 |
+
temp_files = glob.glob("*.stl") + glob.glob("*.inp")
|
| 15 |
for temp_file in temp_files:
|
| 16 |
try:
|
| 17 |
os.remove(temp_file)
|
|
|
|
| 20 |
|
| 21 |
atexit.register(cleanup_temp_files)
|
| 22 |
|
| 23 |
+
# Define 2D and 3D view generation functions with error handling
|
| 24 |
def generate_2d_view(file):
|
| 25 |
try:
|
|
|
|
| 26 |
model = process_cad_file(file)
|
| 27 |
+
two_d_image = model.toSvg()
|
| 28 |
+
return two_d_image
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
except Exception as e:
|
| 30 |
+
return f"Error generating 2D view: {str(e)}"
|
|
|
|
|
|
|
|
|
|
| 31 |
|
|
|
|
| 32 |
def generate_3d_view(file):
|
| 33 |
try:
|
| 34 |
+
# Import CAD file and create a Workplane object
|
| 35 |
model = cq.importers.importStep(file.name)
|
| 36 |
|
| 37 |
+
# Extract solids from the Workplane object
|
| 38 |
+
solids = model.vals() if hasattr(model, 'vals') else model.solids()
|
| 39 |
if not solids:
|
| 40 |
raise ValueError("No solids found in the CAD model.")
|
| 41 |
|
| 42 |
+
# Convert solids into trimesh-compatible meshes
|
| 43 |
+
meshes = []
|
|
|
|
| 44 |
for solid in solids:
|
| 45 |
+
vertices = []
|
| 46 |
+
faces = []
|
| 47 |
+
for face in solid.tessellate():
|
| 48 |
+
vertices.extend(face[0]) # Extract vertices (x, y, z)
|
| 49 |
+
faces.extend([[face[1][i], face[1][i + 1], face[1][i + 2]] for i in range(0, len(face[1]), 3)]) # Triangular faces
|
| 50 |
+
mesh = trimesh.Trimesh(vertices=vertices, faces=faces)
|
| 51 |
+
meshes.append(mesh)
|
| 52 |
|
| 53 |
+
# Combine all meshes into a single trimesh object if multiple solids exist
|
| 54 |
+
combined_mesh = trimesh.util.concatenate(meshes) if len(meshes) > 1 else meshes[0]
|
|
|
|
| 55 |
|
| 56 |
+
# Visualize the mesh
|
| 57 |
+
combined_mesh.show()
|
| 58 |
+
|
| 59 |
+
return "3D view generated successfully."
|
| 60 |
except Exception as e:
|
| 61 |
+
return f"Error generating 3D view: {str(e)}"
|
|
|
|
|
|
|
| 62 |
|
| 63 |
|
| 64 |
+
|
| 65 |
+
# Wrapper function to generate views
|
| 66 |
def generate_views(file):
|
| 67 |
try:
|
| 68 |
+
two_d_view = generate_2d_view(file)
|
| 69 |
+
three_d_view = generate_3d_view(file)
|
| 70 |
+
return two_d_view, three_d_view
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
except Exception as e:
|
| 72 |
+
return f"Error: {str(e)}", None
|
| 73 |
|
| 74 |
+
# Function to process different CAD file formats
|
| 75 |
def process_cad_file(file):
|
| 76 |
file_extension = os.path.splitext(file.name)[-1].lower()
|
| 77 |
if file_extension in [".stp", ".step"]:
|
| 78 |
+
model = cq.importers.importStep(file.name)
|
| 79 |
elif file_extension in [".iges", ".igs"]:
|
| 80 |
+
model = cq.importers.importStep(file.name) # Same as STEP for cadquery
|
| 81 |
elif file_extension == ".sldprt":
|
| 82 |
+
raise NotImplementedError("SLDPRT support is not yet implemented.")
|
| 83 |
elif file_extension == ".dwg":
|
| 84 |
+
raise NotImplementedError("DWG support is not yet implemented.")
|
| 85 |
else:
|
| 86 |
raise ValueError(f"Unsupported file format: {file_extension}")
|
| 87 |
+
return model
|
| 88 |
|
| 89 |
# APDL script generation
|
| 90 |
def generate_apdl_script(file, press_force, material_json):
|
|
|
|
| 93 |
elastic_modulus = material.get("elastic_modulus", 2e11)
|
| 94 |
poisson = material.get("poisson", 0.3)
|
| 95 |
|
| 96 |
+
# Use temporary file path for processing
|
| 97 |
+
step_file_path = file.name
|
| 98 |
model = process_cad_file(file)
|
| 99 |
+
|
| 100 |
+
stl_file = step_file_path.replace(".stp", ".stl")
|
| 101 |
exporters.export(model, stl_file)
|
| 102 |
|
| 103 |
apdl_script = f"""\n
|
| 104 |
/PREP7
|
| 105 |
! Importing Geometry
|
| 106 |
+
/import, '{step_file_path}', geom, STEP
|
| 107 |
! Material Properties
|
| 108 |
MP, EX, 1, {elastic_modulus}
|
| 109 |
MP, PRXY, 1, {poisson}
|
|
|
|
| 116 |
*GET, stress, NODE, 0, S, MAX
|
| 117 |
/EXIT, SAVE
|
| 118 |
"""
|
| 119 |
+
apdl_file_path = step_file_path.replace(".stp", ".inp")
|
| 120 |
with open(apdl_file_path, "w") as apdl_file:
|
| 121 |
apdl_file.write(apdl_script)
|
| 122 |
+
|
| 123 |
return apdl_script, apdl_file_path
|
| 124 |
except Exception as e:
|
| 125 |
+
return f"Error: {str(e)}", None
|
| 126 |
|
| 127 |
+
# Function to find a free port in a range
|
| 128 |
def find_free_port(start_port, end_port):
|
| 129 |
for port in range(start_port, end_port + 1):
|
| 130 |
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
|
|
|
| 132 |
return port
|
| 133 |
raise OSError(f"No available ports in range {start_port}-{end_port}")
|
| 134 |
|
| 135 |
+
# Gradio App
|
| 136 |
def main():
|
| 137 |
with gr.Blocks() as app:
|
| 138 |
gr.Markdown("# Press Tool Design and APDL Script Generator")
|
|
|
|
| 144 |
)
|
| 145 |
|
| 146 |
with gr.Row():
|
| 147 |
+
two_d_output = gr.Textbox(label="2D View/Error Message", interactive=False)
|
| 148 |
+
three_d_output = gr.Textbox(label="3D View/Error Message", interactive=False)
|
|
|
|
|
|
|
|
|
|
| 149 |
generate_views_btn = gr.Button("Generate 2D & 3D Views")
|
| 150 |
|
| 151 |
with gr.Row():
|
|
|
|
| 160 |
download_button = gr.File(label="Download Script")
|
| 161 |
generate_apdl_btn = gr.Button("Generate APDL Script")
|
| 162 |
|
| 163 |
+
# Events for Visualization
|
| 164 |
generate_views_btn.click(
|
| 165 |
fn=generate_views,
|
| 166 |
inputs=step_input,
|
| 167 |
outputs=[two_d_output, three_d_output]
|
| 168 |
)
|
| 169 |
|
| 170 |
+
# Events for APDL Script
|
| 171 |
+
def handle_download(apdl_script, apdl_file_path):
|
| 172 |
+
if apdl_file_path and os.path.exists(apdl_file_path):
|
| 173 |
+
return apdl_file_path
|
| 174 |
+
return None
|
| 175 |
+
|
| 176 |
generate_apdl_btn.click(
|
| 177 |
fn=generate_apdl_script,
|
| 178 |
inputs=[step_input, force_input, material_input],
|
|
|
|
| 183 |
if __name__ == "__main__":
|
| 184 |
app = main()
|
| 185 |
try:
|
| 186 |
+
# Dynamically find a free port in range 7860-7870
|
| 187 |
+
port = find_free_port(7860, 7870)
|
| 188 |
+
print(f"Launching on port: {port}")
|
| 189 |
app.launch(server_port=port, debug=True)
|
| 190 |
except Exception as e:
|
| 191 |
+
print(f"Failed to launch: {str(e)}")
|
|
|