-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
416 lines (334 loc) · 12.3 KB
/
app.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
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
from flask import Flask, render_template, request
import pandas as pd
import numpy as np
import requests
from prophet import Prophet
from collections import Counter
from datetime import datetime
from collections import defaultdict
app = Flask(__name__, static_url_path="/static")
def get_user_ratings(handle):
url = f"https://codeforces.com/api/user.rating?handle={handle}"
response = []
while True:
response = requests.get(url)
if response.status_code == 200:
break
response = response.json()
data = response
if "result" in data:
ratings_data = data["result"]
# Use the newRating data for predictions
ratings = [entry["newRating"] for entry in ratings_data]
return ratings
else:
return []
def get_user_ranks(handle):
url = f"https://codeforces.com/api/user.rating?handle={handle}"
response = []
while True:
response = requests.get(url)
if response.status_code == 200:
break
response = response.json()
data = response
if "result" in data:
ratings_data = data["result"]
# Use the newRating data for predictions
ratings = [entry["rank"] for entry in ratings_data]
return ratings
else:
return []
def get_submission_data(handle):
api_url = f"https://codeforces.com/api/user.status?handle={handle}"
response = []
while True:
response = requests.get(api_url)
if response.status_code == 200:
break
response = response.json()
json_data = response["result"]
verdict_data = [entry["verdict"] for entry in json_data]
verdict_count = {}
for verdict in verdict_data:
if verdict in verdict_count:
verdict_count[verdict] += 1
else:
verdict_count[verdict] = 1
verdictData = [["Verdict", "Count"]] + [
[verdict, count] for verdict, count in verdict_count.items()
]
for item in verdictData:
if "TIME_LIMIT_EXCEEDED" in item:
item[item.index("TIME_LIMIT_EXCEEDED")] = "TLE"
if "WRONG_ANSWER" in item:
item[item.index("WRONG_ANSWER")] = "WA"
if "MEMORY_LIMIT_EXCEEDED" in item:
item[item.index("MEMORY_LIMIT_EXCEEDED")] = "MLE"
if "OK" in item:
item[item.index("OK")] = "AC"
if "COMPILATION_ERROR" in item:
item[item.index("COMPILATION_ERROR")] = "CE"
if "RUNTIME_ERROR" in item:
item[item.index("RUNTIME_ERROR")] = "RE"
verdictData = [item for item in verdictData if "SKIPPED" not in item]
return verdictData
def get_language_data(handle):
api_url = f"https://codeforces.com/api/user.status?handle={handle}"
response = []
while True:
response = requests.get(api_url)
if response.status_code == 200:
break
response = response.json()
json_data = response["result"]
lang_data = [entry["programmingLanguage"] for entry in json_data]
language_count = {}
for language in lang_data:
if language in language_count:
language_count[language] += 1
else:
language_count[language] = 1
# Convert the language counts to a list of lists
langData = [["Language", "Count"]] + [
[lang, count] for lang, count in language_count.items()
]
return langData
def get_ratings_data(handle):
api_url = f"https://codeforces.com/api/user.status?handle={handle}"
response = []
while True:
response = requests.get(api_url)
if response.status_code == 200:
break
response = response.json()
json_data = response["result"]
# Extract the ratings from the JSON data, excluding None values
ratings = [
entry["problem"].get("rating")
for entry in json_data
if entry["problem"].get("rating") is not None
]
# Count occurrences of each rating using Counter
rating_count = Counter(ratings)
# Create a list for the final output, excluding entries with None values
ratingData = [[rating, count] for rating, count in rating_count.items()]
ratingData = sorted(ratingData)
ratingData = [["Rating", "Count"]] + ratingData
return ratingData
def get_problems_data(handle):
api_url = f"https://codeforces.com/api/user.status?handle={handle}"
response = []
while True:
response = requests.get(api_url)
if response.status_code == 200:
break
response = response.json()
json_data = response["result"]
# Extract the ratings from the JSON data, excluding None values
ratings = [
entry["problem"].get("index")
for entry in json_data
if entry["problem"].get("index") is not None
]
# Count occurrences of each rating of user using Counter
rating_count = Counter(ratings)
# Create a list for the final output, excluding entries with None values
ratingData = [
[rating, count] for rating, count in rating_count.items() if rating is not None
]
merged_data = {}
for rating, count in ratingData:
prefix = rating.rstrip("1234567890") # Extract the non-numeric prefix
merged_data.setdefault(prefix, 0)
merged_data[prefix] += count
# Create the final output list
final_rating_data = [[key, value] for key, value in merged_data.items()]
# Sort the final output list
final_rating_data = sorted(final_rating_data)
final_rating_data = [["Problem", "Count"]] + final_rating_data
return final_rating_data
def get_blog_entries(handle):
url = f"https://codeforces.com/api/user.blogEntries?handle={handle}"
response = []
while True:
response = requests.get(url)
if response.status_code == 200:
break
if response.status_code == 200:
data = response.json()
return data.get("result", [])
else:
print(f"Error: {response.status_code}")
return []
def get_codeforces_submissions(handle):
url = f"https://codeforces.com/api/user.status?handle={handle}"
response = []
while True:
response = requests.get(url)
if response.status_code == 200:
break
response = response.json()
data = response["result"]
calendar_data = defaultdict(int)
for submission in data:
timestamp = submission["creationTimeSeconds"]
date = datetime.utcfromtimestamp(timestamp).date()
calendar_data[str(date)] += 1 # Convert date to string
return calendar_data
def get_user_tags(handle):
url = f"https://codeforces.com/api/user.status?handle={handle}"
response = []
while True:
response = requests.get(url)
if response.status_code == 200:
break
response = response.json()
result = response["result"]
tags_count = {}
for submission in result:
problem = submission.get("problem", {})
tags = problem.get("tags", [])
for tag in tags:
tags_count[tag] = tags_count.get(tag, 0) + 1
tags_list = [[tag, count] for tag, count in tags_count.items()]
return tags_list
def get_user_stats(handle):
url = f"https://codeforces.com/api/user.status?handle={handle}"
response = []
while True:
response = requests.get(url)
if response.status_code == 200:
break
response = response.json()
unique_problem_names = set()
successful_attempts = set()
total_attempts = len(response["result"])
for submission in response["result"]:
problem_name = submission["problem"]["name"]
unique_problem_names.add(problem_name)
if submission["verdict"] == "OK":
successful_attempts.add(problem_name)
total_tried = len(unique_problem_names)
successful_attempts_count = len(successful_attempts)
unsolved = total_tried - successful_attempts_count
accuracy = successful_attempts_count / total_attempts if total_attempts > 0 else 0
total_time_spent = sum(
submission["timeConsumedMillis"] for submission in response["result"]
)
total_memory_consumed = sum(
submission["memoryConsumedBytes"] for submission in response["result"]
)
# Convert time to minutes
total_time_spent_minutes = total_time_spent / (1000 * 60)
# Convert memory to megabytes
total_memory_consumed_mb = total_memory_consumed / (1024 * 1024 * 1024)
result_list = [
str(total_tried),
str(successful_attempts_count),
f"{accuracy * 100:.2f}%",
str(unsolved),
f"{total_time_spent_minutes:.2f} minutes",
f"{total_memory_consumed_mb:.2f} GB",
]
return result_list
@app.route("/health")
def healthcheck():
return "OK"
def get_contest_stats(handle):
api_url = f"https://codeforces.com/api/user.rating?handle={handle}"
# Make API call and get JSON response
response = []
while True:
response = requests.get(api_url)
if response.status_code == 200:
break
response = response.json()
data = response
# Check if the API call was successful
contests = data["result"]
unique_contests = len(contests)
# Extract other required stats
best_rank = min(contest["rank"] for contest in contests)
worst_rank = max(contest["rank"] for contest in contests)
max_increase_in_rating = max(
contest["newRating"] - contest["oldRating"] for contest in contests
)
max_decrease_in_rating = min(
contest["newRating"] - contest["oldRating"] for contest in contests
)
# Compile the stats into a list
result_list = [
unique_contests,
best_rank,
worst_rank,
max_increase_in_rating,
max_decrease_in_rating,
]
return result_list
@app.route("/", methods=["GET", "POST"])
def index():
langData = []
if request.method == "POST":
# Get username and number of predictions from the form
username = request.form["username"]
num_predictions = 5
# Get user ratings from Codeforces API
user_ratings = get_user_ratings(username)
user_ranks = get_user_ranks(username)
langData = get_language_data(username)
verdictData = get_submission_data(username)
ratingData = get_ratings_data(username)
problemData = get_problems_data(username)
blog_entries = get_blog_entries(username)
submissionData = get_codeforces_submissions(username)
tags_list = get_user_tags(username)
user_stats = get_user_stats(username)
contest_stats = get_contest_stats(username)
if True:
# Create a new DataFrame with the user's ratings
user_df = pd.DataFrame(
{
"ds": pd.date_range(
start="2023-01-01", periods=len(user_ratings), freq="D"
),
"y": user_ratings,
}
)
# Create Prophet model with user data
model = Prophet(
yearly_seasonality=False,
weekly_seasonality=False,
daily_seasonality=False,
)
model.add_seasonality(name="custom", period=7, fourier_order=5)
model.fit(user_df)
# Predict the ratings for the specified number of contests
future = model.make_future_dataframe(periods=num_predictions)
forecast = model.predict(future)
predicted_ratings = forecast["yhat"].tail(num_predictions).tolist()
# Combine user ratings and predicted ratings
all_ratings = user_ratings + predicted_ratings
# Render the template with data
all_ratings = [int(x) for x in all_ratings]
return render_template(
"index.html",
all_ratings=all_ratings,
user_ranks=user_ranks,
langData=langData,
verdictData=verdictData,
ratingData=ratingData,
problemData=problemData,
blog_entries=blog_entries,
submissionData=submissionData,
tags_list=tags_list,
user_stats=user_stats,
contest_stats=contest_stats,
)
# Render the template without data if it's a GET request
return render_template(
"index.html",
all_ratings=[],
)
if __name__ == "__main__":
app.run(debug=True)