acetwo3ee commited on
Commit
fc50a08
·
verified ·
1 Parent(s): 6a2ff83

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +30 -155
src/streamlit_app.py CHANGED
@@ -1,14 +1,13 @@
1
  import streamlit as st
2
  import requests
3
- import pandas as pd
4
  from google.oauth2.service_account import Credentials
5
  from googleapiclient.discovery import build
6
  from googleapiclient.errors import HttpError
7
- from io import StringIO
8
- import json
9
 
10
  # Streamlit app title
11
- st.title("Rugby Premier League All Data to CSV and Google Sheets")
12
 
13
  # Input field for match ID
14
  match_id = st.text_input("Enter Match ID (e.g., 69)", value="69")
@@ -71,53 +70,37 @@ def get_sheets_service():
71
  st.error(f"Error initializing Google Sheets client: {e}")
72
  return None
73
 
74
- # Function to write DataFrame to Google Sheets
75
- def write_to_google_sheets(df, sheet_id, sheet_name):
76
  service = get_sheets_service()
77
  if service is None:
78
  return False
79
 
80
  try:
81
- # Convert DataFrame to list of lists for Google Sheets
82
- values = [df.columns.tolist()] + df.values.tolist()
 
 
83
 
84
- # Clear existing data in the sheet (expanded range to handle many columns)
85
  service.spreadsheets().values().clear(
86
  spreadsheetId=sheet_id,
87
- range=f"{sheet_name}!A1:ZZ",
88
  ).execute()
89
 
90
- # Write new data
91
  service.spreadsheets().values().update(
92
  spreadsheetId=sheet_id,
93
  range=f"{sheet_name}!A1",
94
  valueInputOption="RAW",
95
  body={"values": values}
96
  ).execute()
97
- st.success(f"Data successfully written to Google Sheet '{sheet_name}'")
98
  return True
99
  except HttpError as e:
100
  st.error(f"Error writing to Google Sheet: {e}")
101
  return False
102
 
103
- # Function to flatten nested dictionaries
104
- def flatten_dict(d, parent_key='', sep='_'):
105
- items = []
106
- for k, v in d.items():
107
- new_key = f"{parent_key}{sep}{k}" if parent_key else k
108
- if isinstance(v, dict):
109
- items.extend(flatten_dict(v, new_key, sep).items())
110
- elif isinstance(v, list):
111
- # Handle lists by indexing them
112
- for i, item in enumerate(v):
113
- if isinstance(item, dict):
114
- items.extend(flatten_dict(item, f"{new_key}_{i}", sep).items())
115
- else:
116
- items.append((f"{new_key}_{i}", item if item is not None else ''))
117
- else:
118
- items.append((new_key, v if v is not None else ''))
119
- return dict(items)
120
-
121
  # Validate match ID
122
  if not match_id.isdigit():
123
  st.error("Please enter a valid numeric Match ID.")
@@ -149,107 +132,8 @@ else:
149
  st.error(f"Error fetching data for Match ID {match_id}: {e}")
150
  return None
151
 
