nick-leland commited on
Commit
cff025c
·
1 Parent(s): ddcf7cb

Simplification

Browse files
Files changed (1) hide show
  1. app.py +56 -87
app.py CHANGED
@@ -8,98 +8,64 @@ sys.path.append("rd2l_pred")
8
  from training_data_prep import list_format, modification, league_money, df_gen
9
  from feature_engineering import heroes, hero_information
10
 
11
- # Global variables for model and feature columns
12
- MODEL = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
- def load_model():
15
- """Load the ONNX model"""
16
- global MODEL
17
- try:
18
- model_path = Path("model/rd2l_forest.onnx")
19
- if not model_path.exists():
20
- return "Model file not found at: " + str(model_path)
21
-
22
- MODEL = ort.InferenceSession(str(model_path))
23
- return "Model loaded successfully"
24
- except Exception as e:
25
- return f"Error loading model: {str(e)}"
26
 
27
- def process_player_data(player_id, mmr, comf_1, comf_2, comf_3, comf_4, comf_5):
28
- """Process player data with correct feature structure"""
29
  try:
30
- # Clean player ID from URL if needed
31
- if "/" in player_id:
32
- player_id = player_id.split("/")[-1]
33
-
34
- # Create initial data structure with basic features
35
- data = {
36
- 'mmr': float(mmr),
37
- 'p1': int(comf_1),
38
- 'p2': int(comf_2),
39
- 'p3': int(comf_3),
40
- 'p4': int(comf_4),
41
- 'p5': int(comf_5),
42
- 'count': 0,
43
- 'mean': 0,
44
- 'std': 0,
45
- 'min': 0,
46
- 'max': 0,
47
- 'sum': 0,
48
- 'total_games_played': 0,
49
- 'total_winrate': 0
50
- }
51
 
52
- # Add hero-specific features
53
- for i in range(1, 139): # Add all possible hero IDs
54
- data[f'games_{i}'] = 0
55
- data[f'winrate_{i}'] = 0
56
-
57
- # Get hero statistics from OpenDota
58
  try:
 
59
  hero_stats = hero_information(player_id)
60
- data['total_games_played'] = hero_stats['total_games_played']
61
- data['total_winrate'] = hero_stats['total_winrate']
62
-
63
- # Update hero-specific stats
64
- for key, value in hero_stats.items():
65
- if key in data:
66
- data[key] = value
67
  except Exception as e:
68
  print(f"Warning - Error fetching hero data: {str(e)}")
69
 
70
- # Convert to DataFrame
71
- df = pd.DataFrame([data])
72
-
73
- print(f"Processed data shape: {df.shape}")
74
- print(f"Number of features: {len(df.columns)}")
75
- print(f"First few columns: {list(df.columns)[:5]}")
76
-
77
- return df
78
- except Exception as e:
79
- return f"Error processing player data: {str(e)}"
80
-
81
- def predict_cost(user_id, mmr, comf_1, comf_2, comf_3, comf_4, comf_5):
82
- """Main prediction function for Gradio interface"""
83
- try:
84
- # Check if model is loaded
85
- if MODEL is None:
86
- result = load_model()
87
- if not result.startswith("Model loaded"):
88
- return result
89
-
90
- # Process input data
91
- processed_data = process_player_data(user_id, mmr, comf_1, comf_2, comf_3, comf_4, comf_5)
92
-
93
- if isinstance(processed_data, str): # Error occurred
94
- return processed_data
95
-
96
  # Make prediction
97
- try:
98
- input_name = MODEL.get_inputs()[0].name
99
- prediction = MODEL.run(None, {input_name: processed_data.values.astype(np.float32)})[0]
100
- predicted_cost = round(float(prediction[0]), 2)
101
- except Exception as e:
102
- return f"Error during prediction: {str(e)}\nProcessed data shape: {processed_data.shape}"
103
 
104
  return f"""Predicted Cost: {predicted_cost}
105
 
@@ -115,7 +81,7 @@ Player Details:
115
  Note: This prediction is based on historical data and player statistics from OpenDota."""
116
 
117
  except Exception as e:
118
- return f"Error in prediction pipeline: {str(e)}"
119
 
120
  # Create Gradio interface
