Delete app.py
Browse files
app.py
DELETED
|
@@ -1,194 +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 |
-
import sys
|
| 8 |
-
|
| 9 |
-
print("=== INICIANDO UFC PREDICTOR ===")
|
| 10 |
-
|
| 11 |
-
# Configurar para evitar warnings
|
| 12 |
-
import warnings
|
| 13 |
-
warnings.filterwarnings('ignore')
|
| 14 |
-
|
| 15 |
-
def safe_load_pickle(filepath, default_value=None):
|
| 16 |
-
"""Cargar archivos pickle de forma segura"""
|
| 17 |
-
try:
|
| 18 |
-
with open(filepath, "rb") as f:
|
| 19 |
-
return pickle.load(f)
|
| 20 |
-
except Exception as e:
|
| 21 |
-
print(f"Error cargando {filepath}: {e}")
|
| 22 |
-
return default_value
|
| 23 |
-
|
| 24 |
-
def safe_load_json(filepath, default_value=None):
|
| 25 |
-
"""Cargar archivos JSON de forma segura"""
|
| 26 |
-
try:
|
| 27 |
-
with open(filepath, "r") as f:
|
| 28 |
-
return json.load(f)
|
| 29 |
-
except Exception as e:
|
| 30 |
-
print(f"Error cargando {filepath}: {e}")
|
| 31 |
-
return default_value
|
| 32 |
-
|
| 33 |
-
# Cargar modelo y preprocesadores de forma segura
|
| 34 |
-
print("Cargando modelo y componentes...")
|
| 35 |
-
|
| 36 |
-
model = safe_load_pickle("ufc_best_model.pkl")
|
| 37 |
-
scaler = safe_load_pickle("ufc_scaler.pkl")
|
| 38 |
-
imputer = safe_load_pickle("ufc_imputer.pkl")
|
| 39 |
-
metadata = safe_load_json("ufc_model_metadata.json", {})
|
| 40 |
-
ranges = safe_load_json("ufc_feature_ranges.json", {})
|
| 41 |
-
|
| 42 |
-
# Verificar que todo se cargó correctamente
|
| 43 |
-
components_loaded = all([model is not None, scaler is not None, imputer is not None])
|
| 44 |
-
if not components_loaded:
|
| 45 |
-
print("❌ ERROR: No se pudieron cargar todos los componentes del modelo")
|
| 46 |
-
# Crear un modelo dummy para evitar crash
|
| 47 |
-
from sklearn.linear_model import LogisticRegression
|
| 48 |
-
model = LogisticRegression()
|
| 49 |
-
# Entrenar con datos dummy
|
| 50 |
-
import numpy as np
|
| 51 |
-
X_dummy = np.random.rand(10, len(metadata.get('feature_columns', 10)))
|
| 52 |
-
y_dummy = np.random.randint(0, 2, 10)
|
| 53 |
-
model.fit(X_dummy, y_dummy)
|
| 54 |
-
print("⚠️ Usando modelo dummy por fallo en carga")
|
| 55 |
-
|
| 56 |
-
print("✅ Componentes cargados")
|
| 57 |
-
|
| 58 |
-
if metadata:
|
| 59 |
-
model_name = metadata.get('best_model_selected', 'Logistic Regression')
|
| 60 |
-
accuracy = metadata.get('evaluation_metrics', {}).get('accuracy', 0.9892)
|
| 61 |
-
print(f"Modelo: {model_name}")
|
| 62 |
-
print(f"Accuracy: {accuracy:.4f}")
|
| 63 |
-
|
| 64 |
-
feature_columns = metadata.get('feature_columns', [])
|
| 65 |
-
if not feature_columns:
|
| 66 |
-
print("⚠️ Advertencia: Usando características por defecto")
|
| 67 |
-
feature_columns = [
|
| 68 |
-
'KD_diff', 'STR_diff', 'TD_diff', 'SUB_diff',
|
| 69 |
-
'Fighter_1_KD', 'Fighter_2_KD', 'Fighter_1_STR', 'Fighter_2_STR',
|
| 70 |
-
'Fighter_1_TD', 'Fighter_2_TD', 'Fighter_1_SUB', 'Fighter_2_SUB',
|
| 71 |
-
'Fighter_1_accuracy', 'Fighter_2_accuracy', 'Round', 'Method_encoded'
|
| 72 |
-
]
|
| 73 |
-
|
| 74 |
-
print(f"Características: {len(feature_columns)}")
|
| 75 |
-
|
| 76 |
-
def predict_ufc_fight(
|
| 77 |
-
fighter_1_kd, fighter_1_str, fighter_1_td, fighter_1_sub,
|
| 78 |
-
fighter_2_kd, fighter_2_str, fighter_2_td, fighter_2_sub,
|
| 79 |
-
round_num, weight_class, method_encoded
|
| 80 |
-
):
|
| 81 |
-
"""Predice el resultado de una pelea UFC"""
|
| 82 |
-
try:
|
| 83 |
-
# Validar entradas
|
| 84 |
-
inputs = [fighter_1_kd, fighter_1_str, fighter_2_kd, fighter_2_str]
|
| 85 |
-
if any(x is None or pd.isna(x) for x in inputs):
|
| 86 |
-
return {"Error": "Valores de entrada inválidos"}
|
| 87 |
-
|
| 88 |
-
# Calcular diferencias
|
| 89 |
-
kd_diff = fighter_1_kd - fighter_2_kd
|
| 90 |
-
str_diff = fighter_1_str - fighter_2_str
|
| 91 |
-
td_diff = fighter_1_td - fighter_2_td
|
| 92 |
-
sub_diff = fighter_1_sub - fighter_2_sub
|
| 93 |
-
|
| 94 |
-
# Calcular precisiones
|
| 95 |
-
fighter_1_accuracy = fighter_1_str / (fighter_1_str + 10) if fighter_1_str >= 0 else 0
|
| 96 |
-
fighter_2_accuracy = fighter_2_str / (fighter_2_str + 10) if fighter_2_str >= 0 else 0
|
| 97 |
-
|
| 98 |
-
# Mapeo de características
|
| 99 |
-
feature_mapping = {
|
| 100 |
-
'KD_diff': kd_diff,
|
| 101 |
-
'STR_diff': str_diff,
|
| 102 |
-
'TD_diff': td_diff,
|
| 103 |
-
'SUB_diff': sub_diff,
|
| 104 |
-
'Fighter_1_KD': fighter_1_kd,
|
| 105 |
-
'Fighter_2_KD': fighter_2_kd,
|
| 106 |
-
'Fighter_1_STR': fighter_1_str,
|
| 107 |
-
'Fighter_2_STR': fighter_2_str,
|
| 108 |
-
'Fighter_1_TD': fighter_1_td,
|
| 109 |
-
'Fighter_2_TD': fighter_2_td,
|
| 110 |
-
'Fighter_1_SUB': fighter_1_sub,
|
| 111 |
-
'Fighter_2_SUB': fighter_2_sub,
|
| 112 |
-
'Fighter_1_accuracy': fighter_1_accuracy,
|
| 113 |
-
'Fighter_2_accuracy': fighter_2_accuracy,
|
| 114 |
-
'Round': round_num,
|
| 115 |
-
'Method_encoded': method_encoded
|
| 116 |
-
}
|
| 117 |
-
|
| 118 |
-
# Construir array de entrada
|
| 119 |
-
input_features = []
|
| 120 |
-
for feature in feature_columns:
|
| 121 |
-
if feature in feature_mapping:
|
| 122 |
-
input_features.append(feature_mapping[feature])
|
| 123 |
-
elif feature.startswith('weight_class_'):
|
| 124 |
-
category_name = feature.replace('weight_class_', '')
|
| 125 |
-
input_features.append(1 if category_name == weight_class else 0)
|
| 126 |
-
else:
|
| 127 |
-
input_features.append(0) # Valor por defecto
|
| 128 |
-
|
| 129 |
-
# Convertir y preprocesar
|
| 130 |
-
input_array = np.array([input_features])
|
| 131 |
-
input_imputed = imputer.transform(input_array)
|
| 132 |
-
input_scaled = scaler.transform(input_imputed)
|
| 133 |
-
|
| 134 |
-
# Predecir
|
| 135 |
-
prediction = model.predict(input_scaled)[0]
|
| 136 |
-
probability = model.predict_proba(input_scaled)[0]
|
| 137 |
-
|
| 138 |
-
# Resultados
|
| 139 |
-
if prediction == 1:
|
| 140 |
-
winner = "Fighter 1"
|
| 141 |
-
confidence = probability[1]
|
| 142 |
-
else:
|
| 143 |
-
winner = "Fighter 2"
|
| 144 |
-
confidence = probability[0]
|
| 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 |
-
return {"Error": f"Error en predicción: {str(e)}"}
|
| 156 |
-
|
| 157 |
-
# Interfaz Gradio
|
| 158 |
-
print("Configurando interfaz...")
|
| 159 |
-
|
| 160 |
-
inputs = [
|
| 161 |
-
gr.Number(label="Fighter 1 - Knockdowns", value=0, minimum=0, maximum=10),
|
| 162 |
-
gr.Number(label="Fighter 1 - Golpes significativos", value=50, minimum=0, maximum=500),
|
| 163 |
-
gr.Number(label="Fighter 1 - Takedowns", value=1, minimum=0, maximum=20),
|
| 164 |
-
gr.Number(label="Fighter 1 - Intentos de sumisión", value=0, minimum=0, maximum=10),
|
| 165 |
-
gr.Number(label="Fighter 2 - Knockdowns", value=0, minimum=0, maximum=10),
|
| 166 |
-
gr.Number(label="Fighter 2 - Golpes significativos", value=45, minimum=0, maximum=500),
|
| 167 |
-
gr.Number(label="Fighter 2 - Takedowns", value=2, minimum=0, maximum=20),
|
| 168 |
-
gr.Number(label="Fighter 2 - Intentos de sumisión", value=1, minimum=0, maximum=10),
|
| 169 |
-
gr.Slider(1, 5, value=3, step=1, label="Round"),
|
| 170 |
-
gr.Dropdown(
|
| 171 |
-
choices=["Bantamweight", "Catch Weight", "Featherweight", "Flyweight",
|
| 172 |
-
"Heavyweight", "Light Heavyweight", "Lightweight", "Middleweight", "Welterweight"],
|
| 173 |
-
value="Lightweight",
|
| 174 |
-
label="Categoría de Peso"
|
| 175 |
-
),
|
| 176 |
-
gr.Slider(0, 10, value=5, step=1, label="Método (0-10)")
|
| 177 |
-
]
|
| 178 |
-
|
| 179 |
-
demo = gr.Interface(
|
| 180 |
-
fn=predict_ufc_fight,
|
| 181 |
-
inputs=inputs,
|
| 182 |
-
outputs="json",
|
| 183 |
-
title="UFC Fight Predictor",
|
| 184 |
-
description="Predice el resultado de peleas UFC usando Machine Learning. Modelo con 98.9% de accuracy.",
|
| 185 |
-
examples=[
|
| 186 |
-
[2, 120, 3, 1, 0, 80, 1, 0, 3, "Lightweight", 5],
|
| 187 |
-
[0, 80, 1, 0, 3, 150, 4, 2, 2, "Welterweight", 5]
|
| 188 |
-
]
|
| 189 |
-
)
|
| 190 |
-
|
| 191 |
-
print("✅ Interfaz lista")
|
| 192 |
-
|
| 193 |
-
if __name__ == "__main__":
|
| 194 |
-
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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