rd2l_prediction / app.py
nick-leland's picture
Simplification
cff025c
raw
history blame
4.92 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
def prepare_single_player_data(user_id, mmr, comf_1, comf_2, comf_3, comf_4, comf_5):
"""Creates a draft sheet format DataFrame for a single player"""
# Create player data in the format expected by the original pipeline
player_data = {
'Discord ID': ['N/A'], # Placeholder for Discord ID
'Dotabuff Link': [user_id],
'MMR': [mmr],
'Comfort (Pos 1)': [comf_1],
'Comfort (Pos 2)': [comf_2],
'Comfort (Pos 3)': [comf_3],
'Comfort (Pos 4)': [comf_4],
'Comfort (Pos 5)': [comf_5],
'Player statement': ['N/A'] # Placeholder for player statement
}
return pd.DataFrame(player_data)
def prepare_mock_captains():
"""Creates a minimal captains DataFrame for the league money calculation"""
captains_data = {
'Name': ['Mock Captain'],
'Dotabuff': ['N/A'],
'MMR': [3000],
"Buck's Bucks": [100],
'Crub Cents': [100],
'Remaining': [100]
}
return pd.DataFrame(captains_data)
def predict_cost(user_id, mmr, comf_1, comf_2, comf_3, comf_4, comf_5):
"""Main prediction function for Gradio interface"""
try:
# Create a single-player draft sheet
draft_df = prepare_single_player_data(user_id, mmr, comf_1, comf_2, comf_3, comf_4, comf_5)
captains_df = prepare_mock_captains()
# Use the original pipeline functions
money = league_money(captains_df, 'prediction')
prepped_data = df_gen(draft_df, money, 'prediction')
# Load and use the model
model_path = Path("model/rd2l_forest.onnx")
session = ort.InferenceSession(str(model_path))
# Get hero information using the original feature engineering
try:
player_id = modification(user_id) # Use the original modification function
hero_stats = hero_information(player_id)
# Add hero stats to prepped data
for col, value in hero_stats.items():
prepped_data[col] = value
except Exception as e:
print(f"Warning - Error fetching hero data: {str(e)}")
# Make prediction
input_name = session.get_inputs()[0].name
prediction = session.run(None, {input_name: prepped_data.values.astype(np.float32)})[0]
predicted_cost = round(float(prediction[0]), 2)
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)}\n\nDebug info:\n{type(e).__name__}: {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
### Notes
- MMR should be the player's current solo MMR
- Position comfort should reflect actual role experience
- Predictions are estimates and may vary from actual draft results"""
)
if __name__ == "__main__":
demo.launch()