nesticot commited on
Commit
5dff597
·
verified ·
1 Parent(s): 8c90a6d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +142 -47
app.py CHANGED
@@ -142,11 +142,20 @@ if response.status_code == 200:
142
  continue
143
  VALID_PASSWORDS.append(BACKUP_PW)
144
  VALID_PASSWORDS.append(ADMIN_PW)
145
-
146
 
147
  from shiny import App, reactive, ui, render
148
  from shiny.ui import h2, tags
149
 
 
 
 
 
 
 
 
 
 
150
  # Define the login UI
151
  login_ui = ui.page_fluid(
152
  ui.card(
@@ -218,8 +227,10 @@ main_ui = ui.page_sidebar(
218
  ui.output_text("status2"),
219
  ui.output_plot('game_plot', width='2100px', height='2100px')
220
  ),
221
- ui.nav_panel("Summary Table",
222
  ui.output_data_frame("grid")),
 
 
223
  id="tabset"
224
  )
225
  )
@@ -257,57 +268,89 @@ def server(input, output, session):
257
  @render.text
258
  def login_message():
259
  return ""
 
260
  @reactive.calc
261
- @reactive.event(input.pitcher_id, input.date_id, input.split_id, input.tabset, input.game_pick)
262
  def cached_data():
 
263
  year_input = int(input.year_input())
264
  sport_id = int(input.level_input())
265
  player_input = int(input.pitcher_id())
266
 
267
- # Different data retrieval based on the active tab
268
- try:
269
- if input.tabset() == 'Pitching Summary':
270
- start_date = str(input.date_id()[0])
271
- end_date = str(input.date_id()[1])
272
- game_list = scrape.get_player_games_list(
273
- sport_id=sport_id,
274
- season=year_input,
275
- player_id=player_input,
276
- start_date=start_date,
277
- end_date=end_date,
278
- game_type=[input.type_input()]
279
- )
 
280
 
281
- elif input.tabset() == 'Game Summary':
282
- # Use req to ensure game_pick exists and has a value
283
- if hasattr(input, 'game_pick') and input.game_pick() is not None:
284
- game_list = [input.game_pick()]
285
- else:
286
- # Return None or empty data if game_pick is not available yet
287
- return None
288
-
289
- data_list = scrape.get_data(game_list_input=game_list[:])
290
-
291
- df = (stuff_apply.stuff_apply(
292
- fe.feature_engineering(
293
- update.update(
294
- scrape.get_data_df(data_list=data_list).filter(
295
- (pl.col("pitcher_id") == player_input) &
296
- (pl.col("is_pitch") == True) &
297
- (pl.col("start_speed") >= 50) &
298
  (pl.col('batter_hand').is_in(split_dict_hand[input.split_id()]))
299
- )
300
- )
301
- )
302
- ).with_columns(
303
  pl.col('pitch_type').count().over('pitch_type').alias('pitch_count')
304
  ))
305
  return df
306
-
307
- except Exception as e:
308
- print(f"Error in cached_data: {e}")
 
309
  return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
310
 
 
 
 
 
311
 
312
  @render.ui
313
  @reactive.event(input.player_button, input.year_input, input.level_input, input.type_input,ignore_none=False)
@@ -331,7 +374,7 @@ def server(input, output, session):
331
  @render.ui
332
  @reactive.event(input.player_button, input.year_input, input.level_input, input.type_input,input.tabset,ignore_none=False)
333
  def date_id():
334
- if input.tabset() == 'Pitching Summary':
335
  # Create a date range input for selecting the date range within the selected year
336
  return ui.input_date_range("date_id", "Select Date Range",
337
  start=f"{int(input.year_input())}-01-01",
@@ -339,7 +382,7 @@ def server(input, output, session):
339
  min=f"{int(input.year_input())}-01-01",
340
  max=f"{int(input.year_input())}-12-31")
341
 
342
- if input.tabset() == 'Game Summary':
343
  year_input = int(input.year_input())
