andrefbfreitas commited on
Commit
1eee5db
·
verified ·
1 Parent(s): 96b1240

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +113 -68
app.py CHANGED
@@ -26,7 +26,7 @@ from OCC.Core.StlAPI import StlAPI_Writer
26
  os.environ['PYVISTA_OFF_SCREEN'] = 'true'
27
  os.environ['VTK_GRAPHICS_BACKEND'] = 'OSMesa'
28
 
29
- st.set_page_config(page_title="CastingSim V27", layout="wide")
30
 
31
  st.markdown("""
32
  <style>
@@ -74,13 +74,13 @@ if 't_sol_segundos' not in st.session_state: st.session_state.t_sol_segundos = 0
74
  if 'relatorio_ia' not in st.session_state: st.session_state.relatorio_ia = ""
75
  if 'relatorio_pdf' not in st.session_state: st.session_state.relatorio_pdf = None
76
 
77
- # --- GERADOR DE RELATÓRIO PDF (V27 - SEM A IMAGEM DE CORTE) ---
78
  def compilar_pdf():
79
  if not HAS_FPDF: return None
80
  pdf = FPDF()
81
  pdf.add_page()
82
  pdf.set_font("Arial", 'B', 16)
83
- pdf.cell(0, 10, "LAUDO DE ENGENHARIA - CASTINGSIM V27", 0, 1, 'C')
84
  pdf.ln(5)
85
 
86
  pdf.set_font("Arial", 'B', 12)
@@ -194,32 +194,18 @@ def gerar_diagnostico_ia(mod_cm, t_sol_total, t_vaz, t_molde, max_risco_rechupe,
194
 
195
  return "\n\n".join(relatorio)
196
 
197
- # ==========================================
198
- # O MODAL POP-UP DO VÍDEO
199
- # ==========================================
200
- @st.dialog("🎬 Telemetria Cinemática: Preenchimento (1x)", width="large")
201
- def modal_video_preenchimento():
202
- st.write(f"Velocidade de Vazamento Simulada: **{st.session_state.vel_vaz} m/s**")
203
- if os.path.exists(st.session_state.gif_path):
204
- with open(st.session_state.gif_path, "rb") as file_:
205
- contents = file_.read()
206
- data_url = base64.b64encode(contents).decode("utf-8")
207
- st.markdown(
208
- f'<img src="data:image/gif;base64,{data_url}" alt="video_alimentacao" style="width:100%; border-radius: 8px;">',
209
- unsafe_allow_html=True,
210
- )
211
- else:
212
- st.warning("Vídeo não gerado. O processo falhou ou foi abortado por segurança de memória.")
213
- if st.button("Fechar Player"):
214
- st.rerun()
215
-
216
  # --- INTERFACE ---
217
- if st.session_state.step in [1, 2, 3, 4]:
218
- st.progress(st.session_state.step / 4)
219
- st.caption(f"**ETAPA {st.session_state.step} DE 4**")
 
 
 
 
 
220
 
221
- if st.session_state.step != 3.5:
222
- st.title("🛡️ CastingSim V27: Bypass Visual Inteligente")
223
  st.markdown("---")
224
 
225
  # ==========================================
@@ -348,12 +334,12 @@ elif st.session_state.step == 3:
348
  st.rerun()
349
 
350
  # ==========================================
351
- # ETAPA 3.5: O TESTE DE GARGALO (PRIORIDADE MATEMÁTICA)
352
  # ==========================================
353
  elif st.session_state.step == 3.5:
354
  st.title("⏳ Processando Solver FEM...")
355
 
356
- progress_bar = st.progress(0, text="Iniciando Motores de Cálculo...")
357
 
358
  try:
359
  progress_bar.progress(10, text="[10%] Lendo geometria base e calculando tensores...")
@@ -362,16 +348,15 @@ elif st.session_state.step == 3.5:
362
  mesh_leve.rotate_y(st.session_state.rot_y, inplace=True)
363
  mesh_leve.rotate_z(st.session_state.rot_z, inplace=True)
364
  p_riser = np.array([st.session_state.off_x, st.session_state.off_y, st.session_state.off_z])
365
- temp_dir = tempfile.mkdtemp()
366
 
367
- progress_bar.progress(20, text="[20%] INICIANDO SUBDIVISÃO ISOTRÓPICA (Refinando malha para a Termodinâmica)...")
368
  time.sleep(0.5)
369
 
370
  mesh_pesada = mesh_leve.copy()
371
  if st.session_state.sub_div > 0:
372
  mesh_pesada = mesh_pesada.subdivide(st.session_state.sub_div, subfilter='linear')
373
 
374
- progress_bar.progress(40, text="[40%] Subdivisão Concluída! Calculando Matrizes Térmicas e Curvatura...")
375
  pts = mesh_pesada.points
376
  dist_ao_massalote = np.linalg.norm(pts - p_riser, axis=1)
377
  max_fluxo = np.max(dist_ao_massalote)
@@ -399,7 +384,7 @@ elif st.session_state.step == 3.5:
399
  mesh_pesada['Heat'] = heatmap_termico
400
  mesh_pesada['Risco'] = risco_rechupe
401
 
402
- progress_bar.progress(60, text="[60%] Amostrando resultados CAE para projeção WebGL (Redução Estrutural)...")
403
 
404
  if st.session_state.sub_div > 0:
405
  mesh_render = mesh_leve.copy()
@@ -415,10 +400,8 @@ elif st.session_state.step == 3.5:
415
  plotter.export_gltf(tmp.name)
416
  with open(tmp.name, "rb") as f: st.session_state.b64_termico = base64.b64encode(f.read()).decode()
417
 
418
- # BYPASS V27: O FATIAMENTO MEDIAL (CLIP) FOI COMPLETAMENTE REMOVIDO DAQUI
419
- progress_bar.progress(75, text="[75%] Consultando Mestre Fundidor IA (Bypass de Fatiamento Matemático)...")
420
 
421
- # Matemática Final e PDF
422
  vol_mm3 = st.session_state.vol_mm3
423
  area_mm2 = mesh_leve.area
424
  mod_cm = (vol_mm3 / area_mm2) / 10
@@ -442,29 +425,7 @@ elif st.session_state.step == 3.5:
442
  st.session_state.relatorio_ia = gerar_diagnostico_ia(mod_cm, t_sol_segundos_totais, st.session_state.t_vaz, st.session_state.t_molde, max_risco_calculado, num_reynolds, st.session_state.vel_vaz)
443
  st.session_state.relatorio_pdf = compilar_pdf()
444
 
445
- # O GARGALO MOVIDO PARA O FINAL
446
- progress_bar.progress(85, text="[85%] Renderizando Vídeo Cinemático (🚨 TESTE DE GARGALO DE RAM)...")
447
- gif_path = os.path.join(temp_dir, "preenchimento.gif")
448
- st.session_state.gif_path = gif_path
449
-
450
- try:
451
- dist_video = np.linalg.norm(mesh_leve.points - p_riser, axis=1)
452
- max_fluxo_vid = np.max(dist_video)
453
- plotter_gif = pv.Plotter(off_screen=True)
454
- plotter_gif.open_gif(gif_path, fps=10)
455
- mesh_leve['Dist_Massalote'] = dist_video
456
- plotter_gif.add_mesh(mesh_leve, color='white', opacity=0.15, style='wireframe')
457
- plotter_gif.camera_position = 'iso'
458
- for i in range(1, 26):
459
- limite = (max_fluxo_vid / 25) * i
460
- frame_mesh = mesh_leve.threshold([0, limite], scalars='Dist_Massalote')
461
- if frame_mesh.n_points > 0:
462
- plotter_gif.add_mesh(frame_mesh, color='#ff4500', metallic=True, smooth_shading=True, name='metal')
463
- plotter_gif.write_frame()
464
- plotter_gif.close()
465
- except Exception as gif_error:
466
- st.warning(f"Vídeo abortado por limite de infraestrutura. Laudo preservado. Erro: {gif_error}")
467
-
468
  progress_bar.progress(100, text="[100%] Cálculos finalizados! Saltando para Resultados...")
469
  time.sleep(0.5)
470
  st.session_state.step = 4
@@ -472,21 +433,19 @@ elif st.session_state.step == 3.5:
472
 
473
  except MemoryError:
474
  st.error("💥 COLAPSO DE INFRAESTRUTURA: OUT OF MEMORY (OOM)")
475
- st.warning("O motor da nuvem desarmou o disjuntor. A malha excedeu o limite de 16 GB de RAM do servidor na hora da subdivisão isotrópica.")
476
- st.info("**Ação Corretiva Exigida:** Volte para a Etapa 1 e garanta que o 'Refino Solver' está definido como 0 ou no máximo 1 para esta geometria específica.")
477
  if st.button("⬅️ Voltar e Reduzir Parâmetros"):
478
  st.session_state.step = 3
479
  st.rerun()
480
  except Exception as e:
481
  st.error("💥 FALHA MATEMÁTICA CRÍTICA DURANTE A COMPILAÇÃO")
482
- st.write("Um tensor ou algoritmo encontrou uma singularidade física impossível. Envie este laudo técnico abaixo para o engenheiro responsável:")
483
  st.code(traceback.format_exc())
484
- if st.button("⬅️ Voltar ao Setup e Tentar Novamente"):
485
  st.session_state.step = 3
486
  st.rerun()
487
 
488
  # ==========================================
489
- # ETAPA 4: RESULTADOS, PDF E BOTÃO DO VÍDEO
490
  # ==========================================
491
  elif st.session_state.step == 4:
492
  st.header("4. Simulação: Laudo da Qualidade")
@@ -499,10 +458,11 @@ elif st.session_state.step == 4:
499
  texto_tempo = f"{st.session_state.t_sol_segundos} s"
500
  st.error(f"⏱️ **TEMPO CRÍTICO DE SOLIDIFICAÇÃO: {texto_tempo}**")
501
  with col_video:
502
- if st.button("▶️ Assistir Alimentação (1x)", use_container_width=True):
503
- modal_video_preenchimento()
 
 
504
 
505
- # V27: Duas colunas em vez de três (Mapa Térmico + IA)
506
  col_v1, col_v2 = st.columns(2)
507
  p_m = [st.session_state.off_x/1000.0, st.session_state.off_y/1000.0, st.session_state.off_z/1000.0]
508
 
@@ -523,7 +483,7 @@ elif st.session_state.step == 4:
523
  st.download_button(
524
  label="📄 Baixar Laudo Técnico (.PDF)",
525
  data=st.session_state.relatorio_pdf,
526
- file_name="Laudo_CastingSim_V27.pdf",
527
  mime="application/pdf",
528
  type="primary",
529
  use_container_width=True
@@ -532,4 +492,89 @@ elif st.session_state.step == 4:
532
  st.write("")
533
  if st.button("⬅️ Voltar e Corrigir Setup"):
534
  st.session_state.step = 3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
535
  st.rerun()
 
26
  os.environ['PYVISTA_OFF_SCREEN'] = 'true'
27
  os.environ['VTK_GRAPHICS_BACKEND'] = 'OSMesa'
28
 
29
+ st.set_page_config(page_title="CastingSim V28", layout="wide")
30
 
31
  st.markdown("""
32
  <style>
 
74
  if 'relatorio_ia' not in st.session_state: st.session_state.relatorio_ia = ""
75
  if 'relatorio_pdf' not in st.session_state: st.session_state.relatorio_pdf = None
76
 
77
+ # --- GERADOR DE RELATÓRIO PDF ---
78
  def compilar_pdf():
79
  if not HAS_FPDF: return None
80
  pdf = FPDF()
81
  pdf.add_page()
82
  pdf.set_font("Arial", 'B', 16)
83
+ pdf.cell(0, 10, "LAUDO DE ENGENHARIA - CASTINGSIM V28", 0, 1, 'C')
84
  pdf.ln(5)
85
 
86
  pdf.set_font("Arial", 'B', 12)
 
194
 
195
  return "\n\n".join(relatorio)
196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
  # --- INTERFACE ---
198
+ if st.session_state.step in [1, 2, 3, 4, 4.5, 5]:
199
+ # Ajuste cosmético da barra de progresso para as novas etapas
200
+ progresso_visual = min(st.session_state.step, 4) / 4
201
+ st.progress(progresso_visual)
202
+ if st.session_state.step <= 4:
203
+ st.caption(f"**ETAPA {st.session_state.step} DE 4**")
204
+ else:
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 V28: Lazy Loading & LOD Proxy")
209
  st.markdown("---")
210
 
211
  # ==========================================
 
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...")
341
 
342
+ progress_bar = st.progress(0, text="Iniciando Motores de Cálculo Termodinâmico...")
343
 
344
  try:
345
  progress_bar.progress(10, text="[10%] Lendo geometria base e calculando tensores...")
 
348
  mesh_leve.rotate_y(st.session_state.rot_y, inplace=True)
349
  mesh_leve.rotate_z(st.session_state.rot_z, inplace=True)
350
  p_riser = np.array([st.session_state.off_x, st.session_state.off_y, st.session_state.off_z])
 
351
 
352
+ progress_bar.progress(30, text="[30%] INICIANDO SUBDIVISÃO ISOTRÓPICA (Refinando malha para a Termodinâmica)...")
353
  time.sleep(0.5)
354
 
355
  mesh_pesada = mesh_leve.copy()
356
  if st.session_state.sub_div > 0:
357
  mesh_pesada = mesh_pesada.subdivide(st.session_state.sub_div, subfilter='linear')
358
 
359
+ progress_bar.progress(50, text="[50%] Subdivisão Concluída! Calculando Matrizes Térmicas e Curvatura...")
360
  pts = mesh_pesada.points
361
  dist_ao_massalote = np.linalg.norm(pts - p_riser, axis=1)
362
  max_fluxo = np.max(dist_ao_massalote)
 
384
  mesh_pesada['Heat'] = heatmap_termico
385
  mesh_pesada['Risco'] = risco_rechupe
386
 
387
+ progress_bar.progress(70, text="[70%] Amostrando resultados CAE para projeção WebGL...")
388
 
389
  if st.session_state.sub_div > 0:
390
  mesh_render = mesh_leve.copy()
 
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
407
  mod_cm = (vol_mm3 / area_mm2) / 10
 
425
  st.session_state.relatorio_ia = gerar_diagnostico_ia(mod_cm, t_sol_segundos_totais, st.session_state.t_vaz, st.session_state.t_molde, max_risco_calculado, num_reynolds, st.session_state.vel_vaz)
426
  st.session_state.relatorio_pdf = compilar_pdf()
427
 
428
+ # O VÍDEO FOI REMOVIDO DAQUI E MOVIDO PARA A ETAPA 4.5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
429
  progress_bar.progress(100, text="[100%] Cálculos finalizados! Saltando para Resultados...")
430
  time.sleep(0.5)
431
  st.session_state.step = 4
 
433
 
434
  except MemoryError:
435
  st.error("💥 COLAPSO DE INFRAESTRUTURA: OUT OF MEMORY (OOM)")
436
+ st.warning("O motor da nuvem desarmou o disjuntor.")
 
437
  if st.button("⬅️ Voltar e Reduzir Parâmetros"):
438
  st.session_state.step = 3
439
  st.rerun()
440
  except Exception as e:
441
  st.error("💥 FALHA MATEMÁTICA CRÍTICA DURANTE A COMPILAÇÃO")
 
442
  st.code(traceback.format_exc())
443
+ if st.button("⬅️ Voltar ao Setup"):
444
  st.session_state.step = 3
445
  st.rerun()
446
 
447
  # ==========================================
448
+ # ETAPA 4: LAUDO (COM BOTÃO DE VÍDEO OPCIONAL)
449
  # ==========================================
450
  elif st.session_state.step == 4:
451
  st.header("4. Simulação: Laudo da Qualidade")
 
458
  texto_tempo = f"{st.session_state.t_sol_segundos} s"
459
  st.error(f"⏱️ **TEMPO CRÍTICO DE SOLIDIFICAÇÃO: {texto_tempo}**")
460
  with col_video:
461
+ # BOTÃO NOVO QUE ATIVA O LAZY LOADING
462
+ if st.button("🎬 Gerar Animação Cinemática", help="Requer processamento extra", use_container_width=True):
463
+ st.session_state.step = 4.5
464
+ st.rerun()
465
 
 
466
  col_v1, col_v2 = st.columns(2)
467
  p_m = [st.session_state.off_x/1000.0, st.session_state.off_y/1000.0, st.session_state.off_z/1000.0]
468
 
 
483
  st.download_button(
484
  label="📄 Baixar Laudo Técnico (.PDF)",
485
  data=st.session_state.relatorio_pdf,
486
+ file_name="Laudo_CastingSim_V28.pdf",
487
  mime="application/pdf",
488
  type="primary",
489
  use_container_width=True
 
492
  st.write("")
493
  if st.button("⬅️ Voltar e Corrigir Setup"):
494
  st.session_state.step = 3
495
+ st.rerun()
496
+
497
+ # ==========================================
498
+ # ETAPA 4.5: RENDER FARM (GERAÇÃO DE VÍDEO SEPARADA)
499
+ # ==========================================
500
+ elif st.session_state.step == 4.5:
501
+ st.title("🎬 Render Farm: Gerando Animação...")
502
+ st.info("A otimização V28 está usando a Malha Proxy (Low-Poly) para renderizar a animação sem estourar a memória RAM.")
503
+ prog_video = st.progress(0, text="Iniciando motor gráfico...")
504
+
505
+ try:
506
+ temp_dir = tempfile.mkdtemp()
507
+ gif_path = os.path.join(temp_dir, "preenchimento_otimizado.gif")
508
+
509
+ prog_video.progress(20, text="[20%] Carregando Holograma Proxy da Memória...")
510
+ # TRUQUE DE MESTRE: Lê a malha leve de 5.000 triângulos em vez da subdividida!
511
+ mesh_video = pv.read(st.session_state.path_proxy_stl)
512
+ mesh_video.rotate_x(st.session_state.rot_x, inplace=True)
513
+ mesh_video.rotate_y(st.session_state.rot_y, inplace=True)
514
+ mesh_video.rotate_z(st.session_state.rot_z, inplace=True)
515
+
516
+ p_riser = np.array([st.session_state.off_x, st.session_state.off_y, st.session_state.off_z])
517
+ dist_video = np.linalg.norm(mesh_video.points - p_riser, axis=1)
518
+ max_fluxo_vid = np.max(dist_video)
519
+
520
+ prog_video.progress(40, text="[40%] Processando Limiares Fluidodinâmicos (15 Frames @ 8 FPS)...")
521
+ plotter_gif = pv.Plotter(off_screen=True)
522
+ # Reduzido de 10 fps para 8 fps para combinar com os 15 frames
523
+ plotter_gif.open_gif(gif_path, fps=8)
524
+ mesh_video['Dist_Massalote'] = dist_video
525
+ plotter_gif.add_mesh(mesh_video, color='white', opacity=0.15, style='wireframe')
526
+ plotter_gif.camera_position = 'iso'
527
+
528
+ # Reduzido de 25 frames para 15 frames
529
+ passos = 15
530
+ for i in range(1, passos + 1):
531
+ limite = (max_fluxo_vid / passos) * i
532
+ frame_mesh = mesh_video.threshold([0, limite], scalars='Dist_Massalote')
533
+ if frame_mesh.n_points > 0:
534
+ plotter_gif.add_mesh(frame_mesh, color='#ff4500', metallic=True, smooth_shading=True, name='metal')
535
+ plotter_gif.write_frame()
536
+ prog_video.progress(40 + int((i/passos)*50), text=f"Renderizando Frame {i}/{passos}...")
537
+
538
+ plotter_gif.close()
539
+ st.session_state.gif_path = gif_path
540
+
541
+ prog_video.progress(100, text="[100%] Fita revelada! Abrindo projetor...")
542
+ time.sleep(0.5)
543
+ st.session_state.step = 5
544
+ st.rerun()
545
+
546
+ except MemoryError:
547
+ st.error("Mesmo com o Proxy, a memória estourou. O servidor está no limite extremo.")
548
+ if st.button("⬅️ Voltar ao Laudo sem Vídeo"):
549
+ st.session_state.step = 4
550
+ st.rerun()
551
+ except Exception as e:
552
+ st.error(f"Falha ao gerar vídeo: {e}")
553
+ if st.button("⬅️ Voltar ao Laudo"):
554
+ st.session_state.step = 4
555
+ st.rerun()
556
+
557
+ # ==========================================
558
+ # ETAPA 5: O CINEMA (EXIBIÇÃO DO VÍDEO)
559
+ # ==========================================
560
+ elif st.session_state.step == 5:
561
+ st.header("5. Telemetria Cinemática (Preenchimento)")
562
+ st.write(f"Velocidade de Vazamento: **{st.session_state.vel_vaz} m/s**")
563
+
564
+ col_centro, _ = st.columns([2, 1])
565
+ with col_centro:
566
+ if os.path.exists(st.session_state.gif_path):
567
+ with open(st.session_state.gif_path, "rb") as file_:
568
+ contents = file_.read()
569
+ data_url = base64.b64encode(contents).decode("utf-8")
570
+ st.markdown(
571
+ f'<img src="data:image/gif;base64,{data_url}" alt="video_alimentacao" style="width:100%; max-width: 800px; border-radius: 8px; border: 1px solid #444;">',
572
+ unsafe_allow_html=True,
573
+ )
574
+ else:
575
+ st.warning("Vídeo corrompido ou não gerado.")
576
+
577
+ st.write("")
578
+ if st.button("⬅️ Voltar ao Laudo Principal (Etapa 4)", type="primary"):
579
+ st.session_state.step = 4
580
  st.rerun()