Delete app.py
Browse files
app.py
DELETED
|
@@ -1,203 +0,0 @@
|
|
| 1 |
-
import gradio as gr
|
| 2 |
-
import pickle
|
| 3 |
-
import numpy as np
|
| 4 |
-
import pandas as pd
|
| 5 |
-
import json
|
| 6 |
-
import os
|
| 7 |
-
|
| 8 |
-
print("=== INICIANDO UFC PREDICTOR ===")
|
| 9 |
-
|
| 10 |
-
def safe_load_pickle(filepath, default_value=None):
|
| 11 |
-
"""Cargar archivos pickle de forma segura"""
|
| 12 |
-
try:
|
| 13 |
-
with open(filepath, "rb") as f:
|
| 14 |
-
return pickle.load(f)
|
| 15 |
-
except Exception as e:
|
| 16 |
-
print(f"Error cargando {filepath}: {e}")
|
| 17 |
-
return default_value
|
| 18 |
-
|
| 19 |
-
def safe_load_json(filepath, default_value=None):
|
| 20 |
-
"""Cargar archivos JSON de forma segura"""
|
| 21 |
-
try:
|
| 22 |
-
with open(filepath, "r") as f:
|
| 23 |
-
return json.load(f)
|
| 24 |
-
except Exception as e:
|
| 25 |
-
print(f"Error cargando {filepath}: {e}")
|
| 26 |
-
return default_value
|
| 27 |
-
|
| 28 |
-
# Cargar modelo y preprocesadores de forma segura
|
| 29 |
-
print("Cargando modelo y componentes...")
|
| 30 |
-
|
| 31 |
-
model = safe_load_pickle("ufc_best_model.pkl")
|
| 32 |
-
scaler = safe_load_pickle("ufc_scaler.pkl")
|
| 33 |
-
imputer = safe_load_pickle("ufc_imputer.pkl")
|
| 34 |
-
metadata = safe_load_json("ufc_model_metadata.json", {})
|
| 35 |
-
ranges = safe_load_json("ufc_feature_ranges.json", {})
|
| 36 |
-
|
| 37 |
-
# Verificar que todo se cargó correctamente
|
| 38 |
-
components_loaded = all([model is not None, scaler is not None, imputer is not None])
|
| 39 |
-
if not components_loaded:
|
| 40 |
-
print("❌ ERROR: No se pudieron cargar todos los componentes del modelo")
|
| 41 |
-
raise Exception("Fallo en la carga de componentes del modelo")
|
| 42 |
-
|
| 43 |
-
print("✅ Todos los componentes cargados correctamente")
|
| 44 |
-
|
| 45 |
-
if metadata:
|
| 46 |
-
print(f"Modelo: {metadata.get('best_model_selected', 'N/A')}")
|
| 47 |
-
print(f"Accuracy: {metadata.get('evaluation_metrics', {}).get('accuracy', 'N/A')}")
|
| 48 |
-
|
| 49 |
-
# Obtener características del modelo
|
| 50 |
-
feature_columns = metadata.get('feature_columns', [])
|
| 51 |
-
if not feature_columns:
|
| 52 |
-
print("⚠️ Advertencia: No se encontraron feature_columns en metadata")
|
| 53 |
-
|
| 54 |
-
print(f"Características del modelo: {len(feature_columns)}")
|
| 55 |
-
|
| 56 |
-
def predict_ufc_fight(
|
| 57 |
-
fighter_1_kd, fighter_1_str, fighter_1_td, fighter_1_sub,
|
| 58 |
-
fighter_2_kd, fighter_2_str, fighter_2_td, fighter_2_sub,
|
| 59 |
-
round_num, weight_class, method_encoded
|
| 60 |
-
):
|
| 61 |
-
"""
|
| 62 |
-
Predice el resultado de una pelea UFC
|
| 63 |
-
"""
|
| 64 |
-
try:
|
| 65 |
-
# Validar entradas básicas
|
| 66 |
-
if any(pd.isna(x) for x in [fighter_1_kd, fighter_1_str, fighter_2_kd, fighter_2_str]):
|
| 67 |
-
return {"Error": "Valores de entrada inválidos o faltantes"}
|
| 68 |
-
|
| 69 |
-
# Calcular diferencias
|
| 70 |
-
kd_diff = fighter_1_kd - fighter_2_kd
|
| 71 |
-
str_diff = fighter_1_str - fighter_2_str
|
| 72 |
-
td_diff = fighter_1_td - fighter_2_td
|
| 73 |
-
sub_diff = fighter_1_sub - fighter_2_sub
|
| 74 |
-
|
| 75 |
-
# Calcular precisiones (evitar división por cero)
|
| 76 |
-
fighter_1_accuracy = fighter_1_str / (fighter_1_str + 10) if fighter_1_str >= 0 else 0
|
| 77 |
-
fighter_2_accuracy = fighter_2_str / (fighter_2_str + 10) if fighter_2_str >= 0 else 0
|
| 78 |
-
|
| 79 |
-
# Crear array de entrada con las características en el orden CORRECTO
|
| 80 |
-
input_features = []
|
| 81 |
-
|
| 82 |
-
# Añadir características en el orden esperado por el modelo
|
| 83 |
-
for feature in feature_columns:
|
| 84 |
-
if feature == 'KD_diff':
|
| 85 |
-
input_features.append(kd_diff)
|
| 86 |
-
elif feature == 'STR_diff':
|
| 87 |
-
input_features.append(str_diff)
|
| 88 |
-
elif feature == 'TD_diff':
|
| 89 |
-
input_features.append(td_diff)
|
| 90 |
-
elif feature == 'SUB_diff':
|
| 91 |
-
input_features.append(sub_diff)
|
| 92 |
-
elif feature == 'Fighter_1_KD':
|
| 93 |
-
input_features.append(fighter_1_kd)
|
| 94 |
-
elif feature == 'Fighter_2_KD':
|
| 95 |
-
input_features.append(fighter_2_kd)
|
| 96 |
-
elif feature == 'Fighter_1_STR':
|
| 97 |
-
input_features.append(fighter_1_str)
|
| 98 |
-
elif feature == 'Fighter_2_STR':
|
| 99 |
-
input_features.append(fighter_2_str)
|
| 100 |
-
elif feature == 'Fighter_1_TD':
|
| 101 |
-
input_features.append(fighter_1_td)
|
| 102 |
-
elif feature == 'Fighter_2_TD':
|
| 103 |
-
input_features.append(fighter_2_td)
|
| 104 |
-
elif feature == 'Fighter_1_SUB':
|
| 105 |
-
input_features.append(fighter_1_sub)
|
| 106 |
-
elif feature == 'Fighter_2_SUB':
|
| 107 |
-
input_features.append(fighter_2_sub)
|
| 108 |
-
elif feature == 'Fighter_1_accuracy':
|
| 109 |
-
input_features.append(fighter_1_accuracy)
|
| 110 |
-
elif feature == 'Fighter_2_accuracy':
|
| 111 |
-
input_features.append(fighter_2_accuracy)
|
| 112 |
-
elif feature == 'Round':
|
| 113 |
-
input_features.append(round_num)
|
| 114 |
-
elif feature == 'Method_encoded':
|
| 115 |
-
input_features.append(method_encoded)
|
| 116 |
-
elif feature.startswith('weight_class_'):
|
| 117 |
-
# One-hot encoding para categorías de peso
|
| 118 |
-
category_name = feature.replace('weight_class_', '')
|
| 119 |
-
input_features.append(1 if category_name == weight_class else 0)
|
| 120 |
-
else:
|
| 121 |
-
# Característica no reconocida, usar 0
|
| 122 |
-
input_features.append(0)
|
| 123 |
-
print(f"⚠️ Caracter��stica no reconocida: {feature}")
|
| 124 |
-
|
| 125 |
-
# Convertir a numpy array
|
| 126 |
-
input_array = np.array([input_features])
|
| 127 |
-
|
| 128 |
-
# Aplicar preprocesamiento
|
| 129 |
-
input_imputed = imputer.transform(input_array)
|
| 130 |
-
input_scaled = scaler.transform(input_imputed)
|
| 131 |
-
|
| 132 |
-
# Hacer predicción
|
| 133 |
-
prediction = model.predict(input_scaled)[0]
|
| 134 |
-
probability = model.predict_proba(input_scaled)[0]
|
| 135 |
-
|
| 136 |
-
# Interpretar resultados
|
| 137 |
-
if prediction == 1:
|
| 138 |
-
winner = "Fighter 1"
|
| 139 |
-
confidence = probability[1]
|
| 140 |
-
color = "#FF6B6B" # Rojo
|
| 141 |
-
else:
|
| 142 |
-
winner = "Fighter 2"
|
| 143 |
-
confidence = probability[0]
|
| 144 |
-
color = "#4ECDC4" # Verde
|
| 145 |
-
|
| 146 |
-
return {
|
| 147 |
-
"Ganador predicho": winner,
|
| 148 |
-
"Confianza": f"{confidence:.1%}",
|
| 149 |
-
"Probabilidad Fighter 1": f"{probability[1]:.1%}",
|
| 150 |
-
"Probabilidad Fighter 2": f"{probability[0]:.1%}",
|
| 151 |
-
"Análisis": f"El modelo predice que {winner} ganará con {confidence:.1%} de confianza"
|
| 152 |
-
}
|
| 153 |
-
|
| 154 |
-
except Exception as e:
|
| 155 |
-
error_msg = f"Error en predicción: {str(e)}"
|
| 156 |
-
print(error_msg)
|
| 157 |
-
return {"Error": error_msg}
|
| 158 |
-
|
| 159 |
-
# Crear interfaz Gradio
|
| 160 |
-
print("Configurando interfaz Gradio...")
|
| 161 |
-
|
| 162 |
-
# Definir inputs con valores por defecto razonables
|
| 163 |
-
inputs = [
|
| 164 |
-
gr.Number(label="Fighter 1 - Knockdowns", value=0, minimum=0, maximum=10, step=1),
|
| 165 |
-
gr.Number(label="Fighter 1 - Golpes significativos", value=50, minimum=0, maximum=500, step=1),
|
| 166 |
-
gr.Number(label="Fighter 1 - Takedowns", value=1, minimum=0, maximum=20, step=1),
|
| 167 |
-
gr.Number(label="Fighter 1 - Intentos de sumisión", value=0, minimum=0, maximum=10, step=1),
|
| 168 |
-
gr.Number(label="Fighter 2 - Knockdowns", value=0, minimum=0, maximum=10, step=1),
|
| 169 |
-
gr.Number(label="Fighter 2 - Golpes significativos", value=45, minimum=0, maximum=500, step=1),
|
| 170 |
-
gr.Number(label="Fighter 2 - Takedowns", value=2, minimum=0, maximum=20, step=1),
|
| 171 |
-
gr.Number(label="Fighter 2 - Intentos de sumisión", value=1, minimum=0, maximum=10, step=1),
|
| 172 |
-
gr.Slider(1, 5, value=3, step=1, label="Round"),
|
| 173 |
-
gr.Dropdown(
|
| 174 |
-
choices=[
|
| 175 |
-
"Bantamweight", "Catch Weight", "Featherweight", "Flyweight",
|
| 176 |
-
"Heavyweight", "Light Heavyweight", "Lightweight", "Middleweight", "Welterweight"
|
| 177 |
-
],
|
| 178 |
-
value="Lightweight",
|
| 179 |
-
label="Categoría de Peso"
|
| 180 |
-
),
|
| 181 |
-
gr.Slider(0, 10, value=5, step=1, label="Método (0-10)")
|
| 182 |
-
]
|
| 183 |
-
|
| 184 |
-
# Crear la aplicación
|
| 185 |
-
demo = gr.Interface(
|
| 186 |
-
fn=predict_ufc_fight,
|
| 187 |
-
inputs=inputs,
|
| 188 |
-
outputs="json",
|
| 189 |
-
title="UFC Fight Predictor",
|
| 190 |
-
description="Predice el resultado de peleas UFC usando Machine Learning. Modelo entrenado con datos reales.",
|
| 191 |
-
examples=[
|
| 192 |
-
[2, 120, 3, 1, 0, 80, 1, 0, 3, "Lightweight", 5],
|
| 193 |
-
[0, 80, 1, 0, 3, 150, 4, 2, 2, "Welterweight", 5],
|
| 194 |
-
[1, 100, 2, 0, 1, 95, 1, 1, 4, "Middleweight", 6]
|
| 195 |
-
],
|
| 196 |
-
theme="default"
|
| 197 |
-
)
|
| 198 |
-
|
| 199 |
-
print("✅ Interfaz configurada")
|
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