Jimin Park commited on
Commit
5e39132
·
1 Parent(s): 284ad13

kermitting soon

Browse files
Files changed (2) hide show
  1. util/app.py +26 -13
  2. util/app_working_backup.py +343 -0
util/app.py CHANGED
@@ -32,28 +32,41 @@ CHAMPIONS = [
32
  "Xin Zhao", "Yasuo", "Yone", "Yorick", "Yuumi", "Zac", "Zed", "Zeri", "Ziggs", "Zilean", "Zoe", "Zyra"
33
  ]
34
 
 
 
 
 
 
 
 
 
35
  # Load model
36
  try:
37
  model_path = hf_hub_download(
38
  repo_id="ivwhy/champion-predictor-model",
39
  filename="champion_predictor.json"
40
  )
41
- model = xgb.Booster()
42
- model.load_model(model_path)
 
 
 
 
 
 
 
 
 
 
 
 
43
  except Exception as e:
44
  print(f"Error loading model: {e}")
45
  model = None
46
 
47
- try:
48
- label_encoder = joblib.load('util/label_encoder.joblib')
49
- print("Label encoder loaded successfully")
50
- except Exception as e:
51
- print(f"Error loading label encoder: {e}")
52
- label_encoder = None
53
-
54
  # Initialize champion name encoder
55
- champion_encoder = LabelEncoder()
56
- champion_encoder.fit(CHAMPIONS)
57
 
58
 
59
  #==================================== Functions =================================================
@@ -169,7 +182,7 @@ def predict_champion(player_opgg_url, *champions):
169
  # Map numeric ID to index in CHAMPIONS list
170
  # Since your label encoder seems to use champion IDs, we need to map these to list indices
171
  try:
172
- # Get the first prediction
173
  champion_id = int(decoded_numeric[0])
174
 
175
  # Print debug information
@@ -334,7 +347,7 @@ with gr.Blocks() as demo:
334
  )
335
 
336
  # Optional: Save the champion encoder for future use
337
- joblib.dump(champion_encoder, 'champion_encoder.joblib')
338
  # Enable queuing
339
  demo.launch(debug=True)
340
 
 
32
  "Xin Zhao", "Yasuo", "Yone", "Yorick", "Yuumi", "Zac", "Zed", "Zeri", "Ziggs", "Zilean", "Zoe", "Zyra"
33
  ]
34
 
35
+ try:
36
+ label_encoder = joblib.load('util/label_encoder.joblib')
37
+ n_classes = len(label_encoder.classes_)
38
+ print("Label encoder loaded successfully")
39
+ except Exception as e:
40
+ print(f"Error loading label encoder: {e}")
41
+ label_encoder = None
42
+
43
  # Load model
44
  try:
45
  model_path = hf_hub_download(
46
  repo_id="ivwhy/champion-predictor-model",
47
  filename="champion_predictor.json"
48
  )
49
+
50
+ # Initialize the model with proper parameters
51
+ model = xgb.XGBClassifier(
52
+ use_label_encoder=False,
53
+ objective='multi:softprob',
54
+ num_class=n_classes
55
+ )
56
+
57
+ # Load the model
58
+ model._Booster = xgb.Booster()
59
+ model._Booster.load_model(model_path)
60
+
61
+ # Set only n_classes_
62
+ model.n_classes_ = n_classes
63
  except Exception as e:
64
  print(f"Error loading model: {e}")
65
  model = None
66
 
 
 
 
 
 
 
 
67
  # Initialize champion name encoder
68
+ # champion_encoder = LabelEncoder()
69
+ # champion_encoder.fit(CHAMPIONS)
70
 
71
 
72
  #==================================== Functions =================================================
 
182
  # Map numeric ID to index in CHAMPIONS list
183
  # Since your label encoder seems to use champion IDs, we need to map these to list indices
184
  try:
185
+ # Get the first 3 prediction
186
  champion_id = int(decoded_numeric[0])
187
 
188
  # Print debug information
 
347
  )
