File size: 5,385 Bytes
7bdf0d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Hugging Face Space for EPL Predictions
Deploy this as a Gradio app on HF Spaces
"""
import gradio as gr
import numpy as np
import pandas as pd
from model_predictor import EPLPredictor
import json

# Initialize predictor
print("Loading models...")
predictor = EPLPredictor(use_local=False)  # Will download from HF
print("Models loaded!")

def predict_match(home_team, away_team, home_odds, draw_odds, away_odds):
    """Predict match outcome"""
    try:
        # Create odds dict
        best_odds = {
            'H': {'odds': home_odds},
            'D': {'odds': draw_odds},
            'A': {'odds': away_odds}
        }

        # Get predictions
        result = predictor.predict(
            home_team=home_team,
            away_team=away_team,
            best_odds=best_odds
        )

        # Format output
        output = f"""
## Match Prediction: {home_team} vs {away_team}

### Ensemble Probabilities:
- **Home Win**: {result['ensemble']['H']:.1%}
- **Draw**: {result['ensemble']['D']:.1%}
- **Away Win**: {result['ensemble']['A']:.1%}
- **Over 2.5 Goals**: {result['ensemble']['over25']:.1%}
- **BTTS**: {result['ensemble']['btts']:.1%}

### Expected Goals:
- {home_team}: {result['expected_goals']['home']:.2f}
- {away_team}: {result['expected_goals']['away']:.2f}

### Model Components:
**Poisson**: H:{result['poisson']['H']:.1%} D:{result['poisson']['D']:.1%} A:{result['poisson']['A']:.1%}
**XGBoost**: H:{result['xgboost']['H']:.1%} D:{result['xgboost']['D']:.1%} A:{result['xgboost']['A']:.1%}
        """

        # Check for value
        value_analysis = ""
        for market, prob in [('Home', result['ensemble']['H']),
                             ('Draw', result['ensemble']['D']),
                             ('Away', result['ensemble']['A'])]:
            if market == 'Home':
                odds = home_odds
            elif market == 'Draw':
                odds = draw_odds
            else:
                odds = away_odds

            value = predictor.calculate_value(prob, odds)
            if value['has_value']:
                value_analysis += f"\n⚡ **VALUE BET**: {market} @ {odds:.2f} (Edge: {value['edge']:.1f}%)"

        if value_analysis:
            output += f"\n### Value Bets Found:{value_analysis}"
        else:
            output += "\n### No value bets found at these odds"

        return output

    except Exception as e:
        return f"Error: {str(e)}"

def batch_predict(csv_text):
    """Predict multiple matches from CSV"""
    try:
        # Parse CSV
        lines = csv_text.strip().split('\n')
        results = []

        for line in lines[1:]:  # Skip header
            parts = line.split(',')
            if len(parts) >= 5:
                home, away = parts[0].strip(), parts[1].strip()
                h_odds, d_odds, a_odds = float(parts[2]), float(parts[3]), float(parts[4])

                pred = predict_match(home, away, h_odds, d_odds, a_odds)
                results.append(pred)

        return "\n---\n".join(results)
    except Exception as e:
        return f"Error processing CSV: {str(e)}"

# Create Gradio interface
with gr.Blocks(title="EPL Match Predictor") as app:
    gr.Markdown("""
    # ⚽ EPL Match Predictor

    Powered by ensemble models (Poisson + XGBoost) trained on EPL data.

    Models available at: [gnosisx/epl-ensemble-1x2](https://huggingface.co/gnosisx/epl-ensemble-1x2)
    """)

    with gr.Tab("Single Match"):
        with gr.Row():
            home_input = gr.Textbox(label="Home Team", value="Liverpool")
            away_input = gr.Textbox(label="Away Team", value="Everton")

        with gr.Row():
            home_odds_input = gr.Number(label="Home Odds", value=1.48)
            draw_odds_input = gr.Number(label="Draw Odds", value=5.0)
            away_odds_input = gr.Number(label="Away Odds", value=8.0)

        predict_btn = gr.Button("Predict", variant="primary")
        output = gr.Markdown()

        predict_btn.click(
            predict_match,
            inputs=[home_input, away_input, home_odds_input, draw_odds_input, away_odds_input],
            outputs=output
        )

    with gr.Tab("Batch Prediction"):
        gr.Markdown("Upload CSV with format: `Home,Away,HomeOdds,DrawOdds,AwayOdds`")

        csv_input = gr.Textbox(
            label="CSV Data",
            lines=10,
            value="Home,Away,H_Odds,D_Odds,A_Odds\nLiverpool,Everton,1.48,5.0,8.0\nArsenal,Chelsea,2.1,3.5,3.8\nMan City,Burnley,1.15,9.0,21.0"
        )

        batch_btn = gr.Button("Predict All", variant="primary")
        batch_output = gr.Markdown()

        batch_btn.click(
            batch_predict,
            inputs=csv_input,
            outputs=batch_output
        )

    with gr.Tab("API"):
        gr.Markdown("""
        ## API Endpoint

        You can also use this as an API:

        ```python
        import requests

        response = requests.post(
            "https://gnosisx-epl-predictor.hf.space/api/predict",
            json={
                "home_team": "Liverpool",
                "away_team": "Everton",
                "best_odds": {
                    "H": {"odds": 1.48},
                    "D": {"odds": 5.0},
                    "A": {"odds": 8.0}
                }
            }
        )
        print(response.json())
        ```
        """)

# Launch app
if __name__ == "__main__":
    app.launch()