acetwo3ee commited on
Commit
079bdfd
·
verified ·
1 Parent(s): 4a657b7

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +88 -46
src/streamlit_app.py CHANGED
@@ -1,9 +1,11 @@
1
  import streamlit as st
2
  import requests
 
3
  import gspread
4
  from oauth2client.service_account import ServiceAccountCredentials
5
- import json
6
  import traceback
 
 
7
 
8
  # Google Sheets configuration
9
  SHEET_ID = "1PCugIPyYM1lF6KOCPUY5hL8xbGI5PWd7gVvCyudrB5c"
@@ -31,7 +33,7 @@ OFYaSHo3HqcamuEMRYBDab5rzRsxQOk0FFjeB6d0Xt3X7MNgdXqfukMEAYaJ0cd+
31
  VWJJsJb/P8xuL64y8sI6NUdTGqTUxqB6CJOriMkLI0b6JVK/vTj3Hd88VthdYwNC
32
  FWvFi0ckT9Ab3Fp9+309oav6ZwKBgQC2bcTjuwsiXRKzTYoODoF/Z/+NIPCI4BZ5
33
  wUAwY/otQ0/dQB7B5+DruLnIWCVM4PzXoPvpLgrs/iiyFPDGTlYtUa2rBTfKHr13
34
- UA0Y97uRvBh6004RAbM/xHoWeX2uSRtD8kzs5TZGlzgPyS0FT7b9nb+1iWPrcMJy
35
  aoQI3hhWOwKBgAlqLrVfBvhi/HU9Zi/dF/OK5QmYkEEhawmOkE9uoKlgvTGyUV1v
36
  RMB7Qkp1GZjYIhVl5miW54osmsjef614pYetHivs6ypnNPEViSQdKR9EyWjbEN0Z
37
  4hs/AzaazAcLs5eFNxGurZrb024FM97NYfAefT2HC/DTzKqgM9XgpxBTAoGBAKEW
@@ -51,7 +53,7 @@ YMSoAW+xwwELc6a+5m8u60ZU
51
  "universe_domain": "googleapis.com"
52
  }
53
 
54
- # Corrected URL
55
  URL = "https://www.rugbypremierleague.in/feeds/live/MatchCenter_MatchID-43.json"
