dieDesign3.0 / app.py
karthikmn's picture
Create app.py
3a47468 verified
import gradio as gr
import matplotlib.pyplot as plt
import numpy as np
import logging
# Configure logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger()
# Function to generate the die design visualization (with more shapes)
def generate_die_ANSYS(length, width, thickness, die_shape):
try:
# Log inputs
logger.info(f"Generating die design: Length={length}, Width={width}, Thickness={thickness}, Shape={die_shape}")
# Validate input dimensions
if length <= 0 or width <= 0 or thickness <= 0:
logger.error("Dimensions must be greater than zero.")
return "Error: Dimensions must be greater than zero.", None
# Simulate a realistic die design with multiple shapes
fig, ax = plt.subplots(figsize=(8, 8))
if die_shape == "Rectangle":
# Visualize a rectangular die
ax.add_patch(plt.Rectangle((0, 0), length, width, linewidth=2, edgecolor='blue', facecolor='cyan', label='Rectangle Die'))
ax.set_xlim(0, length + 20)
ax.set_ylim(0, width + 20)
ax.set_title(f"Progressive Die Design - Rectangle {length}x{width}")
logger.info(f"Created rectangular die with dimensions {length} x {width}.")
elif die_shape == "Circle":
# Visualize a circular die
circle = plt.Circle((length / 2, width / 2), radius=min(length, width) / 2, color='orange', ec='black', lw=2, label='Circular Die')
ax.add_patch(circle)
ax.set_xlim(0, length + 20)
ax.set_ylim(0, width + 20)
ax.set_title(f"Progressive Die Design - Circle {length}x{width}")
logger.info(f"Created circular die with diameter {length} and width {width}.")
elif die_shape == "Ellipse":
# Visualize an elliptical die
ellipse = plt.Ellipse((length / 2, width / 2), width, length, color='green', ec='black', lw=2, label='Elliptical Die')
ax.add_patch(ellipse)
ax.set_xlim(0, length + 20)
ax.set_ylim(0, width + 20)
ax.set_title(f"Progressive Die Design - Ellipse {length}x{width}")
logger.info(f"Created elliptical die with dimensions {length} x {width}.")
elif die_shape == "Hexagon":
# Visualize a hexagonal die
angle = np.linspace(0, 2 * np.pi, 7)
x = length / 2 * np.cos(angle) + length / 2
y = width / 2 * np.sin(angle) + width / 2
ax.fill(x, y, color='purple', edgecolor='black', lw=2, label='Hexagonal Die')
ax.set_xlim(0, length + 20)
ax.set_ylim(0, width + 20)
ax.set_title(f"Progressive Die Design - Hexagon {length}x{width}")
logger.info(f"Created hexagonal die with side length {length}.")
elif die_shape == "Polygon":
# Visualize a polygonal die (random polygon with 5 sides)
num_sides = 5
angle = np.linspace(0, 2 * np.pi, num_sides + 1)
radius = min(length, width) / 2
x = radius * np.cos(angle) + length / 2
y = radius * np.sin(angle) + width / 2
ax.fill(x, y, color='red', edgecolor='black', lw=2, label='Polygonal Die')
ax.set_xlim(0, length + 20)
ax.set_ylim(0, width + 20)
ax.set_title(f"Progressive Die Design - Polygon {length}x{width}")
logger.info(f"Created polygonal die with {num_sides} sides.")
ax.set_xlabel("X Dimension (mm)")
ax.set_ylabel("Y Dimension (mm)")
ax.legend(loc="upper right")
# Log the file saving step
filename = f"generated_die_{die_shape}_{length}x{width}.bmp"
plt.savefig(filename, format='bmp') # Save the plot as a BMP file
logger.info(f"Die design saved as {filename}.")
plt.close(fig) # Close the plot to prevent displaying twice
# Return success message and file path
return f"Die design saved successfully as {filename}. You can download the file.", filename
except Exception as e:
logger.error(f"Error generating die design: {str(e)}")
return f"Error generating die design: {str(e)}", None
# Gradio interface functions
def progressive_die_interface(length, width, thickness, die_shape):
# Generate die design and return file path and plot
die_message, filename = generate_die_ANSYS(length, width, thickness, die_shape)
# Log the completion of the task
logger.info(f"Die design process completed for shape {die_shape} with filename {filename}.")
return die_message, filename
# Create the Gradio Interface
with gr.Blocks() as app:
gr.Markdown("## Progressive Die Design Simulator")
gr.Markdown("This tool simulates the creation of progressive die designs. Select the die shape and enter dimensions to generate the die design.")
with gr.Row():
length = gr.Number(label="Length (mm)", value=100)
width = gr.Number(label="Width (mm)", value=50)
thickness = gr.Number(label="Thickness (mm)", value=10)
die_shape = gr.Dropdown(label="Die Shape", choices=["Rectangle", "Circle", "Ellipse", "Hexagon", "Polygon"], value="Rectangle")
die_button = gr.Button("Generate Die Design")
die_output = gr.Textbox(label="Die Design Message", interactive=False)
die_download = gr.File(label="Download Die Design Image")
die_button.click(progressive_die_interface, inputs=[length, width, thickness, die_shape], outputs=[die_output, die_download])
# Launch the app
app.launch()