andrefbfreitas commited on
Commit
c4a2466
·
verified ·
1 Parent(s): 3a8a149

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -87
app.py CHANGED
@@ -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 V35", layout="wide")
31
 
32
  st.markdown("""
33
  <style>
@@ -82,7 +82,7 @@ def compilar_pdf():
82
  pdf = FPDF()
83
  pdf.add_page()
84
  pdf.set_font("Arial", 'B', 16)
85
- pdf.cell(0, 10, "LAUDO DE ENGENHARIA - CASTINGSIM V35", 0, 1, 'C')
86
  pdf.ln(5)
87
 
88
  pdf.set_font("Arial", 'B', 12)
@@ -206,7 +206,7 @@ if st.session_state.step in [1, 2, 3, 4, 4.5, 5]:
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 V35: Física Unificada e Anti-Payload Crash")
210
  st.markdown("---")
211
 
212
  # ==========================================
@@ -335,7 +335,7 @@ elif st.session_state.step == 3:
335
  st.rerun()
336
 
337
  # ==========================================
338
- # ETAPA 3.5: O NÚCLEO FÍSICO UNIFICADO (V35)
339
  # ==========================================
340
  elif st.session_state.step == 3.5:
341
  st.title("⏳ Processando Solver FEM...")
@@ -357,33 +357,26 @@ elif st.session_state.step == 3.5:
357
  if st.session_state.sub_div > 0:
358
  mesh_pesada = mesh_pesada.subdivide(st.session_state.sub_div, subfilter='linear')
359
 
360
- progress_bar.progress(45, text="[45%] Integrando Cinemática Heurística ao Solver Térmico (A Mágica V35)...")
361
 
362
- # --- A NOVA FÍSICA HEURÍSTICA APLICADA DIRETAMENTE NO SOLVER ---
363
  pts = mesh_pesada.points
364
 
365
- # 1. Gravidade (Tempo de preenchimento aumenta de baixo para cima)
366
  y_coords = pts[:, 1]
367
  y_min, y_max = np.min(y_coords), np.max(y_coords)
368
  y_norm = (y_coords - y_min) / (y_max - y_min + 1e-6)
369
 
370
- # 2. Espalhamento Radial a partir do centro
371
  xc, _, zc = mesh_pesada.center
372
  r_coords = np.sqrt((pts[:, 0] - xc)**2 + (pts[:, 2] - zc)**2)
373
  r_norm = r_coords / (np.max(r_coords) + 1e-6)
374
 
375
- # 3. Turbulência e Caos
376
  turbulencia = np.random.normal(0, 0.08, size=mesh_pesada.n_points)
377
 
378
- # 4. Cálculo do Tensor de Tempo de Chegada
379
  campo_fluido = (y_norm * 0.70) + (r_norm * 0.30) + turbulencia
380
  c_min, c_max = np.min(campo_fluido), np.max(campo_fluido)
381
 
382
- # calor_dinamico: 0 (encheu primeiro, já esfriou mais) a 1 (encheu por último, está muito quente)
383
  calor_dinamico = (campo_fluido - c_min) / (c_max - c_min + 1e-6)
384
 
385
  progress_bar.progress(60, text="[60%] Calculando Massa Térmica e Curvatura...")
386
- # Isolamento tradicional pelo massalote mantido para efeito de gradiente
387
  dist_ao_massalote = np.linalg.norm(pts - p_riser, axis=1)
388
  max_fluxo = np.max(dist_ao_massalote)
389
  isolamento = (dist_ao_massalote / (max_fluxo + 1e-6))
@@ -397,8 +390,6 @@ elif st.session_state.step == 3.5:
397
  curv_filtrada = np.where(curv_negativa > limiar, curv_negativa, 0)
398
  curv_norm = curv_filtrada / (np.max(curv_filtrada) + 1e-6)
399
 
400
- # --- ACOPLAMENTO FINAL (A REVOLUÇÃO) ---
401
- # Substitui a velha distância burra por 'calor_dinamico' guiado pela gravidade
402
  risco_bruto_termico = (massa_termica * 0.4) + (calor_dinamico * 0.4) + (curv_norm * 0.2)
403
  risco_bruto_termico = np.clip(risco_bruto_termico, 0, 1)
404
  fator_hdr = 4.0 * 10
@@ -494,8 +485,7 @@ elif st.session_state.step == 4:
494
  texto_tempo = f"{st.session_state.t_sol_segundos} s"
495
  st.error(f"⏱️ **TEMPO CRÍTICO DE SOLIDIFICAÇÃO: {texto_tempo}**")
496
  with col_video:
497
- # VOLTAMOS PARA 10 FRAMES PARA PREVENIR O ESTOURO DO PAYLOAD DA TELA WEB
498
- if st.button("🎬 Gerar Escoamento (10 Frames)", help="Animação Segura contra Sobrecarga de Rede", use_container_width=True):
499
  st.session_state.step = 4.5
500
  st.rerun()
501
 
@@ -524,7 +514,7 @@ elif st.session_state.step == 4:
524
  st.download_button(
525
  label="📄 Baixar Laudo (.PDF)",
526
  data=st.session_state.relatorio_pdf,
527
- file_name="Laudo_CastingSim_V35.pdf",
528
  mime="application/pdf",
529
  type="primary",
530
  use_container_width=True
@@ -536,15 +526,15 @@ elif st.session_state.step == 4:
536
  st.rerun()
537
 
538
  # ==========================================
539
- # ETAPA 4.5: RENDER FARM (EXTRAÇÃO COM 10 FRAMES SEGUROS)
540
  # ==========================================
541
  elif st.session_state.step == 4.5:
542
- st.title("🎬 Extração Cinemática (Anti-Crash de Payload)")
543
- st.info("Limitando a extração para 10 instantes de tempo chave. Isso protege o websocket de travar na transição para a próxima tela.")
544
- prog_video = st.progress(0, text="Iniciando motor de extração HD...")
545
 
546
  try:
547
- prog_video.progress(10, text="[10%] Recarregando a malha para o projetor WebGL...")
548
  mesh_video = pv.read(st.session_state.path_stl)
549
  mesh_video.rotate_x(st.session_state.rot_x, inplace=True)
550
  mesh_video.rotate_y(st.session_state.rot_y, inplace=True)
@@ -558,9 +548,8 @@ elif st.session_state.step == 4.5:
558
  pass
559
  mesh_molde_wire.points /= 1000.0
560
 
561
- prog_video.progress(20, text="[20%] Injetando o Tensor Físico Unificado no WebGL...")
562
  pts = mesh_video.points
563
-
564
  y_coords = pts[:, 1]
565
  y_min, y_max = np.min(y_coords), np.max(y_coords)
566
  y_norm = (y_coords - y_min) / (y_max - y_min + 1e-6)
@@ -579,7 +568,7 @@ elif st.session_state.step == 4.5:
579
  st.session_state.frames_paths = []
580
  temp_dir = tempfile.mkdtemp()
581
 
582
- # BLINDAGEM DA INFRAESTRUTURA: Cravado em 10 frames para evitar tela branca/crash
583
  passos = 10
584
 
585
  for i in range(1, passos + 1):
@@ -602,14 +591,14 @@ elif st.session_state.step == 4.5:
602
  plotter_export.close()
603
 
604
  time.sleep(0.01)
605
- prog_video.progress(20 + int((i/passos)*80), text=f"Forjando Geometria 4D: Frame {i}/{passos} (Seguro)...")
606
 
607
  try:
608
  del frame_mesh
609
  except: pass
610
  gc.collect()
611
 
612
- prog_video.progress(100, text="[100%] Extração Concluída! Lendo blocos e acionando Tela 5...")
613
  time.sleep(0.5)
614
  st.session_state.step = 5
615
  st.rerun()
@@ -626,71 +615,42 @@ elif st.session_state.step == 4.5:
626
  st.rerun()
627
 
628
  # ==========================================
629
- # ETAPA 5: O CINEMA (10 FRAMES SEGUROS E CADENCIADOS)
630
  # ==========================================
631
  elif st.session_state.step == 5:
632
- st.header("5. Telemetria Cinemática Interativa (WebGL)")
633
- st.write(f"Velocidade de Vazamento: **{st.session_state.vel_vaz} m/s** | Passo a Passo Heurístico (10x)")
634
 
635
  if len(st.session_state.frames_paths) > 0:
636
- frames_b64 = []
637
- for p in st.session_state.frames_paths:
638
- try:
639
- with open(p, "rb") as f:
640
- frames_b64.append(base64.b64encode(f.read()).decode())
641
- except Exception as e:
642
- pass
643
-
644
- frames_js_array = ",\n".join([f'"{b64}"' for b64 in frames_b64])
645
-
646
- html_player = f"""
647
- <html>
648
- <head>
649
- <script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/3.4.0/model-viewer.min.js"></script>
650
- <style>
651
- body {{ margin: 0; background-color: #f4f6f9; display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100vh; overflow: hidden; font-family: sans-serif; }}
652
- model-viewer {{ width: 100%; height: 85%; background-color: #1e1e1e; border-radius: 8px; box-shadow: 0 4px 8px rgba(0,0,0,0.3); }}
653
- .controls {{ height: 15%; display: flex; align-items: center; justify-content: center; width: 100%; gap: 15px; }}
654
- button {{ background-color: #ff4500; color: white; border: none; padding: 12px 24px; font-size: 16px; border-radius: 5px; cursor: pointer; font-weight: bold; transition: 0.2s; }}
655
- button:hover {{ background-color: #e03e00; transform: scale(1.05); }}
656
- .status {{ color: #1e1e1e; font-weight: bold; font-size: 14px; }}
657
- </style>
658
- </head>
659
- <body>
660
- <model-viewer id="mv" src="data:model/gltf-binary;base64,{frames_b64[0]}" camera-controls shadow-intensity="1">
661
- </model-viewer>
662
- <div class="controls">
663
- <button onclick="play()">▶ Reproduzir Cinemática</button>
664
- <div class="status" id="frame-counter">Frame: 1 / {len(frames_b64)}</div>
665
- </div>
666
- <script>
667
- const frames = [{frames_js_array}];
668
- const mv = document.getElementById('mv');
669
- const counter = document.getElementById('frame-counter');
670
- let timer = null;
671
- let isPlaying = false;
672
-
673
- function play() {{
674
- if(isPlaying) return;
675
- isPlaying = true;
676
- let i = 0;
677
- timer = setInterval(() => {{
678
- mv.src = "data:model/gltf-binary;base64," + frames[i];
679
- counter.innerText = "Frame: " + (i + 1) + " / " + frames.length;
680
- i++;
681
- if(i >= frames.length) {{
682
- clearInterval(timer);
683
- isPlaying = false;
684
- }}
685
- }}, 150); // Ajustado para 150ms para compensar os 10 frames (visão clara do salto temporal)
686
- }}
687
 
688
- setTimeout(play, 1000);
689
- </script>
690
- </body>
691
- </html>
692
- """
693
- components.html(html_player, height=600)
 
 
 
 
 
 
 
 
 
 
 
 
694
  else:
695
  st.warning("Motor WebGL não encontrou frames no Disco Rígido.")
696
 
 
27
  os.environ['PYVISTA_OFF_SCREEN'] = 'true'
28
  os.environ['VTK_GRAPHICS_BACKEND'] = 'OSMesa'
29
 
30
+ st.set_page_config(page_title="CastingSim V36", layout="wide")
31
 
32
  st.markdown("""
33
  <style>
 
82
  pdf = FPDF()
83
  pdf.add_page()
84
  pdf.set_font("Arial", 'B', 16)
85
+ pdf.cell(0, 10, "LAUDO DE ENGENHARIA - CASTINGSIM V36", 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 V36: Motor Físico Unificado e Timeline Scrubber")
210
  st.markdown("---")
211
 
212
  # ==========================================
 
335
  st.rerun()
336
 
337
  # ==========================================
338
+ # ETAPA 3.5: O NÚCLEO FÍSICO UNIFICADO
339
  # ==========================================
340
  elif st.session_state.step == 3.5:
341
  st.title("⏳ Processando Solver FEM...")
 
357
  if st.session_state.sub_div > 0:
358
  mesh_pesada = mesh_pesada.subdivide(st.session_state.sub_div, subfilter='linear')
359
 
360
+ progress_bar.progress(45, text="[45%] Integrando Cinemática Heurística ao Solver Térmico (Física V35)...")
361
 
 
362
  pts = mesh_pesada.points
363
 
 
364
  y_coords = pts[:, 1]
365
  y_min, y_max = np.min(y_coords), np.max(y_coords)
366
  y_norm = (y_coords - y_min) / (y_max - y_min + 1e-6)
367
 
 
368
  xc, _, zc = mesh_pesada.center
369
  r_coords = np.sqrt((pts[:, 0] - xc)**2 + (pts[:, 2] - zc)**2)
370
  r_norm = r_coords / (np.max(r_coords) + 1e-6)
371
 
 
372
  turbulencia = np.random.normal(0, 0.08, size=mesh_pesada.n_points)
373
 
 
374
  campo_fluido = (y_norm * 0.70) + (r_norm * 0.30) + turbulencia
375
  c_min, c_max = np.min(campo_fluido), np.max(campo_fluido)
376
 
 
377
  calor_dinamico = (campo_fluido - c_min) / (c_max - c_min + 1e-6)
378
 
379
  progress_bar.progress(60, text="[60%] Calculando Massa Térmica e Curvatura...")
 
380
  dist_ao_massalote = np.linalg.norm(pts - p_riser, axis=1)
381
  max_fluxo = np.max(dist_ao_massalote)
382
  isolamento = (dist_ao_massalote / (max_fluxo + 1e-6))
 
390
  curv_filtrada = np.where(curv_negativa > limiar, curv_negativa, 0)
391
  curv_norm = curv_filtrada / (np.max(curv_filtrada) + 1e-6)
392
 
 
 
393
  risco_bruto_termico = (massa_termica * 0.4) + (calor_dinamico * 0.4) + (curv_norm * 0.2)
394
  risco_bruto_termico = np.clip(risco_bruto_termico, 0, 1)
395
  fator_hdr = 4.0 * 10
 
485
  texto_tempo = f"{st.session_state.t_sol_segundos} s"
486
  st.error(f"⏱️ **TEMPO CRÍTICO DE SOLIDIFICAÇÃO: {texto_tempo}**")
487
  with col_video:
488
+ if st.button("🎬 Inspecionar Escoamento", help="Abra a Linha do Tempo de Preenchimento", use_container_width=True):
 
489
  st.session_state.step = 4.5
490
  st.rerun()
491
 
 
514
  st.download_button(
515
  label="📄 Baixar Laudo (.PDF)",
516
  data=st.session_state.relatorio_pdf,
517
+ file_name="Laudo_CastingSim_V36.pdf",
518
  mime="application/pdf",
519
  type="primary",
520
  use_container_width=True
 
526
  st.rerun()
527
 
528
  # ==========================================
529
+ # ETAPA 4.5: RENDER FARM (EXTRAÇÃO SELETIVA)
530
  # ==========================================
531
  elif st.session_state.step == 4.5:
532
+ st.title("🎬 Preparando a Linha do Tempo (Scrubber)...")
533
+ st.info("Gerando os instantes chave do escoamento. O arquivo HTML será blindado e leve.")
534
+ prog_video = st.progress(0, text="Iniciando motor de extração...")
535
 
536
  try:
537
+ prog_video.progress(10, text="[10%] Recarregando a malha base...")
538
  mesh_video = pv.read(st.session_state.path_stl)
539
  mesh_video.rotate_x(st.session_state.rot_x, inplace=True)
540
  mesh_video.rotate_y(st.session_state.rot_y, inplace=True)
 
548
  pass
549
  mesh_molde_wire.points /= 1000.0
550
 
551
+ prog_video.progress(20, text="[20%] Aplicando campo heurístico gravitacional...")
552
  pts = mesh_video.points
 
553
  y_coords = pts[:, 1]
554
  y_min, y_max = np.min(y_coords), np.max(y_coords)
555
  y_norm = (y_coords - y_min) / (y_max - y_min + 1e-6)
 
568
  st.session_state.frames_paths = []
569
  temp_dir = tempfile.mkdtemp()
570
 
571
+ # 10 frames bastam para um slider manual excelente
572
  passos = 10
573
 
574
  for i in range(1, passos + 1):
 
591
  plotter_export.close()
592
 
593
  time.sleep(0.01)
594
+ prog_video.progress(20 + int((i/passos)*80), text=f"Gerando Instante T={i}/{passos}...")
595
 
596
  try:
597
  del frame_mesh
598
  except: pass
599
  gc.collect()
600
 
601
+ prog_video.progress(100, text="[100%] Prontos para a Inspeção Manual!")
602
  time.sleep(0.5)
603
  st.session_state.step = 5
604
  st.rerun()
 
615
  st.rerun()
616
 
617
  # ==========================================
618
+ # ETAPA 5: O CINEMA (NOVO MODO: SLIDER QUADRO A QUADRO)
619
  # ==========================================
620
  elif st.session_state.step == 5:
621
+ st.header("5. Telemetria Cinemática (Análise Quadro a Quadro)")
622
+ st.write(f"Velocidade de Vazamento: **{st.session_state.vel_vaz} m/s** | Modo: Inspeção Timeline")
623
 
624
  if len(st.session_state.frames_paths) > 0:
625
+ total_frames = len(st.session_state.frames_paths)
626
+
627
+ # A REVOLUÇÃO V36: O Slider de Inspeção. Isso impede o DOM de carregar as 10 malhas de uma vez.
628
+ frame_atual = st.slider("⏳ Controle de Preenchimento (Deslize para avançar o tempo)", 1, total_frames, 1)
629
+
630
+ caminho_frame = st.session_state.frames_paths[frame_atual - 1]
631
+
632
+ try:
633
+ with open(caminho_frame, "rb") as f:
634
+ b64_frame = base64.b64encode(f.read()).decode()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
635
 
636
+ html_player = f"""
637
+ <html>
638
+ <head>
639
+ <script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/3.4.0/model-viewer.min.js"></script>
640
+ <style>
641
+ body {{ margin: 0; background-color: #f4f6f9; display: flex; align-items: center; justify-content: center; height: 100vh; overflow: hidden; font-family: sans-serif; }}
642
+ model-viewer {{ width: 100%; height: 95%; background-color: #1e1e1e; border-radius: 8px; box-shadow: 0 4px 8px rgba(0,0,0,0.3); }}
643
+ </style>
644
+ </head>
645
+ <body>
646
+ <model-viewer src="data:model/gltf-binary;base64,{b64_frame}" camera-controls shadow-intensity="1"></model-viewer>
647
+ </body>
648
+ </html>
649
+ """
650
+ components.html(html_player, height=450)
651
+
652
+ except Exception as e:
653
+ st.error("Falha ao ler o frame selecionado no disco.")
654
  else:
655
  st.warning("Motor WebGL não encontrou frames no Disco Rígido.")
656