-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
416 lines (358 loc) · 16.5 KB
/
app.py
File metadata and controls
416 lines (358 loc) · 16.5 KB
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
import streamlit as st
import pandas as pd
from scraper import MLBStatsScraper
st.set_page_config(page_title="MLB Statistics Viewer", layout="wide")
def format_column_names(df):
"""Convert column names from camelCase/JSON to readable format"""
column_mapping = {
'gamesPlayed': 'Games',
'avg': 'AVG',
'homeRuns': 'HR',
'rbi': 'RBI',
'runs': 'Runs',
'hits': 'Hits',
'doubles': 'Doubles',
'triples': 'Triples',
'stolenBases': 'SB',
'obp': 'OBP',
'slg': 'SLG',
'ops': 'OPS',
'strikeOuts': 'SO',
'baseOnBalls': 'BB',
'atBats': 'AB',
'plateAppearances': 'PA',
'wins': 'W',
'losses': 'L',
'era': 'ERA',
'gamesPitched': 'G',
'gamesStarted': 'GS',
'saves': 'SV',
'inningsPitched': 'IP',
'whip': 'WHIP',
'completeGames': 'CG',
'shutouts': 'SHO',
'season': 'Year',
'team': 'Team',
'position': 'Pos',
'player': 'Player'
}
new_columns = {}
for col in df.columns:
if col in column_mapping:
new_columns[col] = column_mapping[col]
else:
# Convert camelCase to Title Case with spaces
result = col[0].upper()
for i in range(1, len(col)):
if col[i].isupper():
result += ' ' + col[i]
else:
result += col[i]
new_columns[col] = result
return df.rename(columns=new_columns)
@st.cache_data(ttl=3600)
def get_team_list():
try:
scraper = MLBStatsScraper()
return scraper.get_team_list()
except Exception as e:
st.warning(f"Could not fetch live data: {e}. Using stored data instead.")
# Fallback data for common MLB teams
return [
{'id': 'NYY', 'name': 'New York Yankees'},
{'id': 'BOS', 'name': 'Boston Red Sox'},
{'id': 'LAD', 'name': 'Los Angeles Dodgers'},
{'id': 'CHC', 'name': 'Chicago Cubs'},
{'id': 'SFG', 'name': 'San Francisco Giants'},
{'id': 'ATL', 'name': 'Atlanta Braves'},
{'id': 'HOU', 'name': 'Houston Astros'},
{'id': 'NYM', 'name': 'New York Mets'},
{'id': 'STL', 'name': 'St. Louis Cardinals'},
{'id': 'CHW', 'name': 'Chicago White Sox'},
{'id': 'CLE', 'name': 'Cleveland Guardians'},
{'id': 'MIN', 'name': 'Minnesota Twins'},
{'id': 'TOR', 'name': 'Toronto Blue Jays'},
{'id': 'SEA', 'name': 'Seattle Mariners'},
{'id': 'PHI', 'name': 'Philadelphia Phillies'},
{'id': 'BAL', 'name': 'Baltimore Orioles'},
{'id': 'SDP', 'name': 'San Diego Padres'},
{'id': 'DET', 'name': 'Detroit Tigers'},
{'id': 'MIL', 'name': 'Milwaukee Brewers'},
{'id': 'COL', 'name': 'Colorado Rockies'},
{'id': 'PIT', 'name': 'Pittsburgh Pirates'},
{'id': 'OAK', 'name': 'Oakland Athletics'},
{'id': 'TEX', 'name': 'Texas Rangers'},
{'id': 'KCR', 'name': 'Kansas City Royals'},
{'id': 'LAA', 'name': 'Los Angeles Angels'},
{'id': 'ARI', 'name': 'Arizona Diamondbacks'},
{'id': 'TBR', 'name': 'Tampa Bay Rays'},
{'id': 'CIN', 'name': 'Cincinnati Reds'},
{'id': 'MIA', 'name': 'Miami Marlins'},
{'id': 'WSN', 'name': 'Washington Nationals'}
]
@st.cache_data(ttl=3600)
def get_team_stats(team_id, year):
try:
scraper = MLBStatsScraper()
return scraper.get_team_stats(team_id, year)
except Exception as e:
st.warning(f"Could not fetch live data: {e}. Using placeholder data instead.")
# Return empty DataFrames with typical columns
batting_df = pd.DataFrame(columns=['Rank', 'Player', 'Age', 'G', 'PA', 'AB', 'R', 'H', '2B', '3B', 'HR', 'RBI', 'SB', 'CS', 'BB', 'SO', 'BA', 'OBP', 'SLG', 'OPS'])
pitching_df = pd.DataFrame(columns=['Rank', 'Player', 'Age', 'W', 'L', 'ERA', 'G', 'GS', 'CG', 'SHO', 'SV', 'IP', 'H', 'R', 'ER', 'HR', 'BB', 'SO', 'WHIP'])
return {'batting': batting_df, 'pitching': pitching_df}
@st.cache_data(ttl=3600)
def get_team_player_stats(team_id, year):
try:
scraper = MLBStatsScraper()
return scraper.get_team_player_stats(team_id, year)
except Exception as e:
st.warning(f"Could not fetch player stats: {e}")
return {'batting': pd.DataFrame(), 'pitching': pd.DataFrame()}
@st.cache_data(ttl=3600)
def get_team_roster(team_id, year):
try:
scraper = MLBStatsScraper()
return scraper.get_team_roster(team_id, year)
except Exception as e:
st.warning(f"Could not fetch live data: {e}. Using placeholder data instead.")
# Return empty DataFrame with typical columns
return pd.DataFrame(columns=['Number', 'Player', 'Pos', 'Ht', 'Wt', 'Birthday', 'Bats', 'Throws', 'Experience'])
@st.cache_data(ttl=3600)
def get_all_players():
try:
scraper = MLBStatsScraper()
return scraper.get_all_players()
except Exception as e:
st.warning(f"Could not fetch player list: {e}. Using placeholder data instead.")
return [
{'id': '545361', 'name': 'Mike Trout', 'position': 'CF', 'team': 'Los Angeles Angels'},
{'id': '660271', 'name': 'Shohei Ohtani', 'position': 'DH', 'team': 'Los Angeles Dodgers'},
{'id': '592450', 'name': 'Aaron Judge', 'position': 'RF', 'team': 'New York Yankees'},
{'id': '405395', 'name': 'Albert Pujols', 'position': '1B', 'team': 'St. Louis Cardinals'}
]
@st.cache_data(ttl=3600)
def search_players(name):
try:
scraper = MLBStatsScraper()
return scraper.search_players(name)
except Exception as e:
st.warning(f"Could not fetch live data: {e}. Using placeholder data instead.")
# Return sample players that match common searches
if 'trout' in name.lower():
return [{'id': 'troutmi01', 'name': 'Mike Trout'}]
elif 'judge' in name.lower():
return [{'id': 'judgear01', 'name': 'Aaron Judge'}]
elif 'ohtani' in name.lower():
return [{'id': 'ohtansh01', 'name': 'Shohei Ohtani'}]
else:
return []
@st.cache_data(ttl=3600)
def get_player_stats(player_id):
try:
scraper = MLBStatsScraper()
return scraper.get_player_stats(player_id)
except Exception as e:
st.warning(f"Could not fetch live data: {e}. Using placeholder data instead.")
# Return sample data for some known players
if player_id == 'troutmi01': # Mike Trout
batting_df = pd.DataFrame({
'Year': ['2023', 'Career'],
'Age': [31, '-'],
'Tm': ['LAA', 'LAA'],
'G': [82, '1487'],
'AB': [292, '5415'],
'R': [54, '1059'],
'H': [87, '1624'],
'HR': [18, '368'],
'RBI': [44, '940'],
'SB': [2, '207'],
'BA': ['.298', '.300'],
'OBP': ['.383', '.414'],
'SLG': ['.534', '.583'],
'OPS': ['.917', '.997']
})
return {'batting': batting_df}
elif player_id == 'ohtansh01': # Shohei Ohtani
batting_df = pd.DataFrame({
'Year': ['2023', 'Career'],
'Age': [28, '-'],
'Tm': ['LAA', 'LAA'],
'G': [135, '609'],
'AB': [497, '2021'],
'R': [102, '407'],
'H': [151, '608'],
'HR': [44, '171'],
'RBI': [95, '437'],
'SB': [20, '86'],
'BA': ['.304', '.274'],
'OBP': ['.412', '.371'],
'SLG': ['.654', '.556'],
'OPS': ['1.066', '.927']
})
pitching_df = pd.DataFrame({
'Year': ['2023', 'Career'],
'Age': [28, '-'],
'Tm': ['LAA', 'LAA'],
'W': [10, '38'],
'L': [5, '19'],
'ERA': ['3.14', '2.97'],
'G': [23, '87'],
'GS': [23, '86'],
'CG': [0, '1'],
'IP': ['132.0', '481.2'],
'SO': ['167', '608'],
'WHIP': ['1.061', '1.084']
})
return {'batting': batting_df, 'pitching': pitching_df}
else:
# Generic placeholder
return {
'batting': pd.DataFrame(columns=['Year', 'Age', 'Tm', 'G', 'AB', 'R', 'H', 'HR', 'RBI', 'SB', 'BA', 'OBP', 'SLG', 'OPS']),
'pitching': pd.DataFrame(columns=['Year', 'Age', 'Tm', 'W', 'L', 'ERA', 'G', 'GS', 'CG', 'IP', 'SO', 'WHIP'])
}
st.title("MLB Statistics Viewer")
st.caption("Data sourced from MLB.com")
# Sidebar navigation
st.sidebar.title("Navigation")
page = st.sidebar.radio(
"Select a page",
["Teams", "Team Details", "Player Details"]
)
if page == "Teams":
st.header("MLB Teams")
teams = get_team_list()
# Convert teams list to DataFrame for better display
teams_df = pd.DataFrame(teams)
# Drop the 'id' column and simplify division names
if 'id' in teams_df.columns:
teams_df = teams_df.drop(columns=['id'])
# Simplify division names to just East, Central, West, etc.
if 'division' in teams_df.columns:
teams_df['division'] = teams_df['division'].str.split().str[-1]
st.dataframe(teams_df, use_container_width=True, hide_index=True)
elif page == "Team Details":
st.header("Team Details")
# Get teams for selection
teams = get_team_list()
team_options = {team['name']: team['id'] for team in teams}
# Select team and year
col1, col2 = st.columns([2, 1])
with col1:
selected_team_name = st.selectbox("Select Team", list(team_options.keys()))
selected_team_id = team_options[selected_team_name]
with col2:
current_year = pd.Timestamp.now().year
# MLB modern era started in 1900, go back to 1900
years = list(range(current_year, 1899, -1))
selected_year = st.selectbox("Select Year", years, index=0)
if st.button("Get Team Details"):
st.subheader(f"{selected_team_name} ({selected_year})")
stats = get_team_stats(selected_team_id, selected_year)
st.markdown("### Team Statistics")
col1, col2 = st.columns(2)
with col1:
if 'batting' in stats and not stats['batting'].empty:
st.markdown("#### Team Batting")
batting_display = format_column_names(stats['batting'])
st.dataframe(batting_display, use_container_width=True, hide_index=True)
with col2:
if 'pitching' in stats and not stats['pitching'].empty:
st.markdown("#### Team Pitching")
pitching_display = format_column_names(stats['pitching'])
st.dataframe(pitching_display, use_container_width=True, hide_index=True)
st.markdown("---")
st.markdown("### Team Roster")
roster = get_team_roster(selected_team_id, selected_year)
if not roster.empty:
if 'playerId' in roster.columns:
roster = roster.drop(columns=['playerId'])
roster_display = format_column_names(roster)
st.dataframe(roster_display, use_container_width=True, hide_index=True)
else:
st.warning("No roster data available for the selected team and year.")
elif page == "Player Details":
st.header("Player Details")
st.markdown("### Search for a Player")
# Initialize session state
if 'player_results' not in st.session_state:
st.session_state.player_results = []
# Text input for search
search_query = st.text_input(
"Start typing a player name:",
placeholder="e.g., Albert Pujols, Trout, Ohtani",
key="player_search"
)
# Auto-search as user types (3+ characters)
if search_query and len(search_query) >= 3:
if 'last_query' not in st.session_state or st.session_state.last_query != search_query:
with st.spinner("Searching..."):
players = search_players(search_query)
st.session_state.player_results = players
st.session_state.last_query = search_query
# Show results in a selectbox if we have any
selected_player = None
if search_query and len(search_query) >= 3 and st.session_state.player_results:
players = st.session_state.player_results
if len(players) > 0:
player_map = {f"{p['name']} - {p['position']}, {p['team']}": p for p in players}
player_options = list(player_map.keys())
selected_label = st.selectbox(
f"Select from {len(players)} result(s):",
options=player_options,
key="player_selector"
)
selected_player = player_map[selected_label]
elif search_query and len(search_query) >= 3:
st.info("No players found. Try a different search.")
if selected_player:
player_id = selected_player['id']
player_name_display = selected_player['name']
st.markdown("---")
st.subheader(f"{player_name_display} - Career Statistics")
stats = get_player_stats(player_id)
if not stats:
st.warning(f"No statistics found for {player_name_display}.")
else:
if 'batting' in stats and not stats['batting'].empty:
st.markdown("#### Batting Statistics")
batting_df = stats['batting'].copy()
team_col = 'team' if 'team' in batting_df.columns else ('Tm' if 'Tm' in batting_df.columns else None)
season_col = 'season' if 'season' in batting_df.columns else ('Year' if 'Year' in batting_df.columns else None)
if 'position' not in batting_df.columns and 'Pos' not in batting_df.columns:
player_position = selected_player.get('position', 'N/A')
batting_df['position'] = player_position
position_col = 'position' if 'position' in batting_df.columns else ('Pos' if 'Pos' in batting_df.columns else None)
ordered_cols = []
if team_col:
ordered_cols.append(team_col)
if season_col:
ordered_cols.append(season_col)
if position_col:
ordered_cols.append(position_col)
remaining_cols = [col for col in batting_df.columns if col not in ordered_cols]
ordered_cols.extend(remaining_cols)
batting_df = batting_df[ordered_cols]
batting_df = format_column_names(batting_df)
st.dataframe(batting_df, use_container_width=True, hide_index=True)
if 'pitching' in stats and not stats['pitching'].empty:
st.markdown("#### Pitching Statistics")
pitching_df = stats['pitching'].copy()
team_col = 'team' if 'team' in pitching_df.columns else ('Tm' if 'Tm' in pitching_df.columns else None)
season_col = 'season' if 'season' in pitching_df.columns else ('Year' if 'Year' in pitching_df.columns else None)
if 'position' not in pitching_df.columns and 'Pos' not in pitching_df.columns:
player_position = selected_player.get('position', 'P')
pitching_df['position'] = player_position
position_col = 'position' if 'position' in pitching_df.columns else ('Pos' if 'Pos' in pitching_df.columns else None)
ordered_cols = []
if team_col:
ordered_cols.append(team_col)
if season_col:
ordered_cols.append(season_col)
if position_col:
ordered_cols.append(position_col)
remaining_cols = [col for col in pitching_df.columns if col not in ordered_cols]
ordered_cols.extend(remaining_cols)
pitching_df = pitching_df[ordered_cols]
pitching_df = format_column_names(pitching_df)
st.dataframe(pitching_df, use_container_width=True, hide_index=True)