56
  HEADERS = {
57
  "accept": "*/*",
@@ -67,63 +69,91 @@ HEADERS = {
67
  "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"
68
  }
69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  def fetch_json_data():
71
  try:
72
  response = requests.get(URL, headers=HEADERS)
73
  if response.status_code == 200:
74
- st.success("Data fetched successfully!")
75
- st.session_state["last_data"] = response.json()
76
- st.write(f"Data size: {len(json.dumps(st.session_state['last_data']))} characters")
77
- return st.session_state["last_data"]
78
  else:
79
- st.error(f"Failed to fetch data: Status code {response.status_code}")
80
  return None
81
  except Exception as e:
82
- st.error(f"Error fetching data: {str(e)}")
83
  return None
84
 
85
  def write_to_google_sheet(data):
86
  try:
87
  with st.spinner("Writing to Google Sheet..."):
88
  st.write("Debug: Starting Google Sheets write operation")
 
89
  scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
90
  creds = ServiceAccountCredentials.from_json_keyfile_dict(SERVICE_ACCOUNT_INFO, scope)
91
  st.write("Debug: Authentication successful")
92
  client = gspread.authorize(creds)
 
 
93
  st.write("Debug: Opening Google Sheet")
94
  sheet = client.open_by_key(SHEET_ID).worksheet(SHEET_NAME)
 
 
95
  st.write("Debug: Clearing existing data")
96
  sheet.clear()
97
 
98
- # Write key fields (adjust based on actual JSON structure)
99
- st.write("Debug: Writing key fields")
100
- headers = ["Match ID", "Team 1", "Team 2", "Team 1 Score", "Team 2 Score"]
101
- try:
102
- values = [
103
- [
104
- data.get("match", {}).get("id", "N/A"),
105
- data.get("match", {}).get("team1", "N/A"),
106
- data.get("match", {}).get("team2", "N/A"),
107
- data.get("match", {}).get("score", {}).get("team1", "N/A"),
108
- data.get("match", {}).get("score", {}).get("team2", "N/A")
109
- ]
110
- ]
111
- except Exception as e:
112
- st.error(f"Error parsing JSON: {str(e)}")
113
- return False
114
-
115
- sheet.append_row(headers)
116
- for row in values:
117
- sheet.append_row(row)
118
-
119
- # Optional: Write JSON in chunks
120
- st.write("Debug: Writing JSON chunk")
121
- json_str = json.dumps(data, indent=2)
122
- chunk_size = 40000 # Below Google Sheets cell limit
123
- if len(json_str) > chunk_size:
124
- st.warning(f"JSON is too large ({len(json_str)} characters). Writing first {chunk_size} characters.")
125
- json_str = json_str[:chunk_size]
126
- sheet.update('A10', json_str)
127
 
128
  st.success("Data written to Google Sheet successfully!")
129
  return True
@@ -134,25 +164,37 @@ def write_to_google_sheet(data):
134
 
135
  def main():
136
  st.title("Rugby Premier League Data Fetcher")
137
- st.write("Fetching data for match ID 43 (Bengaluru Bravehearts vs. Delhi Redz) at 05:07 PM IST, June 23, 2025")
 
 
 
 
 
 
 
 
138
 
139
- if st.button("Fetch Data"):
 
 
140
  json_data = fetch_json_data()
141
  if json_data:
142
- st.subheader("Fetched Data")
143
  st.json(json_data)
144
  else:
145
- st.warning("No data fetched. Please try again or check the URL.")
146
 
147
- if st.button("Write to Google Sheet"):
 
 
148
  st.write("Debug: Write to Google Sheet button clicked")
149
- if "last_data" in st.session_state:
150
- if write_to_google_sheet(st.session_state["last_data"]):
151
  st.write(f"View the updated sheet [here](https://docs.google.com/spreadsheets/d/{SHEET_ID})")
152
  else:
153
  st.error("Failed to write to Google Sheet. See error details above.")
154
  else:
155
- st.error("No data available to write. Please fetch data first.")
156
 
157
  if __name__ == "__main__":
158
  main()
 
1
  import streamlit as st
2
  import requests
3
+ import pandas as pd
4
  import gspread
5
  from oauth2client.service_account import ServiceAccountCredentials
 
6
  import traceback
7
+ import json
8
+ import io
9
 
10
  # Google Sheets configuration
11
  SHEET_ID = "1PCugIPyYM1lF6KOCPUY5hL8xbGI5PWd7gVvCyudrB5c"
 
33
  VWJJsJb/P8xuL64y8sI6NUdTGqTUxqB6CJOriMkLI0b6JVK/vTj3Hd88VthdYwNC
34
  FWvFi0ckT9Ab3Fp9+309oav6ZwKBgQC2bcTjuwsiXRKzTYoODoF/Z/+NIPCI4BZ5
35
  wUAwY/otQ0/dQB7B5+DruLnIWCVM4PzXoPvpLgrs/iiyFPDGTlYtUa2rBTfKHr13
36
+ UA0Y97uRvBd6004RAbM/xHoWeX2uSRtD8kzs5TZGlzgPyS0FT7b9nb+1iWPrcMJy
37
  aoQI3hhWOwKBgAlqLrVfBvhi/HU9Zi/dF/OK5QmYkEEhawmOkE9uoKlgvTGyUV1v
38
  RMB7Qkp1GZjYIhVl5miW54osmsjef614pYetHivs6ypnNPEViSQdKR9EyWjbEN0Z
39
  4hs/AzaazAcLs5eFNxGurZrb024FM97NYfAefT2HC/DTzKqgM9XgpxBTAoGBAKEW
 
53
  "universe_domain": "googleapis.com"
54
  }
55
 
56
+ # URL and headers (no caching headers)
57
  URL = "https://www.rugbypremierleague.in/feeds/live/MatchCenter_MatchID-43.json"
58
  HEADERS = {
59
  "accept": "*/*",
 
69
  "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"
70
  }
71
 
