Spaces:
Sleeping
Sleeping
backend commit
Browse files- app/main.py +7 -71
- requirements.txt +3 -3
app/main.py
CHANGED
|
@@ -4,7 +4,6 @@ import pandas as pd
|
|
| 4 |
import uvicorn
|
| 5 |
import plotly.graph_objects as go
|
| 6 |
import logging
|
| 7 |
-
import joblib
|
| 8 |
import numpy as np
|
| 9 |
import os
|
| 10 |
import json
|
|
@@ -76,23 +75,8 @@ goals_df['y_coord'] = np.random.uniform(20, 80, len(goals_df)).round()
|
|
| 76 |
teams = set(matches_df['home_team'].unique()).union(set(matches_df['away_team'].unique()))
|
| 77 |
players = sorted([str(scorer) for scorer in goals_df['scorer'].dropna().unique() if pd.notna(scorer)])
|
| 78 |
|
| 79 |
-
#
|
| 80 |
-
|
| 81 |
-
logger.info("Loading logistic_regression_model.pkl")
|
| 82 |
-
logistic_model = joblib.load('model/logistic_regression_model.pkl')
|
| 83 |
-
logger.info("Loading linear_regression_team1_goals.pkl")
|
| 84 |
-
linear_model_team1 = joblib.load('model/linear_regression_team1_goals.pkl')
|
| 85 |
-
logger.info("Loading linear_regression_team2_goals.pkl")
|
| 86 |
-
linear_model_team2 = joblib.load('model/linear_regression_team2_goals.pkl')
|
| 87 |
-
logger.info("Loading label_encoder.pkl")
|
| 88 |
-
le = joblib.load('model/label_encoder.pkl')
|
| 89 |
-
logger.info("Models loaded successfully.")
|
| 90 |
-
except FileNotFoundError as e:
|
| 91 |
-
logger.error(f"Model file not found: {e}")
|
| 92 |
-
raise HTTPException(status_code=500, detail="Trained model files not found.")
|
| 93 |
-
except Exception as e:
|
| 94 |
-
logger.error(f"Error loading models: {str(e)}")
|
| 95 |
-
raise HTTPException(status_code=500, detail=f"Model loading failed: {str(e)}")
|
| 96 |
|
| 97 |
def summarize_with_groq(text):
|
| 98 |
try:
|
|
@@ -179,7 +163,7 @@ def get_head_to_head_stats(team1, team2, num_matches=5):
|
|
| 179 |
|
| 180 |
if matches.empty:
|
| 181 |
return {"total_matches": 0, f"{team1}_wins": 0, f"{team2}_wins": 0, "draws": 0,
|
| 182 |
-
f"{team1}_goals": 0, f"{team2}
|
| 183 |
"last_matches": [], "chart": None}
|
| 184 |
|
| 185 |
total_matches = len(matches)
|
|
@@ -238,51 +222,13 @@ def get_player_stats(player_name):
|
|
| 238 |
return {"player_name": player_name, "country": player_team, "total_goals": total_goals}
|
| 239 |
|
| 240 |
def predict_match_outcome(team1, team2):
|
| 241 |
-
|
| 242 |
-
teams_sorted = sorted([team1, team2])
|
| 243 |
-
team1_encoded = le.transform([teams_sorted[0]])[0] if teams_sorted[0] in le.classes_ else -1
|
| 244 |
-
team2_encoded = le.transform([teams_sorted[1]])[0] if teams_sorted[1] in le.classes_ else -1
|
| 245 |
-
|
| 246 |
-
if team1_encoded == -1 or team2_encoded == -1:
|
| 247 |
-
raise ValueError("One or both teams not found in training data")
|
| 248 |
-
|
| 249 |
-
X_pred = [[team1_encoded, team2_encoded]]
|
| 250 |
-
|
| 251 |
-
probs = logistic_model.predict_proba(X_pred)[0]
|
| 252 |
-
|
| 253 |
-
if team1 < team2:
|
| 254 |
-
outcome_probs = {
|
| 255 |
-
"team1_win": round(probs[0] * 100, 2),
|
| 256 |
-
"team2_win": round(probs[2] * 100, 2),
|
| 257 |
-
"draw": round(probs[1] * 100, 2)
|
| 258 |
-
}
|
| 259 |
-
else:
|
| 260 |
-
outcome_probs = {
|
| 261 |
-
"team1_win": round(probs[2] * 100, 2),
|
| 262 |
-
"team2_win": round(probs[0] * 100, 2),
|
| 263 |
-
"draw": round(probs[1] * 100, 2)
|
| 264 |
-
}
|
| 265 |
-
|
| 266 |
-
if outcome_probs["team1_win"] > outcome_probs["team2_win"] and outcome_probs["team1_win"] >= outcome_probs["draw"]:
|
| 267 |
-
goals_pred = {"team1_goals": 2, "team2_goals": 1}
|
| 268 |
-
elif outcome_probs["team2_win"] > outcome_probs["team1_win"] and outcome_probs["team2_win"] >= outcome_probs["draw"]:
|
| 269 |
-
goals_pred = {"team1_goals": 1, "team2_goals": 2}
|
| 270 |
-
else:
|
| 271 |
-
goals_pred = {"team1_goals": 1, "team2_goals": 1}
|
| 272 |
-
|
| 273 |
-
return {
|
| 274 |
-
"outcome_probabilities": outcome_probs,
|
| 275 |
-
"predicted_goals": goals_pred
|
| 276 |
-
}
|
| 277 |
-
except Exception as e:
|
| 278 |
-
logger.error(f"Prediction error for {team1} vs {team2}: {str(e)}")
|
| 279 |
-
raise HTTPException(status_code=500, detail=f"Prediction error: {str(e)}")
|
| 280 |
|
| 281 |
@app.get("/")
|
| 282 |
async def home():
|
| 283 |
return {
|
| 284 |
"message": "Welcome to Football Prediction API",
|
| 285 |
-
"description": "This API provides football statistics, match predictions, and data visualizations",
|
| 286 |
"available_endpoints": {
|
| 287 |
"/teams": "List all teams",
|
| 288 |
"/players": "List all players",
|
|
@@ -290,7 +236,7 @@ async def home():
|
|
| 290 |
"/team/{team_name}": "Get team statistics",
|
| 291 |
"/head-to-head/{team1}/{team2}": "Get head-to-head statistics",
|
| 292 |
"/player/{player_name}": "Get player statistics",
|
| 293 |
-
"/predict/{team1}/{team2}": "Predict match outcome",
|
| 294 |
"/goal-spatial-heatmap/{team}": "Get goal distribution heatmap"
|
| 295 |
}
|
| 296 |
}
|
|
@@ -363,17 +309,7 @@ async def get_player_statistics(player_name: str, summarize: bool = False):
|
|
| 363 |
|
| 364 |
@app.get("/predict/{team1}/{team2}")
|
| 365 |
async def predict_match(team1: str, team2: str, summarize: bool = False):
|
| 366 |
-
|
| 367 |
-
raise HTTPException(status_code=404, detail="One or both teams not found")
|
| 368 |
-
predictions = predict_match_outcome(team1, team2)
|
| 369 |
-
response = {"team1": team1, "team2": team2, "predictions": predictions}
|
| 370 |
-
if summarize:
|
| 371 |
-
text = (f"Outcome Probabilities: {team1} Win: {predictions['outcome_probabilities']['team1_win']}%, "
|
| 372 |
-
f"{team2} Win: {predictions['outcome_probabilities']['team2_win']}%, Draw: {predictions['outcome_probabilities']['draw']}%\n"
|
| 373 |
-
f"Predicted Goals: {team1}: {predictions['predicted_goals']['team1_goals']}, {team2}: {predictions['predicted_goals']['team2_goals']}")
|
| 374 |
-
summary = summarize_with_groq(text)
|
| 375 |
-
response["summary"] = summary
|
| 376 |
-
return response
|
| 377 |
|
| 378 |
@app.get("/goal-spatial-heatmap/{team}")
|
| 379 |
async def get_goal_spatial_heatmap(team: str, start_year: int = 2000, end_year: int = 2023, summarize: bool = False):
|
|
|
|
| 4 |
import uvicorn
|
| 5 |
import plotly.graph_objects as go
|
| 6 |
import logging
|
|
|
|
| 7 |
import numpy as np
|
| 8 |
import os
|
| 9 |
import json
|
|
|
|
| 75 |
teams = set(matches_df['home_team'].unique()).union(set(matches_df['away_team'].unique()))
|
| 76 |
players = sorted([str(scorer) for scorer in goals_df['scorer'].dropna().unique() if pd.notna(scorer)])
|
| 77 |
|
| 78 |
+
# Skip model loading for now
|
| 79 |
+
logger.warning("Model loading skipped due to compatibility issues. Prediction endpoint disabled.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
|
| 81 |
def summarize_with_groq(text):
|
| 82 |
try:
|
|
|
|
| 163 |
|
| 164 |
if matches.empty:
|
| 165 |
return {"total_matches": 0, f"{team1}_wins": 0, f"{team2}_wins": 0, "draws": 0,
|
| 166 |
+
f"{team1}_goals": 0, f"{team2}_wins": 0, "goal_difference": "Even",
|
| 167 |
"last_matches": [], "chart": None}
|
| 168 |
|
| 169 |
total_matches = len(matches)
|
|
|
|
| 222 |
return {"player_name": player_name, "country": player_team, "total_goals": total_goals}
|
| 223 |
|
| 224 |
def predict_match_outcome(team1, team2):
|
| 225 |
+
raise HTTPException(status_code=503, detail="Prediction functionality is temporarily disabled due to model loading issues.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 226 |
|
| 227 |
@app.get("/")
|
| 228 |
async def home():
|
| 229 |
return {
|
| 230 |
"message": "Welcome to Football Prediction API",
|
| 231 |
+
"description": "This API provides football statistics, match predictions, and data visualizations. Note: Prediction endpoint is currently disabled.",
|
| 232 |
"available_endpoints": {
|
| 233 |
"/teams": "List all teams",
|
| 234 |
"/players": "List all players",
|
|
|
|
| 236 |
"/team/{team_name}": "Get team statistics",
|
| 237 |
"/head-to-head/{team1}/{team2}": "Get head-to-head statistics",
|
| 238 |
"/player/{player_name}": "Get player statistics",
|
| 239 |
+
"/predict/{team1}/{team2}": "Predict match outcome (currently disabled)",
|
| 240 |
"/goal-spatial-heatmap/{team}": "Get goal distribution heatmap"
|
| 241 |
}
|
| 242 |
}
|
|
|
|
| 309 |
|
| 310 |
@app.get("/predict/{team1}/{team2}")
|
| 311 |
async def predict_match(team1: str, team2: str, summarize: bool = False):
|
| 312 |
+
raise HTTPException(status_code=503, detail="Prediction functionality is temporarily disabled due to model loading issues.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 313 |
|
| 314 |
@app.get("/goal-spatial-heatmap/{team}")
|
| 315 |
async def get_goal_spatial_heatmap(team: str, start_year: int = 2000, end_year: int = 2023, summarize: bool = False):
|
requirements.txt
CHANGED
|
@@ -3,8 +3,8 @@ uvicorn==0.23.2
|
|
| 3 |
pandas==2.0.3
|
| 4 |
plotly==5.15.0
|
| 5 |
joblib==1.3.2
|
| 6 |
-
numpy==1.
|
| 7 |
-
groq==0.11.0
|
| 8 |
python-dotenv==1.0.0
|
| 9 |
-
httpx==0.27.0
|
| 10 |
scikit-learn==1.3.2
|
|
|
|
| 3 |
pandas==2.0.3
|
| 4 |
plotly==5.15.0
|
| 5 |
joblib==1.3.2
|
| 6 |
+
numpy==1.24.4 # Trying a version just before 1.25 restructuring
|
| 7 |
+
groq==0.11.0
|
| 8 |
python-dotenv==1.0.0
|
| 9 |
+
httpx==0.27.0
|
| 10 |
scikit-learn==1.3.2
|