152
- # Function to extract and flatten all data
153
- def extract_all_data(data, match_id):
154
- try:
155
- records = []
156
-
157
- # Flatten match_detail
158
- match_detail = data.get('match_detail', {})
159
- flat_match_detail = flatten_dict(match_detail, 'match_detail')
160
-
161
- # Handle teams
162
- teams = data.get('teams', None)
163
- with st.expander("Debug: Teams Field Structure"):
164
- if teams is None:
165
- st.write("`teams` field is None or missing.")
166
- else:
167
- st.write(f"`teams` type: {type(teams)}")
168
- st.write(f"`teams` content: {teams}")
169
-
170
- if teams is None:
171
- st.error("No 'teams' field found in the JSON response.")
172
- return pd.DataFrame()
173
-
174
- # Normalize teams to a list of dictionaries
175
- team_list = []
176
- if isinstance(teams, list):
177
- for team_entry in teams:
178
- if isinstance(team_entry, list) and len(team_entry) == 1 and isinstance(team_entry[0], dict):
179
- team_list.append(team_entry[0])
180
- elif isinstance(team_entry, dict):
181
- team_list.append(team_entry)
182
- else:
183
- st.warning(f"Skipping invalid team entry (type: {type(team_entry)}): {team_entry}")
184
- elif isinstance(teams, dict):
185
- team_list = list(teams.values())
186
- else:
187
- st.error(f"Unsupported 'teams' type: {type(teams)}")
188
- return pd.DataFrame()
189
-
190
- if not team_list:
191
- st.error("No valid teams found in the JSON response.")
192
- return pd.DataFrame()
193
-
194
- # Process teams and squad
195
- for team in team_list:
196
- if not isinstance(team, dict):
197
- st.warning(f"Skipping invalid team entry (type: {type(team)}): {team}")
198
- continue
199
-
200
- team_data = flatten_dict({k: v for k, v in team.items() if k != 'squad'}, 'team')
201
- squad = team.get('squad', []) or team.get('players', [])
202
- if not isinstance(squad, list):
203
- st.warning(f"Invalid 'squad' type for team {team.get('name', 'Unknown')}: {type(squad)}")
204
- continue
205
-
206
- for player in squad:
207
- if not isinstance(player, dict):
208
- st.warning(f"Skipping invalid player entry (type: {type(player)}): {player}")
209
- continue
210
- flat_player = flatten_dict(player, 'player')
211
- record = {**flat_match_detail, **team_data, **flat_player}
212
- records.append(record)
213
-
214
- # Handle events
215
- events = data.get('events', [])
216
- if not isinstance(events, list):
217
- st.warning(f"Invalid 'events' type: {type(events)}")
218
- events = []
219
-
220
- for event in events:
221
- if not isinstance(event, dict):
222
- st.warning(f"Skipping invalid event entry (type: {type(event)}): {event}")
223
- continue
224
- flat_event = flatten_dict(event, 'event')
225
- record = {**flat_match_detail, **flat_event}
226
- records.append(record)
227
-
228
- if not records:
229
- st.warning("No data found in the JSON response.")
230
- return pd.DataFrame()
231
-
232
- # Create DataFrame
233
- df = pd.DataFrame(records)
234
- # Convert numeric and boolean columns where possible
235
- for col in df.columns:
236
- # Try converting to numeric
237
- df[col] = pd.to_numeric(df[col], errors='ignore')
238
- # Convert "1"/"0" to True/False for boolean fields
239
- if df[col].dtype == 'object' and any(x in col for x in [
240
- 'is_onbench', 'is_substitute', 'is_substituted', 'isPlaying', 'starter', 'captain',
241
- 'is_Injured', 'is_home_team', 'yellow_Card', 'red_Card', 'isSubUp'
242
- ]):
243
- df[col] = df[col].apply(lambda x: True if x == '1' or x == 1 else False if x == '0' or x == 0 else x)
244
- # Replace NaN with empty string for Google Sheets compatibility
245
- df = df.fillna('')
246
- return df
247
- except Exception as e:
248
- st.error(f"Error processing data: {e}")
249
- return pd.DataFrame()
250
-
251
  # Fetch and process data when button is clicked
252
- if st.button("Fetch and Process All Data"):
253
  data = fetch_json_data(url, match_id)
254
 
255
  if data:
@@ -257,31 +141,22 @@ else:
257
  with st.expander("View Raw JSON"):
258
  st.json(data)
259
 
260
- # Extract and display all data
261
- df = extract_all_data(data, match_id)
 
 
 
 
262
 
