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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException, File, UploadFile
|
| 2 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
+
from pydantic import BaseModel
|
| 4 |
+
from typing import List
|
| 5 |
+
import uvicorn
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
from .model_utils import model, _get_mock_raisons
|
| 9 |
+
import pandas as pd
|
| 10 |
+
|
| 11 |
+
app = FastAPI(title="Pro Grid Analyzer API", version="1.0.0")
|
| 12 |
+
|
| 13 |
+
# CORS pour l'astro-frontend
|
| 14 |
+
app.add_middleware(
|
| 15 |
+
CORSMiddleware,
|
| 16 |
+
allow_origins=["http://localhost:4321", "http://127.0.0.1:4321"], # Astro dev server
|
| 17 |
+
allow_credentials=True,
|
| 18 |
+
allow_methods=["*"],
|
| 19 |
+
allow_headers=["*"],
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
# Modèles Pydantic
|
| 23 |
+
class PredictionResponse(BaseModel):
|
| 24 |
+
Nom: str
|
| 25 |
+
prediction: float
|
| 26 |
+
confiance: float
|
| 27 |
+
raisons: List[str]
|
| 28 |
+
|
| 29 |
+
@app.get("/")
|
| 30 |
+
async def root():
|
| 31 |
+
return {"message": "Pro Grid Analyzer API"}
|
| 32 |
+
|
| 33 |
+
@app.get("/health")
|
| 34 |
+
async def health_check():
|
| 35 |
+
return {"status": "ok", "model_loaded": True}
|
| 36 |
+
|
| 37 |
+
@app.get("/api/test")
|
| 38 |
+
async def test_endpoint():
|
| 39 |
+
return {"message": "API is working"}
|
| 40 |
+
|
| 41 |
+
@app.post("/api/upload")
|
| 42 |
+
async def upload_tournaments(file: UploadFile = File(...)):
|
| 43 |
+
try:
|
| 44 |
+
# Lire le contenu du fichier
|
| 45 |
+
content = await file.read()
|
| 46 |
+
content_str = content.decode('utf-8')
|
| 47 |
+
|
| 48 |
+
# Parser le CSV
|
| 49 |
+
import csv
|
| 50 |
+
from io import StringIO
|
| 51 |
+
|
| 52 |
+
tournaments = []
|
| 53 |
+
csv_reader = csv.DictReader(StringIO(content_str))
|
| 54 |
+
|
| 55 |
+
for row in csv_reader:
|
| 56 |
+
# Mapper les colonnes CSV vers notre format
|
| 57 |
+
tournament = {
|
| 58 |
+
"Nom": row.get("Nom", row.get("name", "Tournoi")),
|
| 59 |
+
"Mise": float(row.get("Mise", row.get("buyIn", 0))),
|
| 60 |
+
"Participants": int(row.get("Participants", row.get("players", 0))),
|
| 61 |
+
"Date :": row.get("Date", row.get("startTime", "")),
|
| 62 |
+
"Rake": float(row.get("Rake", 0)),
|
| 63 |
+
"Compétence": float(row.get("Compétence", 70)),
|
| 64 |
+
"Compétence moyenne": float(row.get("Compétence moyenne", 65)),
|
| 65 |
+
"Nb_jeux": int(row.get("Nb_jeux", 50)),
|
| 66 |
+
"Type": row.get("Type", row.get("type", "mtt")),
|
| 67 |
+
"Prix": float(row.get("Prix", row.get("prizePool", 0)))
|
| 68 |
+
}
|
| 69 |
+
tournaments.append(tournament)
|
| 70 |
+
|
| 71 |
+
return tournaments
|
| 72 |
+
except Exception as e:
|
| 73 |
+
raise HTTPException(status_code=500, detail=f"Erreur upload: {str(e)}")
|
| 74 |
+
|
| 75 |
+
@app.post("/api/analyze")
|
| 76 |
+
async def analyze_file(file: UploadFile = File(...)):
|
| 77 |
+
try:
|
| 78 |
+
print(f"Fichier reçu: {file.filename}")
|
| 79 |
+
|
| 80 |
+
# Parser le CSV
|
| 81 |
+
content = await file.read()
|
| 82 |
+
content_str = content.decode('utf-8')
|
| 83 |
+
print(f"Contenu CSV: {content_str[:200]}...")
|
| 84 |
+
|
| 85 |
+
import csv
|
| 86 |
+
from io import StringIO
|
| 87 |
+
|
| 88 |
+
tournaments = []
|
| 89 |
+
csv_reader = csv.DictReader(StringIO(content_str))
|
| 90 |
+
|
| 91 |
+
for row in csv_reader:
|
| 92 |
+
# Nettoie les espaces autour des clés
|
| 93 |
+
row = {k.strip(): v for k, v in row.items()}
|
| 94 |
+
print(f"Ligne CSV: {row}")
|
| 95 |
+
tournament = {
|
| 96 |
+
"Nom": row.get("Nom", "Tournoi"),
|
| 97 |
+
"Nom_id": row.get("Nom du jeu", ""),
|
| 98 |
+
"Mise": safe_float(row.get("Mise", 0)),
|
| 99 |
+
"Participants": safe_int(row.get("Participants", 0)),
|
| 100 |
+
"Date :": row.get("Date :", ""),
|
| 101 |
+
"Rake": safe_float(row.get("Rake", 0)),
|
| 102 |
+
"Vitesse": row.get("Vitesse", "Normal"),
|
| 103 |
+
"Structure": row.get("Structure", "standard"),
|
| 104 |
+
"Prix": safe_float(row.get("Prix", 0)),
|
| 105 |
+
"Résultat": safe_float(row.get("Résultat", 0)),
|
| 106 |
+
"Joueur": row.get("Joueur", "user"),
|
| 107 |
+
"Compétence": 70,
|
| 108 |
+
"Compétence moyenne": 65,
|
| 109 |
+
"Nb_jeux": 50,
|
| 110 |
+
"Type": "mtt"
|
| 111 |
+
}
|
| 112 |
+
tournaments.append(tournament)
|
| 113 |
+
|
| 114 |
+
# Créer DataFrame et ajouter colonnes manquantes
|
| 115 |
+
df = pd.DataFrame(tournaments)
|
| 116 |
+
print(f"DataFrame créé avec {len(df)} lignes et colonnes: {df.columns.tolist()}")
|
| 117 |
+
|
| 118 |
+
if "Compétence" not in df.columns:
|
| 119 |
+
df["Compétence"] = 70
|
| 120 |
+
if "Compétence moyenne" not in df.columns:
|
| 121 |
+
df["Compétence moyenne"] = 65
|
| 122 |
+
if "Rake" not in df.columns:
|
| 123 |
+
df["Rake"] = 0
|
| 124 |
+
if "Nb_jeux" not in df.columns:
|
| 125 |
+
df["Nb_jeux"] = 50
|
| 126 |
+
if "Vitesse" not in df.columns:
|
| 127 |
+
df["Vitesse"] = "normal"
|
| 128 |
+
if "Résultat" not in df.columns:
|
| 129 |
+
df["Résultat"] = 0
|
| 130 |
+
if "Joueur" not in df.columns:
|
| 131 |
+
df["Joueur"] = "user"
|
| 132 |
+
if "Structure" not in df.columns:
|
| 133 |
+
df["Structure"] = "standard"
|
| 134 |
+
|
| 135 |
+
# Utiliser des valeurs par défaut pour ABI et ROI
|
| 136 |
+
abi_default = 50
|
| 137 |
+
roi_default = 15
|
| 138 |
+
|
| 139 |
+
# Créer des features simples pour le modèle
|
| 140 |
+
df["ABI"] = abi_default
|
| 141 |
+
df["ROI_total"] = roi_default
|
| 142 |
+
|
| 143 |
+
# Ajouter les colonnes manquantes avec des valeurs par défaut
|
| 144 |
+
required_columns = [
|
| 145 |
+
'Participants', 'Mise', 'Rake', 'Compétence', 'ABI', 'ROI_total',
|
| 146 |
+
'Compétence moyenne', 'BuyIn_gap', 'Est_turbo', 'is_KO',
|
| 147 |
+
'Difficulte_relative', 'Field_ratio', 'Ratio_buyin_vs_ABI', 'ROI_sur_structure',
|
| 148 |
+
'Heure_matin', 'Heure_aprem', 'Heure_soir', 'Heure_nuit'
|
| 149 |
+
]
|
| 150 |
+
|
| 151 |
+
# Calculer les features manquantes avec gestion des erreurs
|
| 152 |
+
df["BuyIn_gap"] = df["Mise"] - df["ABI"]
|
| 153 |
+
df["Difficulte_relative"] = df["Compétence"] - df["Compétence moyenne"]
|
| 154 |
+
|
| 155 |
+
# Éviter division par zéro
|
| 156 |
+
df["Field_ratio"] = df["Nb_jeux"] / df["Participants"].replace(0, 1)
|
| 157 |
+
df["Ratio_buyin_vs_ABI"] = df["Mise"] / df["ABI"].replace(0, 1)
|
| 158 |
+
|
| 159 |
+
# Remplacer inf et -inf par des valeurs finies
|
| 160 |
+
df = df.replace([np.inf, -np.inf], np.nan)
|
| 161 |
+
df = df.fillna(0)
|
| 162 |
+
|
| 163 |
+
df["ROI_sur_structure"] = 0 # Valeur par défaut
|
| 164 |
+
df["Est_turbo"] = 0 # Valeur par défaut
|
| 165 |
+
df["is_KO"] = 0 # Valeur par défaut
|
| 166 |
+
|
| 167 |
+
# Colonnes horaires
|
| 168 |
+
df["Heure_matin"] = 0
|
| 169 |
+
df["Heure_aprem"] = 0
|
| 170 |
+
df["Heure_soir"] = 0
|
| 171 |
+
df["Heure_nuit"] = 0
|
| 172 |
+
|
| 173 |
+
# S'assurer que toutes les colonnes sont présentes
|
| 174 |
+
for col in required_columns:
|
| 175 |
+
if col not in df.columns:
|
| 176 |
+
df[col] = 0
|
| 177 |
+
|
| 178 |
+
# Prédiction
|
| 179 |
+
print(f"Colonnes finales: {df.columns.tolist()}")
|
| 180 |
+
features_df = df[required_columns]
|
| 181 |
+
print(f"Features pour modèle: {features_df.shape}")
|
| 182 |
+
print(f"Types de données: {features_df.dtypes}")
|
| 183 |
+
|
| 184 |
+
# Vérifier et nettoyer les données avant prédiction
|
| 185 |
+
print(f"Valeurs min/max: {features_df.min()}")
|
| 186 |
+
print(f"Valeurs max: {features_df.max()}")
|
| 187 |
+
|
| 188 |
+
# Convertir en float32 et remplacer les valeurs problématiques
|
| 189 |
+
features_df = features_df.astype('float32')
|
| 190 |
+
features_df = features_df.replace([np.inf, -np.inf], 0)
|
| 191 |
+
features_df = features_df.fillna(0)
|
| 192 |
+
|
| 193 |
+
try:
|
| 194 |
+
print("Début de la prédiction...")
|
| 195 |
+
# Utilise predict_proba pour la proba d'être profitable
|
| 196 |
+
if hasattr(model, 'predict_proba'):
|
| 197 |
+
probas = model.predict_proba(features_df)[:, 1]
|
| 198 |
+
else:
|
| 199 |
+
probas = model.predict(features_df) # fallback
|
| 200 |
+
features_df["proba_profitable"] = probas
|
| 201 |
+
|
| 202 |
+
# Raison mock: feature la plus importante (optionnel)
|
| 203 |
+
importances = getattr(model, 'feature_importances_', None)
|
| 204 |
+
if importances is not None:
|
| 205 |
+
main_feature = features_df.columns[np.argmax(importances)]
|
| 206 |
+
else:
|
| 207 |
+
main_feature = "Profil global"
|
| 208 |
+
|
| 209 |
+
features_df["raison"] = features_df.apply(get_reason, axis=1)
|
| 210 |
+
|
| 211 |
+
# Après avoir calculé proba_profitable et raison
|
| 212 |
+
features_df["Nom"] = df["Nom"]
|
| 213 |
+
features_df["Mise"] = df["Mise"]
|
| 214 |
+
features_df["Rake"] = df["Rake"]
|
| 215 |
+
features_df["Participants"] = df["Participants"]
|
| 216 |
+
|
| 217 |
+
# Grouper par Nom pour éviter les doublons
|
| 218 |
+
grouped = features_df.groupby("Nom").agg({
|
| 219 |
+
"Mise": "mean",
|
| 220 |
+
"Rake": "mean",
|
| 221 |
+
"Participants": lambda x: round(x.mean()),
|
| 222 |
+
"proba_profitable": "max",
|
| 223 |
+
"raison": "first"
|
| 224 |
+
}).reset_index()
|
| 225 |
+
|
| 226 |
+
# Trie et prend les 5 meilleurs
|
| 227 |
+
top_results = grouped.sort_values("proba_profitable", ascending=False).head(5)
|
| 228 |
+
|
| 229 |
+
results = top_results[["Nom", "Mise", "Rake", "Participants", "proba_profitable", "raison"]].to_dict(orient="records")
|
| 230 |
+
|
| 231 |
+
summary = {
|
| 232 |
+
"nb_recommandees": int((features_df["proba_profitable"] > 0.5).sum()),
|
| 233 |
+
"max_proba": float(features_df["proba_profitable"].max()),
|
| 234 |
+
"min_proba": float(features_df["proba_profitable"].min()),
|
| 235 |
+
"total_tournois": int(len(features_df))
|
| 236 |
+
}
|
| 237 |
+
return {"results": results, "summary": summary}
|
| 238 |
+
|
| 239 |
+
except Exception as e:
|
| 240 |
+
print(f"Erreur lors de la prédiction: {str(e)}")
|
| 241 |
+
raise e
|
| 242 |
+
|
| 243 |
+
except Exception as e:
|
| 244 |
+
raise HTTPException(status_code=500, detail=f"Erreur analyse: {str(e)}")
|
| 245 |
+
|
| 246 |
+
def safe_float(val):
|
| 247 |
+
try:
|
| 248 |
+
return float(val)
|
| 249 |
+
except (ValueError, TypeError):
|
| 250 |
+
return 0.0
|
| 251 |
+
|
| 252 |
+
def safe_int(val):
|
| 253 |
+
try:
|
| 254 |
+
return int(float(val))
|
| 255 |
+
except (ValueError, TypeError):
|
| 256 |
+
return 0
|
| 257 |
+
|
| 258 |
+
def get_reason(row):
|
| 259 |
+
reasons = []
|
| 260 |
+
if row['Participants'] > 10000:
|
| 261 |
+
reasons.append("Gros field, variance élevée")
|
| 262 |
+
if row['Mise'] > 50:
|
| 263 |
+
reasons.append("Buy-in élevé, attention à la gestion de bankroll")
|
| 264 |
+
if row['Est_turbo'] == 1:
|
| 265 |
+
reasons.append("Structure turbo, favorise l’agressivité")
|
| 266 |
+
if row['is_KO'] == 1:
|
| 267 |
+
reasons.append("Format KO, adapté à ton style")
|
| 268 |
+
if not reasons:
|
| 269 |
+
reasons.append("Profil global adapté")
|
| 270 |
+
return ', '.join(reasons)
|
| 271 |
+
|
| 272 |
+
if __name__ == "__main__":
|
| 273 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|
model.pkl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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import joblib
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import numpy as np
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
# ✅ Chargement unique du modèle v4
|
| 7 |
+
import os
|
| 8 |
+
model_path = os.path.join(os.path.dirname(__file__), "model.pkl")
|
| 9 |
+
model = joblib.load(model_path)
|
| 10 |
+
|
| 11 |
+
# 🎯 Fonction principale de prédiction
|
| 12 |
+
def predict_with_model(profile, tournois):
|
| 13 |
+
# Convertir les tournois en DataFrame
|
| 14 |
+
df = pd.DataFrame(tournois)
|
| 15 |
+
|
| 16 |
+
# Renommer les colonnes pour correspondre au modèle
|
| 17 |
+
df = df.rename(columns={
|
| 18 |
+
"Compétence_moyenne": "Compétence moyenne"
|
| 19 |
+
})
|
| 20 |
+
|
| 21 |
+
# Sauvegarder les noms pour le retour
|
| 22 |
+
noms_tournois = df["Nom"].copy()
|
| 23 |
+
|
| 24 |
+
# Supprimer la colonne Nom qui n'est pas une feature du modèle
|
| 25 |
+
df = df.drop(columns=["Nom"])
|
| 26 |
+
|
| 27 |
+
# Réorganiser les colonnes dans l'ordre exact du modèle d'entraînement
|
| 28 |
+
colonnes_attendues = [
|
| 29 |
+
"Participants", "Mise", "Rake", "Compétence",
|
| 30 |
+
"Compétence moyenne", "BuyIn_gap", "Est_turbo", "is_KO",
|
| 31 |
+
"Difficulte_relative", "Field_ratio", "Ratio_buyin_vs_ABI",
|
| 32 |
+
"ROI_sur_structure", "Heure_matin", "Heure_aprem", "Heure_soir", "Heure_nuit"
|
| 33 |
+
]
|
| 34 |
+
|
| 35 |
+
# Debug: afficher les colonnes pour vérifier
|
| 36 |
+
print("Colonnes avant prédiction:", df.columns.tolist())
|
| 37 |
+
|
| 38 |
+
# Injecter les features du profil joueur (fixes)
|
| 39 |
+
df["ABI"] = profile["ABI"]
|
| 40 |
+
df["ROI_total"] = profile["ROI_total"]
|
| 41 |
+
|
| 42 |
+
# Maintenant réorganiser
|
| 43 |
+
df = df[colonnes_attendues]
|
| 44 |
+
|
| 45 |
+
# Initialiser les colonnes horaires à 0
|
| 46 |
+
for h in ["Heure_matin", "Heure_aprem", "Heure_soir", "Heure_nuit"]:
|
| 47 |
+
df[h] = 0
|
| 48 |
+
|
| 49 |
+
# Activer les bonnes heures selon le profil
|
| 50 |
+
for h in profile["heures"]:
|
| 51 |
+
if h == "matin":
|
| 52 |
+
df["Heure_matin"] = 1
|
| 53 |
+
elif h == "aprem":
|
| 54 |
+
df["Heure_aprem"] = 1
|
| 55 |
+
elif h == "soir":
|
| 56 |
+
df["Heure_soir"] = 1
|
| 57 |
+
elif h == "nuit":
|
| 58 |
+
df["Heure_nuit"] = 1
|
| 59 |
+
|
| 60 |
+
# ⚙️ Prédiction
|
| 61 |
+
print("Colonnes finales:", df.columns.tolist())
|
| 62 |
+
df["prediction"] = model.predict(df)
|
| 63 |
+
|
| 64 |
+
# 🔍 Mock confiance et raisonnement pour affichage
|
| 65 |
+
df["confiance"] = 0.75 # valeur fixe temporaire
|
| 66 |
+
df["raisons"] = df.apply(lambda row: _get_mock_raisons(row), axis=1)
|
| 67 |
+
|
| 68 |
+
# Remettre les noms des tournois
|
| 69 |
+
df["Nom"] = noms_tournois
|
| 70 |
+
|
| 71 |
+
# Grouper par Nom (ou Nom_id si tu veux être plus strict)
|
| 72 |
+
grouped = df.groupby("Nom").agg({
|
| 73 |
+
"Mise": "mean",
|
| 74 |
+
"Rake": "mean",
|
| 75 |
+
"Participants": "mean",
|
| 76 |
+
"prediction": "max", # ou "mean" si tu préfères
|
| 77 |
+
"raisons": "first" # ou une logique custom si tu veux
|
| 78 |
+
}).reset_index()
|
| 79 |
+
|
| 80 |
+
# Trie et prend les 5 meilleurs
|
| 81 |
+
top_results = grouped.sort_values("prediction", ascending=False).head(5)
|
| 82 |
+
|
| 83 |
+
results = top_results[["Nom", "Mise", "Rake", "Participants", "prediction", "raisons"]].to_dict(orient="records")
|
| 84 |
+
|
| 85 |
+
return results
|
| 86 |
+
|
| 87 |
+
# --- FEATURE ENGINEERING ---
|
| 88 |
+
def create_base_features(df):
|
| 89 |
+
df["is_profitable"] = (df["Résultat"] > 0).astype(int)
|
| 90 |
+
df["Gain_net"] = df["Résultat"] - df["Rake"]
|
| 91 |
+
df["Investissement_tournoi"] = df["Mise"] + df["Rake"]
|
| 92 |
+
df["Est_turbo"] = df["Vitesse"].str.lower().str.contains("turbo").astype(int)
|
| 93 |
+
tournoi_col = None
|
| 94 |
+
for col in df.columns:
|
| 95 |
+
if 'tournoi' in col.lower() and 'catalogue' in col.lower():
|
| 96 |
+
tournoi_col = col
|
| 97 |
+
break
|
| 98 |
+
if tournoi_col:
|
| 99 |
+
df["is_KO"] = df[tournoi_col].str.contains("KO|Bounty|PKO", case=False, na=False).astype(int)
|
| 100 |
+
else:
|
| 101 |
+
df["is_KO"] = df["Nom du jeu"].str.contains("KO|Bounty|PKO", case=False, na=False).astype(int)
|
| 102 |
+
return df
|
| 103 |
+
|
| 104 |
+
def create_contextual_features(df):
|
| 105 |
+
df["BuyIn_gap"] = df["Investissement_tournoi"] - df["ABI"]
|
| 106 |
+
df["Difficulte_relative"] = df["Compétence"] - df["Compétence moyenne"]
|
| 107 |
+
df["Field_ratio"] = df["Nb_jeux"] / df["Participants"]
|
| 108 |
+
df["Ratio_buyin_vs_ABI"] = df["Investissement_tournoi"] / df["ABI"]
|
| 109 |
+
return df
|
| 110 |
+
|
| 111 |
+
def create_performance_features(df):
|
| 112 |
+
profit_par_structure = df.groupby(["Joueur", "Structure"])["Gain_net"].transform("sum")
|
| 113 |
+
invest_par_structure = df.groupby(["Joueur", "Structure"])["Investissement_tournoi"].transform("sum")
|
| 114 |
+
df["ROI_sur_structure"] = (profit_par_structure / invest_par_structure).replace([np.inf, -np.inf], np.nan)
|
| 115 |
+
return df
|
| 116 |
+
|
| 117 |
+
def create_time_features(df):
|
| 118 |
+
df["Heure"] = pd.to_datetime(df["Date :"], errors="coerce").dt.hour
|
| 119 |
+
def horaire_bin(h):
|
| 120 |
+
if pd.isna(h): return "inconnu"
|
| 121 |
+
if 6 <= h < 12: return "matin"
|
| 122 |
+
elif 12 <= h < 18: return "aprem"
|
| 123 |
+
elif 18 <= h < 24: return "soir"
|
| 124 |
+
else: return "nuit"
|
| 125 |
+
df["Heure_bin"] = df["Heure"].apply(horaire_bin)
|
| 126 |
+
df = pd.get_dummies(df, columns=['Heure_bin'], prefix='Heure')
|
| 127 |
+
return df
|
| 128 |
+
|
| 129 |
+
# --- PIPELINE POUR L'API ---
|
| 130 |
+
def raw_csv_to_features(df_raw, abi, roi_total):
|
| 131 |
+
df = df_raw.copy()
|
| 132 |
+
df["ABI"] = abi
|
| 133 |
+
df["ROI_total"] = roi_total
|
| 134 |
+
df = create_base_features(df)
|
| 135 |
+
df = create_contextual_features(df)
|
| 136 |
+
df = create_performance_features(df)
|
| 137 |
+
df = create_time_features(df)
|
| 138 |
+
# Imputation des valeurs manquantes
|
| 139 |
+
df['Compétence moyenne'].fillna(df['Compétence moyenne'].mean(), inplace=True)
|
| 140 |
+
df['Difficulte_relative'].fillna(0, inplace=True)
|
| 141 |
+
df['ROI_sur_structure'].fillna(0, inplace=True)
|
| 142 |
+
df.replace([np.inf, -np.inf], np.nan, inplace=True)
|
| 143 |
+
df.fillna(0, inplace=True)
|
| 144 |
+
# Colonnes finales dans l'ordre du modèle
|
| 145 |
+
colonnes_attendues = [
|
| 146 |
+
'Participants', 'Mise', 'Rake', 'Compétence', 'ABI', 'ROI_total',
|
| 147 |
+
'Compétence moyenne', 'BuyIn_gap', 'Est_turbo', 'is_KO',
|
| 148 |
+
'Difficulte_relative', 'Field_ratio', 'Ratio_buyin_vs_ABI', 'ROI_sur_structure',
|
| 149 |
+
'Heure_matin', 'Heure_aprem', 'Heure_soir', 'Heure_nuit'
|
| 150 |
+
]
|
| 151 |
+
# Ajoute les colonnes horaires manquantes si besoin
|
| 152 |
+
for h in ['Heure_matin', 'Heure_aprem', 'Heure_soir', 'Heure_nuit']:
|
| 153 |
+
if h not in df.columns:
|
| 154 |
+
df[h] = 0
|
| 155 |
+
return df[colonnes_attendues]
|
| 156 |
+
|
| 157 |
+
# 🧠 Raisons fictives selon features
|
| 158 |
+
def _get_mock_raisons(row):
|
| 159 |
+
raisons = []
|
| 160 |
+
if row.get("is_KO") == 1:
|
| 161 |
+
raisons.append("KO apprécié par le modèle")
|
| 162 |
+
if row.get("Est_turbo") == 1:
|
| 163 |
+
raisons.append("Structure turbo adaptée")
|
| 164 |
+
if row.get("Participants", 0) < 500:
|
| 165 |
+
raisons.append("Petit field recommandé")
|
| 166 |
+
return raisons[:2] or ["Profil adapté"]
|
requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi==0.104.1
|
| 2 |
+
uvicorn[standard]==0.24.0
|
| 3 |
+
pandas==2.1.3
|
| 4 |
+
scikit-learn==1.3.2
|
| 5 |
+
joblib==1.3.2
|
| 6 |
+
pydantic==2.5.0
|
| 7 |
+
python-multipart==0.0.6
|