rd2l_prediction / app.py
nick-leland's picture
please
ddcf7cb
raw
history blame
5.59 kB
import gradio as gr
import pandas as pd
import numpy as np
import onnxruntime as ort
import sys
from pathlib import Path
sys.path.append("rd2l_pred")
from training_data_prep import list_format, modification, league_money, df_gen
from feature_engineering import heroes, hero_information
# Global variables for model and feature columns
MODEL = None
def load_model():
"""Load the ONNX model"""
global MODEL
try:
model_path = Path("model/rd2l_forest.onnx")
if not model_path.exists():
return "Model file not found at: " + str(model_path)
MODEL = ort.InferenceSession(str(model_path))
return "Model loaded successfully"
except Exception as e:
return f"Error loading model: {str(e)}"
def process_player_data(player_id, mmr, comf_1, comf_2, comf_3, comf_4, comf_5):
"""Process player data with correct feature structure"""
try:
# Clean player ID from URL if needed
if "/" in player_id:
player_id = player_id.split("/")[-1]
# Create initial data structure with basic features
data = {
'mmr': float(mmr),
'p1': int(comf_1),
'p2': int(comf_2),
'p3': int(comf_3),
'p4': int(comf_4),
'p5': int(comf_5),
'count': 0,
'mean': 0,
'std': 0,
'min': 0,
'max': 0,
'sum': 0,
'total_games_played': 0,
'total_winrate': 0
}
# Add hero-specific features
for i in range(1, 139): # Add all possible hero IDs
data[f'games_{i}'] = 0
data[f'winrate_{i}'] = 0
# Get hero statistics from OpenDota
try:
hero_stats = hero_information(player_id)
data['total_games_played'] = hero_stats['total_games_played']
data['total_winrate'] = hero_stats['total_winrate']
# Update hero-specific stats
for key, value in hero_stats.items():
if key in data:
data[key] = value
except Exception as e:
print(f"Warning - Error fetching hero data: {str(e)}")
# Convert to DataFrame
df = pd.DataFrame([data])
print(f"Processed data shape: {df.shape}")
print(f"Number of features: {len(df.columns)}")
print(f"First few columns: {list(df.columns)[:5]}")
return df
except Exception as e:
return f"Error processing player data: {str(e)}"
def predict_cost(user_id, mmr, comf_1, comf_2, comf_3, comf_4, comf_5):
"""Main prediction function for Gradio interface"""
try:
# Check if model is loaded
if MODEL is None:
result = load_model()
if not result.startswith("Model loaded"):
return result
# Process input data
processed_data = process_player_data(user_id, mmr, comf_1, comf_2, comf_3, comf_4, comf_5)
if isinstance(processed_data, str): # Error occurred
return processed_data
# Make prediction
try:
input_name = MODEL.get_inputs()[0].name
prediction = MODEL.run(None, {input_name: processed_data.values.astype(np.float32)})[0]
predicted_cost = round(float(prediction[0]), 2)
except Exception as e:
return f"Error during prediction: {str(e)}\nProcessed data shape: {processed_data.shape}"
return f"""Predicted Cost: {predicted_cost}
Player Details:
- MMR: {mmr}
- Position Comfort:
* Pos 1: {comf_1}
* Pos 2: {comf_2}
* Pos 3: {comf_3}
* Pos 4: {comf_4}
* Pos 5: {comf_5}
Note: This prediction is based on historical data and player statistics from OpenDota."""
except Exception as e:
return f"Error in prediction pipeline: {str(e)}"
# Create Gradio interface
demo = gr.Interface(
fn=predict_cost,
inputs=[
gr.Textbox(label="Player ID or Link to OpenDota/Dotabuff",
placeholder="Enter player ID or full profile URL"),
gr.Number(label="MMR", value=3000),
gr.Slider(1, 5, value=3, step=1, label="Comfort (Pos 1)"),
gr.Slider(1, 5, value=3, step=1, label="Comfort (Pos 2)"),
gr.Slider(1, 5, value=3, step=1, label="Comfort (Pos 3)"),
gr.Slider(1, 5, value=3, step=1, label="Comfort (Pos 4)"),
gr.Slider(1, 5, value=3, step=1, label="Comfort (Pos 5)")
],
examples=[
["https://www.dotabuff.com/players/188649776", 6812, 5, 5, 4, 2, 1]
],
outputs=gr.Textbox(label="Prediction Results"),
title="RD2L Player Cost Predictor",
description="""This tool predicts the auction cost for RD2L players based on their MMR,
position comfort levels, and historical performance data from OpenDota.
Enter a player's OpenDota ID or profile URL along with their current stats
to get a predicted cost.""",
article="""### How it works
- The predictor uses machine learning trained on historical RD2L draft data
- Player statistics are fetched from OpenDota API
- Position comfort levels range from 1 (least comfortable) to 5 (most comfortable)
- Predictions are based on both current stats and historical performance"""
)
if __name__ == "__main__":
print("===== Application Startup =====")
print(load_model())
demo.launch(server_name="0.0.0.0")