-
Notifications
You must be signed in to change notification settings - Fork 3
/
export.py
executable file
·148 lines (129 loc) · 4.4 KB
/
export.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
#!/usr/bin/env python3
from itertools import chain, islice, takewhile
import os
import re
import requests
from time import sleep, time
from string import Template
# Store the value of you cookies in 'cookies.txt'
COOKIES = open('cookies.txt', 'r').read().strip().replace('cookie: ', '', 1)
# Change output dir if you like
LEETCODE_DIR = '../leetcode-solutions'
# Change how many days to look back
DAYS_TO_IMPORT=365*100
SUBMISSIONS_URL = 'https://leetcode.com/api/submissions/?offset={}&limit={}'
PROBLEM_URL = 'https://leetcode.com/problems/{}/'
GRAPHQL_URL = 'https://leetcode.com/graphql'
THROTTLE_SECONDS = 1
EXTENSIONS = {
"cpp": 'cpp',
"java": 'java',
"python": 'py',
"python3": 'py',
"mysql": 'sql',
"mssql": 'sql',
"oraclesql": 'sql',
"c": 'c',
"csharp": 'cs',
"javascript": 'js',
"ruby": 'rb',
"bash": 'sh',
"swift": 'swift',
"golang": 'go',
"scala": 'scala',
"html": 'html',
"pythonml": 'py',
"kotlin": 'kt',
"rust": 'rs',
"php": 'php'
}
SLUG_RE = re.compile(r"[^-0-9a-z ]", re.IGNORECASE)
DESCRIPTION_TEMPLATE = Template("""
${difficulty}: #${questionId} ${title}
=======================
[View on LeetCode](${problem_url})
</hr>
${content}
""")
IMPORT_SINCE = int(time()) - (DAYS_TO_IMPORT * 24 * 60 * 60)
def question_data(slug):
return {
"operationName": "questionData",
"variables": {
"titleSlug": slug
},
"query": """query questionData($titleSlug: String!) {
question(titleSlug: $titleSlug) {
questionId
questionFrontendId
boundTopicId
title
titleSlug
content
difficulty
sampleTestCase
}
}"""
}
def get_submissions(batch_size=20):
"""Gets all submissions in `batch_size` chunks"""
offset = 0
while True:
print(f"getting batch #{offset + 1}")
response = requests.get(
SUBMISSIONS_URL.format(offset, batch_size),
headers={'Cookie': COOKIES})
json_response = response.json()
if 'detail' in json_response:
print(json_response['detail'])
if 'submissions_dump' in json_response:
yield json_response['submissions_dump']
if not 'has_next' in json_response or not json_response['has_next']:
break
offset += 1
sleep(THROTTLE_SECONDS)
def add_description(submission):
title = submission['title']
slug = title_to_slug(title)
print(f'{slug}: getting description')
response = requests.post(
GRAPHQL_URL,
json=question_data(slug),
headers={'Cookie': COOKIES})
json_response = response.json()
problem_url = PROBLEM_URL.format(slug)
return {**submission, **json_response['data']['question'], 'slug': slug, 'problem_url': problem_url}
def is_accepted(submission):
return 'status_display' in submission and submission['status_display'] == 'Accepted'
def is_recent(submission):
return 'timestamp' in submission and submission['timestamp'] >= IMPORT_SINCE
def title_to_slug(title):
return SLUG_RE.sub("", title).replace(" ", "-").lower()
def store_solution(solution):
slug = solution['slug']
print(f'{slug}: storing')
solution_dir = f'{LEETCODE_DIR}/{slug}/'
if not os.path.exists(solution_dir):
os.makedirs(solution_dir)
description_file = open(solution_dir+'README.md', 'w')
description_file.write(DESCRIPTION_TEMPLATE.substitute(solution))
description_file.close
test_file = open(solution_dir+'input.txt', 'w')
test_file.write(solution['sampleTestCase'])
test_file.close
else:
print(f'{slug}: folder exists')
filename = f'{solution_dir}solution_{solution["id"]}.{EXTENSIONS[solution["lang"]]}'
if not os.path.exists(filename):
print(f'{slug}: writing solution #{solution["id"]}')
solution_file = open(filename, 'w')
solution_file.write(solution['code'])
solution_file.close
else:
print(f'{slug}: solution #{solution["id"]} already exists')
submissions = chain.from_iterable(get_submissions())
recent_submissions = takewhile(is_recent, submissions)
accepted_submissions = filter(is_accepted, recent_submissions)
accepted_submissions_details = map(add_description, accepted_submissions)
for solution in accepted_submissions_details:
store_solution(solution)