jithenderchoudary commited on
Commit
86952a6
·
verified ·
1 Parent(s): 7af1d73

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +215 -145
app.py CHANGED
@@ -1,151 +1,221 @@
1
- import gradio as gr
2
  import numpy as np
3
- import pandas as pd
4
- from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier
5
- from joblib import dump, load
6
  import matplotlib.pyplot as plt
 
 
 
 
7
  import os
8
- python -c import ansys.mapdl.core
9
-
10
-
11
- # ========== Train AI Models ==========
12
- def train_models():
13
- # Synthetic training data
14
- data = {
15
- "Thickness": [10, 15, 20, 25],
16
- "Hole_Diameter": [5, 10, 15, 20],
17
- "Force": [5000, 7000, 10000, 12000],
18
- "Max_Stress": [300, 250, 200, 150],
19
- "Max_Deformation": [0.5, 0.4, 0.3, 0.2],
20
- "Pass_Fail": [1, 1, 0, 0], # 1: Pass, 0: Fail
21
- }
22
- df = pd.DataFrame(data)
23
- X = df[["Thickness", "Hole_Diameter", "Force"]]
24
-
25
- # Train regression models
26
- stress_model = RandomForestRegressor().fit(X, df["Max_Stress"])
27
- deformation_model = RandomForestRegressor().fit(X, df["Max_Deformation"])
28
-
29
- # Train classification model
30
- pass_fail_model = RandomForestClassifier().fit(X, df["Pass_Fail"])
31
-
32
- # Save models
33
- dump(stress_model, "stress_model.pkl")
34
- dump(deformation_model, "deformation_model.pkl")
35
- dump(pass_fail_model, "pass_fail_model.pkl")
36
-
37
- # Train the models
38
- train_models()
39
-
40
- # Load models
41
- stress_model = load("stress_model.pkl")
42
- deformation_model = load("deformation_model.pkl")
43
- pass_fail_model = load("pass_fail_model.pkl")
44
-
45
- # ========== ANSYS Simulation ==========
46
- def run_ansys_simulation(thickness, hole_diameter, force):
47
- mapdl = launch_mapdl()
48
- mapdl.clear()
49
- mapdl.prep7()
50
-
51
- # Material properties
52
- mapdl.mp("EX", 1, 2e11)
53
- mapdl.mp("PRXY", 1, 0.3)
54
-
55
- # Geometry
56
- mapdl.block(0, 100, 0, 50, 0, thickness)
57
- mapdl.cylind(0, hole_diameter / 2, 50, 25, 0, thickness)
58
- mapdl.vsubtract("ALL")
59
-
60
- # Meshing
61
- mapdl.et(1, "SOLID185")
62
- mapdl.esize(5)
63
- mapdl.vmesh("ALL")
64
-
65
- # Boundary conditions and force
66
- mapdl.nsel("S", "LOC", "X", 0)
67
- mapdl.d("ALL", "ALL")
68
- mapdl.nsel("S", "LOC", "X", 100)
69
- mapdl.f("ALL", "FY", -force)
70
-
71
- # Solve
72
- mapdl.run("/SOLU")
73
- mapdl.antype("STATIC")
74
- mapdl.solve()
75
- mapdl.finish()
76
-
77
- # Post-process
78
- mapdl.post1()
79
- max_stress = mapdl.get_value("NODE", 0, "S", "EQV")
80
- max_deformation = mapdl.get_value("NODE", 0, "U", "SUM")
81
- mapdl.exit()
82
-
83
- return max_stress, max_deformation
84
-
85
- # ========== AI and Simulation Workflow ==========
86
- def ai_and_simulation_workflow(thickness, hole_diameter, force):
87
- # AI pre-screening
88
- pre_screen = pass_fail_model.predict([[thickness, hole_diameter, force]])[0]
89
- if pre_screen == 0:
90
- return {
91
- "status": "Fail",
92
- "message": "AI predicts failure. Please adjust parameters.",
93
- "stress": None,
94
- "deformation": None,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
 
97
- # Run ANSYS simulation
98
- max_stress, max_deformation = run_ansys_simulation(thickness, hole_diameter, force)
99
-
100
- # Validate results with AI
101
- validation = "Pass" if max_stress < 250 and max_deformation < 0.3 else "Fail"
102
-
103
- # Generate output
104
- return {
105
- "status": validation,
106
- "message": f"Design {validation}.",
107
- "stress": max_stress,
108
- "deformation": max_deformation,
109
- }
110
-
111
- # ========== UI ==========
112
- def visualize_results(results):
113
- fig, ax = plt.subplots()
114
- labels = ["Stress", "Deformation"]
115
- values = [results["stress"], results["deformation"]]
116
- ax.bar(labels, values, color=["#FFA07A", "#20B2AA"])
117
- ax.set_title("Simulation Results")
118
- plt.tight_layout()
119
- image_path = "results.png"
120
- plt.savefig(image_path)
121
- plt.close(fig)
122
- return image_path
123
-
124
- def run_ui(thickness, hole_diameter, force):
125
- results = ai_and_simulation_workflow(thickness, hole_diameter, force)
126
- if results["status"] == "Fail":
127
- return results["message"], None
128
  else:
129
- image_path = visualize_results(results)
130
- return results["message"], image_path
131
-
132
- # Gradio Interface
133
- interface = gr.Interface(
134
- fn=run_ui,
135
- inputs=[
136
- gr.Slider(10, 50, step=1, label="Thickness (mm)"),
137
- gr.Slider(5, 25, step=1, label="Hole Diameter (mm)"),
138
- gr.Slider(1000, 15000, step=500, label="Force (N)"),
139
- ],
140
- outputs=[
141
- gr.Textbox(label="Simulation Status"),
142
- gr.Image(label="Simulation Visualization"),
143
- ],
144
- title="AI-Driven ANSYS Design Validation",
145
- description="Interactive tool for design validation using AI and ANSYS.",
146
- theme="default",
147
- live=True,
148
- )
149
-
150
- # Launch the interface
151
- interface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cadquery as cq
2
  import numpy as np
 
 
 
3
  import matplotlib.pyplot as plt
4
+ import pyvista as pv
5
+ from reportlab.lib.pagesizes import letter
6
+ from reportlab.pdfgen import canvas
7
+ import gradio as gr
8
  import os
9
+ from ansys.mapdl.core import launch_mapdl # For ANSYS integration
10
+
11
+
12
+ # Function for Progressive Die Design
13
+ def generate_die(length, width, thickness):
14
+ try:
15
+ plate = cq.Workplane("XY").box(length, width, thickness)
16
+ punch = cq.Workplane("XY").rect(10, 10).extrude(5).translate((length / 4, width / 4, thickness / 2))
17
+ die = plate.cut(punch)
18
+ filename = "progressive_die.step"
19
+ cq.exporters.export(die, filename)
20
+ return filename
21
+ except Exception as e:
22
+ return f"Error generating die: {str(e)}"
23
+
24
+
25
+ # Function to visualize die in 3D
26
+ def visualize_die(length, width, thickness):
27
+ try:
28
+ plate = cq.Workplane("XY").box(length, width, thickness)
29
+ punch = cq.Workplane("XY").rect(10, 10).extrude(5).translate((length / 4, width / 4, thickness / 2))
30
+ die = plate.cut(punch)
31
+
32
+ # Export to STL for visualization
33
+ cq.exporters.exportShape(die.val(), "STL", "progressive_die.stl")
34
+
35
+ # Visualize with PyVista
36
+ mesh = pv.read("progressive_die.stl")
37
+ plotter = pv.Plotter(off_screen=True)
38
+ plotter.add_mesh(mesh, color="blue")
39
+ screenshot = "progressive_die_visualization.png"
40
+ plotter.screenshot(screenshot)
41
+ return screenshot
42
+ except Exception as e:
43
+ return f"Error visualizing die: {str(e)}"
44
+
45
+
46
+ # Function for Python-based Stress Analysis
47
+ def stress_analysis(force, die_width, die_height, material_strength):
48
+ try:
49
+ stress = force / (die_width * die_height)
50
+ safety_factor = material_strength / stress
51
+
52
+ fig, ax = plt.subplots()
53
+ ax.bar(["Stress", "Material Strength"], [stress, material_strength])
54
+ ax.set_ylabel("Stress (MPa)")
55
+ ax.set_title("Stress Analysis")
56
+ plt.close(fig)
57
+
58
+ return f"Safety Factor: {round(safety_factor, 2)}", fig
59
+ except Exception as e:
60
+ return f"Error in stress analysis: {str(e)}", None
61
+
62
+
63
+ # ANSYS Integration for Stress Analysis
64
+ def run_ansys_simulation(force, die_width, die_height, material_strength):
65
+ try:
66
+ # Launch ANSYS MAPDL instance
67
+ mapdl = launch_mapdl()
68
+ mapdl.prep7() # Enter pre-processing module
69
+
70
+ # Define geometry and material properties
71
+ mapdl.rectng(0, die_width, 0, die_height)
72
+ mapdl.mp('EX', 1, material_strength)
73
+ mapdl.et(1, 'PLANE183')
74
+
75
+ # Apply loads
76
+ mapdl.nsel('S', 'LOC', 'X', 0)
77
+ mapdl.d('ALL', 'UX', 0)
78
+ mapdl.f('ALL', 'FY', -force)
79
+
80
+ # Solve
81
+ mapdl.run('/SOLU')
82
+ mapdl.solve()
83
+ mapdl.finish()
84
+
85
+ # Post-processing
86
+ mapdl.post1()
87
+ stress = mapdl.get_value('NODE', 1, 'S', 'EQV') # Retrieve max equivalent stress
88
+ mapdl.exit()
89
+
90
+ return f"Max Stress: {stress:.2f} MPa"
91
+ except Exception as e:
92
+ return f"Error running ANSYS simulation: {str(e)}"
93
+
94
+
95
+ # SolidWorks Placeholder for Stress Analysis
96
+ def solidworks_stress_analysis(force, die_width, die_height, material_strength):
97
+ # Replace this function with SolidWorks API or external script
98
+ try:
99
+ output_file = "/path/to/solidworks/output.txt" # Replace with actual path
100
+ if os.path.exists(output_file):
101
+ with open(output_file, "r") as file:
102
+ result = file.read()
103
+ return result.strip()
104
+ else:
105
+ return "SolidWorks simulation output not found."
106
+ except Exception as e:
107
+ return f"Error running SolidWorks simulation: {str(e)}"
108
+
109
+
110
+ # Function to generate PDF report
111
+ def generate_pdf_report(data, filename="report.pdf"):
112
+ try:
113
+ c = canvas.Canvas(filename, pagesize=letter)
114
+ c.drawString(100, 750, "Simulation Report")
115
+ c.drawString(100, 730, f"Max Stress: {data.get('stress', 'N/A')} MPa")
116
+ c.drawString(100, 710, f"Safety Factor: {data.get('safety_factor', 'N/A')}")
117
+ c.save()
118
+ return filename
119
+ except Exception as e:
120
+ return f"Error generating report: {str(e)}"
121
+
122
+
123
+ # Tool Optimization Function
124
+ def optimize_tool(speed, feed_rate, depth_of_cut, material):
125
+ try:
126
+ # Example formula for tool optimization
127
+ tool_life = 1000 / (speed * feed_rate * depth_of_cut)
128
+ recommended_speed = 0.8 * speed
129
+ recommended_feed_rate = 0.9 * feed_rate
130
+
131
+ # Return optimization results in dictionary
132
+ results = {
133
+ "Estimated Tool Life (hrs)": round(tool_life, 2),
134
+ "Recommended Speed (m/min)": round(recommended_speed, 2),
135
+ "Recommended Feed Rate (mm/rev)": round(recommended_feed_rate, 2)
136
  }
137
+ return results
138
+ except Exception as e:
139
+ return {"Error": str(e)}
140
+
141
+
142
+ # Gradio interface functions
143
+ def stress_analysis_interface(force, die_width, die_height, material_strength, simulation_tool):
144
+ if simulation_tool == "Python":
145
+ # Python-based stress analysis
146
+ safety_factor, fig = stress_analysis(force, die_width, die_height, material_strength)
147
+ data = {"stress": force / (die_width * die_height), "safety_factor": safety_factor}
148
+ pdf_filename = generate_pdf_report(data)
149
+ return safety_factor, fig, pdf_filename
150
+
151
+ elif simulation_tool == "ANSYS":
152
+ # Run ANSYS-based simulation
153
+ result = run_ansys_simulation(force, die_width, die_height, material_strength)
154
+ return result, None, None
155
+
156
+ elif simulation_tool == "SolidWorks":
157
+ # Run SolidWorks-based simulation
158
+ result = solidworks_stress_analysis(force, die_width, die_height, material_strength)
159
+ return result, None, None
160
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
  else:
162
+ return "Invalid simulation tool selected", None, None
163
+
164
+
165
+ # Create Gradio App
166
+ with gr.Blocks() as app:
167
+ gr.Markdown("## Press Tool AI Suite")
168
+ gr.Markdown("Select a tool below to get started:")
169
+
170
+ with gr.Tabs():
171
+ with gr.Tab("Progressive Die Design"):
172
+ gr.Markdown("### Enter Dimensions for Progressive Die")
173
+ length = gr.Number(label="Length (mm)", value=100)
174
+ width = gr.Number(label="Width (mm)", value=50)
175
+ thickness = gr.Number(label="Thickness (mm)", value=10)
176
+ die_output = gr.Textbox(label="Die Output File")
177
+ visualization_output = gr.Image(label="3D Visualization")
178
+ die_button = gr.Button("Generate Die")
179
+ die_button.click(
180
+ lambda l, w, t: (generate_die(l, w, t), visualize_die(l, w, t)),
181
+ inputs=[length, width, thickness],
182
+ outputs=[die_output, visualization_output],
183
+ )
184
+
185
+ with gr.Tab("Stress Analysis"):
186
+ gr.Markdown("### Select Simulation Tool and Enter Parameters for Stress Analysis")
187
+ simulation_tool = gr.Dropdown(
188
+ choices=["Python", "ANSYS", "SolidWorks"],
189
+ label="Simulation Tool",
190
+ value="Python",
191
+ )
192
+ force = gr.Number(label="Force (N)", value=10000)
193
+ die_width = gr.Number(label="Width (m)", value=0.05)
194
+ die_height = gr.Number(label="Height (m)", value=0.01)
195
+ material_strength = gr.Number(label="Material Strength (MPa)", value=250)
196
+ safety_factor_output = gr.Textbox(label="Safety Factor or Simulation Result")
197
+ stress_chart = gr.Plot()
198
+ pdf_file = gr.File(label="Download Report (Python Only)")
199
+ stress_button = gr.Button("Analyze Stress")
200
+ stress_button.click(
201
+ stress_analysis_interface,
202
+ inputs=[force, die_width, die_height, material_strength, simulation_tool],
203
+ outputs=[safety_factor_output, stress_chart, pdf_file],
204
+ )
205
+
206
+ with gr.Tab("Tool Optimization"):
207
+ gr.Markdown("### Enter Machining Parameters for Tool Optimization")
208
+ speed = gr.Number(label="Cutting Speed (m/min)", value=100)
209
+ feed_rate = gr.Number(label="Feed Rate (mm/rev)", value=0.2)
210
+ depth_of_cut = gr.Number(label="Depth of Cut (mm)", value=1.0)
211
+ material = gr.Dropdown(choices=["Steel", "Aluminum", "Titanium"], label="Material", value="Steel")
212
+ optimization_results = gr.JSON(label="Optimization Results")
213
+ optimize_button = gr.Button("Optimize Tool")
214
+ optimize_button.click(
215
+ optimize_tool,
216
+ inputs=[speed, feed_rate, depth_of_cut, material],
217
+ outputs=optimization_results,
218
+ )
219
+
220
+ # Launch the app
221
+ app.launch()