Spaces:
Sleeping
Sleeping
File size: 16,292 Bytes
373112b dd5f0c1 c09e91b b076993 c52059f d1df99f 080445c d1df99f c52059f b076993 373112b dd5f0c1 373112b dd5f0c1 373112b dd5f0c1 373112b dd5f0c1 373112b c09e91b 373112b c09e91b dd5f0c1 373112b b076993 373112b dd5f0c1 373112b b076993 373112b dd5f0c1 373112b 471b4e5 dd5f0c1 a2f85fb 653a2a6 a2f85fb 99c7136 653a2a6 373112b c52059f 653a2a6 dd5f0c1 c23fe35 dd5f0c1 b076993 dd5f0c1 c23fe35 559d270 c23fe35 559d270 c23fe35 559d270 c23fe35 559d270 653a2a6 c52059f 653a2a6 c52059f 653a2a6 c52059f 653a2a6 2270641 778584d 2270641 778584d 2270641 653a2a6 b076993 373112b dd5f0c1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 |
import streamlit as st
import pandas as pd
import joblib
from sklearn.ensemble import RandomForestRegressor
import plotly.express as px
from sklearn.ensemble import RandomForestRegressor
import plotly.graph_objects as go
from PIL import Image
import plotly.express as px
# Set the page configuration
st.set_page_config(
page_title="NBA Player Performance Predictor",
page_icon="๐",
layout="centered"
)
# Custom CSS for vibrant NBA sidebar styling
st.markdown(
"""
<style>
body {
background: linear-gradient(to bottom, #0033a0, #ed174c); /* NBA team colors gradient */
font-family: 'Trebuchet MS', sans-serif;
margin: 0;
padding: 0;
color: white; /* Set text color to white */
}
.sidebar .sidebar-content {
background: linear-gradient(to bottom, #4B0082, #1E90FF); /* Purple to blue gradient */
border-radius: 10px;
padding: 10px;
color: #ffffff; /* Set sidebar text color to white */
}
.stSidebar h2 {
color: #ffffff;
text-align: center;
font-size: 20px;
font-weight: bold;
text-shadow: 2px 2px #000000;
}
.stButton > button {
background-color: #ffcc00; /* Bold yellow */
color: #0033a0; /* Button text color */
border: none;
border-radius: 5px;
padding: 10px 15px;
font-size: 16px;
transition: background-color 0.3s ease;
}
.stButton > button:hover {
background-color: #ffc107; /* Brighter yellow */
box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.2);
}
.stMarkdown h1, .stMarkdown h2, .stMarkdown h3 {
color: #ffffff; /* Set headings color to white */
text-shadow: 2px 2px #000000; /* Add shadow for better visibility */
}
.stMetric {
color: #FFFFFF !important; /* Make metric text white */
border: none; /* Remove any default borders */
padding: 5px; /* Add padding for better spacing */
font-size: 1.2em; /* Slightly increase font size */
text-align: center; /* Center-align the metric text */
}
.block-container {
border-radius: 10px;
padding: 20px;
background-color: rgba(0, 0, 0, 0.8); /* Dark semi-transparent background */
color: #ffffff; /* Ensure text inside the container is white */
}
.dataframe {
background-color: rgba(255, 255, 255, 0.1); /* Transparent table background */
color: #ffffff; /* Table text color */
border-radius: 10px;
}
.stPlotlyChart {
background-color: rgba(0, 0, 0, 0.8); /* Match dark theme */
padding: 10px;
border-radius: 10px;
box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.5);
}
.styled-table {
width: 100%;
border-collapse: collapse;
margin: 25px 0;
font-size: 18px;
text-align: left;
border-radius: 5px 5px 0 0;
overflow: hidden;
color: #ffffff; /* Table text color */
}
.styled-table th, .styled-table td {
padding: 12px 15px;
}
</style>
""",
unsafe_allow_html=True
)
team_logo_paths = {
"Cleveland Cavaliers": "Clevelan-Cavaliers-logo-2022.png",
"Atlanta Hawks": "nba-atlanta-hawks-logo.png",
"Boston Celtics": "nba-boston-celtics-logo.png",
"Brooklyn Nets": "nba-brooklyn-nets-logo.png",
"Charlotte Hornets": "nba-charlotte-hornets-logo.png",
"Chicago Bulls": "nba-chicago-bulls-logo.png",
"Dallas Mavericks": "nba-dallas-mavericks-logo.png",
"Denver Nuggets": "nba-denver-nuggets-logo-2018.png",
"Detroit Pistons": "nba-detroit-pistons-logo.png",
"Golden State Warriors": "nba-golden-state-warriors-logo-2020.png",
"Houston Rockets": "nba-houston-rockets-logo-2020.png",
"Indiana Pacers": "nba-indiana-pacers-logo.png",
"LA Clippers": "nba-la-clippers-logo.png",
"Los Angeles Lakers": "nba-los-angeles-lakers-logo.png",
"Memphis Grizzlies": "nba-memphis-grizzlies-logo.png",
"Miami Heat": "nba-miami-heat-logo.png",
"Milwaukee Bucks": "nba-milwaukee-bucks-logo.png",
"Minnesota Timberwolves": "nba-minnesota-timberwolves-logo.png",
"New Orleans Pelicans": "nba-new-orleans-pelicans-logo.png",
"New York Knicks": "nba-new-york-knicks-logo.png",
"Oklahoma City Thunder": "nba-oklahoma-city-thunder-logo.png",
"Orlando Magic": "nba-orlando-magic-logo.png",
"Philadelphia 76ers": "nba-philadelphia-76ers-logo.png",
"Phoenix Suns": "nba-phoenix-suns-logo.png",
"Portland Trail Blazers": "nba-portland-trail-blazers-logo.png",
"Sacramento Kings": "nba-sacramento-kings-logo.png",
"San Antonio Spurs": "nba-san-antonio-spurs-logo.png",
"Toronto Raptors": "nba-toronto-raptors-logo-2020.png",
"Utah Jazz": "nba-utah-jazz-logo.png",
"Washington Wizards": "nba-washington-wizards-logo.png",
}
# Mapping for position to numeric values
position_mapping = {
"PG": 1.0, # Point Guard
"SG": 2.0, # Shooting Guard
"SF": 3.0, # Small Forward
"PF": 4.0, # Power Forward
"C": 5.0, # Center
}
# Predefined injury types
injury_types = [
"foot fracture injury",
"hip flexor surgery injury",
"calf strain injury",
"quad injury injury",
"shoulder sprain injury",
"foot sprain injury",
"torn rotator cuff injury injury",
"torn mcl injury",
"hip flexor strain injury",
"fractured leg injury",
"sprained mcl injury",
"ankle sprain injury",
"hamstring injury injury",
"meniscus tear injury",
"torn hamstring injury",
"dislocated shoulder injury",
"ankle fracture injury",
"fractured hand injury",
"bone spurs injury",
"acl tear injury",
"hip labrum injury",
"back surgery injury",
"arm injury injury",
"torn shoulder labrum injury",
"lower back spasm injury"
]
# Injury average days dictionary
average_days_injured = {
"foot fracture injury": 207.666667,
"hip flexor surgery injury": 256.000000,
"calf strain injury": 236.000000,
"quad injury injury": 283.000000,
"shoulder sprain injury": 259.500000,
"foot sprain injury": 294.000000,
"torn rotator cuff injury injury": 251.500000,
"torn mcl injury": 271.000000,
"hip flexor strain injury": 253.000000,
"fractured leg injury": 250.250000,
"sprained mcl injury": 228.666667,
"ankle sprain injury": 231.333333,
"hamstring injury injury": 220.000000,
"meniscus tear injury": 201.250000,
"torn hamstring injury": 187.666667,
"dislocated shoulder injury": 269.000000,
"ankle fracture injury": 114.500000,
"fractured hand injury": 169.142857,
"bone spurs injury": 151.500000,
"acl tear injury": 268.000000,
"hip labrum injury": 247.500000,
"back surgery injury": 215.800000,
"arm injury injury": 303.666667,
"torn shoulder labrum injury": 195.666667,
"lower back spasm injury": 234.000000,
}
# Load player dataset
@st.cache_resource
def load_player_data():
return pd.read_csv("player_data.csv")
# Load Random Forest model
@st.cache_resource
def load_rf_model():
return joblib.load("rf_injury_change_model.pkl")
# Main Streamlit app
def main():
st.title("NBA Player Performance Predictor ๐")
st.write(
"""
Predict how a player's performance metrics (e.g., points, rebounds, assists) might change
if a hypothetical injury occurs, based on their position and other factors.
"""
)
# Load player data
player_data = load_player_data()
rf_model = load_rf_model()
st.sidebar.markdown(
"""
<div style="padding: 10px; background: linear-gradient(to right, #6a11cb, #2575fc); color: white; border-radius: 10px;">
<h3>Player Details</h3>
</div>
""",
unsafe_allow_html=True
)
# Dropdown for player selection
player_list = sorted(player_data['player_name'].dropna().unique())
player_name = st.sidebar.selectbox("Select Player", player_list)
if player_name:
# Retrieve player details
player_row = player_data[player_data['player_name'] == player_name]
team_name = player_row.iloc[0]['team_abbreviation']
position = player_row.iloc[0]['position']
if not player_row.empty:
position = player_row.iloc[0]['position']
position_numeric = position_mapping.get(position, 0)
st.sidebar.write(f"**Position**: {position} (Numeric: {position_numeric})")
# Default values for features
stats_columns = ['age', 'player_height', 'player_weight']
default_stats = {
stat: player_row.iloc[0][stat] if stat in player_row.columns else 0
for stat in stats_columns
}
# Allow manual adjustment of stats
for stat in default_stats.keys():
default_stats[stat] = st.sidebar.number_input(f"{stat}", value=default_stats[stat])
# Injury details
injury_type = st.sidebar.selectbox("Select Hypothetical Injury", injury_types)
# Replace slider with default average based on injury type
default_days_injured = average_days_injured[injury_type] or 30 # Use 30 if None
days_injured = st.sidebar.slider(
"Estimated Days Injured",
0,
365,
int(default_days_injured),
help=f"Default days for {injury_type}: {int(default_days_injured) if default_days_injured else 'N/A'}"
)
injury_occurrences = st.sidebar.number_input("Injury Occurrences", min_value=0, value=1)
# Prepare input data
input_data = pd.DataFrame([{
"days_injured": days_injured,
"injury_occurrences": injury_occurrences,
"position": position_numeric,
"injury_type": injury_type, # Include the selected injury type
**default_stats
}])
# Encode injury type
input_data["injury_type"] = pd.factorize(input_data["injury_type"])[0]
# Load Random Forest model
try:
rf_model = load_rf_model()
# Align input data with the model's feature names
expected_features = rf_model.feature_names_in_
input_data = input_data.reindex(columns=rf_model.feature_names_in_, fill_value=0)
# Predict and display results
# Predict and display results
if st.sidebar.button("Predict ๐ฎ"):
predictions = rf_model.predict(input_data)
prediction_columns = ["Predicted Change in PTS", "Predicted Change in REB", "Predicted Change in AST"]
st.subheader("Predicted Post-Injury Performance")
st.write("Based on the inputs, here are the predicted metrics:")
styled_table = pd.DataFrame(predictions, columns=prediction_columns).style.set_table_attributes('class="styled-table"')
st.write(styled_table.to_html(), unsafe_allow_html=True)
# Plot predictions
prediction_df = pd.DataFrame(predictions, columns=prediction_columns)
fig = go.Figure()
for col in prediction_columns:
fig.add_trace(go.Bar(
x=[col],
y=prediction_df[col],
name=col,
marker=dict(color=px.colors.qualitative.Plotly[prediction_columns.index(col)])
))
fig.update_layout(
title="Predicted Performance Changes",
xaxis_title="Metrics",
yaxis_title="Change Value",
template="plotly_dark",
showlegend=True
)
st.plotly_chart(fig)
except FileNotFoundError:
st.error("Model file not found.")
except ValueError as e:
st.error(f"Error during prediction: {e}")
else:
st.sidebar.error("Player details not found in the dataset.")
else:
st.sidebar.error("Please select a player to view details.")
st.divider()
st.header("Player Overview")
col1, col2 = st.columns([1, 2])
with col1:
st.subheader("Player Details")
st.markdown(f"""
<div style="margin-bottom: 20px;">
<div style="font-size: 1em; color: white; margin-bottom: 5px;">Age</div>
<div style="font-size: 2em; color: white; font-weight: bold;">{default_stats['age']}</div>
</div>
<div style="margin-bottom: 20px;">
<div style="font-size: 1em; color: white; margin-bottom: 5px;">Height (cm)</div>
<div style="font-size: 2em; color: white; font-weight: bold;">{round(default_stats['player_height'], 2)}</div>
</div>
<div style="margin-bottom: 20px;">
<div style="font-size: 1em; color: white; margin-bottom: 5px;">Weight (kg)</div>
<div style="font-size: 2em; color: white; font-weight: bold;">{round(default_stats['player_weight'], 2)}</div>
</div>
""", unsafe_allow_html=True)
with col2:
# Display team logo
if team_name in team_logo_paths:
logo_path = team_logo_paths[team_name]
try:
logo_image = Image.open(logo_path)
st.image(logo_image, caption=f"{team_name} Logo", use_container_width=True)
except FileNotFoundError:
st.error(f"Logo for {team_name} not found.")
# Graphs for PPG, AST, and REB
st.divider()
st.header("Player Performance Graphs")
if st.button("Show Performance Graphs"):
# Filter data for the selected player
player_data_filtered = player_data[player_data["player_name"] == player_name].sort_values(by="season")
# Ensure all seasons are included
all_seasons = pd.Series(range(player_data["season"].min(), player_data["season"].max() + 1))
player_data_filtered = (
pd.DataFrame({"season": all_seasons})
.merge(player_data_filtered, on="season", how="left")
)
if not player_data_filtered.empty:
# PPG Graph
fig_ppg = px.line(
player_data_filtered,
x="season",
y="pts",
title=f"{player_name}: Points Per Game (PPG) Over Seasons",
labels={"pts": "Points Per Game (PPG)", "season": "Season"},
markers=True
)
fig_ppg.update_layout(template="plotly_white")
# AST Graph
fig_ast = px.line(
player_data_filtered,
x="season",
y="ast",
title=f"{player_name}: Assists Per Game (AST) Over Seasons",
labels={"ast": "Assists Per Game (AST)", "season": "Season"},
markers=True
)
fig_ast.update_layout(template="plotly_white")
# REB Graph
fig_reb = px.line(
player_data_filtered,
x="season",
y="reb",
title=f"{player_name}: Rebounds Per Game (REB) Over Seasons",
labels={"reb": "Rebounds Per Game (REB)", "season": "Season"},
markers=True
)
fig_reb.update_layout(template="plotly_white")
# Display graphs
st.plotly_chart(fig_ppg, use_container_width=True)
st.plotly_chart(fig_ast, use_container_width=True)
st.plotly_chart(fig_reb, use_container_width=True)
else:
st.error("No data available for the selected player.")
# Footer
st.divider()
st.markdown("""
### About This Tool
This application predicts how injuries might impact an NBA player's performance using machine learning models. Data is based on historical player stats and injuries.
""")
if __name__ == "__main__":
main() |