-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrating_fetcher.py
More file actions
645 lines (578 loc) · 26.5 KB
/
rating_fetcher.py
File metadata and controls
645 lines (578 loc) · 26.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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
import requests
import time
import logging
import re
import json
from typing import Dict, Any
from bs4 import BeautifulSoup
class RatingFetcher:
"""Class to fetch ratings from various competitive programming platforms"""
def __init__(self):
self.session = requests.Session()
self.session.headers.update({
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
})
def get_leetcode_rating(self, username: str) -> Dict[str, Any]:
"""Fetch LeetCode rating for a user"""
logger = logging.getLogger(__name__)
logger.info(f"Fetching LeetCode rating for user: {username}")
try:
# GraphQL query for LeetCode
url = "https://leetcode.com/graphql"
query = """
query getUserProfile($username: String!) {
matchedUser(username: $username) {
username
profile {
ranking
}
submitStats {
acSubmissionNum {
difficulty
count
}
}
}
userContestRanking(username: $username) {
attendedContestsCount
rating
globalRanking
topPercentage
}
}
"""
payload = {
"query": query,
"variables": {"username": username}
}
response = self.session.post(url, json=payload, timeout=10)
response.raise_for_status()
data = response.json()
if data.get('data') and data['data'].get('matchedUser'):
user_data = data['data']['matchedUser']
contest_data = data['data'].get('userContestRanking')
rating = contest_data['rating'] if contest_data else 0
logger.info(
f"Successfully fetched LeetCode data for {username}: rating={rating}")
result = {
'platform': 'leetcode',
'username': username,
'rating': rating,
'global_ranking': contest_data['globalRanking'] if contest_data else None,
'contests_attended': contest_data['attendedContestsCount'] if contest_data else 0,
'profile_ranking': user_data['profile']['ranking'] if user_data.get('profile') else None,
'status': 'success'
}
return result
else:
logger.warning(f"LeetCode user not found: {username}")
return {
'platform': 'leetcode',
'username': username,
'rating': 0,
'status': 'user_not_found',
'error': 'User not found'
}
except requests.exceptions.Timeout:
logger.error(
f"Timeout while fetching LeetCode data for {username}")
return {
'platform': 'leetcode',
'username': username,
'rating': 0,
'status': 'error',
'error': 'Request timeout'
}
except requests.exceptions.ConnectionError:
logger.error(
f"Connection error while fetching LeetCode data for {username}")
return {
'platform': 'leetcode',
'username': username,
'rating': 0,
'status': 'error',
'error': 'Connection error'
}
except Exception as e:
logger.error(
f"Unexpected error fetching LeetCode data for {username}: {str(e)}")
return {
'platform': 'leetcode',
'username': username,
'rating': 0,
'status': 'error',
'error': str(e)
}
def get_codeforces_rating(self, username: str) -> Dict[str, Any]:
"""Fetch Codeforces rating for a user"""
logger = logging.getLogger(__name__)
logger.info(f"Fetching Codeforces rating for user: {username}")
try:
url = f"https://codeforces.com/api/user.info?handles={username}"
response = self.session.get(url, timeout=10)
response.raise_for_status()
data = response.json()
if data['status'] == 'OK' and data['result']:
user_info = data['result'][0]
rating = user_info.get('rating', 0)
max_rating = user_info.get('maxRating', 0)
logger.info(
f"Successfully fetched Codeforces data for {username}: rating={rating}, max_rating={max_rating}")
return {
'platform': 'codeforces',
'username': username,
'rating': rating,
'max_rating': max_rating,
'rank': user_info.get('rank', 'unrated'),
'max_rank': user_info.get('maxRank', 'unrated'),
'contribution': user_info.get('contribution', 0),
'status': 'success'
}
else:
logger.warning(f"Codeforces user not found: {username}")
return {
'platform': 'codeforces',
'username': username,
'rating': 0,
'status': 'user_not_found',
'error': 'User not found'
}
except requests.exceptions.Timeout:
logger.error(
f"Timeout while fetching Codeforces data for {username}")
return {
'platform': 'codeforces',
'username': username,
'rating': 0,
'status': 'error',
'error': 'Request timeout'
}
except requests.exceptions.ConnectionError:
logger.error(
f"Connection error while fetching Codeforces data for {username}")
return {
'platform': 'codeforces',
'username': username,
'rating': 0,
'status': 'error',
'error': 'Connection error'
}
except Exception as e:
logger.error(
f"Unexpected error fetching Codeforces data for {username}: {str(e)}")
return {
'platform': 'codeforces',
'username': username,
'rating': 0,
'status': 'error',
'error': str(e)
}
def get_codechef_rating(self, username: str) -> Dict[str, Any]:
"""Fetch CodeChef rating for a user"""
logger = logging.getLogger(__name__)
logger.info(f"Fetching CodeChef rating for user: {username}")
try:
url = f"https://www.codechef.com/users/{username}"
response = self.session.get(url, timeout=10)
response.raise_for_status()
# Parse the HTML to extract rating information
html_content = response.text
# Check if user exists (404 or 'Page Not Found')
if response.status_code == 404 or 'page not found' in html_content.lower():
logger.warning(f"CodeChef user not found: {username}")
return {
'platform': 'codechef',
'username': username,
'rating': 0,
'status': 'user_not_found',
'error': 'User not found'
}
soup = BeautifulSoup(html_content, 'html.parser')
# Initialize defaults
rating = 0
max_rating = 0
country_flag = ""
country_name = ""
global_rank = 0
country_rank = 0
stars = "unrated"
# Find current rating
rating_element = soup.select_one(".rating-number")
if rating_element:
rating_text = rating_element.get_text(strip=True)
rating_digits = re.sub(r'[^\d]', '', rating_text)
if rating_digits:
try:
rating = int(rating_digits)
logger.debug(
f"Successfully parsed current rating for {username}: {rating}")
except ValueError:
logger.warning(
f"Failed to parse rating digits for {username}: '{rating_digits}'")
rating = 0
else:
logger.debug(
f"No rating digits found in text: '{rating_text}'")
else:
logger.debug(f"No rating-number element found for {username}")
# Find max rating by traversing parent children
if rating_element and rating_element.parent:
try:
children = rating_element.parent.children
children_list = [
child for child in children if child != '\n']
if len(children_list) > 4:
max_rating_element = children_list[-1]
max_rating_text = max_rating_element.get_text(
strip=True)
if "Rating" in max_rating_text:
# Extract text after "Rating"
max_rating_part = max_rating_text.split("Rating")[
1].strip()
max_rating_digits = re.sub(
r'[^\d]', '', max_rating_part)
if max_rating_digits:
try:
max_rating = int(max_rating_digits)
logger.debug(
f"Successfully parsed max rating for {username}: {max_rating}")
except ValueError:
logger.warning(
f"Failed to parse max rating digits for {username}: '{max_rating_digits}'")
max_rating = 0
else:
logger.debug(
f"No max rating digits found in text: '{max_rating_part}'")
else:
logger.debug(
f"'Rating' keyword not found in max rating text: '{max_rating_text}'")
else:
logger.debug(
f"Insufficient children elements for max rating parsing: {len(children_list)}")
except Exception as e:
logger.debug(
f"Error parsing max rating structure for {username}: {e}")
# Find country flag
try:
country_flag_element = soup.select_one(".user-country-flag")
if country_flag_element:
country_flag = country_flag_element.get('src', '')
logger.debug(
f"Found country flag for {username}: {country_flag}")
except Exception as e:
logger.debug(f"Error parsing country flag for {username}: {e}")
# Find country name
try:
country_name_element = soup.select_one(".user-country-name")
if country_name_element:
country_name = country_name_element.get_text(strip=True)
logger.debug(
f"Found country name for {username}: {country_name}")
except Exception as e:
logger.debug(f"Error parsing country name for {username}: {e}")
# Find global and country ranks
try:
from bs4 import Tag
rating_ranks = soup.select_one(".rating-ranks")
if rating_ranks:
ul_element = rating_ranks.find('ul')
if ul_element and isinstance(ul_element, Tag):
li_elements = ul_element.find_all('li')
for li in li_elements:
if isinstance(li, Tag):
li_text = li.get_text(strip=True)
if 'Global Rank' in li_text:
global_rank_digits = re.sub(
r'[^\d]', '', li_text)
if global_rank_digits:
try:
global_rank = int(
global_rank_digits)
logger.debug(
f"Found global rank for {username}: {global_rank}")
except ValueError:
logger.debug(
f"Failed to parse global rank for {username}: '{global_rank_digits}'")
elif 'Country Rank' in li_text:
country_rank_digits = re.sub(
r'[^\d]', '', li_text)
if country_rank_digits:
try:
country_rank = int(
country_rank_digits)
logger.debug(
f"Found country rank for {username}: {country_rank}")
except ValueError:
logger.debug(
f"Failed to parse country rank for {username}: '{country_rank_digits}'")
except Exception as e:
logger.debug(f"Error parsing ranks for {username}: {e}")
# Find stars (rating category)
try:
stars_element = soup.select_one(".rating")
if stars_element:
stars = stars_element.get_text(strip=True)
logger.debug(
f"Found stars/rating category for {username}: {stars}")
except Exception as e:
logger.debug(f"Error parsing stars for {username}: {e}")
# Ensure max_rating is at least equal to current rating
if max_rating < rating:
logger.debug(
f"Max rating {max_rating} is less than current rating {rating}, setting max_rating = rating")
max_rating = rating
# Edge case: If no rating found at all
if rating == 0 and max_rating == 0:
logger.warning(
f"No rating information found for CodeChef user: {username}")
logger.info(
f"Successfully fetched CodeChef data for {username}: rating={rating}, max_rating={max_rating}, country={country_name}, global_rank={global_rank}")
return {
'platform': 'codechef',
'username': username,
'rating': rating,
'max_rating': max_rating,
'country_flag': country_flag,
'country_name': country_name,
'global_rank': global_rank,
'country_rank': country_rank,
'stars': stars,
'status': 'success'
}
except requests.exceptions.Timeout:
logger.error(
f"Timeout while fetching CodeChef data for {username}")
return {
'platform': 'codechef',
'username': username,
'rating': 0,
'status': 'error',
'error': 'Request timeout'
}
except requests.exceptions.ConnectionError:
logger.error(
f"Connection error while fetching CodeChef data for {username}")
return {
'platform': 'codechef',
'username': username,
'rating': 0,
'status': 'error',
'error': 'Connection error'
}
except Exception as e:
logger.error(
f"Unexpected error fetching CodeChef data for {username}: {str(e)}")
return {
'platform': 'codechef',
'username': username,
'rating': 0,
'status': 'error',
'error': str(e)
}
def get_atcoder_rating(self, username: str) -> Dict[str, Any]:
"""Fetch AtCoder rating for a user"""
logger = logging.getLogger(__name__)
logger.info(f"Fetching AtCoder rating for user: {username}")
try:
url = f"https://atcoder.jp/users/{username}"
response = self.session.get(url, timeout=10)
# Check if user exists (404 or page not found)
if response.status_code == 404:
logger.warning(f"AtCoder user not found: {username}")
return {
'platform': 'atcoder',
'username': username,
'rating': 0,
'status': 'user_not_found',
'error': 'User not found'
}
response.raise_for_status()
html_content = response.text
soup = BeautifulSoup(html_content, 'html.parser')
# Initialize defaults
rating = 0
max_rating = 0
rank = 0
country = ""
# Parse HTML table
try:
# Look for the rating in the user statistics table
table_cells = soup.find_all(['td', 'th'])
for i, cell in enumerate(table_cells):
cell_text = cell.get_text(strip=True)
if cell_text == "Rating":
# Rating value should be in the next cell
if i + 1 < len(table_cells):
rating_text = table_cells[i +
1].get_text(strip=True)
rating_digits = re.sub(
r'[^\d]', '', rating_text)
if rating_digits:
try:
rating = int(rating_digits)
logger.debug(
f"Successfully parsed AtCoder rating from table for {username}: {rating}")
except ValueError:
logger.debug(
f"Failed to parse AtCoder rating from table for {username}: '{rating_text}'")
break
elif "Highest Rating" in cell_text:
if i + 1 < len(table_cells):
max_rating_text = table_cells[i +
1].get_text(strip=True)
max_rating_digits = re.sub(
r'[^\d]', '', max_rating_text)
if max_rating_digits:
try:
max_rating = int(max_rating_digits)
logger.debug(
f"Successfully parsed AtCoder max rating from table for {username}: {max_rating}")
except ValueError:
logger.debug(
f"Failed to parse AtCoder max rating from table for {username}: '{max_rating_text}'")
elif "Rank" in cell_text:
print("rank found")
if i + 1 < len(table_cells):
rank_text = table_cells[i +
1].get_text(strip=True)
rank_text = re.sub(
r'[^\d]', '', rank_text)
if rank_text:
try:
rank = int(rank_text)
logger.debug(
f"Successfully parsed AtCoder rank from table for {username}: {rank}")
except ValueError:
logger.debug(
f"Failed to parse AtCoder rank from table for {username}: '{rank_text}'")
except Exception as e:
logger.debug(
f"Error parsing AtCoder table for {username}: {e}")
# Try to find country information
try:
table_cells = soup.find_all(['td', 'th'])
for i, cell in enumerate(table_cells):
if "Country" in cell.get_text(strip=True):
if i + 1 < len(table_cells):
country = table_cells[i + 1].get_text(strip=True)
logger.debug(
f"Found AtCoder country for {username}: {country}")
break
except Exception as e:
logger.debug(
f"Error parsing AtCoder country for {username}: {e}")
# Ensure max_rating is at least equal to current rating
if max_rating < rating:
max_rating = rating
# Edge case: If no rating found at all
if rating == 0 and max_rating == 0:
logger.warning(
f"No rating information found for AtCoder user: {username}")
logger.info(
f"Successfully fetched AtCoder data for {username}: rating={rating}, max_rating={max_rating}, rank={rank}")
return {
'platform': 'atcoder',
'username': username,
'rating': rating,
'max_rating': max_rating,
'rank': rank,
'country': country,
'status': 'success'
}
except requests.exceptions.Timeout:
logger.error(f"Timeout while fetching AtCoder data for {username}")
return {
'platform': 'atcoder',
'username': username,
'rating': 0,
'status': 'error',
'error': 'Request timeout'
}
except requests.exceptions.ConnectionError:
logger.error(
f"Connection error while fetching AtCoder data for {username}")
return {
'platform': 'atcoder',
'username': username,
'rating': 0,
'status': 'error',
'error': 'Connection error'
}
except Exception as e:
logger.error(
f"Unexpected error fetching AtCoder data for {username}: {str(e)}")
return {
'platform': 'atcoder',
'username': username,
'rating': 0,
'status': 'error',
'error': str(e)
}
def get_rating_by_platform(self, platform: str, username: str) -> Dict[str, Any]:
"""Get rating for a specific platform and username"""
platform = platform.lower().strip()
if platform == 'leetcode':
return self.get_leetcode_rating(username)
elif platform == 'codeforces':
return self.get_codeforces_rating(username)
elif platform == 'codechef':
return self.get_codechef_rating(username)
elif platform == 'atcoder':
return self.get_atcoder_rating(username)
else:
return {
'platform': platform,
'username': username,
'rating': 0,
'status': 'error',
'error': f'Unsupported platform: {platform}'
}
def get_multiple_ratings(self, requests_data: list) -> Dict[str, Any]:
"""
Get ratings for multiple platform/username pairs
requests_data: List of dicts with 'platform' and 'username' keys
"""
logger = logging.getLogger(__name__)
logger.info(
f"Fetching multiple ratings for {len(requests_data)} requests")
results = []
valid_ratings = []
for i, request in enumerate(requests_data, 1):
platform = request.get('platform', '').lower().strip()
username = request.get('username', '').strip()
if not platform or not username:
logger.warning(
f"Request {i}: Missing platform or username - platform: '{platform}', username: '{username}'")
results.append({
'platform': platform,
'username': username,
'rating': 0,
'status': 'error',
'error': 'Platform and username are required'
})
continue
logger.debug(
f"Processing request {i}/{len(requests_data)}: {platform}/{username}")
# Add small delay to avoid rate limiting
if i > 1: # Don't delay on first request
time.sleep(0.5)
logger.debug(f"Applied rate limiting delay before request {i}")
rating_data = self.get_rating_by_platform(platform, username)
results.append(rating_data)
# Collect valid ratings for average calculation
if rating_data['status'] == 'success' and rating_data['rating'] > 0:
valid_ratings.append(rating_data['rating'])
# Calculate average rating
average_rating = sum(valid_ratings) / \
len(valid_ratings) if valid_ratings else 0
successful_requests = len(
[r for r in results if r['status'] == 'success'])
logger.info(f"Completed multiple ratings fetch: {successful_requests}/{len(requests_data)} successful, "
f"average rating: {round(average_rating, 2)}")
return {
'results': results,
'average_rating': round(average_rating, 2),
'total_requests': len(requests_data),
'successful_requests': successful_requests,
'valid_ratings_count': len(valid_ratings)
}