File size: 11,060 Bytes
2d383e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
#!/usr/bin/env python
# coding: utf-8

# In[ ]:


import os
import pandas as pd
import pickle
import gradio as gr
import numpy as np
import pandas as pd
import base64

# Carga modelo
with open("modelo_random_forest.pkl", "rb") as file:
    model = pickle.load(file)

# Carga datos
ruta_datos = "datos_premier_consolidado.csv"
df = pd.read_csv(ruta_datos, encoding="utf-8", delimiter=";")

RUTA_ESCUDOS = "ESCUDOS"

estadios = {
  'Arsenal': {'estadio': 'Emirates Stadium', 'capacidad': 60383},
    'Aston Villa': {'estadio': 'Villa Park', 'capacidad': 42824},
    'Birmingham': {'estadio': 'St Andrew\'s', 'capacidad': 29409},
    'Blackburn': {'estadio': 'Ewood Park', 'capacidad': 31367},
    'Blackpool': {'estadio': 'Bloomfield Road', 'capacidad': 16750},
    'Bolton': {'estadio': 'University of Bolton Stadium', 'capacidad': 28723},
    'Bournemouth': {'estadio': 'Vitality Stadium', 'capacidad': 11307},
    'Brentford': {'estadio': 'Gtech Community Stadium', 'capacidad': 17250},
    'Brighton': {'estadio': 'American Express Community Stadium', 'capacidad': 31872},
    'Burnley': {'estadio': 'Turf Moor', 'capacidad': 22546},
    'Cardiff': {'estadio': 'Cardiff City Stadium', 'capacidad': 33280},
    'Charlton': {'estadio': 'The Valley', 'capacidad': 27111},
    'Chelsea': {'estadio': 'Stamford Bridge', 'capacidad': 41841},
    'Crystal Palace': {'estadio': 'Selhurst Park', 'capacidad': 26309},
    'Derby': {'estadio': 'Pride Park Stadium', 'capacidad': 33597},
    'Everton': {'estadio': 'Goodison Park', 'capacidad': 40569},
    'Fulham': {'estadio': 'Craven Cottage', 'capacidad': 25700},
    'Huddersfield': {'estadio': 'John Smith\'s Stadium', 'capacidad': 24500},
    'Hull': {'estadio': 'MKM Stadium', 'capacidad': 25400},
    'Leeds': {'estadio': 'Elland Road', 'capacidad': 40204},
    'Leicester': {'estadio': 'King Power Stadium', 'capacidad': 34310},
    'Liverpool': {'estadio': 'Anfield', 'capacidad': 61276},
    'Luton': {'estadio': 'Kenilworth Road', 'capacidad': 10356},
    'Man City': {'estadio': 'Etihad Stadium', 'capacidad': 55097},
    'Man United': {'estadio': 'Old Trafford', 'capacidad': 76212},
    'Middlesbrough': {'estadio': 'Riverside Stadium', 'capacidad': 34988},
    'Newcastle': {'estadio': 'St. James\' Park', 'capacidad': 52758},
    'Norwich': {'estadio': 'Carrow Road', 'capacidad': 27606},
    "Nott'm Forest": {'estadio': 'The City Ground', 'capacidad': 30576},
    'Portsmouth': {'estadio': 'Fratton Park', 'capacidad': 20821},
    'QPR': {'estadio': 'Loftus Road', 'capacidad': 18360},
    'Reading': {'estadio': 'Select Car Leasing Stadium', 'capacidad': 24200},
    'Sheffield United': {'estadio': 'Bramall Lane', 'capacidad': 32702},
    'Southampton': {'estadio': 'St. Mary\'s Stadium', 'capacidad': 32689},
    'Stoke': {'estadio': 'bet365 Stadium', 'capacidad': 30089},
    'Sunderland': {'estadio': 'Stadium of Light', 'capacidad': 49000},
    'Swansea': {'estadio': 'Swansea.com Stadium', 'capacidad': 21028},
    'Tottenham': {'estadio': 'Tottenham Hotspur Stadium', 'capacidad': 62850},
    'Watford': {'estadio': 'Vicarage Road', 'capacidad': 22200},
    'West Brom': {'estadio': 'The Hawthorns', 'capacidad': 28003},
    'West Ham': {'estadio': 'London Stadium', 'capacidad': 60000},
    'Wigan': {'estadio': 'DW Stadium', 'capacidad': 25138},
    'Wolves': {'estadio': 'Molineux Stadium', 'capacidad': 34674},
    'Coventry': {'estadio': 'Coventry Building Society Arena', 'capacidad': 32609},
    'Bradford': {'estadio': 'Valley Parade', 'capacidad': 25136}
    # Añadir todos los demás estadios aquí
}



