⚽ Predictor de Valor de Jugadores FIFA
Descubre cuánto valdría tu jugador en el mercado de transferencias
import gradio as gr import joblib import numpy as np import pandas as pd def load_model(): """Carga el modelo y sus metadatos desde el archivo fifa_model.pkl""" try: model_data = joblib.load('fifa_model.pkl') model = model_data.get('model') features = model_data.get('features') r2_score = model_data.get('r2_score', 0.0) mae = model_data.get('mae', 0.0) if model is None or features is None: raise ValueError("El archivo del modelo está incompleto.") print(f"✅ Modelo 'fifa_model.pkl' cargado. R²: {r2_score:.3f}, MAE: {mae:.3f}") return model, features, r2_score, mae except FileNotFoundError: print("❌ Error: No se encontró el archivo 'fifa_model.pkl'.") return None, [], 0.0, 0.0 except Exception as e: print(f"❌ Error al cargar el modelo: {e}") return None, [], 0.0, 0.0 try: model, features, r2_score, mae = load_model() except Exception as e: print(f"Error crítico: {e}") model, features, r2_score, mae = None, [], 0.0, 0.0 # Mapas traducidos al español LEAGUE_RANK_MAP = { "🏴 Premier League (Inglaterra)": 1, "🇪🇸 La Liga (España)": 2, "🇩🇪 Bundesliga (Alemania)": 3, "🇮🇹 Serie A (Italia)": 4, "🇫🇷 Ligue 1 (Francia)": 5, "🇳🇱 Eredivisie (Holanda)": 6, "🇵🇹 Liga NOS (Portugal)": 7, "🌍 Otras ligas europeas top": 8, "🌎 Ligas menores/secundarias": 10 } POSITIONS_SPANISH = { 'ST ⚽': 'Delantero Centro (ST)', 'CF 🎯': 'Centrodelantero (CF)', 'LW ⬅️': 'Extremo Izquierdo (LW)', 'RW ➡️': 'Extremo Derecho (RW)', 'CAM 🎨': 'Mediapunta (CAM)', 'CM ⚙️': 'Centrocampista (CM)', 'CDM 🛡️': 'Mediocentro Defensivo (CDM)', 'LM ↙️': 'Mediocentro Izquierdo (LM)', 'RM ↗️': 'Mediocentro Derecho (RM)', 'CB 🏰': 'Defensa Central (CB)', 'LB 🔄': 'Lateral Izquierdo (LB)', 'RB 🔄': 'Lateral Derecho (RB)', 'LWB 🏃': 'Carrilero Izquierdo (LWB)', 'RWB 🏃': 'Carrilero Derecho (RWB)', 'GK 🥅': 'Portero (GK)' } def predict_player_value( overall, age, pace, shooting, dribbling, defending, physic, height_cm, position, league, elite_skills_count, specialization_score ): """Predice el valor de mercado de un jugador""" if model is None: return "❌ Modelo no disponible" try: # Calcular características derivadas height_efficiency = overall / height_cm * 100 elite_factor = elite_skills_count / 6.0 # Position encoding - extraer código de posición pos_code = position.split('(')[1].split(')')[0] if '(' in position else position.split(' ')[0] pos_defense = 1 if pos_code in ['CB', 'LB', 'RB', 'LWB', 'RWB'] else 0 pos_midfield = 1 if pos_code in ['CM', 'CDM', 'CAM', 'LM', 'RM'] else 0 # League rank - extraer del texto español league_rank = LEAGUE_RANK_MAP.get(league, 10) # Interacciones league_overall_interaction = league_rank * overall age_overall_interaction = age * overall # Crear array de features feature_values = [ overall, height_efficiency, elite_factor, specialization_score, dribbling, league_overall_interaction, age_overall_interaction, age, shooting, defending, pace, physic, pos_defense, pos_midfield, league_rank ] X_pred = np.array(feature_values).reshape(1, -1) log_value_pred = model.predict(X_pred)[0] predicted_value = np.exp(log_value_pred) # Formatear resultado en español if predicted_value >= 1000000: formatted_value = f"💰 €{predicted_value/1000000:.2f} Millones" elif predicted_value >= 1000: formatted_value = f"💵 €{predicted_value/1000:.0f} Mil" else: formatted_value = f"💸 €{predicted_value:.0f}" # Clasificación en español if predicted_value >= 100000000: classification = "🌟 JUGADOR GALÁCTICO" elif predicted_value >= 50000000: classification = "⭐ ESTRELLA MUNDIAL" elif predicted_value >= 20000000: classification = "💎 CLASE MUNDIAL" elif predicted_value >= 10000000: classification = "🔥 MUY VALIOSO" elif predicted_value >= 5000000: classification = "✨ JUGADOR VALIOSO" elif predicted_value >= 1000000: classification = "📈 TALENTO PROMETEDOR" else: classification = "🌱 EN DESARROLLO" return f"{formatted_value} | {classification}" except Exception as e: return f"❌ Error en la predicción: {str(e)}" # CSS en español con ajustes custom_css = """ @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap'); :root { --gradient-1: linear-gradient(135deg, #667eea 0%, #764ba2 100%); --gradient-2: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); --gradient-3: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); } .gradio-container { font-family: 'Inter', sans-serif !important; background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%) !important; max-width: 1400px !important; margin: 0 auto !important; padding: 1rem !important; } .main-header { background: var(--gradient-1); padding: 2rem; margin-bottom: 1.5rem; border-radius: 1rem; text-align: center; box-shadow: 0 8px 32px rgba(0,0,0,0.3); } .main-header h1 { color: white !important; font-size: 2.5rem !important; font-weight: 700 !important; margin: 0 0 0.5rem 0 !important; } .main-header p { color: rgba(255,255,255,0.9) !important; font-size: 1.1rem !important; margin: 0 !important; } .compact-section { background: rgba(30, 41, 59, 0.8) !important; border: 1px solid rgba(148, 163, 184, 0.2) !important; border-radius: 1rem !important; padding: 1.5rem !important; margin-bottom: 1rem !important; backdrop-filter: blur(10px) !important; box-shadow: 0 4px 16px rgba(0,0,0,0.1) !important; } .section-title { color: #f8fafc !important; font-size: 1.1rem !important; font-weight: 600 !important; margin-bottom: 1rem !important; text-align: center !important; border-bottom: 2px solid #fbbf24 !important; padding-bottom: 0.5rem !important; } .gr-slider, .gr-dropdown { margin-bottom: 0.75rem !important; } .gr-slider label, .gr-dropdown label { font-size: 0.9rem !important; color: #cbd5e1 !important; margin-bottom: 0.5rem !important; font-weight: 500 !important; } .predict-btn { background: var(--gradient-2) !important; color: white !important; font-weight: 600 !important; border: none !important; border-radius: 2rem !important; padding: 1rem 3rem !important; font-size: 1.1rem !important; box-shadow: 0 8px 24px rgba(245, 87, 108, 0.4) !important; transition: all 0.3s ease !important; } .predict-btn:hover { transform: translateY(-2px) !important; box-shadow: 0 12px 32px rgba(245, 87, 108, 0.6) !important; } .prediction-output { background: var(--gradient-3) !important; color: white !important; font-size: 1.5rem !important; font-weight: 700 !important; text-align: center !important; padding: 1.5rem !important; border-radius: 1rem !important; border: none !important; box-shadow: 0 8px 24px rgba(79, 172, 254, 0.3) !important; text-shadow: 0 2px 4px rgba(0,0,0,0.2) !important; } .metrics-info { background: rgba(16, 185, 129, 0.1) !important; border: 1px solid rgba(16, 185, 129, 0.3) !important; border-radius: 0.75rem !important; padding: 1rem !important; text-align: center !important; color: #10b981 !important; font-size: 1rem !important; margin-bottom: 1rem !important; font-weight: 500 !important; } .example-button { background: rgba(59, 130, 246, 0.1) !important; border: 1px solid rgba(59, 130, 246, 0.3) !important; color: #60a5fa !important; font-weight: 500 !important; border-radius: 0.5rem !important; transition: all 0.2s ease !important; } .example-button:hover { background: rgba(59, 130, 246, 0.2) !important; transform: translateY(-1px) !important; } .help-text { background: rgba(79, 70, 229, 0.1) !important; border: 1px solid rgba(79, 70, 229, 0.2) !important; border-radius: 0.5rem !important; padding: 0.75rem !important; color: #a5b4fc !important; font-size: 0.85rem !important; margin-top: 0.5rem !important; text-align: center !important; } /* Estilos del dropdown SIN interferir con el posicionamiento */ .gr-dropdown { position: relative !important; } /* Solo estilizar el contenido del dropdown, no su posición */ .gr-dropdown select { background: rgba(30, 41, 59, 0.9) !important; border: 1px solid rgba(148, 163, 184, 0.3) !important; color: #cbd5e1 !important; border-radius: 0.5rem !important; padding: 0.5rem !important; } .gr-dropdown select:focus { outline: none !important; border-color: #fbbf24 !important; box-shadow: 0 0 0 2px rgba(251, 191, 36, 0.2) !important; } /* Responsivo */ @media (max-width: 768px) { .gradio-container { padding: 0.5rem !important; } .main-header h1 { font-size: 1.8rem !important; } .prediction-output { font-size: 1.2rem !important; } .compact-section { padding: 1rem !important; } } """ def create_interface(): with gr.Blocks( theme=gr.themes.Soft(), title="Predictor de Valor FIFA - Español", css=custom_css ) as interface: # Header en español gr.HTML("""
Descubre cuánto valdría tu jugador en el mercado de transferencias