pressTools / app.py
karthikmn's picture
Update app.py
67b1eed verified
import cadquery as cq
import numpy as np
import matplotlib.pyplot as plt
import pyvista as pv
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
import gradio as gr
import os
from ansys.mapdl.core import launch_mapdl # For ANSYS integration
# Function for Progressive Die Design
def generate_die(length, width, thickness):
try:
plate = cq.Workplane("XY").box(length, width, thickness)
punch = cq.Workplane("XY").rect(10, 10).extrude(5).translate((length / 4, width / 4, thickness / 2))
die = plate.cut(punch)
filename = "progressive_die.step"
cq.exporters.export(die, filename)
return filename
except Exception as e:
return f"Error generating die: {str(e)}"
# Function to visualize die in 3D
def visualize_die(length, width, thickness):
try:
plate = cq.Workplane("XY").box(length, width, thickness)
punch = cq.Workplane("XY").rect(10, 10).extrude(5).translate((length / 4, width / 4, thickness / 2))
die = plate.cut(punch)
# Export to STL for visualization
cq.exporters.exportShape(die.val(), "STL", "progressive_die.stl")
# Visualize with PyVista
mesh = pv.read("progressive_die.stl")
plotter = pv.Plotter(off_screen=True)
plotter.add_mesh(mesh, color="blue")
screenshot = "progressive_die_visualization.png"
plotter.screenshot(screenshot)
return screenshot
except Exception as e:
return f"Error visualizing die: {str(e)}"
# Function for Python-based Stress Analysis
def stress_analysis(force, die_width, die_height, material_strength):
try:
stress = force / (die_width * die_height)
safety_factor = material_strength / stress
fig, ax = plt.subplots()
ax.bar(["Stress", "Material Strength"], [stress, material_strength])
ax.set_ylabel("Stress (MPa)")
ax.set_title("Stress Analysis")
plt.close(fig)
return f"Safety Factor: {round(safety_factor, 2)}", fig
except Exception as e:
return f"Error in stress analysis: {str(e)}", None
# ANSYS Integration for Stress Analysis
def run_ansys_simulation(force, die_width, die_height, material_strength):
try:
# Launch ANSYS MAPDL instance
mapdl = launch_mapdl()
mapdl.prep7() # Enter pre-processing module
# Define geometry and material properties
mapdl.rectng(0, die_width, 0, die_height)
mapdl.mp('EX', 1, material_strength)
mapdl.et(1, 'PLANE183')
# Apply loads
mapdl.nsel('S', 'LOC', 'X', 0)
mapdl.d('ALL', 'UX', 0)
mapdl.f('ALL', 'FY', -force)
# Solve
mapdl.run('/SOLU')
mapdl.solve()
mapdl.finish()
# Post-processing
mapdl.post1()
stress = mapdl.get_value('NODE', 1, 'S', 'EQV') # Retrieve max equivalent stress
mapdl.exit()
return f"Max Stress: {stress:.2f} MPa"
except Exception as e:
return f"Error running ANSYS simulation: {str(e)}"
# SolidWorks Placeholder for Stress Analysis
def solidworks_stress_analysis(force, die_width, die_height, material_strength):
# Replace this function with SolidWorks API or external script
try:
output_file = "/path/to/solidworks/output.txt" # Replace with actual path
if os.path.exists(output_file):
with open(output_file, "r") as file:
result = file.read()
return result.strip()
else:
return "SolidWorks simulation output not found."
except Exception as e:
return f"Error running SolidWorks simulation: {str(e)}"
# Function to generate PDF report
def generate_pdf_report(data, filename="report.pdf"):
try:
c = canvas.Canvas(filename, pagesize=letter)
c.drawString(100, 750, "Simulation Report")
c.drawString(100, 730, f"Max Stress: {data.get('stress', 'N/A')} MPa")
c.drawString(100, 710, f"Safety Factor: {data.get('safety_factor', 'N/A')}")
c.save()
return filename
except Exception as e:
return f"Error generating report: {str(e)}"
# Tool Optimization Function
def optimize_tool(speed, feed_rate, depth_of_cut, material):
try:
# Example formula for tool optimization
tool_life = 1000 / (speed * feed_rate * depth_of_cut)
recommended_speed = 0.8 * speed
recommended_feed_rate = 0.9 * feed_rate
# Return optimization results in dictionary
results = {
"Estimated Tool Life (hrs)": round(tool_life, 2),
"Recommended Speed (m/min)": round(recommended_speed, 2),
"Recommended Feed Rate (mm/rev)": round(recommended_feed_rate, 2)
}
return results
except Exception as e:
return {"Error": str(e)}
# Gradio interface functions
def stress_analysis_interface(force, die_width, die_height, material_strength, simulation_tool):
if simulation_tool == "Python":
# Python-based stress analysis
safety_factor, fig = stress_analysis(force, die_width, die_height, material_strength)
data = {"stress": force / (die_width * die_height), "safety_factor": safety_factor}
pdf_filename = generate_pdf_report(data)
return safety_factor, fig, pdf_filename
elif simulation_tool == "ANSYS":
# Run ANSYS-based simulation
result = run_ansys_simulation(force, die_width, die_height, material_strength)
return result, None, None
elif simulation_tool == "SolidWorks":
# Run SolidWorks-based simulation
result = solidworks_stress_analysis(force, die_width, die_height, material_strength)
return result, None, None
else:
return "Invalid simulation tool selected", None, None
# Create Gradio App
# with gr.Tab("Progressive Die Design"):
gr.Markdown("### Enter Dimensions for Progressive Die")
length = gr.Number(label="Length (mm)", value=100)
width = gr.Number(label="Width (mm)", value=50) # Fixed the parenthesis here
thickness = gr.Number(label="Thickness (mm)", value=10)
die_output = gr.Textbox(label="Die Output File")
visualization_output = gr.Image(label="3D Visualization")
die_button = gr.Button("Generate Die")
die_button.click(
lambda l, w, t: (generate_die(l, w, t), visualize_die(l, w, t)),
inputs=[length, width, thickness],
outputs=[die_output, visualization_output],
)