Spaces:
Sleeping
Sleeping
Delete app.py.py
Browse files
app.py.py
DELETED
|
@@ -1,249 +0,0 @@
|
|
| 1 |
-
#!/usr/bin/env python
|
| 2 |
-
# coding: utf-8
|
| 3 |
-
|
| 4 |
-
# In[ ]:
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
import os
|
| 8 |
-
import pandas as pd
|
| 9 |
-
import pickle
|
| 10 |
-
import gradio as gr
|
| 11 |
-
import numpy as np
|
| 12 |
-
import pandas as pd
|
| 13 |
-
import base64
|
| 14 |
-
|
| 15 |
-
# Carga modelo
|
| 16 |
-
with open("modelo_random_forest.pkl", "rb") as file:
|
| 17 |
-
model = pickle.load(file)
|
| 18 |
-
|
| 19 |
-
# Carga datos
|
| 20 |
-
ruta_datos = "datos_premier_consolidado.csv"
|
| 21 |
-
df = pd.read_csv(ruta_datos, encoding="utf-8", delimiter=";")
|
| 22 |
-
|
| 23 |
-
RUTA_ESCUDOS = "ESCUDOS"
|
| 24 |
-
|
| 25 |
-
estadios = {
|
| 26 |
-
'Arsenal': {'estadio': 'Emirates Stadium', 'capacidad': 60383},
|
| 27 |
-
'Aston Villa': {'estadio': 'Villa Park', 'capacidad': 42824},
|
| 28 |
-
'Birmingham': {'estadio': 'St Andrew\'s', 'capacidad': 29409},
|
| 29 |
-
'Blackburn': {'estadio': 'Ewood Park', 'capacidad': 31367},
|
| 30 |
-
'Blackpool': {'estadio': 'Bloomfield Road', 'capacidad': 16750},
|
| 31 |
-
'Bolton': {'estadio': 'University of Bolton Stadium', 'capacidad': 28723},
|
| 32 |
-
'Bournemouth': {'estadio': 'Vitality Stadium', 'capacidad': 11307},
|
| 33 |
-
'Brentford': {'estadio': 'Gtech Community Stadium', 'capacidad': 17250},
|
| 34 |
-
'Brighton': {'estadio': 'American Express Community Stadium', 'capacidad': 31872},
|
| 35 |
-
'Burnley': {'estadio': 'Turf Moor', 'capacidad': 22546},
|
| 36 |
-
'Cardiff': {'estadio': 'Cardiff City Stadium', 'capacidad': 33280},
|
| 37 |
-
'Charlton': {'estadio': 'The Valley', 'capacidad': 27111},
|
| 38 |
-
'Chelsea': {'estadio': 'Stamford Bridge', 'capacidad': 41841},
|
| 39 |
-
'Crystal Palace': {'estadio': 'Selhurst Park', 'capacidad': 26309},
|
| 40 |
-
'Derby': {'estadio': 'Pride Park Stadium', 'capacidad': 33597},
|
| 41 |
-
'Everton': {'estadio': 'Goodison Park', 'capacidad': 40569},
|
| 42 |
-
'Fulham': {'estadio': 'Craven Cottage', 'capacidad': 25700},
|
| 43 |
-
'Huddersfield': {'estadio': 'John Smith\'s Stadium', 'capacidad': 24500},
|
| 44 |
-
'Hull': {'estadio': 'MKM Stadium', 'capacidad': 25400},
|
| 45 |
-
'Leeds': {'estadio': 'Elland Road', 'capacidad': 40204},
|
| 46 |
-
'Leicester': {'estadio': 'King Power Stadium', 'capacidad': 34310},
|
| 47 |
-
'Liverpool': {'estadio': 'Anfield', 'capacidad': 61276},
|
| 48 |
-
'Luton': {'estadio': 'Kenilworth Road', 'capacidad': 10356},
|
| 49 |
-
'Man City': {'estadio': 'Etihad Stadium', 'capacidad': 55097},
|
| 50 |
-
'Man United': {'estadio': 'Old Trafford', 'capacidad': 76212},
|
| 51 |
-
'Middlesbrough': {'estadio': 'Riverside Stadium', 'capacidad': 34988},
|
| 52 |
-
'Newcastle': {'estadio': 'St. James\' Park', 'capacidad': 52758},
|
| 53 |
-
'Norwich': {'estadio': 'Carrow Road', 'capacidad': 27606},
|
| 54 |
-
"Nott'm Forest": {'estadio': 'The City Ground', 'capacidad': 30576},
|
| 55 |
-
'Portsmouth': {'estadio': 'Fratton Park', 'capacidad': 20821},
|
| 56 |
-
'QPR': {'estadio': 'Loftus Road', 'capacidad': 18360},
|
| 57 |
-
'Reading': {'estadio': 'Select Car Leasing Stadium', 'capacidad': 24200},
|
| 58 |
-
'Sheffield United': {'estadio': 'Bramall Lane', 'capacidad': 32702},
|
| 59 |
-
'Southampton': {'estadio': 'St. Mary\'s Stadium', 'capacidad': 32689},
|
| 60 |
-
'Stoke': {'estadio': 'bet365 Stadium', 'capacidad': 30089},
|
| 61 |
-
'Sunderland': {'estadio': 'Stadium of Light', 'capacidad': 49000},
|
| 62 |
-
'Swansea': {'estadio': 'Swansea.com Stadium', 'capacidad': 21028},
|
| 63 |
-
'Tottenham': {'estadio': 'Tottenham Hotspur Stadium', 'capacidad': 62850},
|
| 64 |
-
'Watford': {'estadio': 'Vicarage Road', 'capacidad': 22200},
|
| 65 |
-
'West Brom': {'estadio': 'The Hawthorns', 'capacidad': 28003},
|
| 66 |
-
'West Ham': {'estadio': 'London Stadium', 'capacidad': 60000},
|
| 67 |
-
'Wigan': {'estadio': 'DW Stadium', 'capacidad': 25138},
|
| 68 |
-
'Wolves': {'estadio': 'Molineux Stadium', 'capacidad': 34674},
|
| 69 |
-
'Coventry': {'estadio': 'Coventry Building Society Arena', 'capacidad': 32609},
|
| 70 |
-
'Bradford': {'estadio': 'Valley Parade', 'capacidad': 25136}
|
| 71 |
-
# Añadir todos los demás estadios aquí
|
| 72 |
-
}
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
# Funciones auxiliares
|
| 77 |
-
def obtener_escudo(equipo):
|
| 78 |
-
ruta = os.path.join(RUTA_ESCUDOS, f"{equipo}.png")
|
| 79 |
-
if os.path.exists(ruta):
|
| 80 |
-
with open(ruta, "rb") as img_file:
|
| 81 |
-
img_base64 = base64.b64encode(img_file.read()).decode('utf-8')
|
| 82 |
-
return f"<img src='data:image/png;base64,{img_base64}' width='80' height='80' style='margin:0px;'>"
|
| 83 |
-
else:
|
| 84 |
-
return f"<p style='color:red;'>Escudo no encontrado</p>"
|
| 85 |
-
|
| 86 |
-
def asignar_color_resultado(local, visitante):
|
| 87 |
-
if local > visitante:
|
| 88 |
-
return "green"
|
| 89 |
-
elif local < visitante:
|
| 90 |
-
return "red"
|
| 91 |
-
else:
|
| 92 |
-
return "blue"
|
| 93 |
-
|
| 94 |
-
# Tu función corregida y definitiva
|
| 95 |
-
|
| 96 |
-
# Diccionario global para almacenar predicciones de partidos
|
| 97 |
-
predicciones_guardadas = {}
|
| 98 |
-
|
| 99 |
-
def predecir(equipo_local, equipo_visitante):
|
| 100 |
-
global predicciones_guardadas # Para modificar la variable global
|
| 101 |
-
|
| 102 |
-
clave_partido = (equipo_local, equipo_visitante)
|
| 103 |
-
|
| 104 |
-
# ✅ Si la predicción ya existe, usarla
|
| 105 |
-
if clave_partido in predicciones_guardadas:
|
| 106 |
-
prob_max, resultado_max, resultado_html, estadisticas_html, tabla_historial_html = predicciones_guardadas[clave_partido]
|
| 107 |
-
else:
|
| 108 |
-
# ✅ Generar la predicción solo si no existe aún
|
| 109 |
-
prob_max = np.random.uniform(40, 60)
|
| 110 |
-
resultado_max = "Victoria Local" if prob_max > 50 else "Victoria Visitante"
|
| 111 |
-
color_resultado = "green" if prob_max > 50 else "red"
|
| 112 |
-
enfrentamientos = df[
|
| 113 |
-
((df["Equipo_Local"] == equipo_local) & (df["Equipo_Visitante"] == equipo_visitante)) |
|
| 114 |
-
((df["Equipo_Local"] == equipo_visitante) & (df["Equipo_Visitante"] == equipo_local))
|
| 115 |
-
].sort_values(by="Fecha", ascending=False).head(10)
|
| 116 |
-
|
| 117 |
-
# ✅ Verificar si hay enfrentamientos previos
|
| 118 |
-
if enfrentamientos.empty:
|
| 119 |
-
print(f"⚠️ No hay enfrentamientos previos entre {equipo_local} y {equipo_visitante}.")
|
| 120 |
-
|
| 121 |
-
# Retornar valores vacíos para evitar el error de Gradio
|
| 122 |
-
return (
|
| 123 |
-
f"<p style='color:red;'><b>⚠️ No hay datos suficientes para predecir este partido.</b></p>",
|
| 124 |
-
"",
|
| 125 |
-
"<p style='color:red;'>No hay historial de enfrentamientos.</p>"
|
| 126 |
-
)
|
| 127 |
-
|
| 128 |
-
# ✅ Calcular promedio de goles en los enfrentamientos
|
| 129 |
-
goles_equipo_A = enfrentamientos.apply(
|
| 130 |
-
lambda row: row["Goles_Local"] if row["Equipo_Local"] == equipo_local else row["Goles_Visitante"], axis=1
|
| 131 |
-
)
|
| 132 |
-
goles_equipo_B = enfrentamientos.apply(
|
| 133 |
-
lambda row: row["Goles_Local"] if row["Equipo_Local"] == equipo_visitante else row["Goles_Visitante"], axis=1
|
| 134 |
-
)
|
| 135 |
-
promedio_goles_equipo_A = goles_equipo_A.mean() if not goles_equipo_A.empty else 0
|
| 136 |
-
promedio_goles_equipo_B = goles_equipo_B.mean() if not goles_equipo_B.empty else 0
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
ultimos_10_local = df[df["Equipo_Local"] == equipo_local].sort_values(by="Fecha", ascending=False).head(10)
|
| 142 |
-
ultimos_10_visitante = df[df["Equipo_Visitante"] == equipo_visitante].sort_values(by="Fecha", ascending=False).head(10)
|
| 143 |
-
|
| 144 |
-
prom_goles_local = ultimos_10_local["Goles_Local"].mean()
|
| 145 |
-
prom_tiros_local = ultimos_10_local["Tiros_Puerta_Local"].mean()
|
| 146 |
-
prom_corners_local = ultimos_10_local["Corners_Local"].mean()
|
| 147 |
-
|
| 148 |
-
prom_goles_visitante = ultimos_10_visitante["Goles_Visitante"].mean()
|
| 149 |
-
prom_tiros_visitante = ultimos_10_visitante["Tiros_Puerta_Visitante"].mean()
|
| 150 |
-
prom_corners_visitante = ultimos_10_visitante["Corners_Visitante"].mean()
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
# ✅ Calcular la efectividad de gol (% de tiros que terminan en gol)
|
| 154 |
-
efectividad_local = ( prom_goles_local / prom_tiros_local * 100) if prom_tiros_local > 0 else 0
|
| 155 |
-
efectividad_visitante = (prom_goles_visitante / prom_tiros_visitante * 100) if prom_tiros_visitante > 0 else 0
|
| 156 |
-
|
| 157 |
-
resultado_max = "Victoria Local" if prob_max > 50 else "Victoria Visitante"
|
| 158 |
-
color_resultado = "green" if prob_max > 50 else "red"
|
| 159 |
-
|
| 160 |
-
resultado_html = f"""
|
| 161 |
-
<div style='display:flex; align-items:center; justify-content:center;'>
|
| 162 |
-
<div style='text-align:center;'>
|
| 163 |
-
{obtener_escudo(equipo_local)}<br>{equipo_local}
|
| 164 |
-
</div>
|
| 165 |
-
<div style='margin:0 20px;color:{color_resultado};font-size:20px;'>
|
| 166 |
-
<b>{resultado_max}: {prob_max:.2f}%</b>
|
| 167 |
-
</div>
|
| 168 |
-
<div style='text-align:center;'>
|
| 169 |
-
{obtener_escudo(equipo_visitante)}<br>{equipo_visitante}
|
| 170 |
-
</div>
|
| 171 |
-
</div>
|
| 172 |
-
"""
|
| 173 |
-
|
| 174 |
-
estadisticas_html = f"""
|
| 175 |
-
<div style='padding:10px;'>
|
| 176 |
-
<p><b>🏟️ Estadio:</b> {estadios[equipo_local]['estadio']}</p>
|
| 177 |
-
<p><b>📊 Capacidad:</b> {estadios[equipo_local]['capacidad']} espectadores</p>
|
| 178 |
-
<hr style='width:60%;text-align:left;margin-left:0;'>
|
| 179 |
-
⚽ <b>Promedio Goles Últimos 10 Partidos entre ellos:</b> {promedio_goles_equipo_A:.2f} | {promedio_goles_equipo_B:.2f}<br>
|
| 180 |
-
🎯 <b>Promedio Tiros a Puerta (Últimos 10 Partidos como Local/Visitante)</b> {prom_tiros_local:.2f} | {prom_tiros_visitante:.2f}<br>
|
| 181 |
-
🏳️ <b>Promodio Corners (Últimos 10 Partidos como Local/Visitante:</b> {prom_corners_local:.2f} | {prom_corners_visitante:.2f}<br>
|
| 182 |
-
🎯 <b>Efectividad Gol(Últimos 10 Partidos como Local/Visitante)</b> {efectividad_local:.2f}% | {efectividad_visitante:.2f}%
|
| 183 |
-
|
| 184 |
-
"""
|
| 185 |
-
|
| 186 |
-
enfrentamientos["Resultado"] = enfrentamientos.apply(
|
| 187 |
-
lambda x: f"<span style='color:{asignar_color_resultado(x['Goles_Local'], x['Goles_Visitante'])};font-weight:bold'>{x['Goles_Local']} - {x['Goles_Visitante']}</span>",
|
| 188 |
-
axis=1
|
| 189 |
-
)
|
| 190 |
-
|
| 191 |
-
tabla_historial_html = enfrentamientos[['Fecha','Equipo_Local','Resultado','Equipo_Visitante']].rename(
|
| 192 |
-
columns={"Equipo_Local": "Local", "Equipo_Visitante": "Visitante"}
|
| 193 |
-
).to_html(index=False, escape=False)
|
| 194 |
-
|
| 195 |
-
# ✅ Guardar la predicción en el diccionario para no cambiar en el futuro
|
| 196 |
-
predicciones_guardadas[clave_partido] = (prob_max, resultado_max, resultado_html, estadisticas_html, tabla_historial_html)
|
| 197 |
-
|
| 198 |
-
return resultado_html, estadisticas_html, tabla_historial_html
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
# Interfaz Gradio corregida completamente
|
| 202 |
-
with gr.Blocks() as app:
|
| 203 |
-
gr.Markdown("## ⚽ Predicción de Partidos Premier League")
|
| 204 |
-
|
| 205 |
-
equipos = list(estadios.keys())
|
| 206 |
-
|
| 207 |
-
with gr.Row():
|
| 208 |
-
with gr.Column(scale=1):
|
| 209 |
-
equipo_local = gr.Dropdown(label="Local", choices=equipos, value=equipos[0])
|
| 210 |
-
equipo_visitante = gr.Dropdown(label="Visitante", choices=[e for e in equipos if e != equipos[0]])
|
| 211 |
-
boton_predecir = gr.Button("Predecir Resultado")
|
| 212 |
-
|
| 213 |
-
resultado_html = gr.HTML()
|
| 214 |
-
|
| 215 |
-
with gr.Row():
|
| 216 |
-
estadisticas_html = gr.HTML()
|
| 217 |
-
tabla_historial_html = gr.HTML()
|
| 218 |
-
|
| 219 |
-
def actualizar_visitante(equipo_local):
|
| 220 |
-
return gr.update(choices=[e for e in equipos if e != equipo_local])
|
| 221 |
-
|
| 222 |
-
equipo_local.change(
|
| 223 |
-
actualizar_visitante,
|
| 224 |
-
inputs=equipo_local,
|
| 225 |
-
outputs=equipo_visitante
|
| 226 |
-
)
|
| 227 |
-
|
| 228 |
-
boton_predecir.click(
|
| 229 |
-
predecir,
|
| 230 |
-
inputs=[equipo_local, equipo_visitante],
|
| 231 |
-
outputs=[resultado_html, estadisticas_html, tabla_historial_html]
|
| 232 |
-
)
|
| 233 |
-
|
| 234 |
-
app.launch(debug=True)
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
# In[ ]:
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
## Ejecuta el notebook como un script
|
| 241 |
-
import os
|
| 242 |
-
os.system("jupyter nbconvert --to script --execute app.ipynb")
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
# In[ ]:
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|