121
  demo = gr.Interface(
@@ -143,10 +109,13 @@ demo = gr.Interface(
143
  - The predictor uses machine learning trained on historical RD2L draft data
144
  - Player statistics are fetched from OpenDota API
145
  - Position comfort levels range from 1 (least comfortable) to 5 (most comfortable)
146
- - Predictions are based on both current stats and historical performance"""
 
 
 
 
 
147
  )
148
 
149
  if __name__ == "__main__":
150
- print("===== Application Startup =====")
151
- print(load_model())
152
- demo.launch(server_name="0.0.0.0")
 
8
  from training_data_prep import list_format, modification, league_money, df_gen
9
  from feature_engineering import heroes, hero_information
10
 
11
+ def prepare_single_player_data(user_id, mmr, comf_1, comf_2, comf_3, comf_4, comf_5):
12
+ """Creates a draft sheet format DataFrame for a single player"""
13
+ # Create player data in the format expected by the original pipeline
14
+ player_data = {
15
+ 'Discord ID': ['N/A'], # Placeholder for Discord ID
16
+ 'Dotabuff Link': [user_id],
17
+ 'MMR': [mmr],
18
+ 'Comfort (Pos 1)': [comf_1],
19
+ 'Comfort (Pos 2)': [comf_2],
20
+ 'Comfort (Pos 3)': [comf_3],
21
+ 'Comfort (Pos 4)': [comf_4],
22
+ 'Comfort (Pos 5)': [comf_5],
23
+ 'Player statement': ['N/A'] # Placeholder for player statement
24
+ }
25
+
26
+ return pd.DataFrame(player_data)
27
 
28
+ def prepare_mock_captains():
29
+ """Creates a minimal captains DataFrame for the league money calculation"""
30
+ captains_data = {
31
+ 'Name': ['Mock Captain'],
32
+ 'Dotabuff': ['N/A'],
33
+ 'MMR': [3000],
34
+ "Buck's Bucks": [100],
35
+ 'Crub Cents': [100],
36
+ 'Remaining': [100]
37
+ }
38
+ return pd.DataFrame(captains_data)
 
39
 
40
+ def predict_cost(user_id, mmr, comf_1, comf_2, comf_3, comf_4, comf_5):
41
+ """Main prediction function for Gradio interface"""
42
  try:
43
+ # Create a single-player draft sheet
44
+ draft_df = prepare_single_player_data(user_id, mmr, comf_1, comf_2, comf_3, comf_4, comf_5)
45
+ captains_df = prepare_mock_captains()
46
+
47
+ # Use the original pipeline functions
48
+ money = league_money(captains_df, 'prediction')
49
+ prepped_data = df_gen(draft_df, money, 'prediction')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
 
51
+ # Load and use the model
52
+ model_path = Path("model/rd2l_forest.onnx")
53
+ session = ort.InferenceSession(str(model_path))
54
+
55
+ # Get hero information using the original feature engineering
 
56
  try:
57
+ player_id = modification(user_id) # Use the original modification function
58
  hero_stats = hero_information(player_id)
59
+ # Add hero stats to prepped data
60
+ for col, value in hero_stats.items():
61
+ prepped_data[col] = value
 
 
 
 
62
  except Exception as e:
63
  print(f"Warning - Error fetching hero data: {str(e)}")
64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  # Make prediction
66
+ input_name = session.get_inputs()[0].name
67
+ prediction = session.run(None, {input_name: prepped_data.values.astype(np.float32)})[0]
68
+ predicted_cost = round(float(prediction[0]), 2)
 
 
 
69
 
70
  return f"""Predicted Cost: {predicted_cost}
71
 
 
81
  Note: This prediction is based on historical data and player statistics from OpenDota."""
82
 
83
  except Exception as e:
84
+ return f"Error in prediction pipeline: {str(e)}\n\nDebug info:\n{type(e).__name__}: {str(e)}"
85
 
86
  # Create Gradio interface
87
  demo = gr.Interface(
 
109
  - The predictor uses machine learning trained on historical RD2L draft data
110
  - Player statistics are fetched from OpenDota API
111
  - Position comfort levels range from 1 (least comfortable) to 5 (most comfortable)
112
+ - Predictions are based on both current stats and historical performance
113
+
114
+ ### Notes
115
+ - MMR should be the player's current solo MMR
116
+ - Position comfort should reflect actual role experience
117
+ - Predictions are estimates and may vary from actual draft results"""
118
  )
119
 
120
  if __name__ == "__main__":
121
+ demo.launch()