-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpga.py
executable file
·271 lines (225 loc) · 8.14 KB
/
pga.py
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
#!/usr/bin/env python3
import requests
import time
import re
from argparse import ArgumentParser
from bs4 import BeautifulSoup
from rich.live import Live
from rich.table import Table
players = []
def get_player_data(reset = False):
if reset:
players.clear()
"""Get player data from ESPN"""
# players = []
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36'}
html = requests.get("https://www.espn.com/golf/leaderboard", headers=headers).text
soup = BeautifulSoup(html, features="html.parser")
tournament_title = soup.find('h1', ['Leaderboard__Event__Title']).text
cutline_row = soup.find_all('tr', ['cutline'])
cutline = None
if cutline_row:
cutline_data = list(cutline_row[0].children)
cutline_text = cutline_data[0].text.replace('Projected Cut', '')
cutline = get_as_int(cutline_text)
rows = soup.find_all('tr', ['PlayerRow__Overview'])
lowest_score_today = 0
# Need to see what happens here before tournament starts
current_round_raw = soup.find_all('div', ['status'])[0].text
current_round_html = re.match("Round (\\d*).*", current_round_raw)
# round 5 is tournament over
current_round_text = '5' if current_round_html is None else current_round_html.group(1)
current_round = 0 if get_as_int(current_round_text) is None else get_as_int(current_round_text)
round_indeces = {
0: {
'player': 1,
'thru': 2,
},
1: {
'standing': 1,
'player': 2,
'score': 3,
'today': 4,
'thru': 5,
},
2: {
'standing': 1,
'player': 3,
'score': 4,
'today': 5,
'thru': 6,
},
3: {
'standing': 1,
'player': 3,
'score': 4,
'today': 5,
'thru': 6,
},
4: {
'standing': 1,
'player': 3,
'score': 4,
'today': 5,
'thru': 6,
},
5: {
'standing': 1,
'player': 2,
'score': 3,
'today': 7,
'thru': 9,
},
}
index = 0
indeces = round_indeces[current_round]
for row in rows:
data = list(row.children)
# Round not started, need to make up certain values
if len(data) == 3:
standing = f'{index}' # <-- this is not not technically accurate since they are all tied, but allows for easy filtering
player = data[1].text
score = 'E'
today = None
thru = data[2].text
elif len(data) > 5:
standing = data[indeces['standing']].text
player = data[indeces['player']].text
score = data[indeces['score']].text
today = data[indeces['today']].text
thru = data[indeces['thru']].text
try:
today_score = int(today)
if today_score < lowest_score_today:
lowest_score_today = today_score
except:
today_score = None
is_cut = False
if cutline is not None and score != 'WD':
score_num = get_as_int(score)
if score_num > cutline:
is_cut = True
players.append({"display_order": index, "tournament": tournament_title, "player": player, "standing": standing, "score": score,
"today": today, "today_score": today_score, "thru": thru, "hot": False, "is_cut": is_cut, "round": current_round})
index = index + 1
for player in players:
if current_round < 5:
thru = '18' if player['thru'] == 'F' else player['thru']
if '*' in thru:
thru = thru.replace('*', '')
if player['today_score'] is not None:
if (player['today_score'] == lowest_score_today) or (player['today_score'] - lowest_score_today < 3):
player['hot'] = True
elif (player['today_score'] < 0 and 'M' not in player['thru'] and player['today_score'] + int(thru) <= 2):
player['hot'] = True
def get_as_int(score_txt):
"""Convert score to int"""
score_txt = score_txt.replace('+', '')
if score_txt == 'E':
return 0
try:
final_score = int(score_txt)
except:
final_score = None
pass
return final_score
def generate_table(args) -> Table:
"""Make a new table."""
# players = get_player_data()
sorted_players = sorted(players, key=lambda x: x["display_order"])
first_player = players[0]
last_col_label = 'Thru'
if first_player['round'] == 0:
last_col_label = 'Tee Time'
elif first_player['round'] == 5:
last_col_label = 'Earnings'
table = Table(expand=True, highlight=True)
table.add_column("⛳", justify='center')
table.add_column(first_player['tournament'], overflow='ellipsis')
table.add_column(last_col_label, justify='right')
cutline_added = False
for player in sorted_players:
standing = player['standing']
if standing is not None:
try:
standing = int(standing.replace('T', '').replace('-', ''))
except:
standing = 1000
if (standing is None and args.top is None) or standing <= args.top:
if player['is_cut'] and not cutline_added:
table.add_row(
'', '✂️ -----------------------', ''
)
cutline_added = True
score_color = 'white'
if '-' in player['score']:
score_color = 'red'
elif player['score'] == 'E':
score_color = 'green'
player_name = player['player']
if player['hot']:
player_name = f"{player_name} 🔥"
try:
thru_hole = int(player['thru'])
leader_thru = int(players[0]['thru'])
if thru_hole < leader_thru:
player_name = f"[u]{player_name}[/u]"
except:
pass
if player['thru'] == 'F':
player_name = f"[rgb(150,150,150)]{player_name}"
if player['is_cut']:
player_name = f"[strike]{player_name}[/strike]"
player_text = f"{player_name}"
if player['today'] is not None:
player_text += f" ({player['today']})"
table.add_row(
f"[{score_color}]{player['score']}", player_text, player['thru']
)
return table
# Function to roll the order
def roll_order():
# Shift the first element to the end
players.append(players.pop(0))
# Update the "order" key for each dictionary
for index, item in enumerate(players):
item["display_order"] = index + 1
def get_parser():
""" setup parser and return parsed command line arguments
"""
parser = ArgumentParser(
description='PGA leaderboard from ESPN now in your terminal')
parser.add_argument(
'--top',
type=int,
required=False,
default=1000,
help='Top [n] players to show')
parser.add_argument(
'--snapshot',
action='store_true',
help='Just show a snapshot of players do not continuously update')
return parser
def main():
parser = get_parser()
args = parser.parse_args()
count = 0
get_player_data()
sleep_time = 0.5
with Live(generate_table(args), refresh_per_second=20) as live:
if args.snapshot is False:
while True:
time.sleep(sleep_time)
roll_order()
if count % 60 == 0:
get_player_data(count % 10 == 0)
count = 0
live.update(generate_table(args))
count = count + 1
# with Live(generate_table(args), refresh_per_second=1) as live:
# if args.snapshot is False:
# while True:
# time.sleep(30)
# live.update(generate_table(args))
if __name__ == '__main__':
main()