andrefbfreitas commited on
Commit
51e073a
·
verified ·
1 Parent(s): c767aac

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -30
app.py CHANGED
@@ -8,7 +8,7 @@ import base64
8
  import time
9
  import hashlib
10
  import traceback
11
- import gc # NOVIDADE V29: O "Faxineiro" de RAM
12
 
13
  try:
14
  from fpdf import FPDF
@@ -27,7 +27,7 @@ from OCC.Core.StlAPI import StlAPI_Writer
27
  os.environ['PYVISTA_OFF_SCREEN'] = 'true'
28
  os.environ['VTK_GRAPHICS_BACKEND'] = 'OSMesa'
29
 
30
- st.set_page_config(page_title="CastingSim V29", layout="wide")
31
 
32
  st.markdown("""
33
  <style>
@@ -69,6 +69,7 @@ if 'espessura_tinta' not in st.session_state: st.session_state.espessura_tinta =
69
  if 'vel_vaz' not in st.session_state: st.session_state.vel_vaz = 1.0
70
 
71
  if 'b64_termico' not in st.session_state: st.session_state.b64_termico = ""
 
72
  if 'gif_path' not in st.session_state: st.session_state.gif_path = ""
73
  if 't_sol_minutos' not in st.session_state: st.session_state.t_sol_minutos = 0
74
  if 't_sol_segundos' not in st.session_state: st.session_state.t_sol_segundos = 0
@@ -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 V29", 0, 1, 'C')
85
  pdf.ln(5)
86
 
87
  pdf.set_font("Arial", 'B', 12)
@@ -205,7 +206,7 @@ if st.session_state.step in [1, 2, 3, 4, 4.5, 5]:
205
  st.caption("**ETAPA EXTRA: RENDERIZAÇÃO DE VÍDEO**")
206
 
207
  if st.session_state.step not in [3.5, 4.5]:
208
- st.title("🛡️ CastingSim V29: Renderização High-Res Otimizada")
209
  st.markdown("---")
210
 
211
  # ==========================================
@@ -334,7 +335,7 @@ elif st.session_state.step == 3:
334
  st.rerun()
335
 
336
  # ==========================================
337
- # ETAPA 3.5: NÚCLEO MATEMÁTICO (SEM O VÍDEO)
338
  # ==========================================
339
  elif st.session_state.step == 3.5:
340
  st.title("⏳ Processando Solver FEM...")
@@ -400,7 +401,20 @@ elif st.session_state.step == 3.5:
400
  plotter.export_gltf(tmp.name)
401
  with open(tmp.name, "rb") as f: st.session_state.b64_termico = base64.b64encode(f.read()).decode()
402
 
403
- progress_bar.progress(85, text="[85%] Consultando Mestre Fundidor IA...")
 
 
 
 
 
 
 
 
 
 
 
 
 
404
 
405
  vol_mm3 = st.session_state.vol_mm3
406
  area_mm2 = mesh_leve.area
@@ -432,7 +446,6 @@ elif st.session_state.step == 3.5:
432
 
433
  except MemoryError:
434
  st.error("💥 COLAPSO DE INFRAESTRUTURA: OUT OF MEMORY (OOM)")
435
- st.warning("O motor da nuvem desarmou o disjuntor.")
436
  if st.button("⬅️ Voltar e Reduzir Parâmetros"):
437
  st.session_state.step = 3
438
  st.rerun()
@@ -444,7 +457,7 @@ elif st.session_state.step == 3.5:
444
  st.rerun()
445
 
446
  # ==========================================
447
- # ETAPA 4: LAUDO (COM BOTÃO DE VÍDEO OPCIONAL)
448
  # ==========================================
449
  elif st.session_state.step == 4:
450
  st.header("4. Simulação: Laudo da Qualidade")
@@ -457,31 +470,37 @@ elif st.session_state.step == 4:
457
  texto_tempo = f"{st.session_state.t_sol_segundos} s"
458
  st.error(f"⏱️ **TEMPO CRÍTICO DE SOLIDIFICAÇÃO: {texto_tempo}**")
459
  with col_video:
460
- if st.button("🎬 Gerar Animação Cinemática", help="Requer processamento extra", use_container_width=True):
461
  st.session_state.step = 4.5
462
  st.rerun()
463
 
464
- col_v1, col_v2 = st.columns(2)
 
465
  p_m = [st.session_state.off_x/1000.0, st.session_state.off_y/1000.0, st.session_state.off_z/1000.0]
466
 
467
  with col_v1:
468
- st.write("🔥 **Mapa Térmico de Solidificação**")
469
  html_termico = f"""<script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/3.4.0/model-viewer.min.js"></script>
470
- <model-viewer src="data:model/gltf-binary;base64,{st.session_state.b64_termico}" style="width: 100%; height: 450px; background-color: #1e1e1e;" camera-controls shadow-intensity="1">
471
  <button slot="hotspot-1" data-position="{p_m[0]} {p_m[1]} {p_m[2]}" style="background-color: red; width: 12px; height: 12px; border-radius: 50%; border: 2px solid white;"></button>
472
  </model-viewer>"""
473
- components.html(html_termico, height=500)
474
 
475
  with col_v2:
476
- st.subheader("🤖 Diagnóstico Especialista IA")
 
 
 
 
 
 
477
  st.markdown(st.session_state.relatorio_ia)
478
  st.write("")
479
- st.write("")
480
  if HAS_FPDF and st.session_state.relatorio_pdf:
481
  st.download_button(
482
- label="📄 Baixar Laudo Técnico (.PDF)",
483
  data=st.session_state.relatorio_pdf,
484
- file_name="Laudo_CastingSim_V29.pdf",
485
  mime="application/pdf",
486
  type="primary",
487
  use_container_width=True
@@ -493,19 +512,18 @@ elif st.session_state.step == 4:
493
  st.rerun()
494
 
495
  # ==========================================
496
- # ETAPA 4.5: RENDER FARM (VÍDEO HIGH-RES OTIMIZADO)
497
  # ==========================================
498
  elif st.session_state.step == 4.5:
499
  st.title("🎬 Render Farm: Física e Cinemática")
500
- st.info("A V29 resgata a malha pesada (High-Res) e injeta um faxineiro de memória RAM para não estourar o servidor.")
501
  prog_video = st.progress(0, text="Iniciando motor gráfico...")
502
 
503
  try:
504
  temp_dir = tempfile.mkdtemp()
505
  gif_path = os.path.join(temp_dir, "preenchimento_pesado.gif")
506
 
507
- prog_video.progress(20, text="[20%] Carregando Malha Base (Alta Resolução) da Memória...")
508
- # V29: De volta à malha pesada e rica em detalhes
509
  mesh_video = pv.read(st.session_state.path_stl)
510
  mesh_video.rotate_x(st.session_state.rot_x, inplace=True)
511
  mesh_video.rotate_y(st.session_state.rot_y, inplace=True)
@@ -515,29 +533,35 @@ elif st.session_state.step == 4.5:
515
  dist_video = np.linalg.norm(mesh_video.points - p_riser, axis=1)
516
  max_fluxo_vid = np.max(dist_video)
517
 
518
- prog_video.progress(40, text="[40%] Processando Limiares Fluidodinâmicos (Resolução 450x450px)...")
519
- # O TRUQUE DE MESTRE DA RESOLUÇÃO ESTÁ AQUI:
520
  plotter_gif = pv.Plotter(off_screen=True, window_size=[450, 450])
521
  plotter_gif.open_gif(gif_path, fps=8)
522
 
523
  mesh_video['Dist_Massalote'] = dist_video
524
- # Mantendo o wireframe fantasma para você ver a interação metal/molde
525
- plotter_gif.add_mesh(mesh_video, color='white', opacity=0.15, style='wireframe')
526
- plotter_gif.camera_position = 'iso'
527
 
528
  passos = 15
529
  for i in range(1, passos + 1):
530
  limite = (max_fluxo_vid / passos) * i
 
 
531
  frame_mesh = mesh_video.threshold([0, limite], scalars='Dist_Massalote')
532
 
 
 
 
 
533
  if frame_mesh.n_points > 0:
534
- # O parâmetro name='metal' substitui a malha antiga na tela, evitando acúmulo visual
535
- plotter_gif.add_mesh(frame_mesh, color='#ff4500', metallic=True, smooth_shading=True, name='metal')
536
 
 
537
  plotter_gif.write_frame()
538
- prog_video.progress(40 + int((i/passos)*50), text=f"Renderizando Frame {i}/{passos} (Acionando Faxina de RAM)...")
539
 
540
- # FAXINA DE MEMÓRIA BRUTA:
 
 
 
 
541
  try:
542
  del frame_mesh
543
  except:
 
8
  import time
9
  import hashlib
10
  import traceback
11
+ import gc
12
 
13
  try:
14
  from fpdf import FPDF
 
27
  os.environ['PYVISTA_OFF_SCREEN'] = 'true'
28
  os.environ['VTK_GRAPHICS_BACKEND'] = 'OSMesa'
29
 
30
+ st.set_page_config(page_title="CastingSim V30", layout="wide")
31
 
32
  st.markdown("""
33
  <style>
 
69
  if 'vel_vaz' not in st.session_state: st.session_state.vel_vaz = 1.0
70
 
71
  if 'b64_termico' not in st.session_state: st.session_state.b64_termico = ""
72
+ if 'b64_rechupe_x10' not in st.session_state: st.session_state.b64_rechupe_x10 = "" # NOVO
73
  if 'gif_path' not in st.session_state: st.session_state.gif_path = ""
74
  if 't_sol_minutos' not in st.session_state: st.session_state.t_sol_minutos = 0
75
  if 't_sol_segundos' not in st.session_state: st.session_state.t_sol_segundos = 0
 
82
  pdf = FPDF()
83
  pdf.add_page()
84
  pdf.set_font("Arial", 'B', 16)
85
+ pdf.cell(0, 10, "LAUDO DE ENGENHARIA - CASTINGSIM V30", 0, 1, 'C')
86
  pdf.ln(5)
87
 
88
  pdf.set_font("Arial", 'B', 12)
 
206
  st.caption("**ETAPA EXTRA: RENDERIZAÇÃO DE VÍDEO**")
207
 
208
  if st.session_state.step not in [3.5, 4.5]:
209
+ st.title("🛡️ CastingSim V30: Prevenção de Deadlock C++")
210
  st.markdown("---")
211
 
212
  # ==========================================
 
335
  st.rerun()
336
 
337
  # ==========================================
338
+ # ETAPA 3.5: NÚCLEO MATEMÁTICO (E RECHUPE WARP x10)
339
  # ==========================================
340
  elif st.session_state.step == 3.5:
341
  st.title("⏳ Processando Solver FEM...")
 
401
  plotter.export_gltf(tmp.name)
402
  with open(tmp.name, "rb") as f: st.session_state.b64_termico = base64.b64encode(f.read()).decode()
403
 
404
+ # A MÁGICA VISIONÁRIA: DEFORMAÇÃO FÍSICA x10
405
+ progress_bar.progress(80, text="[80%] Magnificando Rechupe x10 (Deformação Vetorial)...")
406
+ mesh_rechupe_export = mesh_render.copy()
407
+ mesh_rechupe_export.compute_normals(inplace=True)
408
+ # O fator -10 repuxa a malha para dentro fisicamente baseando-se na gravidade do risco
409
+ mesh_deformada = mesh_rechupe_export.warp_by_scalar(scalars='Risco', factor=-10.0)
410
+ mesh_deformada.points /= 1000.0
411
+ with tempfile.NamedTemporaryFile(suffix=".glb", delete=False) as tmp:
412
+ plotter_rec = pv.Plotter(off_screen=True)
413
+ plotter_rec.add_mesh(mesh_deformada, scalars='Risco', cmap="hot", smooth_shading=True)
414
+ plotter_rec.export_gltf(tmp.name)
415
+ with open(tmp.name, "rb") as f: st.session_state.b64_rechupe_x10 = base64.b64encode(f.read()).decode()
416
+
417
+ progress_bar.progress(90, text="[90%] Consultando Mestre Fundidor IA...")
418
 
419
  vol_mm3 = st.session_state.vol_mm3
420
  area_mm2 = mesh_leve.area
 
446
 
447
  except MemoryError:
448
  st.error("💥 COLAPSO DE INFRAESTRUTURA: OUT OF MEMORY (OOM)")
 
449
  if st.button("⬅️ Voltar e Reduzir Parâmetros"):
450
  st.session_state.step = 3
451
  st.rerun()
 
457
  st.rerun()
458
 
459
  # ==========================================
460
+ # ETAPA 4: LAUDO (MAPA, RECHUPE E VÍDEO OPCIONAL)
461
  # ==========================================
462
  elif st.session_state.step == 4:
463
  st.header("4. Simulação: Laudo da Qualidade")
 
470
  texto_tempo = f"{st.session_state.t_sol_segundos} s"
471
  st.error(f"⏱️ **TEMPO CRÍTICO DE SOLIDIFICAÇÃO: {texto_tempo}**")
472
  with col_video:
473
+ if st.button("🎬 Gerar Animação Cinemática", help="Processamento High-Res com FAXINA DE RAM", use_container_width=True):
474
  st.session_state.step = 4.5
475
  st.rerun()
476
 
477
+ # 3 Colunas: Heatmap, Rechupe Warp, IA
478
+ col_v1, col_v2, col_v3 = st.columns(3)
479
  p_m = [st.session_state.off_x/1000.0, st.session_state.off_y/1000.0, st.session_state.off_z/1000.0]
480
 
481
  with col_v1:
482
+ st.write("🔥 **Mapa Térmico Base**")
483
  html_termico = f"""<script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/3.4.0/model-viewer.min.js"></script>
484
+ <model-viewer src="data:model/gltf-binary;base64,{st.session_state.b64_termico}" style="width: 100%; height: 350px; background-color: #1e1e1e;" camera-controls shadow-intensity="1">
485
  <button slot="hotspot-1" data-position="{p_m[0]} {p_m[1]} {p_m[2]}" style="background-color: red; width: 12px; height: 12px; border-radius: 50%; border: 2px solid white;"></button>
486
  </model-viewer>"""
487
+ components.html(html_termico, height=400)
488
 
489
  with col_v2:
490
+ st.write("⚠️ **Rechupe (Deformação x10)**")
491
+ html_rechupe = f"""<script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/3.4.0/model-viewer.min.js"></script>
492
+ <model-viewer src="data:model/gltf-binary;base64,{st.session_state.b64_rechupe_x10}" style="width: 100%; height: 350px; background-color: #1e1e1e;" camera-controls shadow-intensity="1"></model-viewer>"""
493
+ components.html(html_rechupe, height=400)
494
+
495
+ with col_v3:
496
+ st.subheader("🤖 Diagnóstico IA")
497
  st.markdown(st.session_state.relatorio_ia)
498
  st.write("")
 
499
  if HAS_FPDF and st.session_state.relatorio_pdf:
500
  st.download_button(
501
+ label="📄 Baixar Laudo (.PDF)",
502
  data=st.session_state.relatorio_pdf,
503
+ file_name="Laudo_CastingSim_V30.pdf",
504
  mime="application/pdf",
505
  type="primary",
506
  use_container_width=True
 
512
  st.rerun()
513
 
514
  # ==========================================
515
+ # ETAPA 4.5: RENDER FARM (VTK ANTI-DEADLOCK)
516
  # ==========================================
517
  elif st.session_state.step == 4.5:
518
  st.title("🎬 Render Farm: Física e Cinemática")
519
+ st.info("Renderizando em malha pesada com prevenção de deadlock (limpando a bancada a cada frame).")
520
  prog_video = st.progress(0, text="Iniciando motor gráfico...")
521
 
522
  try:
523
  temp_dir = tempfile.mkdtemp()
524
  gif_path = os.path.join(temp_dir, "preenchimento_pesado.gif")
525
 
526
+ prog_video.progress(10, text="[10%] Carregando Malha Base (Alta Resolução) da Memória...")
 
527
  mesh_video = pv.read(st.session_state.path_stl)
528
  mesh_video.rotate_x(st.session_state.rot_x, inplace=True)
529
  mesh_video.rotate_y(st.session_state.rot_y, inplace=True)
 
533
  dist_video = np.linalg.norm(mesh_video.points - p_riser, axis=1)
534
  max_fluxo_vid = np.max(dist_video)
535
 
536
+ prog_video.progress(20, text="[20%] Processando Limiares Fluidodinâmicos (Resolução 450x450px)...")
537
+
538
  plotter_gif = pv.Plotter(off_screen=True, window_size=[450, 450])
539
  plotter_gif.open_gif(gif_path, fps=8)
540
 
541
  mesh_video['Dist_Massalote'] = dist_video
 
 
 
542
 
543
  passos = 15
544
  for i in range(1, passos + 1):
545
  limite = (max_fluxo_vid / passos) * i
546
+ if limite <= 0: limite = 1e-6 # Trava de segurança matemática
547
+
548
  frame_mesh = mesh_video.threshold([0, limite], scalars='Dist_Massalote')
549
 
550
+ # FAXINA DE BANCADA (A SOLUÇÃO DO DEADLOCK)
551
+ plotter_gif.clear()
552
+ plotter_gif.add_mesh(mesh_video, color='white', opacity=0.15, style='wireframe')
553
+
554
  if frame_mesh.n_points > 0:
555
+ plotter_gif.add_mesh(frame_mesh, color='#ff4500', metallic=True, smooth_shading=True)
 
556
 
557
+ plotter_gif.camera_position = 'iso'
558
  plotter_gif.write_frame()
 
559
 
560
+ # Força o Streamlit a atualizar a barra de progresso antes do VTK travar a thread
561
+ time.sleep(0.05)
562
+ prog_video.progress(20 + int((i/passos)*70), text=f"Renderizando Frame {i}/{passos} (Desobstruindo VTK)...")
563
+
564
+ # Destruindo a malha da RAM
565
  try:
566
  del frame_mesh
567
  except: