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("""

⚽ Predictor de Valor de Jugadores FIFA

Descubre cuánto valdría tu jugador en el mercado de transferencias

""") # Métricas del modelo en español if r2_score > 0: gr.HTML(f"""
🎯 Precisión del Modelo: {r2_score*100:.1f}% de exactitud | 📊 Error Promedio: ±{mae:.3f} (escala logarítmica)
""") with gr.Row(): # Columna 1: Estadísticas principales with gr.Column(scale=1, elem_classes=["compact-section"]): gr.HTML('
📊 Estadísticas Principales
') overall = gr.Slider( 40, 99, value=78, step=1, label="🎯 Overall (Puntuación General)", info="De 40 (amateur) a 99 (mejor del mundo)" ) age = gr.Slider( 16, 45, value=25, step=1, label="🎂 Edad del Jugador", info="Los jugadores tienen su pico entre 25-30 años" ) height_cm = gr.Slider( 150, 210, value=180, step=1, label="📏 Altura (centímetros)", info="Altura física del jugador" ) # Columna 2: Habilidades técnicas with gr.Column(scale=1, elem_classes=["compact-section"]): gr.HTML('
⚽ Habilidades Técnicas
') pace = gr.Slider( 10, 99, value=70, step=1, label="🏃 Velocidad (Pace)", info="Qué tan rápido corre el jugador" ) shooting = gr.Slider( 10, 99, value=60, step=1, label="⚽ Definición (Shooting)", info="Capacidad para anotar goles" ) dribbling = gr.Slider( 10, 99, value=65, step=1, label="🎨 Regate (Dribbling)", info="Habilidad para superar rivales con el balón" ) defending = gr.Slider( 10, 99, value=50, step=1, label="🛡️ Defensa (Defending)", info="Capacidad para quitar balones y defender" ) physic = gr.Slider( 10, 99, value=70, step=1, label="💪 Físico (Physical)", info="Fuerza, resistencia y duelos físicos" ) # Fila 2: Posición y contexto with gr.Row(): with gr.Column(scale=1, elem_classes=["compact-section"]): gr.HTML('
🎯 Posición y Liga
') position = gr.Dropdown( choices=list(POSITIONS_SPANISH.values()), value="Centrocampista (CM)", label="⚽ Posición del Jugador", info="Dónde juega habitualmente en el campo", interactive=True ) league = gr.Dropdown( choices=list(LEAGUE_RANK_MAP.keys()), value="🏴󠁧󠁢󠁥󠁮󠁧󠁿 Premier League (Inglaterra)", label="🏆 Liga donde Juega", info="Las ligas mejores dan más valor al jugador", interactive=True ) gr.HTML("""
💡 Consejo: Los jugadores de Premier League, La Liga y Bundesliga suelen tener valores más altos
""") with gr.Column(scale=1, elem_classes=["compact-section"]): gr.HTML('
🌟 Factores Especiales
') elite_skills_count = gr.Slider( 0, 6, value=2, step=1, label="⭐ Habilidades Élite", info="¿Cuántas estadísticas tiene por encima de 85?" ) specialization_score = gr.Slider( 0.0, 1.0, value=0.5, step=0.1, label="🎯 Nivel de Especialización", info="0.0 = Versátil, 1.0 = Muy especializado en su posición" ) gr.HTML("""
🔥 Tip: Jugadores especializados en su posición y con múltiples habilidades élite valen más
""") # Botón de predicción with gr.Row(): with gr.Column(scale=2): pass with gr.Column(scale=1): predict_btn = gr.Button( "🔮 ¡Calcular Valor del Jugador!", variant="primary", size="lg", elem_classes=["predict-btn"] ) with gr.Column(scale=2): pass # Resultado de la predicción with gr.Row(): output = gr.Textbox( label="💰 Valor Estimado en el Mercado", placeholder="Ajusta los parámetros de tu jugador y haz clic en '¡Calcular Valor del Jugador!'", elem_classes=["prediction-output"], interactive=False, lines=1 ) # Ejemplos predefinidos en español gr.HTML('''
💡 Prueba estos ejemplos famosos:
''') with gr.Row(): example1_btn = gr.Button("⭐ Lionel Messi (Leyenda)", size="sm", elem_classes=["example-button"]) example2_btn = gr.Button("🏰 Virgil van Dijk (Defensor Élite)", size="sm", elem_classes=["example-button"]) example3_btn = gr.Button("🌱 Joven Promesa (19 años)", size="sm", elem_classes=["example-button"]) # Información adicional gr.HTML("""
📝 Cómo usar:
1️⃣ Ajusta las estadísticas de tu jugador
2️⃣ Selecciona su posición y liga
3️⃣ Indica sus habilidades especiales
4️⃣ ¡Descubre su valor de mercado!
""") # Event handlers def handle_prediction(*args): return predict_player_value(*args) predict_btn.click( fn=handle_prediction, inputs=[overall, age, pace, shooting, dribbling, defending, physic, height_cm, position, league, elite_skills_count, specialization_score], outputs=output ) # Ejemplos de jugadores famosos def set_messi(): return [92, 36, 70, 95, 92, 35, 75, 170, "Extremo Derecho (RW)", "🇪🇸 La Liga (España)", 4, 0.9] def set_van_dijk(): return [88, 32, 65, 25, 70, 92, 86, 193, "Defensa Central (CB)", "🏴󠁧󠁢󠁥󠁮󠁧󠁿 Premier League (Inglaterra)", 2, 0.8] def set_young_talent(): return [75, 19, 85, 65, 78, 30, 72, 175, "Extremo Izquierdo (LW)", "🇫🇷 Ligue 1 (Francia)", 1, 0.6] example1_btn.click( fn=set_messi, outputs=[overall, age, pace, shooting, dribbling, defending, physic, height_cm, position, league, elite_skills_count, specialization_score] ) example2_btn.click( fn=set_van_dijk, outputs=[overall, age, pace, shooting, dribbling, defending, physic, height_cm, position, league, elite_skills_count, specialization_score] ) example3_btn.click( fn=set_young_talent, outputs=[overall, age, pace, shooting, dribbling, defending, physic, height_cm, position, league, elite_skills_count, specialization_score] ) return interface if __name__ == "__main__": app = create_interface() app.launch( share=True, server_name="0.0.0.0", server_port=7860, show_error=True )