263
- if not df.empty:
264
- st.write(f"### All Data for Match ID {match_id}")
265
- st.write(f"**Number of records**: {len(df)}")
266
- st.write(f"**Columns**: {', '.join(df.columns)}")
267
- st.dataframe(df, use_container_width=True)
268
-
269
- # Provide CSV download
270
- csv = df.to_csv(index=False)
271
- st.download_button(
272
- label="Download all data as CSV",
273
- data=csv,
274
- file_name=f"rugby_match_{match_id}_all_data.csv",
275
- mime="text/csv"
276
- )
277
-
278
- # Upload to Google Sheets
279
- if st.button("Upload to Google Sheets"):
280
- if write_to_google_sheets(df, SHEET_ID, SHEET_NAME):
281
- st.write(f"View the sheet [here](https://docs.google.com/spreadsheets/d/{SHEET_ID})")
282
- else:
283
- st.error("Failed to upload data to Google Sheets.")
284
- else:
285
- st.warning(f"No data available for Match ID {match_id}.")
286
  else:
287
  st.warning(f"Failed to fetch data for Match ID {match_id}.")
 
1
  import streamlit as st
2
  import requests
3
+ import json
4
  from google.oauth2.service_account import Credentials
5
  from googleapiclient.discovery import build
6
  from googleapiclient.errors import HttpError
7
+ import pandas as pd
 
8
 
9
  # Streamlit app title
10
+ st.title("Rugby Premier League Raw JSON to Google Sheets and CSV")
11
 
12
  # Input field for match ID
13
  match_id = st.text_input("Enter Match ID (e.g., 69)", value="69")
 
70
  st.error(f"Error initializing Google Sheets client: {e}")
71
  return None
72
 
73
+ # Function to write JSON to Google Sheets
74
+ def write_json_to_google_sheets(json_data, sheet_id, sheet_name):
75
  service = get_sheets_service()
76
  if service is None:
77
  return False
78
 
79
  try:
80
+ # Convert JSON to a string
81
+ json_str = json.dumps(json_data, indent=2)
82
+ # Prepare data as a single cell value
83
+ values = [[json_str]]
84
 
85
+ # Clear existing data in the sheet
86
  service.spreadsheets().values().clear(
87
  spreadsheetId=sheet_id,
88
+ range=f"{sheet_name}!A1:Z",
89
  ).execute()
90
 
91
+ # Write JSON string to A1
92
  service.spreadsheets().values().update(
93
  spreadsheetId=sheet_id,
94
  range=f"{sheet_name}!A1",
95
  valueInputOption="RAW",
96
  body={"values": values}
97
  ).execute()
98
+ st.success(f"Raw JSON successfully written to Google Sheet '{sheet_name}' in cell A1")
99
  return True
100
  except HttpError as e:
101
  st.error(f"Error writing to Google Sheet: {e}")
102
  return False
103
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
  # Validate match ID
105
  if not match_id.isdigit():
106
  st.error("Please enter a valid numeric Match ID.")
 
132
  st.error(f"Error fetching data for Match ID {match_id}: {e}")
133
  return None
134
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  # Fetch and process data when button is clicked
136
+ if st.button("Fetch and Upload JSON"):
137
  data = fetch_json_data(url, match_id)
138
 
139
  if data:
 
141
  with st.expander("View Raw JSON"):
142
  st.json(data)
143
 
144
+ # Upload JSON to Google Sheets
145
+ if st.button("Upload Raw JSON to Google Sheets"):
146
+ if write_json_to_google_sheets(data, SHEET_ID, SHEET_NAME):
147
+ st.write(f"View the sheet [here](https://docs.google.com/spreadsheets/d/{SHEET_ID})")
148
+ else:
149
+ st.error("Failed to upload JSON to Google Sheets.")
150
 
151
+ # Provide CSV download with JSON string
152
+ json_str = json.dumps(data, indent=2)
153
+ df_csv = pd.DataFrame([["json_data"], [json_str]], columns=["key", "value"])
154
+ csv = df_csv.to_csv(index=False)
155
+ st.download_button(
156
+ label="Download JSON as CSV",
157
+ data=csv,
158
+ file_name=f"rugby_match_{match_id}_raw.json.csv",
159
+ mime="text/csv"
160
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
161
  else:
162
  st.warning(f"Failed to fetch data for Match ID {match_id}.")