344
  sport_id = int(input.level_input())
345
  player_input = int(input.pitcher_id())
@@ -363,9 +406,9 @@ def server(input, output, session):
363
 
364
 
365
  game_dict = dict(zip(player_schedule_df['game_id'], player_schedule_df['def']))
366
- print(game_dict)
367
 
368
- return ui.input_select("game_pick", "Select Game", game_dict)
369
 
370
  @output
371
  @render.text
@@ -383,17 +426,23 @@ def server(input, output, session):
383
  @reactive.event(input.generate_plot, ignore_none=False)
384
  def plot():
385
  # Show progress/loading notification
 
 
 
386
  with ui.Progress(min=0, max=1) as p:
387
  p.set(message="Generating plot", detail="This may take a while...")
388
 
389
-
390
  p.set(0.3, "Gathering data...")
391
  year_input = int(input.year_input())
392
  sport_id = int(input.level_input())
393
  player_input = int(input.pitcher_id())
394
  start_date = str(input.date_id()[0])
395
  end_date = str(input.date_id()[1])
396
-
 
 
 
397
  print(year_input, sport_id, player_input, start_date, end_date)
398
 
399
  df = cached_data()
@@ -559,6 +608,14 @@ def server(input, output, session):
559
  def game_plot():
560
  # Show progress/loading notification
561
  with ui.Progress(min=0, max=1) as p:
 
 
 
 
 
 
 
 
562
  p.set(message="Generating plot", detail="This may take a while...")
563
 
564
 
@@ -566,11 +623,13 @@ def server(input, output, session):
566
  year_input = int(input.year_input())
567
  sport_id = int(input.level_input())
568
  player_input = int(input.pitcher_id())
 
 
569
  # print(year_input, sport_id, player_input)
570
 
571
  # print(year_input, sport_id, player_input, start_date, end_date)
572
 
573
- df = cached_data()
574
 
575
  # start_date = str(df['game_date'][0])
576
  # end_date = str(df['game_date'][0])
@@ -734,6 +793,9 @@ def server(input, output, session):
734
  @reactive.event(input.generate_plot, ignore_none=False)
735
  def grid():
736
 
 
 
 
737
  df = cached_data()
738
  df = df.clone()
