Oraculo / app.py
caarleexx's picture
Update app.py
7bf55c6 verified
Raw History Blame Contribute Delete
10.5 kB
import gradio as gr
import numpy as np
import matplotlib.pyplot as plt
from scipy.special import comb
import time
import threading
from queue import Queue
import io
from PIL import Image
# ============================================================
# FUNÇÕES MATEMÁTICAS (idênticas ao original)
# ============================================================
def bernstein_poly(i, n, t):
return comb(n, i) * (t**i) * ((1-t)**(n-i))
def bezier_curve(points, n_times=20):
points = np.array(points)
t = np.linspace(0, 1, n_times)
n = len(points) - 1
curve = np.zeros((n_times, 3))
for i, p in enumerate(points):
curve += np.outer(bernstein_poly(i, n, t), p)
return curve.T
def quantize(value, multiple=4):
return multiple * round(value / multiple)
def learn_from_echo(echo_points):
if len(echo_points) < 2:
return np.array([0, 0, 0])
p1, p2 = np.array(echo_points[0]), np.array(echo_points[-1])
return p2 - p1
# ============================================================
# SIMULAÇÃO COM RASTRO IDÊNTICO AO ORIGINAL + ESFERA TRANSPARENTE
# ============================================================
class CometSimulation:
def __init__(self):
self.queue = Queue(maxsize=2)
self.running = False
self.thread = None
def start(self, camera_angle, auto_rotate):
if not self.running:
self.running = True
self.thread = threading.Thread(
target=self._run_simulation,
args=(camera_angle, auto_rotate),
daemon=True
)
self.thread.start()
return self.queue
def stop(self):
self.running = False
if self.thread:
self.thread.join(timeout=1.0)
def _run_simulation(self, camera_angle, auto_rotate):
# Estado inicial (quantizado como no original)
pos = np.array([quantize(0.), quantize(0.), quantize(0.)])
inertia = np.array([quantize(10.), quantize(10.), quantize(10.)])
history = [pos.tolist()]
# Configuração da figura
dpi = 100
fig = plt.figure(figsize=(12, 8), dpi=dpi)
# Layout: 3D à esquerda (2/3), painéis à direita (1/3)
gs = fig.add_gridspec(2, 3, hspace=0.3, wspace=0.3)
ax_3d = fig.add_subplot(gs[:, 0:2], projection='3d')
ax_info = fig.add_subplot(gs[0, 2]) # estatísticas de inércia
ax_stats = fig.add_subplot(gs[1, 2]) # posição atual
bg_color = '#0a0a0a'
fig.patch.set_facecolor(bg_color)
for ax in [ax_3d, ax_info, ax_stats]:
ax.set_facecolor(bg_color)
# ========== ESFERA TRANSPARENTE (MELHORIA VISUAL) ==========
# Malha da esfera – referência espacial sem poluir
u = np.linspace(0, 2*np.pi, 20)
v = np.linspace(0, np.pi, 15)
sphere_x = 28 * np.outer(np.cos(u), np.sin(v))
sphere_y = 28 * np.outer(np.sin(u), np.sin(v))
sphere_z = 28 * np.outer(np.ones_like(u), np.cos(v))
# ============================================================
cycle = 0
frame_global = 0
while self.running:
cycle += 1
# Ângulo da câmera (com rotação automática opcional)
if auto_rotate:
current_angle = (camera_angle + frame_global * 0.8) % 360
else:
current_angle = camera_angle
# Ponto atual é o último do histórico
current_point = np.array(history[-1])
# Gera novo alvo aleatório quantizado (igual ao original)
random_target = np.random.rand(3) * 50 - 25
target = np.array([quantize(v) for v in random_target])
# Calcula trajetória Bézier
control = current_point + inertia
curve = bezier_curve([current_point, control, target], n_times=20)
x_cycle, y_cycle, z_cycle = curve[0], curve[1], curve[2]
# Atualiza histórico
new_points = list(zip(x_cycle, y_cycle, z_cycle))
history.extend([list(p) for p in new_points])
history = history[-150:] # max_trail_length = 150
# Aprende inércia do eco (últimos 10 pontos)
echo_points = history[-10:]
inertia = learn_from_echo(echo_points)
# Anima a curva
for frame_idx in range(len(x_cycle)):
if not self.running:
break
frame_global += 1
ax_3d.clear()
ax_info.clear()
ax_stats.clear()
# ===== CONFIGURAÇÃO 3D (igual ao original) =====
ax_3d.set_facecolor(bg_color)
ax_3d.xaxis.pane.fill = False
ax_3d.yaxis.pane.fill = False
ax_3d.zaxis.pane.fill = False
ax_3d.grid(color='#222222', linestyle='--')
ax_3d.view_init(elev=30., azim=current_angle)
ax_3d.set_xlim(-30, 30)
ax_3d.set_ylim(-30, 30)
ax_3d.set_zlim(-30, 30)
ax_3d.set_xticklabels([])
ax_3d.set_yticklabels([])
ax_3d.set_zticklabels([])
# ========== DESENHA A ESFERA TRANSPARENTE ==========
ax_3d.plot_wireframe(sphere_x, sphere_y, sphere_z,
color='#4488ff', alpha=0.1, linewidth=0.5)
# ===================================================
# ===== ELEMENTOS ESTÁTICOS (igual ao original) =====
ax_3d.scatter(*current_point, s=150, c='lime', alpha=0.7) # ponto inicial do ciclo
ax_3d.scatter(*target, s=150, c='red', marker='X', alpha=0.9) # alvo
# ===== RASTRO IDÊNTICO AO ORIGINAL =====
# Índices: últimos 12 pontos antes do frame atual
trail_end = len(history) - len(x_cycle) + frame_idx
trail_start = max(0, trail_end - 12)
trail_segment = history[trail_start:trail_end+1]
if len(trail_segment) > 1:
for i in range(len(trail_segment) - 1):
p1, p2 = trail_segment[i], trail_segment[i+1]
# Alpha = 0.8 * (i/12) – exatamente como no original
alpha = 0.8 * (i / 12)
ax_3d.plot([p1[0], p2[0]], [p1[1], p2[1]], [p1[2], p2[2]],
color='#ff4500', linewidth=4, alpha=alpha)
# ===== AGENTE (laranja, igual ao original) =====
ax_3d.plot([x_cycle[frame_idx]], [y_cycle[frame_idx]], [z_cycle[frame_idx]],
'o', color='#ff4500', markersize=10, markeredgecolor='white')
# ===== TEXTO INFO (igual ao original) =====
info_text = f"Ciclo: {cycle}\nAlvo: {np.round(target)}"
ax_3d.text2D(0.05, 0.95, info_text, transform=ax_3d.transAxes,
color='white', fontsize=10,
bbox=dict(boxstyle='round', facecolor='#222222', alpha=0.7))
# ===== PAINEL INFO (MELHORIA) =====
ax_info.set_title('📊 INÉRCIA', color='white', fontsize=11)
ax_info.axis('off')
inertia_text = f"""Vetor:
({inertia[0]:.1f}, {inertia[1]:.1f}, {inertia[2]:.1f})
Histórico: {len(history)} pontos
Eco: {len(echo_points)} pontos"""
ax_info.text(0.1, 0.8, inertia_text, transform=ax_info.transAxes,
color='#ffaa00', fontsize=9, verticalalignment='top')
# ===== PAINEL STATS (MELHORIA) =====
ax_stats.set_title('📍 POSIÇÃO', color='white', fontsize=11)
ax_stats.axis('off')
pos_text = f"""X: {x_cycle[frame_idx]:.1f}
Y: {y_cycle[frame_idx]:.1f}
Z: {z_cycle[frame_idx]:.1f}"""
ax_stats.text(0.1, 0.6, pos_text, transform=ax_stats.transAxes,
color='#88ccff', fontsize=12, fontweight='bold')
# Renderiza e envia
fig.canvas.draw()
buf = io.BytesIO()
fig.savefig(buf, format='png', dpi=dpi,
facecolor=bg_color, bbox_inches='tight',
pad_inches=0.1)
buf.seek(0)
if self.queue.qsize() < 2:
self.queue.put(buf)
time.sleep(0.01) # igual ao original
# Prepara próximo ciclo
pos = target
# ============================================================
# INTERFACE GRADIO (COM ROTAÇÃO E PAINÉIS)
# ============================================================
simulation = CometSimulation()
def get_frame(camera_angle, auto_rotate):
queue = simulation.start(camera_angle, auto_rotate)
try:
while True:
buf = queue.get(timeout=1.0)
img = Image.open(buf)
yield np.array(img)
except Exception as e:
print(f"Error: {e}")
finally:
simulation.stop()
with gr.Blocks(theme=gr.themes.Base(primary_hue="purple", secondary_hue="orange")) as demo:
gr.HTML("""
<div style="text-align: center; margin-bottom: 15px;">
<h1 style="color: #ff4500; font-size: 2.2rem; margin: 0;">
✨ CAUSAL CONVERGENCE SIMULATOR ✨
</h1>
<p style="color: #cccccc;">rastro original • esfera transparente • estatísticas</p>
</div>
""")
with gr.Row():
with gr.Column(scale=1):
camera = gr.Slider(-180, 180, value=25, label="🎥 Camera Angle (Azimuth)")
auto_rotate = gr.Checkbox(label="🌀 Auto-rotate", value=True)
btn = gr.Button("🚀 START SIMULATION", variant="primary", size="lg")
with gr.Column(scale=3):
output = gr.Image(label="Real-Time Visualization", height=600)
btn.click(
fn=get_frame,
inputs=[camera, auto_rotate],
outputs=output
)
if __name__ == "__main__":
demo.launch()