-
Notifications
You must be signed in to change notification settings - Fork 1
/
codewars_downloader.py
65 lines (45 loc) · 2.06 KB
/
codewars_downloader.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
import csv
import os
from configparser import ConfigParser
import requests
from bs4 import BeautifulSoup
from tqdm import tqdm
from utils.challenge import Challenge
from utils.download_source import download_source
from utils.parser import Parser
CHALLENGE_URL = 'https://www.codewars.com/api/v1/code-challenges/{}'
config = ConfigParser()
config.read('settings/config.ini')
directory = config.get('settings', 'directory')
with open('settings/programming_languages.csv', newline='') as csvfile:
reader = csv.DictReader(csvfile)
file_formats = {row['Language']: row['Extension'] for row in reader}
if __name__ == '__main__':
download_source()
with open('./challenges.html', 'r') as file:
soup = BeautifulSoup(file.read(), 'html.parser')
solutions_elements = soup.findAll('div', {'class': 'list-item solutions'})
# dict to store the challenges
challenges = {'%d kyu' % n: [] for n in range(1, 9)}
challenges['unrated'] = []
for solution_element in tqdm(solutions_elements, 'Parsing challenges'):
parser = Parser(solution_element)
challenge_id = parser.parse_id()
# using codewars api to get info about the challenge
response = requests.get(CHALLENGE_URL.format(challenge_id))
js = response.json()
# creating a challenge object
challenge = Challenge.fromjson(js)
if challenge.kyu == None:
challenge.kyu = 'unrated'
challenge.code = parser.parse_code()
challenge.language = parser.parse_language()
challenges[challenge.kyu].append(challenge)
for kyu, challenge_list in challenges.items():
for challenge in tqdm(challenge_list, 'Saving {}'.format(kyu)):
kyu_path = os.path.join(directory, kyu, challenge.name)
os.makedirs(kyu_path, exist_ok=True)
with open(os.path.join(kyu_path, 'README.md'), 'w') as f:
f.write(challenge.description)
with open(os.path.join(kyu_path, challenge.name + file_formats[challenge.language]), 'w') as f:
f.write(challenge.code)