348
 
349
  # Optional: Save the champion encoder for future use
350
+ #joblib.dump(champion_encoder, 'champion_encoder.joblib')
351
  # Enable queuing
352
  demo.launch(debug=True)
353
 
util/app_working_backup.py ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+ import gradio as gr
3
+ import xgboost as xgb
4
+ from xgboost import DMatrix
5
+ from huggingface_hub import hf_hub_download
6
+ from app_training_df_getter import create_app_user_training_df
7
+ import pandas as pd
8
+ from sklearn.model_selection import train_test_split
9
+ from sklearn.preprocessing import LabelEncoder
10
+ from helper import *
11
+ import joblib
12
+
13
+
14
+ # Define champion list for dropdowns
15
+ CHAMPIONS = [
16
+ "Aatrox", "Ahri", "Akali", "Akshan", "Alistar", "Amumu", "Anivia", "Annie", "Aphelios", "Ashe",
17
+ "Aurelion Sol", "Azir", "Bard", "Bel'Veth", "Blitzcrank", "Brand", "Braum", "Caitlyn", "Camille",
18
+ "Cassiopeia", "Cho'Gath", "Corki", "Darius", "Diana", "Dr. Mundo", "Draven", "Ekko", "Elise",
19
+ "Evelynn", "Ezreal", "Fiddlesticks", "Fiora", "Fizz", "Galio", "Gangplank", "Garen", "Gnar",
20
+ "Gragas", "Graves", "Gwen", "Hecarim", "Heimerdinger", "Illaoi", "Irelia", "Ivern", "Janna",
21
+ "Jarvan IV", "Jax", "Jayce", "Jhin", "Jinx", "Kai'Sa", "Kalista", "Karma", "Karthus", "Kassadin",
22
+ "Katarina", "Kayle", "Kayn", "Kennen", "Kha'Zix", "Kindred", "Kled", "Kog'Maw", "KSante", "LeBlanc",
23
+ "Lee Sin", "Leona", "Lillia", "Lissandra", "Lucian", "Lulu", "Lux", "Malphite", "Malzahar", "Maokai",
24
+ "Master Yi", "Milio", "Miss Fortune", "Mordekaiser", "Morgana", "Naafiri", "Nami", "Nasus", "Nautilus",
25
+ "Neeko", "Nidalee", "Nilah", "Nocturne", "Nunu & Willump", "Olaf", "Orianna", "Ornn", "Pantheon",
26
+ "Poppy", "Pyke", "Qiyana", "Quinn", "Rakan", "Rammus", "Rek'Sai", "Rell", "Renata Glasc", "Renekton",
27
+ "Rengar", "Riven", "Rumble", "Ryze", "Samira", "Sejuani", "Senna", "Seraphine", "Sett", "Shaco",
28
+ "Shen", "Shyvana", "Singed", "Sion", "Sivir", "Skarner", "Sona", "Soraka", "Swain", "Sylas",
29
+ "Syndra", "Tahm Kench", "Taliyah", "Talon", "Taric", "Teemo", "Thresh", "Tristana", "Trundle",
30
+ "Tryndamere", "Twisted Fate", "Twitch", "Udyr", "Urgot", "Varus", "Vayne", "Veigar", "Vel'Koz",
31
+ "Vex", "Vi", "Viego", "Viktor", "Vladimir", "Volibear", "Warwick", "Wukong", "Xayah", "Xerath",
32
+ "Xin Zhao", "Yasuo", "Yone", "Yorick", "Yuumi", "Zac", "Zed", "Zeri", "Ziggs", "Zilean", "Zoe", "Zyra"
33
+ ]
34
+
35
+ # Load model
36
+ try:
37
+ model_path = hf_hub_download(
38
+ repo_id="ivwhy/champion-predictor-model",
39
+ filename="champion_predictor.json"
40
+ )
41
+ model = xgb.Booster()
42
+ model.load_model(model_path)
43
+ except Exception as e:
44
+ print(f"Error loading model: {e}")
45
+ model = None
46
+
47
+ try:
48
+ label_encoder = joblib.load('util/label_encoder.joblib')
49
+ print("Label encoder loaded successfully")
50
+ except Exception as e:
51
+ print(f"Error loading label encoder: {e}")
52
+ label_encoder = None
53
+
54
+ # Initialize champion name encoder
55
+ champion_encoder = LabelEncoder()
56
+ champion_encoder.fit(CHAMPIONS)
57
+
58
+
59
+ #==================================== Functions =================================================
60
+ def get_user_training_df(player_opgg_url):
61
+ try:
62
+ print("========= Inside get_user_training_df(player_opgg_url) ============= \n")
63
+ #print("player_opgg_url: ", player_opgg_url, "\n type(player_opgg_url): ", type(player_opgg_url), "\n")
64
+
65
+ # Add input validation
66
+ if not player_opgg_url or not isinstance(player_opgg_url, str):
67
+ return "Invalid URL provided"
68
+
69
+ training_df = create_app_user_training_df(player_opgg_url)
70
+ return training_df
71
+ except Exception as e:
72
+
73
+ # Add more detailed error information
74
+ import traceback
75
+ error_trace = traceback.format_exc()
76
+ print(f"Full error trace:\n{error_trace}")
77
+ return f"Error getting training data: {str(e)}"
78
+
79
+ #return f"Error getting training data: {e}"
80
+
81
+ def show_stats(player_opgg_url):
82
+ """Display player statistics and recent matches"""
83
+ if not player_opgg_url:
84
+ return "Please enter a player link to OPGG", None
85
+
86
+ try:
87
+ training_features = get_user_training_df(player_opgg_url)
88
+
89
+ print("training_features: ", training_features, "\n")
90
+
91
+ if isinstance(training_features, str): # Error message
92
+ return training_features, None
93
+
94
+ wins = training_features['result'].sum()
95
+ losses = len(training_features) - wins
96
+ winrate = f"{(wins / len(training_features)) * 100:.0f}%"
97
+ favorite_champions = (
98
+ training_features['champion']
99
+ .value_counts()
100
+ .head(3)
101
+ .index.tolist()
102
+ )
103
+
104
+ stats_html = f"""
105
+ <div style='padding: 20px; background: #f5f5f5; border-radius: 10px;'>
106
+ <h3>Player's Recent Stats</h3>
107
+ <p>Wins: {wins} | Losses: {losses}</p>
108
+ <p>Winrate: {winrate}</p>
109
+ <p>Favorite Champions: {', '.join(favorite_champions)}</p>
110
+ </div>
111
+ """
112
+
113
+ return stats_html, None
114
+ except Exception as e:
115
+ return f"Error processing stats: {e}. ", None
116
+
117
+ def predict_champion(player_opgg_url, *champions):
118
+ """Make prediction based on selected champions"""
119
+ if not player_opgg_url or None in champions:
120
+ return "Please fill in all fields"
121
+
122
+ try:
123
+ if model is None:
124
+ return "Model not loaded properly"
125
+
126
+ if label_encoder is None:
127
+ return "Label encoder not loaded properly"
128
+
129
+ # Get and process the data
130
+ training_df = get_user_training_df(player_opgg_url)
131
+
132
+ if isinstance(training_df, str):
133
+ return training_df
134
+
135
+ training_df = convert_df(training_df)
136
+ #print("type(training_df): ", type(training_df), "\n")
137
+ print("check_datatypes(training_df) BEFORE feature eng: \n", check_datatypes(training_df), "\n")
138
+
139
+ training_df = apply_feature_engineering(training_df)
140
+ print("check_datatypes(training_df) AFTER feature eng: \n", check_datatypes(training_df), "\n")
141
+
142
+ # Get feature columns
143
+ feature_columns = [col for col in training_df.columns
144
+ if col not in ['champion', 'region', 'stratify_label']]
145
+ X = training_df[feature_columns]
146
+
147
+ # Handle categorical features
148
+ categorical_columns = X.select_dtypes(include=['category']).columns
149
+ X_processed = X.copy()
150
+
151
+ for col in categorical_columns:
152
+ X_processed[col] = X_processed[col].cat.codes
153
+
154
+ X_processed = X_processed.astype('float32')
155
+
156
+ # Create DMatrix and predict
157
+ dtest = DMatrix(X_processed, enable_categorical=True)
158
+ predictions = model.predict(dtest)
159
+
160
+ # Get prediction indices
161
+ if len(predictions.shape) > 1:
162
+ pred_indices = predictions.argmax(axis=1)
163
+ else:
164
+ pred_indices = predictions.astype(int)
165
+
166
+ # First get the numeric ID from the original label encoder
167
+ decoded_numeric = label_encoder.inverse_transform(pred_indices)
168
+
169
+ # Map numeric ID to index in CHAMPIONS list
170
+ # Since your label encoder seems to use champion IDs, we need to map these to list indices
171
+ try:
172
+ # Get the first prediction
173
+ champion_id = int(decoded_numeric[0])
174
+
175
+ # Print debug information
176
+ print(f"Champion ID from model: {champion_id}")
177
+
178
+ # Find the closest matching index
179
+ # Note: This assumes champion IDs roughly correspond to their position in the list
180
+ champion_index = min(max(champion_id - 1, 0), len(CHAMPIONS) - 1)
181
+ predicted_champion = CHAMPIONS[champion_index]
182
+
183
+ print(f"Mapped to champion: {predicted_champion}")
184
+
185
+ return f"{predicted_champion}"
186
+
187
+ except Exception as e:
188
+ print(f"Error mapping champion ID: {e}")
189
+ return f"Error: Could not map champion ID {decoded_numeric[0]}"
190
+
191
+ except Exception as e:
192
+ import traceback
193
+ print(f"Full error trace:\n{traceback.format_exc()}")
194
+ return f"Error making prediction: {e}"
195
+
196
+ ''' current working function!!!!!!
197
+ def predict_champion(player_opgg_url, *champions):
198
+ """Make prediction based on selected champions"""
199
+
200
+ print("==================== Inside: predict_champion() ===================== \n")
201
+ if not player_opgg_url or None in champions:
202
+ return "Please fill in all fields"
203
+
204
+ try:
205
+ if model is None:
206
+ return "Model not loaded properly"
207
+
208
+ if label_encoder is None:
209
+ return "Label encoder not loaded properly"
210
+
211
+ # Print label encoder information
212
+ print("\nLabel Encoder Information:")
213
+ print("Classes in encoder:", label_encoder.classes_)
214
+ print("Number of classes:", len(label_encoder.classes_))
215
+
216
+ # Get and process the data
217
+ training_df = get_user_training_df(player_opgg_url)
218
+ print("training_df retrieved: ", training_df, "\n")
219
+
220
+ if isinstance(training_df, str): # Error message
221
+ return training_df
222
+
223
+ # Apply necessary transformations
224
+ training_df = convert_df(training_df)
225
+ training_df = apply_feature_engineering(training_df)
226
+ print("training_df converted and feature engineered: ", training_df, "\n")
227
+
228
+ # Get feature columns (excluding champion and region)
229
+ feature_columns = [col for col in training_df.columns
230
+ if col not in ['champion', 'region', 'stratify_label']]
231
+ X = training_df[feature_columns]
232
+ print("Got feature columns X: ", X, "\n")
233
+
234
+ # Handle categorical features
235
+ categorical_columns = X.select_dtypes(include=['category']).columns
236
+ X_processed = X.copy()
237
+ print("Handled categorical features, X_processed = ", X_processed, "\n")
238
+
239
+ # Convert categorical columns to numeric
240
+ for col in categorical_columns:
241
+ X_processed[col] = X_processed[col].cat.codes
242
+ print("Converted categorical columns to numeric: ", categorical_columns, "\n")
243
+
244
+ # Convert to float32
245
+ X_processed = X_processed.astype('float32')
246
+ print("Converted X_processed to float32: ", X_processed, "\n")
247
+
248
+ # Create DMatrix with categorical feature support
249
+ dtest = DMatrix(X_processed, enable_categorical=True)
250
+ print("Converted to Dmatrix: ", dtest, "\n")
251
+
252
+ # Make prediction
253
+ print("Starting model prediction...\n")
254
+ predictions = model.predict(dtest)
255
+ print("Model prediction complete\n")
256
+
257
+ print("\nPrediction Information:")
258
+ print("Raw predictions shape:", predictions.shape)
259
+ print("Raw predictions:", predictions)
260
+
261
+ # Get the highest probability prediction
262
+ if len(predictions.shape) > 1:
263
+ pred_indices = predictions.argmax(axis=1)
264
+ else:
265
+ pred_indices = predictions.astype(int)
266
+
267
+ print("\nPrediction Indices:")
268
+ print("Indices shape:", pred_indices.shape)
269
+ print("Indices:", pred_indices)
270
+
271
+ # Check if indices are within valid range
272
+ print("\nValidation:")
273
+ print("Min index:", pred_indices.min())
274
+ print("Max index:", pred_indices.max())
275
+ print("Valid index range:", 0, len(label_encoder.classes_) - 1)
276
+ # Try to decode predictions
277
+
278
+ try:
279
+ decoded_preds = label_encoder.inverse_transform(pred_indices)
280
+ print("\nDecoded Predictions:")
281
+ print("Type:", type(decoded_preds))
282
+ print("Value:", decoded_preds)
283
+ print("==================== Exiting: predict_champion()===================\n")
284
+ return f"Predicted champion: {decoded_preds[0]}"
285
+ except Exception as e:
286
+ print(f"\nError during decoding: {e}")
287
+ # Fallback: try to directly index into classes
288
+ try:
289
+ champion = label_encoder.classes_[int(pred_indices[0])]
290
+ return f"Predicted champion: {champion}"
291
+ except Exception as e2:
292
+ print(f"Fallback error: {e2}")
293
+ return f"Error decoding prediction: {pred_indices[0]}"
294
+
295
+ except Exception as e:
296
+ import traceback
297
+ print(f"Full error trace:\n{traceback.format_exc()}")
298
+ return f"Error making prediction: {e}"
299
+ '''
300
+
301
+ # Define your interface
302
+ with gr.Blocks() as demo:
303
+ gr.Markdown("# League of Legends Champion Prediction")
304
+
305
+ with gr.Row():
306
+ player_opgg_url = gr.Textbox(label="OPGG Player URL")
307
+ show_button = gr.Button("Show Player Stats")
308
+
309
+ with gr.Row():
310
+ stats_output = gr.HTML(label="Player Statistics")
311
+ recent_matches = gr.HTML(label="Recent Matches")
312
+
313
+ with gr.Row():
314
+ champion_dropdowns = [
315
+ gr.Dropdown(choices=CHAMPIONS, label=f"Champion {i+1}")
316
+ for i in range(9)
317
+ ]
318
+
319
+ with gr.Row():
320
+ predict_button = gr.Button("Predict")
321
+ prediction_output = gr.Text(label="Prediction")
322
+
323
+ # Set up event handlers
324
+ show_button.click(
325
+ fn=show_stats,
326
+ inputs=[player_opgg_url],
327
+ outputs=[stats_output, recent_matches]
328
+ )
329
+
330
+ predict_button.click(
331
+ fn=predict_champion,
332
+ inputs=[player_opgg_url] + champion_dropdowns,
333
+ outputs=prediction_output
334
+ )
335
+
336
+ # Optional: Save the champion encoder for future use
337
+ joblib.dump(champion_encoder, 'champion_encoder.joblib')
338
+ # Enable queuing
339
+ demo.launch(debug=True)
340
+
341
+ # For local testing
342
+ if __name__ == "__main__":
343
+ demo.launch()