File size: 10,334 Bytes
d0e7981
 
 
 
 
 
977ef2a
d0e7981
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a504793
c6f6b34
 
 
3822cd2
c6f6b34
3822cd2
fb7a65f
 
 
c6f6b34
 
 
 
 
fb7a65f
d0e7981
a504793
 
c6f6b34
 
 
 
fb7a65f
 
 
c6f6b34
 
 
 
 
 
d0e7981
 
 
 
 
 
977ef2a
 
 
 
 
 
 
 
 
d0e7981
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6f6b34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0e7981
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6f6b34
 
 
 
 
 
 
 
 
 
 
 
d0e7981
 
 
c6f6b34
977ef2a
d0e7981
 
 
c6f6b34
d0e7981
c6f6b34
d0e7981
 
 
 
 
 
 
 
 
 
 
 
 
 
977ef2a
 
 
 
 
2800ce0
 
 
 
 
d0e7981
 
 
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
import gradio as gr
import polars as pl
import numpy as np

from datetime import datetime
from functools import partial
from typing import Optional

from data import data_df
from stats import compute_player_stats, filter_data_by_date_and_game_kind
from convert import team_names_short_to_color, get_text_color_from_team
from plotting import stat_cmap


TEAMS  = [
    'Yomiuri',
    'Yakult',
    'DeNA',
    'Chunichi',
    'Hanshin',
    'Hiroshima',
    'Nipponham',
    'Rakuten',
    'Seibu',
    'Lotte',
    'ORIX',
    'SoftBank'
]


notes = '''**Limitations**
- [Column widths get messed up when filtering](https://github.com/gradio-app/gradio/issues/11564)

**To-do**
- Fix IP calculation
- Add post-season
'''


def get_col_width(col, player_team_type):
  match col:
    case 'Pitcher' | 'Batter':
      return 125
    case 'Team':
      return 75
    case 'Throws' | 'Bats':
      return 60
    case 'IP':
      return 60 if player_team_type == 'team pitching' else 50
    case _:
      return max(50, 10*len(col))


