Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import pandas as pd | |
| import numpy as np | |
| from sklearn.preprocessing import StandardScaler | |
| from sklearn.linear_model import LogisticRegression | |
| import pickle | |
| # Cargar componentes guardados | |
| try: | |
| # Cargar modelo | |
| with open("logistic_model_2.pkl", "rb") as file: | |
| logistic = pickle.load(file) | |
| print("✅ Modelo cargado correctamente") | |
| # Cargar scaler | |
| with open("scaler_2.pkl", "rb") as file: | |
| scaler = pickle.load(file) | |
| print("✅ Scaler cargado correctamente") | |
| # Cargar datos | |
| tad = pd.read_csv("tad_2.csv") | |
| print("✅ Datos cargados correctamente") | |
| except Exception as e: | |
| print(f"⚠️ Error al cargar archivos: {e}") | |
| exit(1) | |
| # Función de predicción | |
| def predict_basketball_matchup(team1, team2, model, scaler, historical_data): | |
| required_features = [ | |
| 'PAINT_DOMINANCE', 'FG_PCT', 'SHOOTING_EFF', | |
| 'DEF_PRESSURE', 'REB', 'FG3_PCT' | |
| ] | |
| def calculate_team_metrics(team_name, n_recent_games=5): | |
| team_data = historical_data[ | |
| historical_data['TEAM_NAME'] == team_name | |
| ].sort_values('GAME_DATE').tail(n_recent_games) | |
| return { | |
| 'PAINT_DOMINANCE': team_data['PAINT_DOMINANCE'].mean(), | |
| 'FG_PCT': team_data['FG_PCT'].mean(), | |
| 'SHOOTING_EFF': team_data['SHOOTING_EFF'].mean(), | |
| 'DEF_PRESSURE': team_data['DEF_PRESSURE'].mean(), | |
| 'REB': team_data['REB'].mean(), | |
| 'FG3_PCT': team_data['FG3_PCT'].mean() | |
| } | |
| team1_metrics = calculate_team_metrics(team1) | |
| team2_metrics = calculate_team_metrics(team2) | |
| X1 = pd.DataFrame([team1_metrics])[required_features] | |
| X2 = pd.DataFrame([team2_metrics])[required_features] | |
| X1_scaled = scaler.transform(X1) | |
| X2_scaled = scaler.transform(X2) | |
| prob_team1 = model.predict_proba(X1_scaled)[0][1] | |
| prob_team2 = model.predict_proba(X2_scaled)[0][1] | |
| favorite = team1 if prob_team1 > prob_team2 else team2 | |
| win_prob = max(prob_team1, prob_team2) | |
| return { | |
| 'team1_probability': prob_team1, | |
| 'team2_probability': prob_team2, | |
| 'favorite': favorite, | |
| 'win_probability': win_prob, | |
| 'metrics_comparison': { | |
| team1: team1_metrics, | |
| team2: team2_metrics | |
| } | |
| } | |
| def gradio_predict(team1, team2): | |
| """ | |
| Función adaptada para Gradio que ejecuta predict_basketball_matchup | |
| """ | |
| # Validación de equipos diferentes | |
| if team1 == team2: | |
| return """ | |
| # ⚠️ Error de Selección | |
| Por favor, seleccione dos equipos diferentes para realizar la predicción. | |
| El mismo equipo no puede jugar contra sí mismo. | |
| """ | |
| resultado = predict_basketball_matchup(team1, team2, logistic, scaler, tad) | |
| # Formateamos la salida con mejor estructura y formato | |
| output = f""" | |
| # 🏀 PREDICCIÓN DE ENFRENTAMIENTO NBA | |
| ## Probabilidades de Victoria | |
| ---------------------------- | |
| ### {team1} | |
| * **Probabilidad**: {resultado['team1_probability']:.1%} | |
| * **Estatus**: {"✨ FAVORITO" if resultado['favorite'] == team1 else ""} | |
| ### {team2} | |
| * **Probabilidad**: {resultado['team2_probability']:.1%} | |
| * **Estatus**: {"✨ FAVORITO" if resultado['favorite'] == team2 else ""} | |
| ## 📊 Análisis Comparativo de Métricas | |
| ------------------------------------ | |
| """ | |
| # Formato de tabla para métricas | |
| output += """ | |
| | Métrica | {} | {} | | |
| |---------|-----|-----|""".format(team1, team2) | |
| # Diccionario para nombres más descriptivos de las métricas | |
| metric_names = { | |
| 'PAINT_DOMINANCE': 'Dominancia en la Pintura', | |
| 'FG_PCT': 'Porcentaje de Tiros de Campo', | |
| 'SHOOTING_EFF': 'Eficiencia en Tiros', | |
| 'DEF_PRESSURE': 'Presión Defensiva', | |
| 'REB': 'Rebotes', | |
| 'FG3_PCT': 'Porcentaje de Triples' | |
| } | |
| # Agregar cada métrica a la tabla | |
| for metric in resultado['metrics_comparison'][team1]: | |
| metric_display = metric_names.get(metric, metric) | |
| value1 = resultado['metrics_comparison'][team1][metric] | |
| value2 = resultado['metrics_comparison'][team2][metric] | |
| # Determinar quién tiene mejor valor en cada métrica | |
| better_value = max(value1, value2) | |
| value1_str = f"**{value1:.3f}**" if value1 == better_value else f"{value1:.3f}" | |
| value2_str = f"**{value2:.3f}**" if value2 == better_value else f"{value2:.3f}" | |
| output += f"\n| {metric_display} | {value1_str} | {value2_str} |" | |
| # Agregar conclusión | |
| output += f""" | |
| ## 🎯 Conclusión | |
| -------------- | |
| **{resultado['favorite']}** es el favorito con una probabilidad de victoria del **{resultado['win_probability']:.1%}** | |
| """ | |
| return output | |
| # Interfaz de Gradio | |
| with gr.Blocks(theme=gr.themes.Soft()) as demo: | |
| gr.Markdown(""" | |
| # 🏀 Predicción de Partidos NBA | |
| Seleccione dos equipos diferentes para predecir el resultado del enfrentamiento | |
| """) | |
| with gr.Row(): | |
| team1 = gr.Dropdown( | |
| label="Equipo Local", | |
| choices=sorted(tad["TEAM_NAME"].unique().tolist()), | |
| container=False | |
| ) | |
| team2 = gr.Dropdown( | |
| label="Equipo Visitante", | |
| choices=sorted(tad["TEAM_NAME"].unique().tolist()), | |
| container=False | |
| ) | |
| btn = gr.Button("📊 Predecir Resultado", size="lg") | |
| resultado_texto = gr.Markdown("") | |
| btn.click(fn=gradio_predict, inputs=[team1, team2], outputs=resultado_texto) | |
| # Lanzar la interfaz | |
| if __name__ == "__main__": | |
| demo.launch() |