72
+ # Excel data as a string (from provided DOCUMENT)
73
+ EXCEL_DATA = """id name short_name jersey_no position_id position is_substitute is_substituted isPlaying minutes_played jersey starter captain is_Injured offloads line_breaks defenders_beaten points try_assists tries tackles turnovers_won yellow_cards red_cards handling_errors knock_ons conversions penalty_goals points_scored tries_scored conversions penalty_goals
74
+ 165 Pol Pla Pol Pla 7 4 Back 0 0 0 18 7 1 1 0 0 0 0 0 1 0 3 0 0 0 0 0 0 0 0 0 0 0
75
+ 191 Tone Ng Shiu Tone Ng Shiu 3 3 Hybrid 0 0 0 12 3 1 0 0 1 0 2 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0
76
+ 245 Iowane Teba Iowane Teba 10 4 Back 1 0 1 6 10 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0
77
+ 370 Liam Poulton Liam Poulton 14 4 Back 0 0 1 19 14 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0
78
+ 371 Mak Kwai Chung Mak Kwai Chung 99 4 Back 1 0 1 14 99 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0
79
+ 372 Akuila Rokolisoa Akuila Rokolisoa 4 4 Back 0 0 1 25 4 1 0 0 0 2 2 16 0 2 3 0 0 0 0 0 3 0 16 2 3 0
80
+ 373 Scott Curry Scott Curry 37 5 Forward 1 0 1 13 37 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
81
+ 374 Mohit Khatri Mohit Khatri 6 3 Hybrid 1 0 1 14 6 0 0 0 0 0 0 0 0 0 2 1 0 0 0 0 0 0 0 0 0 0
82
+ 375 Karan Rajbhar Karan Rajbhar 1 3 Hybrid 1 0 1 13 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
83
+ 376 Arpan Chhetri Arpan Chhetri 12 5 Forward 1 0 0 1 12 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
84
+ 377 Suresh Kumar Suresh Kumar 2 5 Forward 0 0 0 10 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
85
+ 378 Prashant Singh Prashant Singh 5 3 Hybrid 0 1 0 10 5 1 0 0 0 0 3 0 0 0 2 0 0 0 1 0 0 0 0 0 0 0
86
+ 1575 Philip Wokorach Philip Wokorach 15 4 Back 0 0 0 17 15 1 0 0 2 1 2 5 1 1 2 0 0 0 0 0 0 0 5 1 0 0
87
+ 1589 Govind Gupta Govind Gupta 17 5 Forward 0 0 0 0 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
88
+ 140 Matteo Graziano Matteo Graziano 1 5 Forward 1 0 1 9 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
89
+ 144 Matias Osadczuk Matias Osadczuk 97 5 Forward 0 0 1 22 97 1 1 0 0 1 2 9 0 1 0 0 1 0 0 0 2 0 9 1 2 0
90
+ 168 Alejandro Laforga Alejandro Laforga 19 4 Back 0 0 1 25 19 1 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0
91
+ 270 Patrick Odongo Okongo Patrick Odongo Okongo 11 4 Back 0 0 1 25 11 1 0 0 0 2 2 10 0 2 2 0 0 0 0 0 0 0 10 2 0 0
92
+ 284 Jordan Conroy Jordan Conroy 7 4 Back 1 0 0 0 7 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
93
+ 410 Michael Coverdale Michael Coverdale 25 5 Forward 0 0 0 19 25 1 0 0 0 0 0 0 1 0 1 1 0 0 0 0 0 0 0 0 0 0
94
+ 411 Moritz Noll Moritz Noll 77 4 Back 1 0 0 0 77 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
95
+ 413 Rajdeep Saha Rajdeep Saha 4 4 Back 0 0 1 25 4 1 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0
96
+ 414 Deepak Punia Deepak Punia 10 4 Back 0 0 1 25 10 1 0 0 0 0 0 2 0 0 0 1 0 0 2 0 1 0 2 0 1 0
97
+ 416 Sunil Chawan Sunil Chawan 20 4 Back 1 0 0 0 20 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
98
+ 417 Raj Kumar Raj Kumar 5 3 Hybrid 1 0 0 0 5 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0
99
+ 1578 Robin Plumpe Robin Plumpe 27 3 Hybrid 0 0 1 25 27 1 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0
100
+ 1584 Mohit Mohit 9 4 Back 1 0 0 0 9 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0"""
101
+
102
+ def load_excel_data():
103
+ try:
104
+ # Read Excel data from string
105
+ df = pd.read_csv(io.StringIO(EXCEL_DATA), sep='\t')
106
+ # Select required columns
107
+ columns = ['id', 'name', 'short_name', 'jersey_no', 'position', 'is_substitute', 'is_substituted',
108
+ 'isPlaying', 'minutes_played', 'starter', 'captain', 'is_Injured', 'offloads',
109
+ 'line_breaks', 'defenders_beaten', 'points', 'try_assists', 'tries', 'tackles',
110
+ 'turnovers_won', 'yellow_cards', 'red_cards', 'handling_errors', 'knock_ons',
111
+ 'conversions', 'penalty_goals', 'points_scored', 'tries_scored', 'conversions',
112
+ 'penalty_goals']
113
+ df = df[columns]
114
+ st.session_state["excel_data"] = df
115
+ return df
116
+ except Exception as e:
117
+ st.error(f"Error loading Excel data: {str(e)}\n{traceback.format_exc()}")
118
+ return None
119
+
120
  def fetch_json_data():
