jithenderchoudary commited on
Commit
cc27276
·
verified ·
1 Parent(s): 03d5edf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -57
app.py CHANGED
@@ -11,7 +11,7 @@ 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,71 +20,74 @@ def cleanup_temp_files():
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,17 +96,14 @@ 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,15 +116,14 @@ SOLVE
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,7 +131,7 @@ def find_free_port(start_port, end_port):
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,8 +143,8 @@ def main():
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,19 +159,14 @@ def main():
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,9 +177,8 @@ def main():
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)}")
 
 
11
 
12
  # Cleanup function to remove temporary files
13
  def cleanup_temp_files():
14
+ temp_files = glob.glob("/tmp/*.svg") + glob.glob("/tmp/*.obj") + glob.glob("/tmp/*.stl") + glob.glob("/tmp/*.inp")
15
  for temp_file in temp_files:
16
  try:
17
  os.remove(temp_file)
 
20
 
21
  atexit.register(cleanup_temp_files)
22
 
23
+ # Generate 2D View
24
  def generate_2d_view(file):
25
  try:
26
  model = process_cad_file(file)
27
+ svg_content = model.toSvg()
28
+
29
+ # Save SVG to a temporary file
30
+ svg_path = "/tmp/2d_view.svg"
31
+ with open(svg_path, "w") as svg_file:
32
+ svg_file.write(svg_content)
33
+ return svg_path
34
  except Exception as e:
35
  return f"Error generating 2D view: {str(e)}"
36
 
37
+ # Generate 3D View
38
  def generate_3d_view(file):
39
  try:
 
40
  model = cq.importers.importStep(file.name)
41
 
42
+ # Extract solids
43
+ solids = model.solids()
44
  if not solids:
45
  raise ValueError("No solids found in the CAD model.")
46
 
47
+ vertices = []
48
+ faces = []
49
  for solid in solids:
50
+ for face in solid.tessellate(tolerance=0.01): # Tolerance for tessellation
51
+ vertices.extend(face[0])
52
+ faces.extend([[face[1][i], face[1][i + 1], face[1][i + 2]] for i in range(0, len(face[1]), 3)])
 
 
 
 
 
 
 
53
 
54
+ # Generate trimesh mesh
55
+ mesh = trimesh.Trimesh(vertices=vertices, faces=faces)
56
 
57
+ # Save mesh as OBJ file
58
+ obj_path = "/tmp/3d_view.obj"
59
+ mesh.export(obj_path)
60
+ return obj_path
61
  except Exception as e:
62
  return f"Error generating 3D view: {str(e)}"
63
 
64
+ # Wrapper to generate both 2D and 3D views
 
 
65
  def generate_views(file):
66
  try:
67
+ two_d_view = generate_2d_view(file) # Generate 2D View
68
+ three_d_view = generate_3d_view(file) # Generate 3D View
69
+
70
+ # Check if 3D generation was successful
71
+ if "Error" in three_d_view:
72
+ return two_d_view, {"error": True, "message": three_d_view}
73
+ else:
74
+ return two_d_view, {"error": False, "message": "3D view generated successfully!"}
75
  except Exception as e:
76
+ return f"Error: {str(e)}", f"Error: {str(e)}"
77
 
78
+ # Process CAD file for 2D/3D generation
79
  def process_cad_file(file):
80
  file_extension = os.path.splitext(file.name)[-1].lower()
81
  if file_extension in [".stp", ".step"]:
82
+ return cq.importers.importStep(file.name)
83
  elif file_extension in [".iges", ".igs"]:
84
+ return cq.importers.importStep(file.name)
85
  elif file_extension == ".sldprt":
86
+ raise NotImplementedError("SLDPRT support is not implemented.")
87
  elif file_extension == ".dwg":
88
+ raise NotImplementedError("DWG support is not implemented.")
89
  else:
90
  raise ValueError(f"Unsupported file format: {file_extension}")
 
91
 
92
  # APDL script generation
93
  def generate_apdl_script(file, press_force, material_json):
 
96
  elastic_modulus = material.get("elastic_modulus", 2e11)
97
  poisson = material.get("poisson", 0.3)
98
 
 
 
99
  model = process_cad_file(file)
100
+ stl_file = "/tmp/model.stl"
 
101
  exporters.export(model, stl_file)
102
 
103
  apdl_script = f"""\n
104
  /PREP7
105
  ! Importing Geometry
106
+ /import, '{file.name}', 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 = "/tmp/apdl_script.inp"
120
  with open(apdl_file_path, "w") as apdl_file:
121
  apdl_file.write(apdl_script)
 
122
  return apdl_script, apdl_file_path
123
  except Exception as e:
124
+ return f"Error generating APDL script: {str(e)}", None
125
 
126
+ # Find free port for Gradio app
127
  def find_free_port(start_port, end_port):
128
  for port in range(start_port, end_port + 1):
129
  with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
 
131
  return port
132
  raise OSError(f"No available ports in range {start_port}-{end_port}")
133
 
134
+ # Main Gradio app
135
  def main():
136
  with gr.Blocks() as app:
137
  gr.Markdown("# Press Tool Design and APDL Script Generator")
 
143
  )
144
 
145
  with gr.Row():
146
+ two_d_output = gr.Image(label="2D View", type="file") # 2D as Image
147
+ three_d_output = gr.Label(label="3D View Status") # 3D as Label
148
  generate_views_btn = gr.Button("Generate 2D & 3D Views")
149
 
150
  with gr.Row():
 
159
  download_button = gr.File(label="Download Script")
160
  generate_apdl_btn = gr.Button("Generate APDL Script")
161
 
162
+ # Visualization Events
163
  generate_views_btn.click(
164
  fn=generate_views,
165
  inputs=step_input,
166
  outputs=[two_d_output, three_d_output]
167
  )
168
 
169
+ # APDL Script Events
 
 
 
 
 
170
  generate_apdl_btn.click(
171
  fn=generate_apdl_script,
172
  inputs=[step_input, force_input, material_input],
 
177
  if __name__ == "__main__":
178
  app = main()
179
  try:
180
+ port = find_free_port(7860, 7870) # Find available port
 
 
181
  app.launch(server_port=port, debug=True)
182
  except Exception as e:
183
  print(f"Failed to launch: {str(e)}")
184
+