acetwo3ee commited on
Commit
65f66ec
Β·
verified Β·
1 Parent(s): 61c7fcb

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +393 -23
src/streamlit_app.py CHANGED
@@ -1,40 +1,410 @@
 
1
  import streamlit as st
2
- import requests
3
  import pandas as pd
 
 
 
 
 
4
 
5
- st.title("WNBA Player Overview - RapidAPI")
 
 
 
 
 
 
6
 
7
- player_id = st.text_input("Enter Player ID", "4433403")
 
 
 
 
 
 
8
 
9
- if st.button("Fetch Player Overview"):
10
- st.info("Fetching data, please wait...")
 
11
 
12
- url = f"https://wnba-api.p.rapidapi.com/player-overview?playerId={player_id}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
  headers = {
15
- "x-rapidapi-key": "1ac1586d40msh8f06d59fafd1b99p180008jsn0ed93153e2d7",
16
- "x-rapidapi-host": "wnba-api.p.rapidapi.com"
 
 
 
 
 
 
 
 
 
 
 
17
  }
18
 
19
- try:
20
- response = requests.get(url, headers=headers, timeout=15)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
- if response.status_code == 200:
23
- data = response.json()
24
- st.success("Data fetched successfully!")
25
 
26
- st.json(data) # Show raw JSON
27
 
28
- if isinstance(data, dict):
29
- df = pd.json_normalize(data)
30
- st.dataframe(df)
 
 
31
 
32
- csv = df.to_csv(index=False).encode("utf-8")
33
- st.download_button("Download CSV", csv, "player_overview.csv", "text/csv")
34
- else:
35
- st.warning("Unexpected response structure.")
36
  else:
37
- st.error(f"Request failed with status code: {response.status_code}")
38
 
 
 
 
 
39
  except Exception as e:
40
- st.error(f"Error: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
  import streamlit as st
 
3
  import pandas as pd
4
+ import numpy as np
5
+ import requests
6
+ import json
7
+ from datetime import datetime
8
+ import io
9
 
10
+ # Try to import plotly, but make it optional
11
+ try:
12
+ import plotly.express as px
13
+ import plotly.graph_objects as go
14
+ PLOTLY_AVAILABLE = True
15
+ except ImportError:
16
+ PLOTLY_AVAILABLE = False
17
 
18
+ # Page configuration - MUST be first Streamlit command
19
+ st.set_page_config(
20
+ page_title="WNBA Dashboard",
21
+ page_icon="πŸ€",
22
+ layout="wide",
23
+ initial_sidebar_state="expanded"
24
+ )
25
 
26
+ # Show plotly warning after page config
27
+ if not PLOTLY_AVAILABLE:
28
+ st.warning("Plotly not available. Some visualizations will be disabled.")
29
 
30
+ # Custom CSS
31
+ st.markdown("""
32
+ <style>
33
+ .main-header {
34
+ font-size: 3rem;
35
+ color: #FF6B6B;
36
+ text-align: center;
37
+ margin-bottom: 2rem;
38
+ }
39
+ .metric-card {
40
+ background-color: #F0F2F6;
41
+ padding: 1rem;
42
+ border-radius: 0.5rem;
43
+ border-left: 5px solid #FF6B6B;
44
+ }
45
+ </style>
46
+ """, unsafe_allow_html=True)
47
+
48
+ def fetch_wnba_player_gamelogs(season="2025", season_type="Regular Season"):
49
+ """
50
+ Fetch WNBA player game logs from the official WNBA stats API
51
+ """
52
+ url = "https://stats.wnba.com/stats/playergamelogs"
53
 
54
  headers = {
55
+ 'Accept': 'application/json, text/plain, */*',
56
+ 'Accept-Encoding': 'gzip, deflate, br, zstd',
57
+ 'Accept-Language': 'en-US,en;q=0.9',
58
+ 'Referer': 'https://stats.wnba.com/players/boxscores-traditional/',
59
+ 'Sec-Ch-Ua': '"Google Chrome";v="137", "Chromium";v="137", "Not/A)Brand";v="24"',
60
+ 'Sec-Ch-Ua-Mobile': '?0',
61
+ 'Sec-Ch-Ua-Platform': '"Windows"',
62
+ 'Sec-Fetch-Dest': 'empty',
63
+ 'Sec-Fetch-Mode': 'cors',
64
+ 'Sec-Fetch-Site': 'same-origin',
65
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36',
66
+ 'X-Nba-Stats-Origin': 'stats',
67
+ 'X-Nba-Stats-Token': 'true'
68
  }
69
 
70
+ params = {
71
+ 'DateFrom': '',
72
+ 'DateTo': '',
73
+ 'GameSegment': '',
74
+ 'LastNGames': '0',
75
+ 'LeagueID': '10', # WNBA League ID
76
+ 'Location': '',
77
+ 'MeasureType': 'Base',
78
+ 'Month': '0',
79
+ 'OpponentTeamID': '0',
80
+ 'Outcome': '',
81
+ 'PORound': '0',
82
+ 'PaceAdjust': 'N',
83
+ 'PerMode': 'Totals',
84
+ 'Period': '0',
85
+ 'PlusMinus': 'N',
86
+ 'Rank': 'N',
87
+ 'Season': season,
88
+ 'SeasonSegment': '',
89
+ 'SeasonType': season_type,
90
+ 'ShotClockRange': '',
91
+ 'VsConference': '',
92
+ 'VsDivision': ''
93
+ }
94
 
95
+ try:
96
+ response = requests.get(url, headers=headers, params=params, timeout=30)
97
+ response.raise_for_status()
98
 
99
+ data = response.json()
100
 
101
+ # Extract the data from the API response
102
+ if 'resultSets' in data and len(data['resultSets']) > 0:
103
+ result_set = data['resultSets'][0]
104
+ headers_list = result_set['headers']
105
+ rows = result_set['rowSet']
106
 
107
+ # Create DataFrame
108
+ df = pd.DataFrame(rows, columns=headers_list)
109
+ return df, None
 
110
  else:
111
+ return None, "No data found in API response"
112
 
113
+ except requests.exceptions.RequestException as e:
114
+ return None, f"API request failed: {str(e)}"
115
+ except json.JSONDecodeError as e:
116
+ return None, f"Failed to parse JSON response: {str(e)}"
117
  except Exception as e:
118
+ return None, f"Unexpected error: {str(e)}"
119
+
120
+ def convert_df_to_excel(df):
121
+ """
122
+ Convert DataFrame to Excel format and return as bytes
123
+ """
124
+ output = io.BytesIO()
125
+ try:
126
+ with pd.ExcelWriter(output, engine='openpyxl') as writer:
127
+ df.to_excel(writer, index=False, sheet_name='WNBA_Player_GameLogs')
128
+ except ImportError:
129
+ # Fallback to xlsxwriter if openpyxl is not available
130
+ try:
131
+ with pd.ExcelWriter(output, engine='xlsxwriter') as writer:
132
+ df.to_excel(writer, index=False, sheet_name='WNBA_Player_GameLogs')
133
+ except ImportError:
134
+ # If both fail, return CSV data with Excel extension
135
+ st.warning("Excel libraries not available. Downloading as CSV format instead.")
136
+ return df.to_csv(index=False).encode('utf-8')
137
+
138
+ output.seek(0)
139
+ return output.getvalue()
140
+
141
+ def main():
142
+ # Header
143
+ st.markdown('<h1 class="main-header">πŸ€ WNBA Dashboard</h1>', unsafe_allow_html=True)
144
+
145
+ # Sidebar
146
+ st.sidebar.title("Navigation")
147
+ page = st.sidebar.selectbox("Choose a page", ["Home", "WNBA API Data", "Data Analysis", "Visualizations", "Settings"])
148
+
149
+ if page == "Home":
150
+ show_home_page()
151
+ elif page == "WNBA API Data":
152
+ show_wnba_api_data()
153
+ elif page == "Data Analysis":
154
+ show_data_analysis()
155
+ elif page == "Visualizations":
156
+ show_visualizations()
157
+ elif page == "Settings":
158
+ show_settings()
159
+
160
+ def show_home_page():
161
+ st.header("Welcome to the WNBA Dashboard")
162
+
163
+ col1, col2, col3 = st.columns(3)
164
+
165
+ with col1:
166
+ st.markdown('<div class="metric-card">', unsafe_allow_html=True)
167
+ st.metric("Total Teams", "12", "0")
168
+ st.markdown('</div>', unsafe_allow_html=True)
169
+
170
+ with col2:
171
+ st.markdown('<div class="metric-card">', unsafe_allow_html=True)
172
+ st.metric("Season Games", "204", "+12")
173
+ st.markdown('</div>', unsafe_allow_html=True)
174
+
175
+ with col3:
176
+ st.markdown('<div class="metric-card">', unsafe_allow_html=True)
177
+ st.metric("Active Players", "144", "+5")
178
+ st.markdown('</div>', unsafe_allow_html=True)
179
+
180
+ st.markdown("---")
181
+
182
+ # Sample data display
183
+ st.subheader("Recent Games")
184
+ sample_data = pd.DataFrame({
185
+ 'Date': ['2024-07-01', '2024-07-02', '2024-07-03'],
186
+ 'Home Team': ['Las Vegas Aces', 'New York Liberty', 'Connecticut Sun'],
187
+ 'Away Team': ['Seattle Storm', 'Chicago Sky', 'Indiana Fever'],
188
+ 'Score': ['89-76', '92-85', '78-71']
189
+ })
190
+ st.dataframe(sample_data, use_container_width=True)
191
+
192
+ def show_wnba_api_data():
193
+ st.header("πŸ€ WNBA Official API Data")
194
+ st.write("Fetch real-time player game logs from the official WNBA Stats API")
195
+
196
+ # API Configuration
197
+ col1, col2 = st.columns(2)
198
+
199
+ with col1:
200
+ season = st.selectbox(
201
+ "Select Season",
202
+ ["2025", "2024", "2023", "2022", "2021"],
203
+ index=0
204
+ )
205
+
206
+ with col2:
207
+ season_type = st.selectbox(
208
+ "Season Type",
209
+ ["Regular Season", "Playoffs", "Pre Season"],
210
+ index=0
211
+ )
212
+
213
+ # Fetch Data Button
214
+ if st.button("πŸ”„ Fetch WNBA Player Game Logs", type="primary"):
215
+ with st.spinner("Fetching data from WNBA API..."):
216
+ df, error = fetch_wnba_player_gamelogs(season, season_type)
217
+
218
+ if error:
219
+ st.error(f"❌ Error fetching data: {error}")
220
+ st.info("πŸ’‘ Try again in a few moments. The API might be temporarily unavailable.")
221
+ else:
222
+ st.success(f"βœ… Successfully fetched {len(df)} player game logs!")
223
+
224
+ # Store data in session state
225
+ st.session_state['wnba_data'] = df
226
+ st.session_state['fetch_timestamp'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
227
+
228
+ # Display data if available
229
+ if 'wnba_data' in st.session_state:
230
+ df = st.session_state['wnba_data']
231
+ timestamp = st.session_state.get('fetch_timestamp', 'Unknown')
232
+
233
+ st.markdown(f"**Data fetched at:** {timestamp}")
234
+ st.markdown(f"**Total records:** {len(df)}")
235
+
236
+ # Data preview
237
+ st.subheader("πŸ“Š Data Preview")
238
+ st.dataframe(df.head(10), use_container_width=True)
239
+
240
+ # Data summary
241
+ col1, col2 = st.columns(2)
242
+
243
+ with col1:
244
+ st.subheader("πŸ“ˆ Quick Stats")
245
+ if 'PTS' in df.columns:
246
+ avg_points = df['PTS'].mean()
247
+ max_points = df['PTS'].max()
248
+ st.metric("Average Points", f"{avg_points:.1f}")
249
+ st.metric("Highest Points", f"{max_points}")
250
+
251
+ if 'PLAYER_NAME' in df.columns:
252
+ unique_players = df['PLAYER_NAME'].nunique()
253
+ st.metric("Unique Players", unique_players)
254
+
255
+ with col2:
256
+ st.subheader("πŸ† Top Performers")
257
+ if 'PTS' in df.columns and 'PLAYER_NAME' in df.columns:
258
+ top_scorers = df.nlargest(5, 'PTS')[['PLAYER_NAME', 'PTS', 'GAME_DATE']]
259
+ st.dataframe(top_scorers, use_container_width=True)
260
+
261
+ # Export options
262
+ st.subheader("πŸ’Ύ Export Data")
263
+ col1, col2, col3 = st.columns(3)
264
+
265
+ with col1:
266
+ # Excel download
267
+ excel_data = convert_df_to_excel(df)
268
+ st.download_button(
269
+ label="πŸ“Š Download as Excel",
270
+ data=excel_data,
271
+ file_name=f"wnba_player_gamelogs_{season}_{season_type.replace(' ', '_')}.xlsx",
272
+ mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
273
+ )
274
+
275
+ with col2:
276
+ # CSV download
277
+ csv_data = df.to_csv(index=False)
278
+ st.download_button(
279
+ label="πŸ“„ Download as CSV",
280
+ data=csv_data,
281
+ file_name=f"wnba_player_gamelogs_{season}_{season_type.replace(' ', '_')}.csv",
282
+ mime="text/csv"
283
+ )
284
+
285
+ with col3:
286
+ # JSON download
287
+ json_data = df.to_json(orient='records', indent=2)
288
+ st.download_button(
289
+ label="πŸ”— Download as JSON",
290
+ data=json_data,
291
+ file_name=f"wnba_player_gamelogs_{season}_{season_type.replace(' ', '_')}.json",
292
+ mime="application/json"
293
+ )
294
+
295
+ # Advanced filtering
296
+ with st.expander("πŸ” Advanced Filtering"):
297
+ if 'PLAYER_NAME' in df.columns:
298
+ selected_players = st.multiselect(
299
+ "Filter by Players",
300
+ options=sorted(df['PLAYER_NAME'].unique()),
301
+ default=[]
302
+ )
303
+
304
+ if selected_players:
305
+ filtered_df = df[df['PLAYER_NAME'].isin(selected_players)]
306
+ st.write(f"Filtered data: {len(filtered_df)} records")
307
+ st.dataframe(filtered_df, use_container_width=True)
308
+
309
+ else:
310
+ st.info("πŸ‘† Click the button above to fetch WNBA player game logs data")
311
+
312
+ # API Information
313
+ st.subheader("ℹ️ About the WNBA Stats API")
314
+ st.write("""
315
+ This tool fetches real-time data from the official WNBA Stats API, including:
316
+
317
+ - **Player Game Logs**: Individual player performance in each game
318
+ - **Season Data**: Regular season, playoffs, and preseason statistics
319
+ - **Comprehensive Stats**: Points, rebounds, assists, shooting percentages, and more
320
+ - **Export Options**: Download data in Excel, CSV, or JSON format
321
+
322
+ The data is fetched directly from `stats.wnba.com` and includes all official WNBA statistics.
323
+ """)
324
+
325
+ def show_data_analysis():
326
+ st.header("Data Analysis")
327
+
328
+ # File uploader
329
+ uploaded_file = st.file_uploader("Upload your WNBA data", type=['csv', 'xlsx'])
330
+
331
+ if uploaded_file is not None:
332
+ try:
333
+ if uploaded_file.name.endswith('.csv'):
334
+ df = pd.read_csv(uploaded_file)
335
+ else:
336
+ df = pd.read_excel(uploaded_file)
337
+
338
+ st.success("Data uploaded successfully!")
339
+ st.dataframe(df.head(), use_container_width=True)
340
+
341
+ # Basic statistics
342
+ st.subheader("Data Summary")
343
+ st.write(df.describe())
344
+
345
+ except Exception as e:
346
+ st.error(f"Error loading data: {str(e)}")
347
+ else:
348
+ st.info("Please upload a CSV or Excel file to begin analysis.")
349
+
350
+ def show_visualizations():
351
+ st.header("Data Visualizations")
352
+
353
+ if PLOTLY_AVAILABLE:
354
+ # Sample visualization
355
+ st.subheader("Sample Team Performance Chart")
356
+
357
+ # Generate sample data
358
+ teams = ['Las Vegas Aces', 'New York Liberty', 'Connecticut Sun', 'Seattle Storm', 'Chicago Sky']
359
+ wins = np.random.randint(15, 25, len(teams))
360
+ losses = np.random.randint(5, 15, len(teams))
361
+
362
+ fig = px.bar(
363
+ x=teams,
364
+ y=[wins, losses],
365
+ title="Team Wins vs Losses",
366
+ labels={'x': 'Teams', 'y': 'Games'},
367
+ color_discrete_sequence=['#FF6B6B', '#4ECDC4']
368
+ )
369
+
370
+ st.plotly_chart(fig, use_container_width=True)
371
+ else:
372
+ st.info("Advanced visualizations require plotly. Using basic charts instead.")
373
+
374
+ # Interactive chart (using Streamlit's built-in charts)
375
+ st.subheader("Interactive Player Stats")
376
+ chart_type = st.selectbox("Select chart type", ["Bar Chart", "Line Chart", "Area Chart"])
377
+
378
+ # Sample data
379
+ chart_data = pd.DataFrame({
380
+ 'Points': np.random.randint(10, 30, 10),
381
+ 'Rebounds': np.random.randint(5, 15, 10),
382
+ 'Assists': np.random.randint(2, 12, 10)
383
+ })
384
+
385
+ if chart_type == "Bar Chart":
386
+ st.bar_chart(chart_data)
387
+ elif chart_type == "Line Chart":
388
+ st.line_chart(chart_data)
389
+ elif chart_type == "Area Chart":
390
+ st.area_chart(chart_data)
391
+
392
+ def show_settings():
393
+ st.header("Settings")
394
+
395
+ st.subheader("Display Preferences")
396
+ theme = st.selectbox("Choose theme", ["Light", "Dark"])
397
+ show_sidebar = st.checkbox("Show sidebar by default", value=True)
398
+
399
+ st.subheader("Data Preferences")
400
+ auto_refresh = st.checkbox("Auto-refresh data")
401
+ refresh_interval = st.slider("Refresh interval (minutes)", 1, 60, 5)
402
+
403
+ st.subheader("Export Settings")
404
+ export_format = st.selectbox("Default export format", ["CSV", "Excel", "JSON"])
405
+
406
+ if st.button("Save Settings"):
407
+ st.success("Settings saved successfully!")
408
+
409
+ if __name__ == "__main__":
410
+ main()