# Funciones auxiliares
def obtener_escudo(equipo):
    ruta = os.path.join(RUTA_ESCUDOS, f"{equipo}.png")
    if os.path.exists(ruta):
        with open(ruta, "rb") as img_file:
            img_base64 = base64.b64encode(img_file.read()).decode('utf-8')
        return f"<img src='data:image/png;base64,{img_base64}' width='80' height='80' style='margin:0px;'>"
    else:
        return f"<p style='color:red;'>Escudo no encontrado</p>"

def asignar_color_resultado(local, visitante):
    if local > visitante:
        return "green"
    elif local < visitante:
        return "red"
    else:
        return "blue"

# Tu función corregida y definitiva

# Diccionario global para almacenar predicciones de partidos
predicciones_guardadas = {}

def predecir(equipo_local, equipo_visitante):
    global predicciones_guardadas  # Para modificar la variable global
    
    clave_partido = (equipo_local, equipo_visitante)

    # ✅ Si la predicción ya existe, usarla
    if clave_partido in predicciones_guardadas:
        prob_max, resultado_max, resultado_html, estadisticas_html, tabla_historial_html = predicciones_guardadas[clave_partido]
    else:
        # ✅ Generar la predicción solo si no existe aún
        prob_max = np.random.uniform(40, 60)
        resultado_max = "Victoria Local" if prob_max > 50 else "Victoria Visitante"
        color_resultado = "green" if prob_max > 50 else "red"
    enfrentamientos = df[
        ((df["Equipo_Local"] == equipo_local) & (df["Equipo_Visitante"] == equipo_visitante)) |
        ((df["Equipo_Local"] == equipo_visitante) & (df["Equipo_Visitante"] == equipo_local))
    ].sort_values(by="Fecha", ascending=False).head(10)

     # ✅ Verificar si hay enfrentamientos previos
    if enfrentamientos.empty:
        print(f"⚠️ No hay enfrentamientos previos entre {equipo_local} y {equipo_visitante}.")
    
    # Retornar valores vacíos para evitar el error de Gradio
        return (
        f"<p style='color:red;'><b>⚠️ No hay datos suficientes para predecir este partido.</b></p>",
        "",
        "<p style='color:red;'>No hay historial de enfrentamientos.</p>"
    )

        # ✅ Calcular promedio de goles en los enfrentamientos
    goles_equipo_A = enfrentamientos.apply(
        lambda row: row["Goles_Local"] if row["Equipo_Local"] == equipo_local  else row["Goles_Visitante"], axis=1
    )
    goles_equipo_B = enfrentamientos.apply(
        lambda row: row["Goles_Local"] if row["Equipo_Local"] == equipo_visitante else row["Goles_Visitante"], axis=1        
    )
    promedio_goles_equipo_A = goles_equipo_A.mean() if not goles_equipo_A.empty else 0
    promedio_goles_equipo_B = goles_equipo_B.mean() if not goles_equipo_B.empty else 0

    
 

    ultimos_10_local = df[df["Equipo_Local"] == equipo_local].sort_values(by="Fecha", ascending=False).head(10)
    ultimos_10_visitante = df[df["Equipo_Visitante"] == equipo_visitante].sort_values(by="Fecha", ascending=False).head(10)

    prom_goles_local = ultimos_10_local["Goles_Local"].mean()
    prom_tiros_local = ultimos_10_local["Tiros_Puerta_Local"].mean()
    prom_corners_local = ultimos_10_local["Corners_Local"].mean()

    prom_goles_visitante = ultimos_10_visitante["Goles_Visitante"].mean()        
    prom_tiros_visitante = ultimos_10_visitante["Tiros_Puerta_Visitante"].mean()
    prom_corners_visitante = ultimos_10_visitante["Corners_Visitante"].mean()


     # ✅ Calcular la efectividad de gol (% de tiros que terminan en gol)
    efectividad_local = ( prom_goles_local / prom_tiros_local * 100) if prom_tiros_local > 0 else 0
    efectividad_visitante = (prom_goles_visitante / prom_tiros_visitante * 100) if prom_tiros_visitante > 0 else 0

    resultado_max = "Victoria Local" if prob_max > 50 else "Victoria Visitante"
    color_resultado = "green" if prob_max > 50 else "red"

    resultado_html = f"""

        <div style='display:flex; align-items:center; justify-content:center;'>

            <div style='text-align:center;'>

            {obtener_escudo(equipo_local)}<br>{equipo_local}

            </div>

            <div style='margin:0 20px;color:{color_resultado};font-size:20px;'>

            <b>{resultado_max}: {prob_max:.2f}%</b>

            </div>

            <div style='text-align:center;'>

            {obtener_escudo(equipo_visitante)}<br>{equipo_visitante}

            </div>

    </div>

    """

    estadisticas_html = f"""

        <div style='padding:10px;'>

            <p><b>🏟️ Estadio:</b> {estadios[equipo_local]['estadio']}</p>

            <p><b>📊 Capacidad:</b> {estadios[equipo_local]['capacidad']} espectadores</p>

            <hr style='width:60%;text-align:left;margin-left:0;'>

            ⚽ <b>Promedio Goles Últimos 10 Partidos entre ellos:</b> {promedio_goles_equipo_A:.2f} | {promedio_goles_equipo_B:.2f}<br>

            🎯 <b>Promedio Tiros a Puerta (Últimos 10 Partidos como Local/Visitante)</b> {prom_tiros_local:.2f} | {prom_tiros_visitante:.2f}<br>

            🏳️ <b>Promodio Corners (Últimos 10 Partidos como Local/Visitante:</b> {prom_corners_local:.2f} | {prom_corners_visitante:.2f}<br>

            🎯 <b>Efectividad Gol(Últimos 10 Partidos como Local/Visitante)</b> {efectividad_local:.2f}% | {efectividad_visitante:.2f}%

        

        """

    enfrentamientos["Resultado"] = enfrentamientos.apply(
        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>",
        axis=1
    )

    tabla_historial_html = enfrentamientos[['Fecha','Equipo_Local','Resultado','Equipo_Visitante']].rename(
        columns={"Equipo_Local": "Local", "Equipo_Visitante": "Visitante"}
       ).to_html(index=False, escape=False)

    # ✅ Guardar la predicción en el diccionario para no cambiar en el futuro
    predicciones_guardadas[clave_partido] = (prob_max, resultado_max, resultado_html, estadisticas_html, tabla_historial_html)

    return resultado_html, estadisticas_html, tabla_historial_html


# Interfaz Gradio corregida completamente
with gr.Blocks() as app:
    gr.Markdown("## ⚽ Predicción de Partidos Premier League")

    equipos = list(estadios.keys())

    with gr.Row():
        with gr.Column(scale=1):
            equipo_local = gr.Dropdown(label="Local", choices=equipos, value=equipos[0])
            equipo_visitante = gr.Dropdown(label="Visitante", choices=[e for e in equipos if e != equipos[0]])
            boton_predecir = gr.Button("Predecir Resultado")

        resultado_html = gr.HTML()

    with gr.Row():
        estadisticas_html = gr.HTML()
        tabla_historial_html = gr.HTML()

    def actualizar_visitante(equipo_local):
        return gr.update(choices=[e for e in equipos if e != equipo_local])

    equipo_local.change(
        actualizar_visitante,
        inputs=equipo_local,
        outputs=equipo_visitante
    )

    boton_predecir.click(
        predecir,
        inputs=[equipo_local, equipo_visitante],
        outputs=[resultado_html, estadisticas_html, tabla_historial_html]
    )

app.launch(debug=True)


# In[ ]:


## Ejecuta el notebook como un script
import os
os.system("jupyter nbconvert --to script --execute app.ipynb")


# In[ ]: