Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -2,36 +2,110 @@ import gradio as gr
|
|
2 |
import joblib
|
3 |
import numpy as np
|
4 |
import os
|
|
|
|
|
|
|
|
|
|
|
5 |
|
6 |
-
#
|
|
|
|
|
|
|
|
|
|
|
7 |
modelo_path = "modelo_colmena.pkl"
|
|
|
|
|
8 |
if os.path.exists(modelo_path):
|
9 |
modelo = joblib.load(modelo_path)
|
10 |
else:
|
11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
|
13 |
# Función para hacer predicciones con el modelo
|
14 |
def predecir(temp, humedad, peso, co2, vco, frecuencia, voltaje, temp_ext, humedad_ext, ver_tempSelect):
|
15 |
-
# Convertir valores a números y reemplazar NaN con 0
|
16 |
valores = [temp, humedad, peso, co2, vco, frecuencia, voltaje, temp_ext, humedad_ext, ver_tempSelect]
|
17 |
valores_limpios = [0 if v is None or np.isnan(v) else v for v in valores] # Reemplaza NaN y None con 0
|
18 |
|
19 |
entrada = np.array([valores_limpios])
|
20 |
|
21 |
-
prediccion = modelo.predict(entrada)[0] # El modelo devuelve [
|
22 |
|
23 |
-
mensaje = f"🔹
|
24 |
-
mensaje += f"\n🔹
|
|
|
25 |
|
26 |
return mensaje
|
27 |
|
28 |
# Crear la API en Gradio
|
29 |
iface = gr.Interface(
|
30 |
fn=predecir,
|
31 |
-
inputs=["number", "number", "number", "number", "number", "number", "number", "number", "number"],
|
32 |
outputs="text",
|
33 |
title="🐝 IA Inteligente para Colmenas",
|
34 |
-
description="Introduce los datos de la colmena y la IA predecirá si es necesario activar ventilador y
|
35 |
)
|
36 |
|
37 |
# Lanzar la API
|
|
|
2 |
import joblib
|
3 |
import numpy as np
|
4 |
import os
|
5 |
+
import requests
|
6 |
+
import time
|
7 |
+
import threading
|
8 |
+
from datetime import datetime
|
9 |
+
from sklearn.ensemble import RandomForestClassifier
|
10 |
|
11 |
+
# Configuración de la API de Node-RED
|
12 |
+
NODE_RED_URL = "https://appairedecolmena.es/colmena1/datos"
|
13 |
+
USERNAME = "tu_usuario"
|
14 |
+
PASSWORD = "tu_contraseña"
|
15 |
+
|
16 |
+
# Ruta del modelo
|
17 |
modelo_path = "modelo_colmena.pkl"
|
18 |
+
|
19 |
+
# Cargar el modelo si existe, si no, crearlo vacío
|
20 |
if os.path.exists(modelo_path):
|
21 |
modelo = joblib.load(modelo_path)
|
22 |
else:
|
23 |
+
modelo = RandomForestClassifier(n_estimators=100)
|
24 |
+
|
25 |
+
# Variable para rastrear el último timestamp
|
26 |
+
ultimo_timestamp = None
|
27 |
+
|
28 |
+
def obtener_datos_colmena():
|
29 |
+
"""Obtiene los datos de Node-RED con autenticación."""
|
30 |
+
try:
|
31 |
+
respuesta = requests.get(NODE_RED_URL, auth=(USERNAME, PASSWORD), timeout=5)
|
32 |
+
if respuesta.status_code == 200:
|
33 |
+
return respuesta.json()
|
34 |
+
else:
|
35 |
+
print(f"⚠️ Error en la API de Node-RED: {respuesta.status_code}")
|
36 |
+
return None
|
37 |
+
except Exception as e:
|
38 |
+
print("❌ No se pudo conectar a Node-RED:", e)
|
39 |
+
return None
|
40 |
+
|
41 |
+
def entrenar_nuevo_modelo(datos):
|
42 |
+
"""Entrena un nuevo modelo con los datos recibidos."""
|
43 |
+
global modelo
|
44 |
+
|
45 |
+
# Convertir los datos en un array
|
46 |
+
entrada = np.array([[float(datos["temperaturaInterior"]), float(datos["humedadInterior"]), float(datos["peso"]),
|
47 |
+
float(datos["co2"]), float(datos["vco"]), float(datos["frecuencia"]),
|
48 |
+
float(datos["voltaje"]), float(datos["temperatura_exterior"]),
|
49 |
+
float(datos["humedad_exterior"]), float(datos["ver_tempSelect"])]])
|
50 |
+
|
51 |
+
# Salidas: [ultrasonido, calefactor, ventilador]
|
52 |
+
salida = np.array([[int(datos["ver_ultrasonido"]), int(datos["ver_calefactor"]), int(datos["ver_ventilador"])]])
|
53 |
+
|
54 |
+
# Reentrenar el modelo
|
55 |
+
modelo.fit(entrada, salida)
|
56 |
+
|
57 |
+
# Guardar el nuevo modelo
|
58 |
+
joblib.dump(modelo, modelo_path)
|
59 |
+
print("✅ Modelo actualizado con nuevos datos.")
|
60 |
+
|
61 |
+
def verificar_nuevos_datos():
|
62 |
+
"""Consulta Node-RED cada hora y aprende si hay datos nuevos."""
|
63 |
+
global ultimo_timestamp
|
64 |
+
|
65 |
+
while True:
|
66 |
+
datos = obtener_datos_colmena()
|
67 |
+
|
68 |
+
if datos:
|
69 |
+
timestamp_actual = datos["timestamp"]
|
70 |
+
|
71 |
+
if timestamp_actual != ultimo_timestamp:
|
72 |
+
print(f"📌 Nuevos datos detectados: {timestamp_actual}")
|
73 |
+
entrenar_nuevo_modelo(datos)
|
74 |
+
ultimo_timestamp = timestamp_actual
|
75 |
+
else:
|
76 |
+
print("⏳ No hay datos nuevos, esperando la próxima consulta...")
|
77 |
+
else:
|
78 |
+
print("⚠️ No se pudieron obtener datos.")
|
79 |
+
|
80 |
+
# Esperar 1 hora antes de la próxima consulta
|
81 |
+
time.sleep(3600)
|
82 |
+
|
83 |
+
# Iniciar el proceso en segundo plano
|
84 |
+
thread = threading.Thread(target=verificar_nuevos_datos, daemon=True)
|
85 |
+
thread.start()
|
86 |
|
87 |
# Función para hacer predicciones con el modelo
|
88 |
def predecir(temp, humedad, peso, co2, vco, frecuencia, voltaje, temp_ext, humedad_ext, ver_tempSelect):
|
|
|
89 |
valores = [temp, humedad, peso, co2, vco, frecuencia, voltaje, temp_ext, humedad_ext, ver_tempSelect]
|
90 |
valores_limpios = [0 if v is None or np.isnan(v) else v for v in valores] # Reemplaza NaN y None con 0
|
91 |
|
92 |
entrada = np.array([valores_limpios])
|
93 |
|
94 |
+
prediccion = modelo.predict(entrada)[0] # El modelo devuelve [ultrasonido, calefactor, ventilador]
|
95 |
|
96 |
+
mensaje = f"🔹 Ultrasonido: {'ENCENDER' if prediccion[0] == 1 else 'APAGAR'}"
|
97 |
+
mensaje += f"\n🔹 Calefactor: {'ENCENDER' if prediccion[1] == 1 else 'APAGAR'}"
|
98 |
+
mensaje += f"\n🔹 Ventilador: {'ENCENDER' if prediccion[2] == 1 else 'APAGAR'}"
|
99 |
|
100 |
return mensaje
|
101 |
|
102 |
# Crear la API en Gradio
|
103 |
iface = gr.Interface(
|
104 |
fn=predecir,
|
105 |
+
inputs=["number", "number", "number", "number", "number", "number", "number", "number", "number", "number"],
|
106 |
outputs="text",
|
107 |
title="🐝 IA Inteligente para Colmenas",
|
108 |
+
description="Introduce los datos de la colmena y la IA predecirá si es necesario activar ventilador, calefactor y ultrasonidos."
|
109 |
)
|
110 |
|
111 |
# Lanzar la API
|