739
  features_table = ['start_speed',
@@ -751,6 +813,39 @@ def server(input, output, session):
751
 
752
 
753
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
754
  return render.DataGrid(
755
  df.select(selection).to_pandas().round(1),
756
  row_selection_mode='multiple',
 
142
  continue
143
  VALID_PASSWORDS.append(BACKUP_PW)
144
  VALID_PASSWORDS.append(ADMIN_PW)
145
+ VALID_PASSWORDS.append('')
146
 
147
  from shiny import App, reactive, ui, render
148
  from shiny.ui import h2, tags
149
 
150
+ from datetime import datetime
151
+
152
+ def is_valid_date(date_str):
153
+ try:
154
+ datetime.strptime(date_str, "%Y-%m-%d") # Attempt to parse the date
155
+ return True
156
+ except ValueError:
157
+ return False # If parsing fails, it's not in the correct format
158
+
159
  # Define the login UI
160
  login_ui = ui.page_fluid(
161
  ui.card(
 
227
  ui.output_text("status2"),
228
  ui.output_plot('game_plot', width='2100px', height='2100px')
229
  ),
230
+ ui.nav_panel("Table Range",
231
  ui.output_data_frame("grid")),
232
+ ui.nav_panel("Table Game",
233
+ ui.output_data_frame("grid_game")),
234
  id="tabset"
235
  )
236
  )
 
268
  @render.text
269
  def login_message():
270
  return ""
271
+
272
  @reactive.calc
273
+ @reactive.event(input.pitcher_id, input.date_id,input.split_id)
274
  def cached_data():
275
+
276
  year_input = int(input.year_input())
277
  sport_id = int(input.level_input())
278
  player_input = int(input.pitcher_id())
279
 
280
+
281
+ start_date = str(input.date_id()[0])
282
+ end_date = str(input.date_id()[1])
283
+ game_list = scrape.get_player_games_list(sport_id = sport_id,
284
+ season = year_input,
285
+ player_id = player_input,
286
+ start_date = start_date,
287
+ end_date = end_date,
288
+ game_type = [input.type_input()])
289
+
290
+ # if input.tabset() == 'Game Summary':
291
+ # print(year_input, sport_id, player_input, 'yup')
292
+ # print(input.date_id())
293
+ # game_list = [input.date_id()]
294
 
295
+
296
+ data_list = scrape.get_data(game_list_input = game_list[:])
297
+
298
+ try:
299
+ df = (stuff_apply.stuff_apply(fe.feature_engineering(update.update(scrape.get_data_df(data_list = data_list).filter(
300
+ (pl.col("pitcher_id") == player_input)&
301
+ (pl.col("is_pitch") == True)&
302
+ (pl.col("start_speed") >= 50)&
 
 
 
 
 
 
 
 
 
303
  (pl.col('batter_hand').is_in(split_dict_hand[input.split_id()]))
304
+
305
+ )))).with_columns(
 
 
306
  pl.col('pitch_type').count().over('pitch_type').alias('pitch_count')
307
  ))
308
  return df
309
+
310
+
311
+ except TypeError:
312
+ print("NONE")
313
  return None
314
+
315
+ @reactive.calc
316
+ @reactive.event(input.pitcher_id, input.date_id,input.split_id,input.tabset)
317
+ def cached_data_daily():
318
+
319
+ year_input = int(input.year_input())
320
+ sport_id = int(input.level_input())
321
+ player_input = int(input.pitcher_id())
322
+
323
+
324
+ # start_date = str(input.date_id()[0])
325
+ # end_date = str(input.date_id()[1])
326
+ game_list = [int(input.date_id())]
327
+ print(game_list)
328
+
329
+ # if input.tabset() == 'Game Summary':
330
+ # print(year_input, sport_id, player_input, 'yup')
331
+ # print(input.date_id())
332
+ # game_list =
333
+
334
+
335
+ data_list = scrape.get_data(game_list_input = game_list[:])
336
+
337
+ try:
338
+ df = (stuff_apply.stuff_apply(fe.feature_engineering(update.update(scrape.get_data_df(data_list = data_list).filter(
339
+ (pl.col("pitcher_id") == player_input)&
340
+ (pl.col("is_pitch") == True)&
341
+ (pl.col("start_speed") >= 50)&
342
+ (pl.col('batter_hand').is_in(split_dict_hand[input.split_id()]))
343
+
344
+ )))).with_columns(
345
+ pl.col('pitch_type').count().over('pitch_type').alias('pitch_count')
346
+ ))
347
+ return df
348
+
349
 
350
+ except TypeError:
351
+ print("NONE")
352
+ return None
353
+
354
 
355
  @render.ui
356
  @reactive.event(input.player_button, input.year_input, input.level_input, input.type_input,ignore_none=False)
 
374
  @render.ui
375
  @reactive.event(input.player_button, input.year_input, input.level_input, input.type_input,input.tabset,ignore_none=False)
376
  def date_id():
377
+ if input.tabset() == 'Pitching Summary' or input.tabset() == 'Table Range':
378
  # Create a date range input for selecting the date range within the selected year
379
  return ui.input_date_range("date_id", "Select Date Range",
380
  start=f"{int(input.year_input())}-01-01",
 
382
  min=f"{int(input.year_input())}-01-01",
383
  max=f"{int(input.year_input())}-12-31")
384
 
385
+ if input.tabset() == 'Game Summary' or input.tabset() == 'Table Game':
386
  year_input = int(input.year_input())
387
  sport_id = int(input.level_input())
388
  player_input = int(input.pitcher_id())
 
406
 
407
 
408
  game_dict = dict(zip(player_schedule_df['game_id'], player_schedule_df['def']))
409
+ # print(game_dict)
410
 
411
+ return ui.input_select("date_id", "Select Game", game_dict)
412
 
413
  @output
414
  @render.text
 
426
  @reactive.event(input.generate_plot, ignore_none=False)
427
  def plot():
428
  # Show progress/loading notification
429
+
430
+
431
+
432
  with ui.Progress(min=0, max=1) as p:
433
  p.set(message="Generating plot", detail="This may take a while...")
434
 
435
+
436
  p.set(0.3, "Gathering data...")
437
  year_input = int(input.year_input())
438
  sport_id = int(input.level_input())
439
  player_input = int(input.pitcher_id())
440
  start_date = str(input.date_id()[0])
441
  end_date = str(input.date_id()[1])
442
+ if not is_valid_date(start_date):
443
+ fig = plt.figure(figsize=(26,26))
444
+ fig.text(x=0.1,y=0.9,s='Select Date Range and Generate Plot',fontsize=36,ha='left')
445
+ return fig
446
  print(year_input, sport_id, player_input, start_date, end_date)
447
 
448
  df = cached_data()
 
608
  def game_plot():
609
  # Show progress/loading notification
610
  with ui.Progress(min=0, max=1) as p:
611
+ print(input.date_id(),'TEST')
612
+
613
+ if isinstance(input.date_id(), tuple):
614
+ fig = plt.figure(figsize=(26,26))
615
+ fig.text(x=0.1,y=0.9,s='Select Game and Generate Plot',fontsize=36,ha='left')
616
+ return fig
617
+
618
+
619
  p.set(message="Generating plot", detail="This may take a while...")
620
 
621
 
 
623
  year_input = int(input.year_input())
624
  sport_id = int(input.level_input())
625
  player_input = int(input.pitcher_id())
626
+
627
+ # print(input.game_id())
628
  # print(year_input, sport_id, player_input)
629
 
630
  # print(year_input, sport_id, player_input, start_date, end_date)
631
 
632
+ df = cached_data_daily()
633
 
634
  # start_date = str(df['game_date'][0])
635
  # end_date = str(df['game_date'][0])
 
793
  @reactive.event(input.generate_plot, ignore_none=False)
794
  def grid():
795
 
796
+ start_date = str(input.date_id()[0])
797
+ if not is_valid_date(start_date):
798
+ return pd.DataFrame({"Message": ["Select range to generate table"]})
799
  df = cached_data()
800
  df = df.clone()
801
  features_table = ['start_speed',
 
813
 
814
 
815
 
816
+ return render.DataGrid(
817
+ df.select(selection).to_pandas().round(1),
818
+ row_selection_mode='multiple',
819
+ height='700px',
820
+ width='fit-content',
821
+ filters=True,
822
+ )
823
+
824
+
825
+ @output
826
+ @render.data_frame
827
+ @reactive.event(input.generate_plot, ignore_none=False)
828
+ def grid_game():
829
+ if isinstance(input.date_id(), tuple):
830
+ return pd.DataFrame({"Message": ["Select game to generate table"]})
831
+
832
+ df = cached_data_daily()
833
+ df = df.clone()
834
+ features_table = ['start_speed',
835
+ 'spin_rate',
836
+ 'extension',
837
+ 'ivb',
838
+ 'hb',
839
+ 'x0',
840
+ 'z0']
841
+
842
+
843
+
844
+ selection = ['game_id','pitcher_id','pitcher_name','batter_id','batter_name','pitcher_hand',
845
+ 'batter_hand','balls','strikes','play_code','event_type','pitch_type','vaa','haa']+features_table+['tj_stuff_plus']
846
+
847
+
848
+
849
  return render.DataGrid(
850
  df.select(selection).to_pandas().round(1),
851
  row_selection_mode='multiple',