121
  try:
122
  response = requests.get(URL, headers=HEADERS)
123
  if response.status_code == 200:
124
+ st.success("JSON data fetched successfully!")
125
+ st.session_state["json_data"] = response.json()
126
+ return st.session_state["json_data"]
 
127
  else:
128
+ st.error(f"Failed to fetch JSON data: Status code {response.status_code}")
129
  return None
130
  except Exception as e:
131
+ st.error(f"Error fetching JSON data: {str(e)}\n{traceback.format_exc()}")
132
  return None
133
 
134
  def write_to_google_sheet(data):
135
  try:
136
  with st.spinner("Writing to Google Sheet..."):
137
  st.write("Debug: Starting Google Sheets write operation")
138
+ # Authenticate
139
  scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
140
  creds = ServiceAccountCredentials.from_json_keyfile_dict(SERVICE_ACCOUNT_INFO, scope)
141
  st.write("Debug: Authentication successful")
142
  client = gspread.authorize(creds)
143
+
144
+ # Open sheet
145
  st.write("Debug: Opening Google Sheet")
146
  sheet = client.open_by_key(SHEET_ID).worksheet(SHEET_NAME)
147
+
148
+ # Clear existing data
149
  st.write("Debug: Clearing existing data")
150
  sheet.clear()
151
 
152
+ # Write data (pandas DataFrame)
153
+ st.write("Debug: Writing Excel data")
154
+ # Convert DataFrame to list of lists (including headers)
155
+ data_values = [data.columns.tolist()] + data.values.tolist()
156
+ sheet.update('A1', data_values)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
 
158
  st.success("Data written to Google Sheet successfully!")
159
  return True
 
164
 
165
  def main():
166
  st.title("Rugby Premier League Data Fetcher")
167
+ st.write("Processing data for match ID 43 (Bengaluru Bravehearts vs. Delhi Redz) at 05:17 PM IST, June 23, 2025")
168
+
169
+ # Load Excel data
170
+ st.subheader("Excel Data (Squad)")
171
+ excel_data = load_excel_data()
172
+ if excel_data is not None:
173
+ st.dataframe(excel_data)
174
+ else:
175
+ st.warning("No Excel data loaded.")
176
 
177
+ # Fetch JSON data
178
+ st.subheader("Fetch JSON Data")
179
+ if st.button("Fetch JSON Data"):
180
  json_data = fetch_json_data()
181
  if json_data:
182
+ st.subheader("Fetched JSON Data")
183
  st.json(json_data)
184
  else:
185
+ st.warning("No JSON data fetched. Please try again or check the URL.")
186
 
187
+ # Write to Google Sheet
188
+ st.subheader("Write to Google Sheet")
189
+ if st.button("Write Excel Data to Google Sheet"):
190
  st.write("Debug: Write to Google Sheet button clicked")
191
+ if "excel_data" in st.session_state:
192
+ if write_to_google_sheet(st.session_state["excel_data"]):
193
  st.write(f"View the updated sheet [here](https://docs.google.com/spreadsheets/d/{SHEET_ID})")
194
  else:
195
  st.error("Failed to write to Google Sheet. See error details above.")
196
  else:
197
+ st.error("No Excel data available to write. Please ensure data is loaded.")
198
 
199
  if __name__ == "__main__":
200
  main()