def create_player_team_leaderboard_app(player_team_type):
  pitching = player_team_type in ('pitcher', 'team pitching')
  team = 'team' in player_team_type

  # stats
  if pitching:
    pct_stats = ['K%', 'BB%', 'Swing%', 'Z-Swing%', 'Chase%', 'Contact%', 'Z-Contact%', 'O-Contact%', 'SwStr%', 'Whiff%', 'CSW%', 'Strike%', 'Ball%', 'F-Str%', 'PAR%', 'GB%', 'FB%', 'LD%', 'OFFB%', 'IFFB%', 'AIR%', 'Zone%', 'Arm%', 'Glove%', 'High%', 'Low%', 'MM%', 'Behind%']
    stats_with_pctls = ['FB Velo', 'K%', 'BB%', 'Swing%', 'Z-Swing%', 'Chase%', 'Contact%', 'Z-Contact%', 'O-Contact%', 'SwStr%', 'Whiff%', 'CSW%', 'Strike%', 'Ball%', 'F-Str%', 'PAR%', 'GB%', 'FB%', 'LD%', 'OFFB%', 'IFFB%', 'AIR%', 'Zone%', 'Behind%']
    # cols = ['Pitcher', 'Team', 'Throws', 'IP', 'TBF', 'FB Velo', 'K%', 'BB%', 'Swing%', 'Z-Swing%', 'Chase%', 'Contact%', 'Z-Contact%', 'O-Contact%', 'SwStr%', 'Whiff%', 'CSW%', 'Strike%', 'Ball%', 'F-Str%', 'PAR%', 'GB%', 'FB%', 'LD%', 'OFFB%', 'IFFB%', 'AIR%', 'Zone%', 'Arm%', 'Glove%', 'High%', 'Low%', 'MM%', 'Behind%']
    prefix_cols = ['Pitcher', 'Team', 'Throws', 'IP', 'TBF', 'FB Velo', 'K%', 'BB%']
    plate_disc_cols = ['Swing%', 'Z-Swing%', 'Chase%', 'Contact%', 'Z-Contact%', 'O-Contact%', 'SwStr%', 'Whiff%', 'CSW%', 'Strike%', 'Ball%', 'F-Str%', 'PAR%']
    batted_ball_cols = ['GB%', 'FB%', 'LD%', 'OFFB%', 'IFFB%', 'AIR%']
    approach_cols = ['Zone%', 'Arm%', 'Glove%', 'High%', 'Low%', 'MM%', 'Behind%']
    if team:
      # cols = [col for col in cols if col not in ('Pitcher', 'Throws')]
      prefix_cols = [col for col in prefix_cols if col not in ('Pitcher', 'Throws')]
    all_cols = {
      theme: prefix_cols + cols 
      for theme, cols 
      in {'Plate Discipline': plate_disc_cols, 'Batted Ball': batted_ball_cols, 'Approach': approach_cols}.items()
    }
    
  else:
    pct_stats = ['K%', 'BB%', 'Swing%', 'Z-Swing%', 'Chase%', 'Contact%', 'Z-Contact%', 'O-Contact%', 'SwStr%', 'Whiff%', 'CSW%', 'GB%', 'FB%', 'LD%', 'OFFB%', 'IFFB%', 'AIR%', 'Zone%', 'Arm%', 'Glove%', 'High%', 'Low%', 'MM%']
    stats_with_pctls = ['K%', 'BB%', 'Swing%', 'Z-Swing%', 'Chase%', 'Contact%', 'Z-Contact%', 'O-Contact%', 'SwStr%', 'Whiff%', 'CSW%', 'GB%', 'FB%', 'LD%', 'OFFB%', 'IFFB%', 'AIR%', 'Zone%'] # , 'OBP']
    # cols = ['Batter', 'Team', 'Bats', 'PA', 'K%', 'BB%', 'Swing%', 'Z-Swing%', 'Chase%', 'Contact%', 'Z-Contact%', 'O-Contact%', 'SwStr%', 'Whiff%', 'CSW%', 'GB%', 'FB%', 'LD%', 'OFFB%', 'IFFB%', 'AIR%']#, 'AB', 'H', 'BB', 'HBP', 'SF', 'OBP']
    prefix_cols = ['Batter', 'Team', 'Bats', 'PA', 'K%', 'BB%']
    plate_disc_cols = ['Swing%', 'Z-Swing%', 'Chase%', 'Contact%', 'Z-Contact%', 'O-Contact%', 'SwStr%', 'Whiff%', 'CSW%']
    batted_ball_cols = ['GB%', 'FB%', 'LD%', 'OFFB%', 'IFFB%', 'AIR%']
    if team:
      # cols = [col for col in cols if col not in ('Batter', 'Bats')]
      prefix_cols = [col for col in prefix_cols if col not in ('Batter', 'Bats')]
    all_cols = {
      theme: prefix_cols + cols 
      for theme, cols 
      in {'Plate Discipline': plate_disc_cols, 'Batted Ball': batted_ball_cols}.items()
    }
      

  # col names
  player_type = 'pitcher' if pitching else 'batter'
  id_col = f'{player_type[:3].lower()}Id' if not team else f'{player_type}_team_name_short'
  qual_name = 'IP' if pitching else 'PA'
  
  def gr_create_player_team_leaderboard(
    start_date: datetime, 
    end_date: datetime, 
    min_qual: int, 
    qualified: bool, 
    pitcher_lr: str='Both', 
    batter_lr: str = 'Both', 
    include_teams: Optional[list[str]] = None
  ):
    assert pitcher_lr in ['Both', 'Left', 'Right']
    assert batter_lr in ['Both', 'Left', 'Right']

    data = data_df.filter(pl.col('ballKind_code') != '-')
    
    data = filter_data_by_date_and_game_kind(data, start_date=start_date, end_date=end_date, game_kind='Regular Season')
    
    rename = {f'{player_type}_team_name_short': 'Team'}
    if not team:
      rename[f'{player_type}_name'] = player_type.title()
    if pitching:
      rename['PA'] = 'TBF'

    # typically "qualified" should be a valid input for min_ip for the current function, 
    # but we separate it from a numerical min_ip argument for API compabtibility
    pitcher_stats = (
          compute_player_stats(
            data, player_type=player_team_type, 
            pitcher_lr='both' if pitcher_lr=='Both' else pitcher_lr[0].lower(), 
            batter_lr='both' if batter_lr == 'Both' else batter_lr[0].lower(), 
            qual='qualified' if qualified else min_qual,
            group_by_team=not team
          )
          .filter(pl.col('qualified'))
          .drop(['qualified'] + ([id_col] if not team else []))
          .rename(rename)
          .with_columns(
            pl.col(stat).mul(100)
            for stat in pct_stats
          )
    )

    # if not team:
    if include_teams is not None:
      pitcher_stats = pitcher_stats.filter(pl.col('Team').is_in(include_teams))

    def create_df_value(cols):
      styling = []
      for i, row in enumerate(pitcher_stats[cols].iter_rows()):
        styling_row = []
        for col, item in zip(pitcher_stats[cols].columns, row):
          # _styling = 'font-size: 0.75em; '
          if col in stats_with_pctls:
            r, g, b = (stat_cmap([pitcher_stats[f'{col}_pctl'][i]])[0, :3]*255).astype(np.uint8)
            styling_row.append(f'color: black; background-color: rgba({r}, {g}, {b})')
          elif col == 'Team':
            styling_row.append(f'color: {get_text_color_from_team(item)}; background-color: {team_names_short_to_color[item]}')
          else:
            styling_row.append('')
        styling.append(styling_row)

      display_value = []
      for row in pitcher_stats[cols].iter_rows():
        display_value_row = []
        for col, item in zip(cols, row):
          if col in pct_stats:
            display_value_row.append(f'{item:.1f}%')
          elif col in ['OBP']:
            display_value_row.append(f'{item:.3f}')
          elif isinstance(item, float):
            display_value_row.append(f'{item:.1f}')
          else:
            display_value_row.append(item)
        display_value.append(display_value_row)

      value = {
          'data': pitcher_stats[cols].rows(),
          'headers': cols,
          'metadata': {
              'styling': styling,
              'display_value': display_value,
          }
      }
      
      return value

    return [create_df_value(cols) for cols in all_cols.values()]


  now = datetime.now()
  start_datetime_init = datetime(now.year, 1, 1)
  end_datetime_init = now
  with gr.Blocks() as app:
    gr.Markdown(f'# {player_team_type.title()} Leaderboard')
    with gr.Row():
      start_date = gr.DateTime(start_datetime_init, include_time=False, type='datetime', label='Start')
      end_date = gr.DateTime(end_datetime_init, include_time=False, type='datetime', label='End')
    with gr.Row():
      if not team:
        with gr.Group():
          min_ip = gr.Number(100, label=f'Min. {qual_name}', precision=0, minimum=0, interactive=False)
          qualified = gr.Checkbox(True, label='Qualified')
      else:
        min_ip = gr.State(0)
        qualified = gr.State(False)
      with gr.Group():
        pitcher_lr = gr.Radio(['Both', 'Left', 'Right'], value='Both', label='Pitcher handedness') 
        batter_lr = gr.Radio(['Both', 'Left', 'Right'], value='Both', label='Batter handedness')
    with gr.Row():
      include_teams = gr.CheckboxGroup(TEAMS, value=TEAMS, label='Teams', scale=3)
      all_teams = gr.Button('Select/Deselect all teams')
        
    search = gr.Button('Search')
    pin_columns = gr.Checkbox(True, label='Pin columns')
    leaderboards = []
    for theme, cols in all_cols.items():
      with gr.Tab(theme):
        leaderboard = gr.DataFrame(
          pl.DataFrame({'Pitcher': [], 'Pitch': []}),
          column_widths=[get_col_width(col, player_team_type) for col in cols],
          show_copy_button=True,
          show_search='filter',
          pinned_columns=1,
          elem_id='leaderboard'
        )
        leaderboards.append(leaderboard)

    gr.Markdown(notes)

    search.click(gr_create_player_team_leaderboard, inputs=[start_date, end_date, min_ip, qualified, pitcher_lr, batter_lr, include_teams], outputs=leaderboards)
    # gr.api(gr_create_player_team_leaderboard, api_name=f'gr_create_{player_team_type.replace(" ", "_")}_leaderboard')
    all_teams.click(lambda _teams : [] if _teams == TEAMS else TEAMS, inputs=include_teams, outputs=include_teams)
    qualified.change(lambda qualified: gr.Number(interactive=not qualified), inputs=qualified, outputs=min_ip)
    pin_columns.input(
      lambda pin: [gr.DataFrame(pinned_columns=1 if pin else None)]*len(all_cols),
      inputs=pin_columns,
      outputs=leaderboards
    )
    
  return app

create_pitcher_leaderboard = partial(
  create_player_team_leaderboard_app,
  player_team_type='pitcher'
)

create_team_pitching_leaderboard = partial(
  create_player_team_leaderboard_app,
  player_team_type='team pitching'
)

create_batter_leaderboard = partial(
  create_player_team_leaderboard_app,
  player_team_type='batter'
)

create_team_batting_leaderboard = partial(
  create_player_team_leaderboard_app,
  player_team_type='team batting'
)

if __name__ == '__main__':
  app = foo()
  app.launch()