Spaces:
Sleeping
Sleeping
Download app.py from tessida/per36_NBA_App: direct link, hf CLI and curl.
- Browser
- Download file 8.72 kB
-
https://huggingface.co/spaces/tessida/per36_NBA_App/resolve/main/app.py
- Command line
-
hf download hf://spaces/tessida/per36_NBA_App/app.py
-
curl -L -o app.py https://huggingface.co/spaces/tessida/per36_NBA_App/resolve/main/app.py
8.72 kB
| import pandas as pd | |
| import gradio as gr | |
| from datetime import datetime | |
| df = pd.read_csv("hgl3 (4).csv") | |
| df['GAME_DATE_PACIFIC'] = pd.to_datetime(df['GAME_DATE_PACIFIC']) | |
| raw_stat_cols = { | |
| 'POINTS': 'Points', | |
| 'REBOUNDS': 'Rebounds', | |
| 'ASSISTS': 'Assists', | |
| 'THREES_MADE': 'Threes Made', | |
| 'BLOCKS': 'Blocks', | |
| 'STEALS': 'Steals', | |
| 'TURNOVERS': 'Turnovers' | |
| } | |
| combo_stats = { | |
| 'Points + Assists': ['POINTS', 'ASSISTS'], | |
| 'Points + Assists + Rebounds': ['POINTS', 'ASSISTS', 'REBOUNDS'], | |
| 'Rebounds + Assists': ['REBOUNDS', 'ASSISTS'], | |
| 'Steals + Blocks': ['STEALS', 'BLOCKS'] | |
| } | |
| default_start = df['GAME_DATE_PACIFIC'].min().date() | |
| default_end = df['GAME_DATE_PACIFIC'].max().date() | |
| def get_opponents(team): | |
| opponents = sorted(df[df['PLAYER_TEAM'] == team]['OPPONENT'].unique()) | |
| return ["All Opponents"] + opponents | |
| def was_traded(player, start_date, end_date): | |
| teams_played_for = df[ | |
| (df['PLAYER'] == player) & | |
| (df['GAME_DATE_PACIFIC'] >= start_date) & | |
| (df['GAME_DATE_PACIFIC'] <= end_date) | |
| ]['PLAYER_TEAM'].nunique() | |
| return teams_played_for > 1 | |
| def get_season_per36(player): | |
| player_df = df[df['PLAYER'] == player] | |
| total_minutes = player_df['MINUTES_PLAYED'].sum() | |
| if total_minutes == 0: | |
| return {**{display_name: 0.0 for display_name in raw_stat_cols.values()}, **{k: 0.0 for k in combo_stats}} | |
| season_stats = {} | |
| for raw_col, display_name in raw_stat_cols.items(): | |
| total_stat = player_df[raw_col].sum() | |
| per36_value = (total_stat / total_minutes) * 36 | |
| season_stats[display_name] = round(per36_value, 2) | |
| for combo_name, components in combo_stats.items(): | |
| total = player_df[components].sum(axis=1).sum() | |
| per36_value = (total / total_minutes) * 36 | |
| season_stats[combo_name] = round(per36_value, 2) | |
| return season_stats | |
| def format_stat(per36, diff, show_diff): | |
| if not show_diff: | |
| return f"{round(per36, 2)}" | |
| color = "green" if diff > 0 else "red" if diff < 0 else "black" | |
| sign = "+" if diff > 0 else "" | |
| return f"{round(per36, 2)} (<span style='color:{color}'>{sign}{round(diff, 2)}</span>)" | |
| def get_per36_stats(player_team, opponent, date_range, min_minutes, show_diff): | |
| team_df = df[df['PLAYER_TEAM'] == player_team] | |
| if opponent != "All Opponents": | |
| team_df = team_df[team_df['OPPONENT'] == opponent] | |
| start_date, end_date = date_range | |
| team_df = team_df[ | |
| (team_df['GAME_DATE_PACIFIC'] >= start_date) & | |
| (team_df['GAME_DATE_PACIFIC'] <= end_date) & | |
| (team_df['MINUTES_PLAYED'] >= min_minutes) | |
| ] | |
| if team_df.empty: | |
| return "No data available for this selection." | |
| season_avg_cache = {} | |
| output_rows = [] | |
| for player_name, group in team_df.groupby('PLAYER'): | |
| total_minutes = group['MINUTES_PLAYED'].sum() | |
| if total_minutes == 0: | |
| continue | |
| stats = {'Player': player_name, 'Minutes Played': round(total_minutes, 1)} | |
| if player_name not in season_avg_cache: | |
| season_avg_cache[player_name] = get_season_per36(player_name) | |
| season_avg = season_avg_cache[player_name] | |
| for raw_col, display_name in raw_stat_cols.items(): | |
| total_stat = group[raw_col].sum() | |
| per36_value = (total_stat / total_minutes) * 36 | |
| diff = per36_value - season_avg[display_name] | |
| stats[display_name] = format_stat(per36_value, diff, show_diff) | |
| for combo_name, components in combo_stats.items(): | |
| total = group[components].sum(axis=1).sum() | |
| per36_value = (total / total_minutes) * 36 | |
| diff = per36_value - season_avg[combo_name] | |
| stats[combo_name] = format_stat(per36_value, diff, show_diff) | |
| if was_traded(player_name, start_date, end_date): | |
| stats['Player'] += ' *' | |
| output_rows.append(stats) | |
| result_df = pd.DataFrame(output_rows) | |
| result_df.sort_values(by="Minutes Played", ascending=False, inplace=True) | |
| return result_df.to_html(escape=False, index=False) | |
| def get_opponent_stats(opponent, player_team, date_range, min_minutes, show_diff): | |
| if opponent == "All Opponents": | |
| return "" | |
| opponent_df = df[ | |
| (df['PLAYER_TEAM'] == opponent) & | |
| (df['OPPONENT'] == player_team) | |
| ] | |
| start_date, end_date = date_range | |
| opponent_df = opponent_df[ | |
| (opponent_df['GAME_DATE_PACIFIC'] >= start_date) & | |
| (opponent_df['GAME_DATE_PACIFIC'] <= end_date) & | |
| (opponent_df['MINUTES_PLAYED'] >= min_minutes) | |
| ] | |
| if opponent_df.empty: | |
| return "" | |
| season_avg_cache = {} | |
| output_rows = [] | |
| for player_name, group in opponent_df.groupby('PLAYER'): | |
| total_minutes = group['MINUTES_PLAYED'].sum() | |
| if total_minutes == 0: | |
| continue | |
| stats = {'Player': player_name, 'Minutes Played': round(total_minutes, 1)} | |
| if player_name not in season_avg_cache: | |
| season_avg_cache[player_name] = get_season_per36(player_name) | |
| season_avg = season_avg_cache[player_name] | |
| for raw_col, display_name in raw_stat_cols.items(): | |
| total_stat = group[raw_col].sum() | |
| per36_value = (total_stat / total_minutes) * 36 | |
| diff = per36_value - season_avg[display_name] | |
| stats[display_name] = format_stat(per36_value, diff, show_diff) | |
| for combo_name, components in combo_stats.items(): | |
| total = group[components].sum(axis=1).sum() | |
| per36_value = (total / total_minutes) * 36 | |
| diff = per36_value - season_avg[combo_name] | |
| stats[combo_name] = format_stat(per36_value, diff, show_diff) | |
| if was_traded(player_name, start_date, end_date): | |
| stats['Player'] += ' *' | |
| output_rows.append(stats) | |
| result_df = pd.DataFrame(output_rows) | |
| result_df.sort_values(by="Minutes Played", ascending=False, inplace=True) | |
| return result_df.to_html(escape=False, index=False) | |
| def wrapper(team, opponent, start_date_str, end_date_str, min_min, show_diff): | |
| try: | |
| start_date = datetime.strptime(start_date_str, "%Y-%m-%d") | |
| end_date = datetime.strptime(end_date_str, "%Y-%m-%d") | |
| except ValueError: | |
| return "Invalid date format. Use YYYY-MM-DD.", "" | |
| team_table = get_per36_stats(team, opponent, [start_date, end_date], min_min, show_diff) | |
| opponent_table = get_opponent_stats(opponent, team, [start_date, end_date], min_min, show_diff) | |
| return team_table, opponent_table | |
| with gr.Blocks() as demo: | |
| gr.Markdown("### Team PER 36 Stats Viewer with Filters") | |
| with gr.Row(): | |
| team_dropdown = gr.Dropdown(label="Select Team", choices=sorted(df['PLAYER_TEAM'].unique()), scale=1) | |
| opponent_dropdown = gr.Dropdown(label="Select Opponent", choices=["All Opponents"], scale=1) | |
| with gr.Row(): | |
| gr.Markdown(""" | |
| **Key Dates (Pacific Time):** | |
| - Regular Season Start: 2024-10-22 | |
| - In-Season Tournament Start: 2024-11-08 | |
| - In-Season Tournament End: 2024-12-09 | |
| """) | |
| gr.Markdown(""" | |
| - Trade Deadline: 2025-02-06 | |
| - All-Star Game: 2025-02-16 | |
| - Regular Season End: 2025-04-13 | |
| - Postseason Start: 2025-04-19 | |
| """) | |
| with gr.Row(): | |
| start_date_input = gr.Textbox(label="Start Date (YYYY-MM-DD)", value=str(default_start), type="text", scale=1, min_width=200) | |
| end_date_input = gr.Textbox(label="End Date (YYYY-MM-DD)", value=str(default_end), type="text", scale=1, min_width=200) | |
| min_minutes = gr.Slider(label="Minimum Minutes Played", minimum=0, maximum=48, value=0, step=1, scale=1) | |
| run_button = gr.Button("Show Stats") | |
| show_diff_checkbox = gr.Checkbox(label="Show Differences vs Full Season Average", value=True) | |
| gr.Markdown("*Players marked with an asterisk (\\*) were traded during the selected date range.*") | |
| gr.Markdown("#### Selected Team") | |
| team_output = gr.HTML() | |
| gr.Markdown("#### Opponent Team (if selected)") | |
| opponent_output = gr.HTML() | |
| team_dropdown.change( | |
| fn=lambda t: gr.update(choices=get_opponents(t), value="All Opponents"), | |
| inputs=team_dropdown, | |
| outputs=opponent_dropdown | |
| ) | |
| show_diff_checkbox.change( | |
| fn=wrapper, | |
| inputs=[team_dropdown, opponent_dropdown, start_date_input, end_date_input, min_minutes, show_diff_checkbox], | |
| outputs=[team_output, opponent_output] | |
| ) | |
| run_button.click( | |
| fn=wrapper, | |
| inputs=[team_dropdown, opponent_dropdown, start_date_input, end_date_input, min_minutes, show_diff_checkbox], | |
| outputs=[team_output, opponent_output] | |
| ) | |
| demo.launch() | |