andrefbfreitas commited on
Commit
bd36a99
·
verified ·
1 Parent(s): 3dc2c42

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -37
app.py CHANGED
@@ -25,7 +25,7 @@ from OCC.Core.StlAPI import StlAPI_Writer
25
  os.environ['PYVISTA_OFF_SCREEN'] = 'true'
26
  os.environ['VTK_GRAPHICS_BACKEND'] = 'OSMesa'
27
 
28
- st.set_page_config(page_title="CastingSim V23", layout="wide")
29
 
30
  st.markdown("""
31
  <style>
@@ -40,7 +40,8 @@ st.markdown("""
40
  if 'step' not in st.session_state: st.session_state.step = 1
41
  if 'cache_hash' not in st.session_state: st.session_state.cache_hash = ""
42
  if 'path_stl' not in st.session_state: st.session_state.path_stl = None
43
- if 'path_proxy_stl' not in st.session_state: st.session_state.path_proxy_stl = None # NOVO: Cache do Proxy Leve
 
44
  if 'vol_mm3' not in st.session_state: st.session_state.vol_mm3 = 0.0
45
  if 'coord_iniciada' not in st.session_state: st.session_state.coord_iniciada = False
46
 
@@ -81,7 +82,7 @@ def compilar_pdf():
81
  pdf = FPDF()
82
  pdf.add_page()
83
  pdf.set_font("Arial", 'B', 16)
84
- pdf.cell(0, 10, "LAUDO DE ENGENHARIA - CASTINGSIM V23", 0, 1, 'C')
85
  pdf.ln(5)
86
 
87
  pdf.set_font("Arial", 'B', 12)
@@ -147,29 +148,36 @@ def processar_malha_com_telemetria(file_bytes, lin_def, ang_def):
147
  path_stl = os.path.join(temp_dir, "malha_alta_resolucao.stl")
148
  StlAPI_Writer().Write(shape, path_stl)
149
 
150
- # NOVIDADE V23: Gera o Proxy Leve APENAS UMA VEZ aqui, e não na tela.
151
  prog_bar.progress(90, text="🛠️ 90% - Forjando Holograma Proxy (Baixa Resolução) para a UI...")
152
  mesh_alta = pv.read(path_stl)
153
  path_proxy = os.path.join(temp_dir, "malha_proxy_ui.stl")
154
 
155
  try:
156
  if mesh_alta.n_faces > 5000:
157
- # Calcula o fator exato para reduzir a peça para ~5000 triângulos
158
  fator = 1.0 - (5000.0 / mesh_alta.n_faces)
159
  fator = np.clip(fator, 0.10, 0.98)
160
  mesh_proxy = mesh_alta.decimate(fator)
161
  else:
162
  mesh_proxy = mesh_alta
163
  except:
164
- mesh_proxy = mesh_alta # Failsafe de engenharia caso a topologia esteja quebrada
165
 
166
  mesh_proxy.save(path_proxy)
167
 
 
 
 
 
 
 
 
 
 
168
  prog_bar.progress(100, text="✅ 100% - Setup Concluído!")
169
  time.sleep(0.3)
170
  prog_bar.empty()
171
 
172
- return path_stl, path_proxy, vol_mm3
173
 
174
  # --- MOTOR DE IA ---
175
  def gerar_diagnostico_ia(mod_cm, t_sol_total, t_vaz, t_molde, max_risco_rechupe, reynolds, velocidade):
@@ -218,7 +226,7 @@ if st.session_state.step in [1, 2, 3, 4]:
218
  st.caption(f"**ETAPA {st.session_state.step} DE 4**")
219
 
220
  if st.session_state.step != 3.5:
221
- st.title("🛡️ CastingSim V23: Performance com Proxy em Cache")
222
  st.markdown("---")
223
 
224
  # ==========================================
@@ -259,7 +267,7 @@ elif st.session_state.step == 2:
259
  if st.button("Avançar para Geometria ➡️", type="primary"): st.session_state.step = 3; st.rerun()
260
 
261
  # ==========================================
262
- # ETAPA 3: GAIOLA DE FARADAY + CACHE DE PROXY INSTANTÂNEO
263
  # ==========================================
264
  elif st.session_state.step == 3:
265
  st.header("3. Inspeção, Rotação Espacial e Massalote")
@@ -270,26 +278,22 @@ elif st.session_state.step == 3:
270
  current_hash = gerar_hash(file_bytes, st.session_state.lin_def, st.session_state.ang_def)
271
 
272
  if st.session_state.cache_hash != current_hash:
273
- # Recebe agora O DOIS caminhos: O pesado (Física) e o Leve (UI)
274
- path_stl, path_proxy_stl, vol_mm3 = processar_malha_com_telemetria(file_bytes, st.session_state.lin_def, st.session_state.ang_def)
275
  st.session_state.cache_hash = current_hash
276
  st.session_state.path_stl = path_stl
277
  st.session_state.path_proxy_stl = path_proxy_stl
 
278
  st.session_state.vol_mm3 = vol_mm3
279
  st.session_state.coord_iniciada = False
280
 
281
- # A MÁGICA DA V23: O PyVista agora carrega a malha que JÁ FOI decimada lá no passo do upload. Carregamento quase instantâneo.
282
- mesh_preview = pv.read(st.session_state.path_proxy_stl)
283
- mesh_preview.rotate_x(st.session_state.rot_x, inplace=True)
284
- mesh_preview.rotate_y(st.session_state.rot_y, inplace=True)
285
- mesh_preview.rotate_z(st.session_state.rot_z, inplace=True)
286
-
287
- vol_mm3 = st.session_state.vol_mm3
288
- massa_kg = (vol_mm3 * 2.7) / 1e6
289
 
 
290
  if not st.session_state.coord_iniciada:
291
- c = mesh_preview.center
292
- b = mesh_preview.bounds
 
293
  st.session_state.off_x = float(c[0])
294
  st.session_state.off_y = float(c[1])
295
  st.session_state.off_z = float(b[5])
@@ -329,22 +333,15 @@ elif st.session_state.step == 3:
329
  """, height=0)
330
 
331
  with col_view:
332
- st.caption("Visão Proxy em Cache Constante (Mínima Latência)")
333
- temp_mesh = mesh_preview.copy()
334
- # O BLOCO TRY/EXCEPT DEMORADO DA V22 FOI EXTIRPADO DAQUI!
335
-
336
- temp_mesh.points /= 1000.0
337
- with tempfile.NamedTemporaryFile(suffix=".glb", delete=False) as tmp:
338
- plotter = pv.Plotter(off_screen=True)
339
- plotter.add_mesh(temp_mesh, color="#cccccc", lighting=False)
340
- plotter.export_gltf(tmp.name)
341
- with open(tmp.name, "rb") as f:
342
- b64 = base64.b64encode(f.read()).decode()
343
-
344
  p_m = [st.session_state.off_x/1000.0, st.session_state.off_y/1000.0, st.session_state.off_z/1000.0]
 
 
345
  html = f"""
346
  <script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/3.4.0/model-viewer.min.js"></script>
347
- <model-viewer src="data:model/gltf-binary;base64,{b64}" style="width: 100%; height: 480px; background-color: #f4f6f9;" camera-controls>
 
 
348
  <button slot="hotspot-1" data-position="{p_m[0]} {p_m[1]} {p_m[2]}" style="background-color: red; width: 16px; height: 16px; border-radius: 50%; border: 2px solid white;"></button>
349
  </model-viewer>
350
  """
@@ -365,9 +362,9 @@ elif st.session_state.step == 3:
365
  # ==========================================
366
  elif st.session_state.step == 3.5:
367
  st.title("⏳ Processando Solver FEM...")
368
- progress_bar = st.progress(10, text="Rotacionando Tensores (Malha Leve)...")
369
 
370
- # O Solver volta a buscar a Malha Pesada (path_stl) original e ignorar a Proxy
371
  mesh_leve = pv.read(st.session_state.path_stl)
372
  mesh_leve.rotate_x(st.session_state.rot_x, inplace=True)
373
  mesh_leve.rotate_y(st.session_state.rot_y, inplace=True)
@@ -533,7 +530,7 @@ elif st.session_state.step == 4:
533
  st.download_button(
534
  label="📄 Baixar Laudo Técnico (.PDF)",
535
  data=st.session_state.relatorio_pdf,
536
- file_name="Laudo_CastingSim_V23.pdf",
537
  mime="application/pdf",
538
  type="primary"
539
  )
 
25
  os.environ['PYVISTA_OFF_SCREEN'] = 'true'
26
  os.environ['VTK_GRAPHICS_BACKEND'] = 'OSMesa'
27
 
28
+ st.set_page_config(page_title="CastingSim V24", layout="wide")
29
 
30
  st.markdown("""
31
  <style>
 
40
  if 'step' not in st.session_state: st.session_state.step = 1
41
  if 'cache_hash' not in st.session_state: st.session_state.cache_hash = ""
42
  if 'path_stl' not in st.session_state: st.session_state.path_stl = None
43
+ if 'path_proxy_stl' not in st.session_state: st.session_state.path_proxy_stl = None
44
+ if 'b64_proxy' not in st.session_state: st.session_state.b64_proxy = "" # NOVO: Cache estático do modelo 3D
45
  if 'vol_mm3' not in st.session_state: st.session_state.vol_mm3 = 0.0
46
  if 'coord_iniciada' not in st.session_state: st.session_state.coord_iniciada = False
47
 
 
82
  pdf = FPDF()
83
  pdf.add_page()
84
  pdf.set_font("Arial", 'B', 16)
85
+ pdf.cell(0, 10, "LAUDO DE ENGENHARIA - CASTINGSIM V24", 0, 1, 'C')
86
  pdf.ln(5)
87
 
88
  pdf.set_font("Arial", 'B', 12)
 
148
  path_stl = os.path.join(temp_dir, "malha_alta_resolucao.stl")
149
  StlAPI_Writer().Write(shape, path_stl)
150
 
 
151
  prog_bar.progress(90, text="🛠️ 90% - Forjando Holograma Proxy (Baixa Resolução) para a UI...")
152
  mesh_alta = pv.read(path_stl)
153
  path_proxy = os.path.join(temp_dir, "malha_proxy_ui.stl")
154
 
155
  try:
156
  if mesh_alta.n_faces > 5000:
 
157
  fator = 1.0 - (5000.0 / mesh_alta.n_faces)
158
  fator = np.clip(fator, 0.10, 0.98)
159
  mesh_proxy = mesh_alta.decimate(fator)
160
  else:
161
  mesh_proxy = mesh_alta
162
  except:
163
+ mesh_proxy = mesh_alta
164
 
165
  mesh_proxy.save(path_proxy)
166
 
167
+ # NOVIDADE V24: Já converte para GLB Base64 direto no upload.
168
+ mesh_proxy.points /= 1000.0
169
+ with tempfile.NamedTemporaryFile(suffix=".glb", delete=False) as tmp:
170
+ plotter = pv.Plotter(off_screen=True)
171
+ plotter.add_mesh(mesh_proxy, color="#cccccc", lighting=False)
172
+ plotter.export_gltf(tmp.name)
173
+ with open(tmp.name, "rb") as f:
174
+ b64_final = base64.b64encode(f.read()).decode()
175
+
176
  prog_bar.progress(100, text="✅ 100% - Setup Concluído!")
177
  time.sleep(0.3)
178
  prog_bar.empty()
179
 
180
+ return path_stl, path_proxy, vol_mm3, b64_final
181
 
182
  # --- MOTOR DE IA ---
183
  def gerar_diagnostico_ia(mod_cm, t_sol_total, t_vaz, t_molde, max_risco_rechupe, reynolds, velocidade):
 
226
  st.caption(f"**ETAPA {st.session_state.step} DE 4**")
227
 
228
  if st.session_state.step != 3.5:
229
+ st.title("🛡️ CastingSim V24: Engine WebGL Dinâmica")
230
  st.markdown("---")
231
 
232
  # ==========================================
 
267
  if st.button("Avançar para Geometria ➡️", type="primary"): st.session_state.step = 3; st.rerun()
268
 
269
  # ==========================================
270
+ # ETAPA 3: RENDERIZAÇÃO INSTANTÂNEA E DESACOPLADA
271
  # ==========================================
272
  elif st.session_state.step == 3:
273
  st.header("3. Inspeção, Rotação Espacial e Massalote")
 
278
  current_hash = gerar_hash(file_bytes, st.session_state.lin_def, st.session_state.ang_def)
279
 
280
  if st.session_state.cache_hash != current_hash:
281
+ # Extrai a malha pesada, a proxy e já o B64 final!
282
+ path_stl, path_proxy_stl, vol_mm3, b64_final = processar_malha_com_telemetria(file_bytes, st.session_state.lin_def, st.session_state.ang_def)
283
  st.session_state.cache_hash = current_hash
284
  st.session_state.path_stl = path_stl
285
  st.session_state.path_proxy_stl = path_proxy_stl
286
+ st.session_state.b64_proxy = b64_final
287
  st.session_state.vol_mm3 = vol_mm3
288
  st.session_state.coord_iniciada = False
289
 
290
+ massa_kg = (st.session_state.vol_mm3 * 2.7) / 1e6
 
 
 
 
 
 
 
291
 
292
+ # Inicia o centro se for a primeira vez, lendo APENAS a geometria pura sem processar visual
293
  if not st.session_state.coord_iniciada:
294
+ mesh_leitura = pv.read(st.session_state.path_proxy_stl)
295
+ c = mesh_leitura.center
296
+ b = mesh_leitura.bounds
297
  st.session_state.off_x = float(c[0])
298
  st.session_state.off_y = float(c[1])
299
  st.session_state.off_z = float(b[5])
 
333
  """, height=0)
334
 
335
  with col_view:
336
+ st.caption("Visão WebGL Direta (Processamento via GPU Local)")
 
 
 
 
 
 
 
 
 
 
 
337
  p_m = [st.session_state.off_x/1000.0, st.session_state.off_y/1000.0, st.session_state.off_z/1000.0]
338
+
339
+ # A MÁGICA DA V24: Sem PyVista aqui. Nós apenas passamos a string HTML com o orientation nativo.
340
  html = f"""
341
  <script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/3.4.0/model-viewer.min.js"></script>
342
+ <model-viewer src="data:model/gltf-binary;base64,{st.session_state.b64_proxy}"
343
+ orientation="{st.session_state.rot_x}deg {st.session_state.rot_y}deg {st.session_state.rot_z}deg"
344
+ style="width: 100%; height: 480px; background-color: #f4f6f9;" camera-controls>
345
  <button slot="hotspot-1" data-position="{p_m[0]} {p_m[1]} {p_m[2]}" style="background-color: red; width: 16px; height: 16px; border-radius: 50%; border: 2px solid white;"></button>
346
  </model-viewer>
347
  """
 
362
  # ==========================================
363
  elif st.session_state.step == 3.5:
364
  st.title("⏳ Processando Solver FEM...")
365
+ progress_bar = st.progress(10, text="Rotacionando Tensores Matemáticos (Malha Base)...")
366
 
367
+ # O Solver continua rotacionando a matemática com o PyVista normalmente
368
  mesh_leve = pv.read(st.session_state.path_stl)
369
  mesh_leve.rotate_x(st.session_state.rot_x, inplace=True)
370
  mesh_leve.rotate_y(st.session_state.rot_y, inplace=True)
 
530
  st.download_button(
531
  label="📄 Baixar Laudo Técnico (.PDF)",
532
  data=st.session_state.relatorio_pdf,
533
+ file_name="Laudo_CastingSim_V24.pdf",
534
  mime="application/pdf",
535
  type="primary"
536
  )