Andrey0206 commited on
Commit
500985a
·
verified ·
1 Parent(s): 0aebeb0

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +129 -0
app.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import gymnasium as gym
3
+ from gymnasium import spaces
4
+ import numpy as np
5
+ import matplotlib.pyplot as plt
6
+ from stable_baselines3 import PPO
7
+
8
+ # --- 1. DEFINIMOS EL ENTORNO (Igual que en Colab) ---
9
+ class DataCenterEnv(gym.Env):
10
+ def __init__(self):
11
+ super(DataCenterEnv, self).__init__()
12
+ self.action_space = spaces.Discrete(5)
13
+ self.observation_space = spaces.Box(low=0, high=100, shape=(1,), dtype=np.float32)
14
+ self.state = 20
15
+ self.max_steps = 100
16
+ self.current_step = 0
17
+ self.temps = []
18
+ self.energies = []
19
+
20
+ def reset(self, seed=None, options=None):
21
+ super().reset(seed=seed)
22
+ self.state = 20 + np.random.rand()
23
+ self.current_step = 0
24
+ self.temps = [self.state]
25
+ self.energies = []
26
+ return np.array([self.state], dtype=np.float32), {}
27
+
28
+ def step(self, action):
29
+ # Usamos variables globales para simular la carga que el usuario elija en la web
30
+ global USER_CPU_LOAD_MIN, USER_CPU_LOAD_MAX
31
+ cpu_load = np.random.uniform(USER_CPU_LOAD_MIN, USER_CPU_LOAD_MAX)
32
+
33
+ cooling_effect = action * 2.5 # Potencia industrial
34
+ energy_cost = action ** 2
35
+
36
+ self.state = self.state + cpu_load - cooling_effect
37
+ self.state = np.clip(self.state, 10, 100)
38
+ self.current_step += 1
39
+
40
+ reward = 0
41
+ if 37 <= self.state <= 60: reward += 5
42
+ else: reward -= 2
43
+ if self.state > 80: reward -= 50
44
+ reward -= (energy_cost * 0.1)
45
+
46
+ terminated = False
47
+ if self.current_step >= self.max_steps: terminated = True
48
+
49
+ self.temps.append(self.state)
50
+ self.energies.append(energy_cost)
51
+
52
+ return np.array([self.state], dtype=np.float32), reward, terminated, False, {}
53
+
54
+ # Variables globales para controlar la dificultad desde la web
55
+ USER_CPU_LOAD_MIN = 1
56
+ USER_CPU_LOAD_MAX = 4
57
+
58
+ # --- 2. FUNCIÓN DE SIMULACIÓN (Lo que hace la web) ---
59
+ def run_simulation(load_min, load_max):
60
+ # Actualizamos las variables globales con lo que el usuario eligió
61
+ global USER_CPU_LOAD_MIN, USER_CPU_LOAD_MAX
62
+ USER_CPU_LOAD_MIN = load_min
63
+ USER_CPU_LOAD_MAX = load_max
64
+
65
+ # 1. Crear entorno y Cargar Modelo
66
+ env = DataCenterEnv()
67
+
68
+ # INTENTA CARGAR TU MODELO. Si no lo encuentra, usa uno aleatorio (para que no falle la demo)
69
+ try:
70
+ model = PPO.load("agente_aire_acondicionado.zip", env=env)
71
+ msg = "✅ Modelo Inteligente Cargado Correctamente."
72
+ except:
73
+ model = None
74
+ msg = "⚠️ ADVERTENCIA: No se encontró 'agente_aire_acondicionado.zip'. Usando acciones aleatorias."
75
+
76
+ # 2. Correr la simulación
77
+ obs, _ = env.reset()
78
+ done = False
79
+
80
+ while not done:
81
+ if model:
82
+ action, _ = model.predict(obs)
83
+ else:
84
+ action = env.action_space.sample() # Fallback aleatorio
85
+
86
+ obs, reward, done, truncated, info = env.step(action)
87
+
88
+ # 3. Generar Gráficos
89
+ fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
90
+
91
+ # Gráfico Temperatura
92
+ ax1.plot(env.temps, color="red", label="Temperatura")
93
+ ax1.axhline(y=37, color='green', linestyle='--', label="Mínimo (37°C)")
94
+ ax1.axhline(y=60, color='green', linestyle='--', label="Máximo (60°C)")
95
+ ax1.set_title("Control de Temperatura")
96
+ ax1.set_ylabel("°C")
97
+ ax1.set_ylim(10, 90)
98
+ ax1.legend()
99
+ ax1.grid(True)
100
+
101
+ # Gráfico Energía
102
+ ax2.plot(env.energies, color="blue", label="Energía")
103
+ ax2.set_title("Consumo de Energía")
104
+ ax2.set_ylabel("Watts")
105
+ ax2.grid(True)
106
+
107
+ plt.tight_layout()
108
+ return fig, msg
109
+
110
+ # --- 3. INTERFAZ GRÁFICA (Gradio) ---
111
+ with gr.Blocks() as demo:
112
+ gr.Markdown("# ❄️ AI Cooling System Optimization Agent")
113
+ gr.Markdown("Este agente de Aprendizaje por Refuerzo (RL) controla el aire acondicionado de un servidor para ahorrar energía sin que se sobrecaliente.")
114
+
115
+ with gr.Row():
116
+ with gr.Column():
117
+ gr.Markdown("### Configuración de Carga")
118
+ s_min = gr.Slider(1, 10, value=1, label="Carga Mínima de CPU (Calor)")
119
+ s_max = gr.Slider(1, 10, value=4, label="Carga Máxima de CPU (Calor)")
120
+ btn = gr.Button("🚀 Ejecutar Simulación")
121
+ status = gr.Textbox(label="Estado del Agente")
122
+
123
+ with gr.Column():
124
+ plot = gr.Plot(label="Resultados en Tiempo Real")
125
+
126
+ btn.click(fn=run_simulation, inputs=[s_min, s_max], outputs=[plot, status])
127
+
128
+ # Lanzar la app
129
+ demo.launch()