Upload 27 files
Browse filesFiles changed (20)
- Dockerfile+12-12
- README.md+20-20
- api_scraper.py
- app.py+339-427
- functions/__pycache__/df_update.cpython-39.pyc
- functions/__pycache__/pitch_summary_functions.cpython-39.pyc
- functions/df_update.py+20-124
- functions/pitch_summary_functions.py
- joblib_model/barrel_model.joblib+2-2
- joblib_model/in_zone.joblib+2-2
- joblib_model/in_zone_model_knn_20240410.joblib+2-2
- joblib_model/linear_reg_model_x.joblib+2-2
- joblib_model/linear_reg_model_z.joblib+2-2
- joblib_model/model_attack_zone.joblib+2-2
- joblib_model/no_swing.joblib+2-2
- joblib_model/swing.joblib+2-2
- joblib_model/xwoba_model.joblib+2-2
- requirements.txt+15-16
- stuff_model/__pycache__/feature_engineering.cpython-39.pyc
- stuff_model/lgbm_model_2020_2023.joblib+2-2
12345678910111213FROM python:3.9WORKDIR /codeCOPY ./requirements.txt /code/requirements.txtRUN pip install --no-cache-dir --upgrade -r /code/requirements.txtCOPY . .EXPOSE 7860CMD ["shiny", "run", "app.py", "--host", "0.0.0.0", "--port", "7860"]12345678910111213FROM python:3.9WORKDIR /codeCOPY ./requirements.txt /code/requirements.txtRUN pip install --no-cache-dir --upgrade -r /code/requirements.txtCOPY . .EXPOSE 7860CMD ["shiny", "run", "app.py", "--host", "0.0.0.0", "--port", "7860"]
1234567891011121314151617181920---title: Pitching Summaryemoji: 🌍colorFrom: yellowcolorTo: indigosdk: dockerpinned: falselicense: mit---This is a templated Space for [Shiny for Python](https://shiny.rstudio.com/py/).To get started with a new app do the following:1) Install Shiny with `pip install shiny`2) Create a new app with `shiny create`3) Then run the app with `shiny run --reload`To learn more about this framework please see the [Documentation](https://shiny.rstudio.com/py/docs/overview.html).1234567891011121314151617181920---title: Pitching Summaryemoji: 🌍colorFrom: yellowcolorTo: indigosdk: dockerpinned: falselicense: mit---This is a templated Space for [Shiny for Python](https://shiny.rstudio.com/py/).To get started with a new app do the following:1) Install Shiny with `pip install shiny`2) Create a new app with `shiny create`3) Then run the app with `shiny run --reload`To learn more about this framework please see the [Documentation](https://shiny.rstudio.com/py/docs/overview.html).
12347 unmodified lines12131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488from shiny import App, ui, render, reactiveimport polars as plimport numpy as npimport pandas as pd7 unmodified linesimport requestsimport joblibfrom matplotlib.gridspec import GridSpecimport mathfrom pytabulator import TableOptions, Tabulator, output_tabulator, render_tabulator, themetheme.tabulator_site()colour_palette = ['#FFB000','#648FFF','#785EF0','#DC267F','#FE6100','#3D1EB2','#894D80','#16AA02','#B5592B','#A3C1ED']# df = pl.read_csv("data.csv")# df = pl.read_parquet("data_small.parquet")[:]# df = pl.read_parquet("data.parquet")[:]# print('df')season = 2024df_mlb = pl.read_parquet("data/data_mlb_2024.parquet")[:]df_aaa = pl.read_parquet("data/data_aaa_2024.parquet")[:]df_a = pl.read_parquet("data/data_a_2024.parquet")[:]def df_final(df:pl.dataframe,year_input:int,sport_id:int):df_schedule = scrape.get_schedule(year_input=[year_input],sport_id=[sport_id])df = df.join(df_schedule, on='game_id', how='left')df = df.with_columns(pl.when((pl.col('batter_team_id') == pl.col('away_id'))).then(pl.lit('Away')).when((pl.col('batter_team_id') == pl.col('home_id'))).then(pl.lit('Home')).otherwise(None).alias('home_away'))df = df.with_columns(pl.when((pl.col('pitcher_team_id') == pl.col('away_id'))).then(pl.lit('Away')).when((pl.col('pitcher_team_id') == pl.col('home_id'))).then(pl.lit('Home')).otherwise(None).alias('home_away_pitcher'))print('schedule')df_stuff = stuff_apply.stuff_apply(fe.feature_engineering(df))print('stuff')df_up = update.update(df)print('update')df_total = df_up.join(df_stuff[['play_id','tj_stuff_plus']], on='play_id', how='left')print('total')return df_totaldf_mlb_total = df_final(df=df_mlb,year_input=season,sport_id=1)df_aaa_total = df_final(df=df_aaa,year_input=season,sport_id=11)df_a_total = df_final(df=df_a.drop_nulls(subset=['start_speed']),year_input=season,sport_id=14)rounding_dict = {'pa': 0,'bip': 0,'hits': 0,'k': 0,'bb': 0,'max_launch_speed': 1,'launch_speed_90': 1,'launch_speed': 1,'pitches': 0,'tj_stuff_plus_avg': 0,'avg': 3,'obp': 3,'slg': 3,'ops': 3,'k_percent': 3,'bb_percent': 3,'k_minus_bb_percent': 3,'sweet_spot_percent': 3,'woba_percent': 3,'xwoba_percent': 3,'woba_percent_contact': 3,'xwoba_percent_contact': 3,'hard_hit_percent': 3,'barrel_percent': 3,'zone_contact_percent': 3,'zone_swing_percent': 3,'zone_percent': 3,'chase_percent': 3,'chase_contact': 3,'swing_percent': 3,'whiff_rate': 3,'swstr_rate': 3,'ground_ball_percent': 3,'line_drive_percent': 3,'fly_ball_percent': 3,'pop_up_percent': 3,'heart_zone_swing_percent': 3,'shadow_zone_swing_percent': 3,'chase_zone_swing_percent': 3,'waste_zone_swing_percent': 3,'heart_zone_whiff_percent': 3,'shadow_zone_whiff_percent': 3,'chase_zone_whiff_percent': 3,'waste_zone_whiff_percent': 3,'start_speed_avg': 1,'vb_avg': 1,'ivb_avg': 1,'hb_avg': 1,'z0_avg': 1,'x0_avg': 1,'vaa_avg': 1,'haa_avg': 1,'spin_rate_avg': 0,'extension_avg': 1}columns = [{ "title": "PA", "field": "pa", "width": 150},{ "title": "BBE", "field": "bip", "width": 150 },{ "title": "H", "field": "hits", "width": 150 },{ "title": "K", "field": "k", "width": 150 },{ "title": "BB", "field": "bb", "width": 150 },{ "title": "Max EV", "field": "max_launch_speed", "width": 150 },{ "title": "90th% EV", "field": "launch_speed_90", "width": 150 },{ "title": "EV", "field": "launch_speed", "width": 150 },{ "title": "Pitches", "field": "pitches", "width": 150 },{ "title": "AVG", "field": "avg", "width": 150 },{ "title": "OBP", "field": "obp", "width": 150 },{ "title": "SLG", "field": "slg", "width": 150 },{ "title": "OPS", "field": "ops", "width": 150 },{ "title": "K%", "field": "k_percent", "width": 150,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "BB%", "field": "bb_percent", "width": 150,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "K-BB%", "field": "k_minus_bb_percent", "width": 150,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "SwSpot%", "field": "sweet_spot_percent", "width": 150,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "wOBA", "field": "woba_percent", "width": 150 },{ "title": "xwOBA", "field": "xwoba_percent", "width": 150 },{ "title": "wOBACON", "field": "woba_percent_contact", "width": 150 },{ "title": "xwOBACON", "field": "xwoba_percent_contact", "width": 150 },{ "title": "HardHit%", "field": "hard_hit_percent", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "Barrel%", "field": "barrel_percent", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "Z-Contact%", "field": "zone_contact_percent", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "Z-Swing%", "field": "zone_swing_percent", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "Zone%", "field": "zone_percent", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "O-Swing%", "field": "chase_percent", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "O-Contact%", "field": "chase_contact", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "Swing%", "field": "swing_percent", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "Whiff%", "field": "whiff_rate", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "SwStr%", "field": "swstr_rate", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "GB%", "field": "ground_ball_percent", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "LD%", "field": "line_drive_percent", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "FB%", "field": "fly_ball_percent", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "PU%", "field": "pop_up_percent", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "Heart Swing%", "field": "heart_zone_swing_percent", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "Shadow Swing%", "field": "shadow_zone_swing_percent", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "Chase Swing%", "field": "chase_zone_swing_percent", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "Waste Swing%", "field": "waste_zone_swing_percent", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "Heart Whiff%", "field": "heart_zone_whiff_percent", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "Shadow Whiff%", "field": "shadow_zone_whiff_percent", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "Chase Whiff%", "field": "chase_zone_whiff_percent", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "Waste Whiff%", "field": "waste_zone_whiff_percent", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "tjStuff+", "field": "tj_stuff_plus_avg", "width": 150 },{ "title": "Velocity", "field": "start_speed_avg", "width": 150 },{ "title": "Extension", "field": "extension_avg", "width": 150 },{ "title": "VB", "field": "vb_avg", "width": 150 },{ "title": "iVB", "field": "ivb_avg", "width": 150 },{ "title": "HB", "field": "hb_avg", "width": 150 },{ "title": "vRel", "field": "z0_avg", "width": 150 },{ "title": "hRel", "field": "x0_avg", "width": 150 },{ "title": "VAA", "field": "vaa_avg", "width": 150 },{ "title": "HAA", "field": "haa_avg", "width": 150 },{ "title": "Spin Rate", "field": "spin_rate_avg", "width": 150 },{ "title": "Extension", "field": "extension_avg", "width": 150 },]stat_titles = dict(zip([col["field"] for col in columns],[col["title"] for col in columns]))stat_selection = [key for key in stat_titles.keys()]agg_titles = {'batter_id':'Batter ID','batter_name':'Batter Name','batter_team':'Batter Team','batter_hand':'Batter Hand','pitcher_id':'Pitcher ID','pitcher_name':'Pitcher Name','pitcher_team':'Pitcher Team','pitcher_hand':'Pitcher Hand','pitch_type':'Pitch Type','pitch_group':'Pitch Group','home_away_batter':'Home/Away Batter','home_away_pitcher':'Home/Away Pitcher','is_swing':'Is Swing?','is_bip':'Is BIP?','in_zone_final':'In Zone?','attack_zone_final':'Attack Zone'}columns_group = [{ "title": "Batter ID", "field": "batter_id", "width": 150, "headerFilter":"input","frozen":True,},{ "title": "Batter Name", "field": "batter_name", "width": 200,"frozen":True, "headerFilter":"input" },{ "title": "Batter Team", "field": "batter_team", "width": 150,"frozen":True, "headerFilter":"input" },{ "title": "Batter Hand", "field": "batter_hand", "width": 150,"frozen":True, "headerFilter":"input" },{ "title": "Pitcher ID", "field": "pitcher_id", "width": 150,"frozen":True, "headerFilter":"input" },{ "title": "Pitcher Name", "field": "pitcher_name", "width": 200,"frozen":True, "headerFilter":"input" },{ "title": "Pitcher Team", "field": "pitcher_team", "width": 150,"frozen":True, "headerFilter":"input" },{ "title": "Pitcher Hand", "field": "pitcher_hand", "width": 150,"frozen":True, "headerFilter":"input" },{ "title": "Pitch Type", "field": "pitch_type", "width": 150,"frozen":True, "headerFilter":"input" },{ "title": "Pitch Group", "field": "pitch_group", "width": 150,"frozen":True, "headerFilter":"input" },{ "title": "Home/Away Batter", "field": "home_away_batter", "width": 150,"frozen":True, "headerFilter":"input" },{ "title": "Home/Away Pitcher", "field": "home_away_pitcher", "width": 150,"frozen":True, "headerFilter":"input" },{ "title": "Is Swing?", "field": "is_swing", "width": 150,"frozen":True, "headerFilter":"input" },{ "title": "Is BIP?", "field": "is_bip", "width": 150,"frozen":True, "headerFilter":"input" },{ "title": "In Zone?", "field": "in_zone_final", "width": 150,"frozen":True, "headerFilter":"input" },{ "title": "Attack Zone", "field": "attack_zone_final", "width": 150,"frozen":True, "headerFilter":"input" }]app_ui = ui.page_sidebar(ui.sidebar(ui.input_selectize("level_input","Select Level:",choices=['MLB','AAA','A'],multiple=False,selected=['MLB']),ui.input_selectize("list_input","Select Aggregation:",choices=agg_titles,multiple=True,selected=['batter_id', 'batter_name']),ui.input_selectize("list_stats","Select Stats:",choices=stat_titles,multiple=True,selected=['pa']),ui.input_date_range("date_id","Select Date Range",start=f'{season}-01-01',end=f'{season}-12-01',min=f'{season}-01-01',max=f'{season}-12-01',),ui.hr(),ui.h4("Filters"),ui.div({"id": "filter-container"},ui.div({"class": "filter-row", "id": "filter_row_1"}, # Add id for deletionui.row(ui.column(5, # Adjusted column widths to make room for delete buttonui.input_select("filter_column_1","Metric",choices={})),ui.column(3,ui.input_select("filter_operator_1","Operator",choices=[">=", "<="]),),ui.column(3,ui.input_numeric("filter_value_1","Value",value=0)),ui.column(1,ui.markdown(" "),ui.input_action_button(f"delete_filter_1","",class_="btn-danger btn-sm",style="padding: 3px 6px;",icon='✖'))))),ui.input_action_button("add_filter","Add Filter",class_="btn-secondary"),ui.br(),ui.br(),ui.input_action_button("generate_table","Generate Table",class_="btn-primary"),width="400px"),ui.navset_tab(ui.nav_panel("Leaderboard",ui.card(#ui.card_header("Leaderboard"),output_tabulator("tabulator"))),))def server(input, output, session):# Store the number of active filtersfilter_count = reactive.value(1)# Store active filter IDsactive_filters = reactive.value([1])@reactive.effect@reactive.event(input.list_stats)def _():stat_choices = {k: k for k in input.list_stats()}filtered_stat_choices = {key: stat_titles[key] for key in stat_choices}ui.update_select("filter_column_1", choices=filtered_stat_choices)@reactive.effect@reactive.event(input.add_filter)def _():current_count = filter_count.get()new_count = current_count + 1stat_choices = {k: k for k in input.list_stats()}filtered_stat_choices = {key: stat_titles[key] for key in stat_choices}ui.insert_ui(selector="#filter-container",where="beforeEnd",ui=ui.div({"class": "filter-row", "id": f"filter_row_{new_count}"},ui.row(ui.column(5,ui.input_select(f"filter_column_{new_count}","Metric",choices=filtered_stat_choices),),ui.column(3,ui.input_select(f"filter_operator_{new_count}","Operator",choices=[">=", "<="]),),ui.column(3,ui.input_numeric(f"filter_value_{new_count}","Value",value=0)),ui.column(1,ui.markdown(" "),ui.input_action_button(f"delete_filter_{new_count}","",class_="btn-danger btn-sm",style="padding: 3px 6px;",icon='✖')))))filter_count.set(new_count)current_filters = active_filters.get()current_filters.append(new_count)active_filters.set(current_filters)@reactive.effectdef _():# Monitor all possible delete buttonsfor i in range(1, filter_count.get() + 1):try:if getattr(input, f"delete_filter_{i}")() > 0:# Remove the filter rowui.remove_ui(f"#filter_row_{i}")# Update active filterscurrent_filters = active_filters.get()if i in current_filters:current_filters.remove(i)active_filters.set(current_filters)except:continue@output@render_tabulator@reactive.event(input.generate_table, ignore_none=False)def tabulator():columns_c = columns.copy()selection_list = list(input.list_input())start_date = str(input.date_id()[0])end_date = str(input.date_id()[1])if input.level_input() == "MLB":df_agg = update.update_summary_select(df=df_mlb_total.filter((pl.col('game_date')>=start_date)&(pl.col('game_date')<=end_date)),selection=selection_list)elif input.level_input() == "AAA":df_agg = update.update_summary_select(df=df_aaa_total.filter((pl.col('game_date')>=start_date)&(pl.col('game_date')<=end_date)),selection=selection_list)elif input.level_input() == "A":df_agg = update.update_summary_select(df=df_a_total.filter((pl.col('game_date')>=start_date)&(pl.col('game_date')<=end_date)),selection=selection_list)df_agg = df_agg.select(selection_list + list(input.list_stats()))#.sort('pa', descending=True)# Apply filters - only for active filtersfor i in active_filters.get():try:col_name = getattr(input, f"filter_column_{i}")()if col_name: # Only apply filter if column is selectedoperator = getattr(input, f"filter_operator_{i}")()if col_name in [col["field"] for col in columns_c if col.get("formatter") == "money"]:value = getattr(input, f"filter_value_{i}")()/100else:value = getattr(input, f"filter_value_{i}")()if operator == ">=":df_agg = df_agg.filter(pl.col(col_name) >= value)elif operator == "<=":df_agg = df_agg.filter(pl.col(col_name) <= value)except:continuefor col in df_agg.columns[len(selection_list):]:if col in rounding_dict:df_agg = df_agg.with_columns(pl.col(col).round(rounding_dict[col]))for column in columns_c:if column.get("formatter") == "money" and column.get("field") in df_agg.columns:df_agg = df_agg.with_columns(pl.col(column.get("field"))*100)col_group = []for column in columns_group:if column.get("field") in df_agg.columns:col_group.append(column)col_group_stats = []for column in columns_c:if column.get("field") in df_agg.columns:col_group_stats.append(column)columns_c = col_group + col_group_statsreturn Tabulator(df_agg.to_pandas(),table_options=TableOptions(height=800,columns=columns_c,))app = App(app_ui, server)1237 unmodified lines1112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400import polars as plimport numpy as npimport pandas as pd7 unmodified linesimport requestsimport joblibfrom matplotlib.gridspec import GridSpecfrom shiny import App, reactive, ui, renderfrom shiny.ui import h2, tagsimport matplotlib.pyplot as pltimport matplotlib.gridspec as gridspecimport seaborn as snsfrom functions.pitch_summary_functions import *from shiny import App, reactive, ui, renderfrom shiny.ui import h2, tagscolour_palette = ['#FFB000','#648FFF','#785EF0','#DC267F','#FE6100','#3D1EB2','#894D80','#16AA02','#B5592B','#A3C1ED']year_list = [2017,2018,2019,2020,2021,2022,2023,2024]level_dict = {'1':'MLB','11':'AAA',# '12':'AA',#'13':'A+','14':'A','17':'AFL','22':'College','21':'Prospects','51':'International' }function_dict={'velocity_kdes':'Velocity Distributions','break_plot':'Pitch Movement','tj_stuff_roling':'Rolling tjStuff+ by Pitch','tj_stuff_roling_game':'Rolling tjStuff+ by Game','location_plot_lhb':'Locations vs LHB','location_plot_rhb':'Locations vs RHB',}split_dict = {'all':'All','left':'LHH','right':'RHH'}split_dict_hand = {'all':['L','R'],'left':['L'],'right':['R']}type_dict = {'R':'Regular Season','S':'Spring','P':'Playoffs' }# List of MLB teams and their corresponding ESPN logo URLsmlb_teams = [{"team": "AZ", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/ari.png&h=500&w=500"},{"team": "ATH", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/oak.png&h=500&w=500"},{"team": "ATL", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/atl.png&h=500&w=500"},{"team": "BAL", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/bal.png&h=500&w=500"},{"team": "BOS", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/bos.png&h=500&w=500"},{"team": "CHC", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/chc.png&h=500&w=500"},{"team": "CWS", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/chw.png&h=500&w=500"},{"team": "CIN", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/cin.png&h=500&w=500"},{"team": "CLE", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/cle.png&h=500&w=500"},{"team": "COL", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/col.png&h=500&w=500"},{"team": "DET", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/det.png&h=500&w=500"},{"team": "HOU", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/hou.png&h=500&w=500"},{"team": "KC", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/kc.png&h=500&w=500"},{"team": "LAA", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/laa.png&h=500&w=500"},{"team": "LAD", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/lad.png&h=500&w=500"},{"team": "MIA", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/mia.png&h=500&w=500"},{"team": "MIL", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/mil.png&h=500&w=500"},{"team": "MIN", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/min.png&h=500&w=500"},{"team": "NYM", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/nym.png&h=500&w=500"},{"team": "NYY", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/nyy.png&h=500&w=500"},{"team": "PHI", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/phi.png&h=500&w=500"},{"team": "PIT", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/pit.png&h=500&w=500"},{"team": "SD", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/sd.png&h=500&w=500"},{"team": "SF", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/sf.png&h=500&w=500"},{"team": "SEA", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/sea.png&h=500&w=500"},{"team": "STL", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/stl.png&h=500&w=500"},{"team": "TB", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/tb.png&h=500&w=500"},{"team": "TEX", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/tex.png&h=500&w=500"},{"team": "TOR", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/tor.png&h=500&w=500"},{"team": "WSH", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/wsh.png&h=500&w=500"},{"team": "ZZZ", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/leagues/500/mlb.png&w=500&h=500"}]df_image = pd.DataFrame(mlb_teams)image_dict = df_image.set_index('team')['logo_url'].to_dict()image_dict_flip = df_image.set_index('logo_url')['team'].to_dict()# # Define the features to be used for training# features_table = ['start_speed',# 'spin_rate',# 'extension',# 'ivb',# 'hb',# 'x0',# 'z0',# 'tj_stuff_plus']from shiny import App, reactive, ui, renderfrom shiny.ui import h2, tags# Define the UI layout for the appapp_ui = ui.page_sidebar(ui.sidebar(# Row for selecting season and levelui.row(ui.column(4, ui.input_select('year_input', 'Select Season', year_list, selected=2024)),ui.column(4, ui.input_select('level_input', 'Select Level', level_dict)),ui.column(4, ui.input_select('type_input', 'Select Type', type_dict,selected='R'))),# Row for the action button to get player listui.row(ui.input_action_button("player_button", "Get Player List", class_="btn-primary")),# Row for selecting the playerui.row(ui.column(12, ui.output_ui('player_select_ui', 'Select Player'))),# Row for selecting the date rangeui.row(ui.column(12, ui.output_ui('date_id', 'Select Date'))),# Rows for selecting plots and split optionsui.row(ui.column(4, ui.input_select('plot_id_1', 'Plot Left', function_dict, multiple=False, selected='velocity_kdes')),ui.column(4, ui.input_select('plot_id_2', 'Plot Middle', function_dict, multiple=False, selected='tj_stuff_roling')),ui.column(4, ui.input_select('plot_id_3', 'Plot Right', function_dict, multiple=False, selected='break_plot'))),ui.row(ui.column(6, ui.input_select('split_id', 'Select Split', split_dict, multiple=False)),ui.column(6, ui.input_numeric('rolling_window', 'Rolling Window (for tjStuff+ Plot)', min=1, value=50))),ui.row(ui.column(6, ui.input_switch("switch", "Custom Team?", False)),ui.column(6, ui.input_select('logo_select', 'Select Custom Logo', image_dict_flip, multiple=False))),# Row for the action button to generate plotui.row(ui.input_action_button("generate_plot", "Generate Plot", class_="btn-primary")),width="400px" # Added this parameter to control sidebar width),# Main content area with tabs (placed directly in page_sidebar)ui.navset_tab(ui.nav_panel("Pitching Summary",ui.output_text("status"),ui.output_plot('plot', width='2100px', height='2100px')),ui.nav_panel("Summary Table",ui.output_data_frame("grid"))))def server(input, output, session):@reactive.calc@reactive.event(input.pitcher_id, input.date_id,input.split_id)def cached_data():year_input = int(input.year_input())sport_id = int(input.level_input())player_input = int(input.pitcher_id())start_date = str(input.date_id()[0])end_date = str(input.date_id()[1])# Simulate an expensive data operationgame_list = scrape.get_player_games_list(sport_id = sport_id,season = year_input,player_id = player_input,start_date = start_date,end_date = end_date,game_type = [input.type_input()])data_list = scrape.get_data(game_list_input = game_list[:])df = (stuff_apply.stuff_apply(fe.feature_engineering(update.update(scrape.get_data_df(data_list = data_list).filter((pl.col("pitcher_id") == player_input)&(pl.col("is_pitch") == True)&(pl.col("start_speed") >= 50)&(pl.col('batter_hand').is_in(split_dict_hand[input.split_id()])))))).with_columns(pl.col('pitch_type').count().over('pitch_type').alias('pitch_count')))return df@render.ui@reactive.event(input.player_button, input.year_input, input.level_input, input.type_input,ignore_none=False)def player_select_ui():# Get the list of pitchers for the selected level and seasondf_pitcher_info = scrape.get_players(sport_id=int(input.level_input()), season=int(input.year_input()), game_type = [input.type_input()]).filter(pl.col("position").is_in(['P','TWP'])).sort("name")# Create a dictionary of pitcher IDs and namespitcher_dict = dict(zip(df_pitcher_info['player_id'], df_pitcher_info['name']))# Return a select input for choosing a pitcherreturn ui.input_select("pitcher_id", "Select Pitcher", pitcher_dict, selectize=True)@render.ui@reactive.event(input.player_button, input.year_input, input.level_input, input.type_input,ignore_none=False)def date_id():# Create a date range input for selecting the date range within the selected yearreturn ui.input_date_range("date_id", "Select Date Range",start=f"{int(input.year_input())}-01-01",end=f"{int(input.year_input())}-12-31",min=f"{int(input.year_input())}-01-01",max=f"{int(input.year_input())}-12-31")@output@render.textdef status():# Only show status when generatingif input.generate == 0:return ""return ""@output@render.plot@reactive.event(input.generate_plot, ignore_none=False)def plot():# Show progress/loading notificationwith ui.Progress(min=0, max=1) as p:p.set(message="Generating plot", detail="This may take a while...")p.set(0.3, "Gathering data...")year_input = int(input.year_input())sport_id = int(input.level_input())player_input = int(input.pitcher_id())start_date = str(input.date_id()[0])end_date = str(input.date_id()[1])print(year_input, sport_id, player_input, start_date, end_date)df = cached_data()df = df.clone()p.set(0.6, "Creating plot...")#plt.rcParams["figure.figsize"] = [10,10]fig = plt.figure(figsize=(26,26))plt.rcParams.update({'figure.autolayout': True})fig.set_facecolor('white')sns.set_theme(style="whitegrid", palette=colour_palette)print('this is the one plot')gs = gridspec.GridSpec(6, 8,height_ratios=[5,20,12,36,36,7],width_ratios=[4,18,18,18,18,18,18,4])gs.update(hspace=0.2, wspace=0.5)# Define the positions of each subplot in the gridax_headshot = fig.add_subplot(gs[1,1:3])ax_bio = fig.add_subplot(gs[1,3:5])ax_logo = fig.add_subplot(gs[1,5:7])ax_season_table = fig.add_subplot(gs[2,1:7])ax_plot_1 = fig.add_subplot(gs[3,1:3])ax_plot_2 = fig.add_subplot(gs[3,3:5])ax_plot_3 = fig.add_subplot(gs[3,5:7])ax_table = fig.add_subplot(gs[4,1:7])ax_footer = fig.add_subplot(gs[-1,1:7])ax_header = fig.add_subplot(gs[0,1:7])ax_left = fig.add_subplot(gs[:,0])ax_right = fig.add_subplot(gs[:,-1])# Hide axes for footer, header, left, and rightax_footer.axis('off')ax_header.axis('off')ax_left.axis('off')ax_right.axis('off')sns.set_theme(style="whitegrid", palette=colour_palette)fig.set_facecolor('white')df_teams = scrape.get_teams()player_headshot(player_input=player_input, ax=ax_headshot,sport_id=sport_id,season=year_input)player_bio(pitcher_id=player_input, ax=ax_bio,sport_id=sport_id,year_input=year_input)if input.switch():# Get the logo URL from the image dictionary using the team abbreviationlogo_url = input.logo_select()# Send a GET request to the logo URLresponse = requests.get(logo_url)# Open the image from the response contentimg = Image.open(BytesIO(response.content))# Display the image on the axisax_logo.set_xlim(0, 1.3)ax_logo.set_ylim(0, 1)ax_logo.imshow(img, extent=[0.3, 1.3, 0, 1], origin='upper')# Turn off the axisax_logo.axis('off')else:plot_logo(pitcher_id=player_input, ax=ax_logo, df_team=df_teams,df_players=scrape.get_players(sport_id,year_input))stat_summary_table(df=df,ax=ax_season_table,player_input=player_input,split=input.split_id(),sport_id=sport_id,game_type=[input.type_input()])# break_plot(df=df_plot,ax=ax2)for x,y,z in zip([input.plot_id_1(),input.plot_id_2(),input.plot_id_3()],[ax_plot_1,ax_plot_2,ax_plot_3],[1,3,5]):if x == 'velocity_kdes':velocity_kdes(df,ax=y,gs=gs,gs_x=[3,4],gs_y=[z,z+2],fig=fig)if x == 'tj_stuff_roling':tj_stuff_roling(df=df,window=int(input.rolling_window()),ax=y)if x == 'tj_stuff_roling_game':tj_stuff_roling_game(df=df,window=int(input.rolling_window()),ax=y)if x == 'break_plot':break_plot(df = df,ax=y)if x == 'location_plot_lhb':location_plot(df = df,ax=y,hand='L')if x == 'location_plot_rhb':location_plot(df = df,ax=y,hand='R')summary_table(df=df,ax=ax_table)plot_footer(ax_footer)fig.subplots_adjust(left=0.01, right=0.99, top=0.99, bottom=0.01)@output@render.data_frame@reactive.event(input.generate_plot, ignore_none=False)def grid():df = cached_data()df = df.clone()features_table = ['start_speed','spin_rate','extension','ivb','hb','x0','z0']selection = ['game_id','pitcher_id','pitcher_name','batter_id','batter_name','pitcher_hand','batter_hand','balls','strikes','play_code','event_type','pitch_type','vaa','haa']+features_table+['tj_stuff_plus']return render.DataGrid(df.select(selection).to_pandas().round(1),row_selection_mode='multiple',height='700px',width='fit-content',filters=True,)app = App(app_ui, server)app = App(app_ui, server)
137 unmodified lines1381391401411421431441451461471481491501511521531541551561571581591601611621631641652 unmodified lines16816917017117217317417517617717817918018118218318418548 unmodified lines234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317144 unmodified lines46246346446546646746837 unmodified lines5065075085095105115125135145155165175185195205215225 unmodified lines52852953053153253353428 unmodified lines563564565566567568569570571572573574575576577578137 unmodified lines])df = df.with_columns([pl.when(df['event_type'].is_in(woba_codes)).then(1).otherwise(None).alias('woba_codes'),pl.when(df['event_type'].is_in(woba_codes)).then(1).otherwise(None).alias('xwoba_codes'),pl.when((pl.col('tb') >= 0)).then(df['woba']).otherwise(None).alias('woba_contact'),pl.when(pl.col('px').is_null()).then(pl.col('px_predict')).otherwise(pl.col('px')).alias('px'),pl.when(pl.col('pz').is_null()).then(pl.col('pz_predict')).otherwise(pl.col('pz')).alias('pz'),pl.when(pl.col('in_zone').is_null()).then(pl.col('in_zone_predict')).otherwise(pl.col('in_zone')).alias('in_zone_final'),])df = df.with_columns([pl.when(df['launch_speed'].is_null()).then(None).otherwise(df['barrel']).alias('barrel'),pl.lit('average').alias('average'),pl.when(pl.col('in_zone_final') == False).then(True).otherwise(False).alias('out_zone'),pl.when((pl.col('in_zone_final') == True) & (pl.col('swings') == 1)).then(True).otherwise(False).alias('zone_swing'),pl.when((pl.col('in_zone_final') == True) & (pl.col('swings') == 1) & (pl.col('whiffs') == 0)).then(True).otherwise(False).alias('zone_contact'),pl.when((pl.col('in_zone_final') == False) & (pl.col('swings') == 1)).then(True).otherwise(False).alias('ozone_swing'),pl.when((pl.col('in_zone_final') == False) & (pl.col('swings') == 1) & (pl.col('whiffs') == 0)).then(True).otherwise(False).alias('ozone_contact'),pl.when(pl.col('event_type').str.contains('strikeout')).then(True).otherwise(False).alias('k'),pl.when(pl.col('event_type').is_in(['walk', 'intent_walk'])).then(True).otherwise(False).alias('bb'),pl.when(pl.col('attack_zone').is_null()).then(pl.col('attack_zone_predict')).otherwise(pl.col('attack_zone')).alias('attack_zone_final'),])2 unmodified lines(df['k'].cast(pl.Float32) - df['bb'].cast(pl.Float32)).alias('k_minus_bb'),(df['bb'].cast(pl.Float32) - df['k'].cast(pl.Float32)).alias('bb_minus_k'),(df['launch_speed'] > 0).alias('bip_div'),(df['attack_zone_final'] == 0).alias('heart'),(df['attack_zone_final'] == 1).alias('shadow'),(df['attack_zone_final'] == 2).alias('chase'),(df['attack_zone_final'] == 3).alias('waste'),((df['attack_zone_final'] == 0) & (df['swings'] == 1)).alias('heart_swing'),((df['attack_zone_final'] == 1) & (df['swings'] == 1)).alias('shadow_swing'),((df['attack_zone_final'] == 2) & (df['swings'] == 1)).alias('chase_swing'),((df['attack_zone_final'] == 3) & (df['swings'] == 1)).alias('waste_swing'),((df['attack_zone_final'] == 0) & (df['whiffs'] == 1)).alias('heart_whiff'),((df['attack_zone_final'] == 1) & (df['whiffs'] == 1)).alias('shadow_whiff'),((df['attack_zone_final'] == 2) & (df['whiffs'] == 1)).alias('chase_whiff'),((df['attack_zone_final'] == 3) & (df['whiffs'] == 1)).alias('waste_whiff')])48 unmodified lines# Check if 'trajectory_null' column exists and drop itif 'trajectory_null' in df.columns:df = df.drop('trajectory_null')pitch_cat = {'FA': None,'FF': 'Fastball','FT': 'Fastball','FC': 'Fastball','FS': 'Off-Speed','FO': 'Off-Speed','SI': 'Fastball','ST': 'Breaking','SL': 'Breaking','CU': 'Breaking','KC': 'Breaking','SC': 'Off-Speed','GY': 'Off-Speed','SV': 'Breaking','CS': 'Breaking','CH': 'Off-Speed','KN': 'Off-Speed','EP': 'Breaking','UN': None,'IN': None,'PO': None,'AB': None,'AS': None,'NP': None}df = df.with_columns(df["pitch_type"].map_elements(lambda x: pitch_cat.get(x, x)).alias("pitch_group"))df = df.with_columns([(-(pl.col('vy0')**2 - (2 * pl.col('ay') * (pl.col('y0') - 17/12)))**0.5).alias('vy_f'),])df = df.with_columns([((pl.col('vy_f') - pl.col('vy0')) / pl.col('ay')).alias('t'),])df = df.with_columns([(pl.col('vz0') + (pl.col('az') * pl.col('t'))).alias('vz_f'),(pl.col('vx0') + (pl.col('ax') * pl.col('t'))).alias('vx_f')])df = df.with_columns([(-np.arctan(pl.col('vz_f') / pl.col('vy_f')) * (180 / np.pi)).alias('vaa'),(-np.arctan(pl.col('vx_f') / pl.col('vy_f')) * (180 / np.pi)).alias('haa')])# Mirror horizontal break for left-handed pitchersdf = df.with_columns(pl.when(pl.col('pitcher_hand') == 'L').then(-pl.col('ax')).otherwise(pl.col('ax')).alias('ax'))# Mirror horizontal break for left-handed pitchersdf = df.with_columns(pl.when(pl.col('pitcher_hand') == 'L').then(-pl.col('hb')).otherwise(pl.col('hb')).alias('hb'))# Mirror horizontal release point for left-handed pitchersdf = df.with_columns(pl.when(pl.col('pitcher_hand') == 'L').then(pl.col('x0')).otherwise(-pl.col('x0')).alias('x0'))df = df.with_columns([pl.when(df['swings'].is_null()).then(None).otherwise(df['swings']).alias('is_swing'),pl.when(df['bip'].is_null()).then(None).otherwise(df['bip']).alias('is_bip')])return df# Assuming df is your Polars DataFrame144 unmodified linespl.col('k').sum().alias('k'),pl.col('bb').sum().alias('bb'),pl.col('bb_minus_k').sum().alias('bb_minus_k'),pl.col('k_minus_bb').sum().alias('k_minus_bb'),pl.col('csw').sum().alias('csw'),pl.col('bip').sum().alias('bip'),pl.col('bip_div').sum().alias('bip_div'),37 unmodified linespl.col('shadow_whiff').sum().alias('shadow_whiff'),pl.col('chase_whiff').sum().alias('chase_whiff'),pl.col('waste_whiff').sum().alias('waste_whiff'),pl.col('tj_stuff_plus').sum().alias('tj_stuff_plus'),pl.col('start_speed').sum(),pl.col('vb').sum(),pl.col('ivb').sum(),pl.col('hb').sum(),pl.col('x0').sum(),pl.col('z0').sum(),pl.col('vaa').sum(),pl.col('haa').sum(),pl.col('spin_rate').sum(),pl.col('extension').sum(),])# Add calculated columns to the summary DataFrame5 unmodified lines(pl.col('k') / pl.col('pa')).alias('k_percent'),(pl.col('bb') / pl.col('pa')).alias('bb_percent'),(pl.col('bb_minus_k') / pl.col('pa')).alias('bb_minus_k_percent'),(pl.col('k_minus_bb') / pl.col('pa')).alias('k_minus_bb_percent'),(pl.col('bb') / pl.col('k')).alias('bb_over_k_percent'),(pl.col('csw') / pl.col('pitches')).alias('csw_percent'),(pl.col('sweet_spot') / pl.col('bip_div')).alias('sweet_spot_percent'),28 unmodified lines(pl.col('xwoba') / pl.col('xwoba_codes')).alias('xwoba_percent'),(pl.col('xwoba_contact') / pl.col('bip')).alias('xwoba_percent_contact'),(pl.col('tj_stuff_plus') / pl.col('pitches')).alias('tj_stuff_plus_avg'),(pl.col('start_speed')/ pl.col('pitches')).alias('start_speed_avg'),(pl.col('vb')/ pl.col('pitches')).alias('vb_avg'),(pl.col('ivb')/ pl.col('pitches')).alias('ivb_avg'),(pl.col('hb')/ pl.col('pitches')).alias('hb_avg'),(pl.col('x0')/ pl.col('pitches')).alias('x0_avg'),(pl.col('z0')/ pl.col('pitches')).alias('z0_avg'),(pl.col('vaa')/ pl.col('pitches')).alias('vaa_avg'),(pl.col('haa')/ pl.col('pitches')).alias('haa_avg'),(pl.col('spin_rate')/ pl.col('pitches')).alias('spin_rate_avg'),(pl.col('extension')/ pl.col('pitches')).alias('extension_avg'),])137 unmodified lines1381391401411421431441451461471481491501511521531541551561571581591602 unmodified lines16316416516616716816917017117217317417517617717817918048 unmodified lines229230231232233234235144 unmodified lines38038138238338438537 unmodified lines4234244254264274284295 unmodified lines43543643743843944028 unmodified lines469470471472473474137 unmodified lines])df = df.with_columns([pl.when(df['event_type'].is_in(woba_codes)).then(1).otherwise(None).alias('woba_codes'),pl.when(df['event_type'].is_in(woba_codes)).then(1).otherwise(None).alias('xwoba_codes'),pl.when((pl.col('tb') >= 0)).then(df['woba']).otherwise(None).alias('woba_contact'),pl.when(pl.col('px').is_null()).then(pl.col('px_predict')).otherwise(pl.col('px')).alias('px'),pl.when(pl.col('pz').is_null()).then(pl.col('pz_predict')).otherwise(pl.col('pz')).alias('pz'),pl.when(pl.col('in_zone').is_null()).then(pl.col('in_zone_predict')).otherwise(pl.col('in_zone')).alias('in_zone'),pl.when(df['launch_speed'].is_null()).then(None).otherwise(df['barrel']).alias('barrel'),pl.lit('average').alias('average'),pl.when(pl.col('in_zone') == False).then(True).otherwise(False).alias('out_zone'),pl.when((pl.col('in_zone') == True) & (pl.col('swings') == 1)).then(True).otherwise(False).alias('zone_swing'),pl.when((pl.col('in_zone') == True) & (pl.col('swings') == 1) & (pl.col('whiffs') == 0)).then(True).otherwise(False).alias('zone_contact'),pl.when((pl.col('in_zone') == False) & (pl.col('swings') == 1)).then(True).otherwise(False).alias('ozone_swing'),pl.when((pl.col('in_zone') == False) & (pl.col('swings') == 1) & (pl.col('whiffs') == 0)).then(True).otherwise(False).alias('ozone_contact'),pl.when(pl.col('event_type').str.contains('strikeout')).then(True).otherwise(False).alias('k'),pl.when(pl.col('event_type').is_in(['walk', 'intent_walk'])).then(True).otherwise(False).alias('bb'),pl.when(pl.col('attack_zone').is_null()).then(pl.col('attack_zone_predict')).otherwise(pl.col('attack_zone')).alias('attack_zone'),])2 unmodified lines(df['k'].cast(pl.Float32) - df['bb'].cast(pl.Float32)).alias('k_minus_bb'),(df['bb'].cast(pl.Float32) - df['k'].cast(pl.Float32)).alias('bb_minus_k'),(df['launch_speed'] > 0).alias('bip_div'),(df['attack_zone'] == 0).alias('heart'),(df['attack_zone'] == 1).alias('shadow'),(df['attack_zone'] == 2).alias('chase'),(df['attack_zone'] == 3).alias('waste'),((df['attack_zone'] == 0) & (df['swings'] == 1)).alias('heart_swing'),((df['attack_zone'] == 1) & (df['swings'] == 1)).alias('shadow_swing'),((df['attack_zone'] == 2) & (df['swings'] == 1)).alias('chase_swing'),((df['attack_zone'] == 3) & (df['swings'] == 1)).alias('waste_swing'),((df['attack_zone'] == 0) & (df['whiffs'] == 1)).alias('heart_whiff'),((df['attack_zone'] == 1) & (df['whiffs'] == 1)).alias('shadow_whiff'),((df['attack_zone'] == 2) & (df['whiffs'] == 1)).alias('chase_whiff'),((df['attack_zone'] == 3) & (df['whiffs'] == 1)).alias('waste_whiff')])48 unmodified lines# Check if 'trajectory_null' column exists and drop itif 'trajectory_null' in df.columns:df = df.drop('trajectory_null')return df# Assuming df is your Polars DataFrame144 unmodified linespl.col('k').sum().alias('k'),pl.col('bb').sum().alias('bb'),pl.col('bb_minus_k').sum().alias('bb_minus_k'),pl.col('csw').sum().alias('csw'),pl.col('bip').sum().alias('bip'),pl.col('bip_div').sum().alias('bip_div'),37 unmodified linespl.col('shadow_whiff').sum().alias('shadow_whiff'),pl.col('chase_whiff').sum().alias('chase_whiff'),pl.col('waste_whiff').sum().alias('waste_whiff'),pl.col('tj_stuff_plus').sum().alias('tj_stuff_plus')])# Add calculated columns to the summary DataFrame5 unmodified lines(pl.col('k') / pl.col('pa')).alias('k_percent'),(pl.col('bb') / pl.col('pa')).alias('bb_percent'),(pl.col('bb_minus_k') / pl.col('pa')).alias('bb_minus_k_percent'),(pl.col('bb') / pl.col('k')).alias('bb_over_k_percent'),(pl.col('csw') / pl.col('pitches')).alias('csw_percent'),(pl.col('sweet_spot') / pl.col('bip_div')).alias('sweet_spot_percent'),28 unmodified lines(pl.col('xwoba') / pl.col('xwoba_codes')).alias('xwoba_percent'),(pl.col('xwoba_contact') / pl.col('bip')).alias('xwoba_percent_contact'),(pl.col('tj_stuff_plus') / pl.col('pitches')).alias('tj_stuff_plus_avg'),])
123version https://git-lfs.github.com/spec/v1oid sha256:9428e89f2a408148377efb3cd169dc8790bcc89df9495cb895b9db5a955e8fb7size 11447123version https://git-lfs.github.com/spec/v1oid sha256:6b0ddc8cb10b3b8b52fbae3039e17b470967dae57564567848403f7ce7c54d6bsize 130
123version https://git-lfs.github.com/spec/v1oid sha256:c5300b15a6ccfb1dd1e79c85bd9ea478a1945c454845e6be31cd8815e4063a3esize 54459064123version https://git-lfs.github.com/spec/v1oid sha256:93cbdcde8fffdc81b5817b979ebf8eda4375f8e6cdd7d9d652b17caf4af7c5ffsize 133
123version https://git-lfs.github.com/spec/v1oid sha256:82d6d95be88b006bea7efd4bbf0464a0a50f261f6f65f060bf022114300721edsize 46782024123version https://git-lfs.github.com/spec/v1oid sha256:584aacfffca94352d0305db4975aeb63d5513cf6adaa773af785e44b5deaaa9fsize 133
123version https://git-lfs.github.com/spec/v1oid sha256:179663ae0fa65c626b9a941b6934bda1ce58bdf02a69c0daefc28abd28154201size 579123version https://git-lfs.github.com/spec/v1oid sha256:90e65ec79a8f003432d2c991e40f564eaba695d7b9557f560a37caa0234158fesize 128
123version https://git-lfs.github.com/spec/v1oid sha256:3ceabc302949cdbe5515b428f900bce98d6f6bedf99153c8d8a645cb0240ef8bsize 579123version https://git-lfs.github.com/spec/v1oid sha256:c9e6629bbfeffaba8b37bb30f5b04ef948f013d96c20d1971240300beeef8409size 128
123version https://git-lfs.github.com/spec/v1oid sha256:2671d4db2606cfee299dcffba2a94138fce77c1b7ef6ad14695a972a38dda3c8size 50570139123version https://git-lfs.github.com/spec/v1oid sha256:b895a99631588abf80042e50ffc87320c76b81a05ef43bfc86542ca31967bc10size 133
123version https://git-lfs.github.com/spec/v1oid sha256:c3da3e7ab2b513b87d05e90ae30c788ac819dfcaa7cc1cd9943fc13d2958a00fsize 279409123version https://git-lfs.github.com/spec/v1oid sha256:4dfb7cd67c8415fb8c14c5bfcdcfcd618524a5311486fac04fe5b715696af412size 131
123version https://git-lfs.github.com/spec/v1oid sha256:4fef4a66363e5f3fdc70ae45c5382bd986c800ff8bf9296a1f9b334461e70fd4size 262137123version https://git-lfs.github.com/spec/v1oid sha256:b5cba3138b84208d41355bd3ce810eec7faa46ec36bd22210beeba1501c61ff1size 131
123version https://git-lfs.github.com/spec/v1oid sha256:05bade9c0420657d3f0dfe35f0b1adbd2d5ae25c87a07bdf6629987f29926438size 10684246123version https://git-lfs.github.com/spec/v1oid sha256:1747435104c4dc0e5a8778a992138ced3e4ff70f71e569547007ca5a8ceb351dsize 133
12345678910111213141516joblib==1.3.2lightgbmmatplotlib==3.5.1numpy==1.23.5pandas==1.5.2polars==1.12.0Requests==2.31.0scipy==1.11.1seaborn==0.11.1scikit-learn==1.0.1shiny==0.6.1Jinja2==3.1.4tqdm==4.62.3pyarrowtabulator123456789101112131415joblib==1.3.2lightgbmmatplotlib==3.5.1numpy==1.23.5pandas==1.5.2polars==1.12.0Requests==2.31.0scipy==1.11.1seaborn==0.11.1scikit-learn==1.0.1shiny==0.6.1Jinja2==3.1.4tqdm==4.62.3pyarrow
123version https://git-lfs.github.com/spec/v1oid sha256:41001a1acf6ce7dbe247f1b8b7e68a1bb1b112f39d080b7e95a83479e56cb7c1size 3092328123version https://git-lfs.github.com/spec/v1oid sha256:975989d422d2a2a5882eb0c296c811575b7b48ad0fbe6b22a901dfad76ea4a88size 132
Dockerfile+12-12
README.md+20-20
api_scraper.py
app.py+339-427
functions/__pycache__/df_update.cpython-39.pyc
functions/__pycache__/pitch_summary_functions.cpython-39.pyc
functions/df_update.py+20-124
functions/pitch_summary_functions.py
joblib_model/barrel_model.joblib+2-2
joblib_model/in_zone.joblib+2-2
joblib_model/in_zone_model_knn_20240410.joblib+2-2
joblib_model/linear_reg_model_x.joblib+2-2
joblib_model/linear_reg_model_z.joblib+2-2
joblib_model/model_attack_zone.joblib+2-2
joblib_model/no_swing.joblib+2-2
joblib_model/swing.joblib+2-2
joblib_model/xwoba_model.joblib+2-2
requirements.txt+15-16
stuff_model/__pycache__/feature_engineering.cpython-39.pyc
stuff_model/lgbm_model_2020_2023.joblib+2-2