Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import urllib.request
|
| 2 |
+
from urllib.error import HTTPError
|
| 3 |
+
import requests
|
| 4 |
+
from bs4 import BeautifulSoup
|
| 5 |
+
import os
|
| 6 |
+
import json
|
| 7 |
+
import streamlit as st
|
| 8 |
+
import pandas as pd
|
| 9 |
+
from st_aggrid import AgGrid, GridOptionsBuilder, GridUpdateMode
|
| 10 |
+
|
| 11 |
+
# Set Streamlit page configuration
|
| 12 |
+
st.set_page_config(layout="wide")
|
| 13 |
+
|
| 14 |
+
# Inject custom CSS to set the width of the container to 1250px
|
| 15 |
+
st.markdown(
|
| 16 |
+
"""
|
| 17 |
+
<style>
|
| 18 |
+
.main-container {
|
| 19 |
+
max-width: 1250px;
|
| 20 |
+
margin: 0 auto;
|
| 21 |
+
}
|
| 22 |
+
</style>
|
| 23 |
+
""",
|
| 24 |
+
unsafe_allow_html=True
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
# Wrap the main content in a container with the specified width
|
| 28 |
+
st.markdown('<div class="main-container">', unsafe_allow_html=True)
|
| 29 |
+
|
| 30 |
+
# Load the data
|
| 31 |
+
df = pd.read_csv("2024_regular_data.csv", index_col=[0])
|
| 32 |
+
df['batter_name_team'] = df['batter_name'] + ' - ' + df['batter_team']
|
| 33 |
+
|
| 34 |
+
# Sample dictionary
|
| 35 |
+
fielders = df.drop_duplicates(['batter_id']).sort_values(['batter_name']).set_index('batter_id')['batter_name_team'].to_dict()
|
| 36 |
+
fielders_reversed = {v: k for k, v in fielders.items()}
|
| 37 |
+
|
| 38 |
+
# Create a selectbox for selecting a key from the dictionary
|
| 39 |
+
selected_fielder = st.selectbox("Select Fielder:", list(fielders_reversed.keys()))
|
| 40 |
+
|
| 41 |
+
# Retrieve the corresponding pitcher ID
|
| 42 |
+
fielder_select = fielders_reversed[selected_fielder]
|
| 43 |
+
|
| 44 |
+
# Define the URL
|
| 45 |
+
url = f'https://baseballsavant.mlb.com/savant-player/{fielder_select}?stats=statcast-r-fielding-mlb'
|
| 46 |
+
|
| 47 |
+
# Make the GET request
|
| 48 |
+
response = requests.get(url)
|
| 49 |
+
|
| 50 |
+
# Check if the request was successful
|
| 51 |
+
if response.status_code == 200:
|
| 52 |
+
print(response.status_code)
|
| 53 |
+
else:
|
| 54 |
+
print(f"Failed to fetch data, status code: {response.status_code}")
|
| 55 |
+
|
| 56 |
+
# Format the string as a JSON array
|
| 57 |
+
text = response.text
|
| 58 |
+
dict_catch = text.split('rangeLine')[1].split('data')[0].split('[')[1].split(']')[0]
|
| 59 |
+
formatted_dict_catch = f'[{dict_catch}]'
|
| 60 |
+
|
| 61 |
+
# Convert the formatted string to a list of dictionaries
|
| 62 |
+
dict_catch_list = json.loads(formatted_dict_catch)
|
| 63 |
+
|
| 64 |
+
df_catch = pd.DataFrame(dict_catch_list)
|
| 65 |
+
df_catch['hang_time'] = df_catch['hang_time'].astype(float).round(1)
|
| 66 |
+
df_catch['distance'] = df_catch['distance'].astype(float).round(1)
|
| 67 |
+
|
| 68 |
+
df_merge = df.merge(df_catch, on='play_id', how='right', suffixes=('', '_fielder')).reset_index(drop=True)
|
| 69 |
+
|
| 70 |
+
# Format the 'catch_rate' column as a percentage
|
| 71 |
+
df_merge['catch_rate'] = df_merge['catch_rate'].astype(float).apply(lambda x: f"{x:.2%}")
|
| 72 |
+
|
| 73 |
+
# Use a container to control the width of the AgGrid display
|
| 74 |
+
with st.container():
|
| 75 |
+
st.write("### Fielder Data")
|
| 76 |
+
# Configure the AgGrid options
|
| 77 |
+
gb = GridOptionsBuilder.from_dataframe(df_merge[['batter_name', 'pitcher_name', 'name_display_first_last', 'event', 'out', 'wall', 'back', 'stars', 'distance', 'hang_time', 'catch_rate']])
|
| 78 |
+
gb.configure_selection('single', use_checkbox=True)
|
| 79 |
+
grid_options = gb.build()
|
| 80 |
+
|
| 81 |
+
# Display the dataframe using AgGrid
|
| 82 |
+
grid_response = AgGrid(
|
| 83 |
+
df_merge[['batter_name', 'pitcher_name', 'name_display_first_last', 'event', 'out', 'wall', 'back', 'stars', 'distance', 'hang_time', 'catch_rate']],
|
| 84 |
+
gridOptions=grid_options,
|
| 85 |
+
update_mode=GridUpdateMode.SELECTION_CHANGED,
|
| 86 |
+
height=300,
|
| 87 |
+
allow_unsafe_jscode=True,
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
# Get the selected row index
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
try:
|
| 94 |
+
# Update the video URL based on the selected row
|
| 95 |
+
selected_row_index = int(grid_response['selected_rows'].index.values[0])
|
| 96 |
+
a = requests.get(f'https://baseballsavant.mlb.com/sporty-videos?playId={df_merge["play_id"].values[selected_row_index]}')
|
| 97 |
+
soup = BeautifulSoup(a.content, 'lxml')
|
| 98 |
+
video_url = str(soup).split('<source src="')[1].split('" ')[0]
|
| 99 |
+
# Share the video through Streamlit
|
| 100 |
+
st.video(video_url)
|
| 101 |
+
except AttributeError:
|
| 102 |
+
st.write("Select Row to Display Video")
|
| 103 |
+
|
| 104 |
+
st.markdown('</div>', unsafe_allow_html=True)
|