Grandediw's picture
Create app.py
7418c14 verified
raw
history blame
2.79 kB
import gradio as gr
import pandas as pd
from xgboost import Booster, DMatrix
import numpy as np
# Define the mapping of card names to IDs (placeholder example)
card_numbers = {
"Card 1": 1,
"Card 2": 2,
"Card 3": 3,
"Card 4": 4,
"Card 5": 5,
"Card 6": 6,
"Card 7": 7,
"Card 8": 8,
# Add all 181 cards here...
}
MODEL_PATH = "clash_royale_model/model.json"
def deck_to_ids(deck, mapping):
"""Convert card names to IDs based on the mapping."""
return [mapping.get(card, 0) - 1 for card in deck] # Zero-based indices
def preprocess_deck(deck):
"""Prepare the selected deck for the model."""
# Convert cards to IDs
deck_ids = deck_to_ids(deck, card_numbers)
# Perform one-hot encoding
num_choices = 181 # Total number of cards
one_hot = np.zeros(num_choices, dtype=int)
one_hot[np.array(deck_ids)] = 1 # Set 1 for selected cards
# Add additional features (placeholder for now)
trophy_difference = 0 # Placeholder for trophy difference
elixir_leaked = 0 # Placeholder for leaked elixir
# Combine features
features = np.concatenate(([trophy_difference, elixir_leaked], one_hot))
return pd.DataFrame([features])
def load_model(model_path):
"""Load the saved XGBoost model."""
model = Booster()
model.load_model(model_path)
return model
# Load the model at startup
model = load_model(MODEL_PATH)
def predict_outcome(opponent_deck):
"""Make a prediction based on the opponent's deck."""
# Prepare the opponent deck data
deck_data = preprocess_deck(opponent_deck)
# Make the prediction
dmatrix = DMatrix(deck_data) # Convert data to DMatrix format
prediction = model.predict(dmatrix)
# Interpret the prediction
result = f"Probability of Winning: {prediction[0] * 100:.2f}%"
return result
# List of cards for selection
card_list = list(card_numbers.keys())
# Create the Gradio interface
with gr.Blocks() as interface:
gr.Markdown("## Clash Royale Prediction")
gr.Markdown("Select the 8 cards from the opponent's deck to predict the probability of winning!")
opponent_deck = gr.CheckboxGroup(
choices=card_list,
label="Select 8 cards from the opponent's deck:",
info="Select exactly 8 cards."
)
result = gr.Textbox(label="Prediction Result:", interactive=False)
def validate_and_predict(deck):
"""Validate the number of selected cards and make a prediction."""
if len(deck) != 8:
return "Error: Select exactly 8 cards."
return predict_outcome(deck)
predict_button = gr.Button("Make Prediction")
predict_button.click(validate_and_predict, inputs=[opponent_deck], outputs=[result])
# Launch the interface
interface.launch()