kattis2canvas 0.1.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,107 @@
1
+ Metadata-Version: 2.4
2
+ Name: kattis2canvas
3
+ Version: 0.1.3
4
+ Summary: CLI tool to integrate Kattis offerings with Canvas LMS courses
5
+ Author: bcr33d
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/bcr33d/kattis2canvas
8
+ Project-URL: Repository, https://github.com/bcr33d/kattis2canvas
9
+ Keywords: kattis,canvas,lms,education,grading
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Education
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.8
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Topic :: Education
21
+ Requires-Python: >=3.8
22
+ Description-Content-Type: text/markdown
23
+ Requires-Dist: click>=8.0
24
+ Requires-Dist: requests>=2.25
25
+ Requires-Dist: beautifulsoup4>=4.9
26
+ Requires-Dist: canvasapi>=2.0
27
+ Requires-Dist: python-dateutil>=2.8
28
+
29
+ # kattis2canvas
30
+
31
+ this is a simple python tool that uses the canvasapi toolkit to integrate a kattis offering with a canvas course. the tool was specifically made to work with the commercial kattis (as you will see in a moment). it would take a bit of tweaking on the web scraping to make it work with open.kattis.com.
32
+
33
+ the kattis connection is done using web scraping and thus it is very fragile! at the end, i will highlight where it is most vulnerable.
34
+
35
+ # setting up kattis2canvas
36
+
37
+ ## the config file
38
+
39
+ first you will need to set up the config file. it has all your authorization tokens so DON'T CHECK IT IN. i specificially look for it in the app_dir as defined by click to get it far away from source. on linux this ends up being a file called ~/.config/kattis2canvas.ini. this is how it should be populated:
40
+
41
+ ```
42
+ [kattis]
43
+ username: YOUR_KATTIS_USERNAME_NOT_EMAIL
44
+ token: SOME_RANDOM_CHARACTERS
45
+ hostname: THE_DOMAIN_NAME_OF_YOUR_KATTIS_INSTANCE
46
+ loginurl: THE_URL_TO_LOG_IN_TO_KATTIS
47
+
48
+ [canvas]
49
+ url=URL_OF_YOUR_CANVAS_INSTANCE
50
+ token=SOME_RANDOM_CHARACTERS
51
+ ```
52
+
53
+ you can easily get the kattis section by going to https://\<kattis>/download/kattisrc where \<kattis> is your instance of kattis. you will need to move the lines around slightly. for canvas the url is the one you use to access the main page of canvas. you generate the token in the bottom of the Account -> Settings page.
54
+
55
+ you can check that everything is set up by running:
56
+
57
+ ```
58
+ kattis2canvas list-offerings
59
+ kattis2canvas list-assignments
60
+ ```
61
+
62
+ or if you built the pyz file using make_zipapp.sh
63
+
64
+ ```
65
+ kattis2canvas list-offerings
66
+ kattis2canvas list-assignments
67
+ ```
68
+
69
+ ## mapping student kattis accounts to canvas accounts
70
+
71
+ in canvas, you can associate various URLs with your account in the Links section of Account -> Profile. students need to put the URL of their kattis account in a link with the word "kattis" (in any case) in the title. this ends up being the join key for kattis2canvas.
72
+
73
+ you can check if the students have set up the links properly using
74
+
75
+ ```
76
+ kattis2canvas kattislinks
77
+ ```
78
+
79
+ # using kattis2canvas
80
+
81
+ ## populating kattis assignments in canvas
82
+
83
+ when you create new kattis assignments, you will need to get it mirrored into canvas. currently the **course2canvas** command will put all of the assignments into an assignment group called kattis. the assignment group must be created in your course before **course2canvas**.
84
+
85
+ when you specify the names of offerings in kattis and courses in canvas, you can specify a substring of the name and **kattis2canvas** will be able to use it as long as it matches exactly one name. if it doesn't, it will show it what it found.
86
+
87
+ when creating the assignment in canvas, anything you have put in the description in kattis will also be replicated in canvas along with a link to the kattis assignment.
88
+
89
+ if you have made changes to a kattis assignment that you have already populated in canvas, use the --force option to force an update. (right now there isn't a way to force individual assignments.)
90
+
91
+ if you use modules, you can use the **--add-to-module** flag to add the kattis assignments to a module. at this point, it puts all of the kattis assignments into that one module.
92
+
93
+ ## getting the results to canvas
94
+
95
+ the **submissions2canvas** will replicate results from student submissions to kattis into canvas. it will only replicate results that are either better or the same as or newer than previous results it has replicated. a summary of the problem, score, and link to the submission will be added as a comment for the student in the gradebook for the relevant assignment. the idea is that when it's time to grade, you have easy access to the results and the link to the source from canvas speedgrader.
96
+
97
+ # kattis webscraping
98
+
99
+ unfortuately, scraping the kattis API is very adhoc and it would be naive to think that it wouldn't change in ways that will break this tool. we use BeautifulSoupe (it's pretty beautiful...) so here are the features that the script relies on for kattis webpages: (note the term "assume" is used for things we have to believe because that is the only reasonable way that we can use the information we are given.)
100
+
101
+ * the list of offerings: (HOSTNAME is from the config file above) we assume http://HOSTNAME/ will give us a page will all the offerings and the urls in the href of those offerings will have the form **/courses/[^/]+/[^/]+**
102
+ * the list of assignments: we assume the offering page will have the detail page for assignments in hrefs of anchor tabs of the form "assignments/\w+$".
103
+ * the assignment details: we assume the assignment detail page will have an \<h2> tag with the text "Description" followed by a sibling \<p> tag that entirely contains the description. we also assume that there will be a \<td> for "start time" and another for "end time" we do case insensitve comparisons to find them. we assume that the following \<td> tage will have the time.
104
+ * time: TIME IS HARD! if the time is recent, kattis will drop the date, so if we get a time with no date, we take the current time and up date the HH:MM:SS with the date we get from kattis. we also assume all dates are UTC.
105
+ * getting submissions: we assume the submissions for an assignment are found at https://HOSTNAME/OFFERING/assignments/ASSIGNMENT_ID/submissions it appears that all submissions for the assignment are listed on that page. submissions for a problem outside of the assignment time period will not show up on that page. the submissions are in a table called "judege"table". the headers \<th> that we are looking for are "User" for the user url, "Problem" for the name of the problem, "Test cases" for the score reflected as sucess/count with -/- indicating no tries, and "" indicating the header for the url of the submission. once we know the column numbers we want, we have to look for the \<tbody> child of the table (problems happen if you try to look for \<td> recursively from the table!) then we look for \<tr> children of \<tbody> which have a "data-submission-id" attribute.
106
+
107
+
@@ -0,0 +1,79 @@
1
+ # kattis2canvas
2
+
3
+ this is a simple python tool that uses the canvasapi toolkit to integrate a kattis offering with a canvas course. the tool was specifically made to work with the commercial kattis (as you will see in a moment). it would take a bit of tweaking on the web scraping to make it work with open.kattis.com.
4
+
5
+ the kattis connection is done using web scraping and thus it is very fragile! at the end, i will highlight where it is most vulnerable.
6
+
7
+ # setting up kattis2canvas
8
+
9
+ ## the config file
10
+
11
+ first you will need to set up the config file. it has all your authorization tokens so DON'T CHECK IT IN. i specificially look for it in the app_dir as defined by click to get it far away from source. on linux this ends up being a file called ~/.config/kattis2canvas.ini. this is how it should be populated:
12
+
13
+ ```
14
+ [kattis]
15
+ username: YOUR_KATTIS_USERNAME_NOT_EMAIL
16
+ token: SOME_RANDOM_CHARACTERS
17
+ hostname: THE_DOMAIN_NAME_OF_YOUR_KATTIS_INSTANCE
18
+ loginurl: THE_URL_TO_LOG_IN_TO_KATTIS
19
+
20
+ [canvas]
21
+ url=URL_OF_YOUR_CANVAS_INSTANCE
22
+ token=SOME_RANDOM_CHARACTERS
23
+ ```
24
+
25
+ you can easily get the kattis section by going to https://\<kattis>/download/kattisrc where \<kattis> is your instance of kattis. you will need to move the lines around slightly. for canvas the url is the one you use to access the main page of canvas. you generate the token in the bottom of the Account -> Settings page.
26
+
27
+ you can check that everything is set up by running:
28
+
29
+ ```
30
+ kattis2canvas list-offerings
31
+ kattis2canvas list-assignments
32
+ ```
33
+
34
+ or if you built the pyz file using make_zipapp.sh
35
+
36
+ ```
37
+ kattis2canvas list-offerings
38
+ kattis2canvas list-assignments
39
+ ```
40
+
41
+ ## mapping student kattis accounts to canvas accounts
42
+
43
+ in canvas, you can associate various URLs with your account in the Links section of Account -> Profile. students need to put the URL of their kattis account in a link with the word "kattis" (in any case) in the title. this ends up being the join key for kattis2canvas.
44
+
45
+ you can check if the students have set up the links properly using
46
+
47
+ ```
48
+ kattis2canvas kattislinks
49
+ ```
50
+
51
+ # using kattis2canvas
52
+
53
+ ## populating kattis assignments in canvas
54
+
55
+ when you create new kattis assignments, you will need to get it mirrored into canvas. currently the **course2canvas** command will put all of the assignments into an assignment group called kattis. the assignment group must be created in your course before **course2canvas**.
56
+
57
+ when you specify the names of offerings in kattis and courses in canvas, you can specify a substring of the name and **kattis2canvas** will be able to use it as long as it matches exactly one name. if it doesn't, it will show it what it found.
58
+
59
+ when creating the assignment in canvas, anything you have put in the description in kattis will also be replicated in canvas along with a link to the kattis assignment.
60
+
61
+ if you have made changes to a kattis assignment that you have already populated in canvas, use the --force option to force an update. (right now there isn't a way to force individual assignments.)
62
+
63
+ if you use modules, you can use the **--add-to-module** flag to add the kattis assignments to a module. at this point, it puts all of the kattis assignments into that one module.
64
+
65
+ ## getting the results to canvas
66
+
67
+ the **submissions2canvas** will replicate results from student submissions to kattis into canvas. it will only replicate results that are either better or the same as or newer than previous results it has replicated. a summary of the problem, score, and link to the submission will be added as a comment for the student in the gradebook for the relevant assignment. the idea is that when it's time to grade, you have easy access to the results and the link to the source from canvas speedgrader.
68
+
69
+ # kattis webscraping
70
+
71
+ unfortuately, scraping the kattis API is very adhoc and it would be naive to think that it wouldn't change in ways that will break this tool. we use BeautifulSoupe (it's pretty beautiful...) so here are the features that the script relies on for kattis webpages: (note the term "assume" is used for things we have to believe because that is the only reasonable way that we can use the information we are given.)
72
+
73
+ * the list of offerings: (HOSTNAME is from the config file above) we assume http://HOSTNAME/ will give us a page will all the offerings and the urls in the href of those offerings will have the form **/courses/[^/]+/[^/]+**
74
+ * the list of assignments: we assume the offering page will have the detail page for assignments in hrefs of anchor tabs of the form "assignments/\w+$".
75
+ * the assignment details: we assume the assignment detail page will have an \<h2> tag with the text "Description" followed by a sibling \<p> tag that entirely contains the description. we also assume that there will be a \<td> for "start time" and another for "end time" we do case insensitve comparisons to find them. we assume that the following \<td> tage will have the time.
76
+ * time: TIME IS HARD! if the time is recent, kattis will drop the date, so if we get a time with no date, we take the current time and up date the HH:MM:SS with the date we get from kattis. we also assume all dates are UTC.
77
+ * getting submissions: we assume the submissions for an assignment are found at https://HOSTNAME/OFFERING/assignments/ASSIGNMENT_ID/submissions it appears that all submissions for the assignment are listed on that page. submissions for a problem outside of the assignment time period will not show up on that page. the submissions are in a table called "judege"table". the headers \<th> that we are looking for are "User" for the user url, "Problem" for the name of the problem, "Test cases" for the score reflected as sucess/count with -/- indicating no tries, and "" indicating the header for the url of the submission. once we know the column numbers we want, we have to look for the \<tbody> child of the table (problems happen if you try to look for \<td> recursively from the table!) then we look for \<tr> children of \<tbody> which have a "data-submission-id" attribute.
78
+
79
+
@@ -0,0 +1,45 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "kattis2canvas"
7
+ version = "0.1.3"
8
+ description = "CLI tool to integrate Kattis offerings with Canvas LMS courses"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.8"
12
+ authors = [
13
+ {name = "bcr33d"}
14
+ ]
15
+ keywords = ["kattis", "canvas", "lms", "education", "grading"]
16
+ classifiers = [
17
+ "Development Status :: 4 - Beta",
18
+ "Environment :: Console",
19
+ "Intended Audience :: Education",
20
+ "Operating System :: OS Independent",
21
+ "Programming Language :: Python :: 3",
22
+ "Programming Language :: Python :: 3.8",
23
+ "Programming Language :: Python :: 3.9",
24
+ "Programming Language :: Python :: 3.10",
25
+ "Programming Language :: Python :: 3.11",
26
+ "Programming Language :: Python :: 3.12",
27
+ "Topic :: Education",
28
+ ]
29
+ dependencies = [
30
+ "click>=8.0",
31
+ "requests>=2.25",
32
+ "beautifulsoup4>=4.9",
33
+ "canvasapi>=2.0",
34
+ "python-dateutil>=2.8",
35
+ ]
36
+
37
+ [project.urls]
38
+ Homepage = "https://github.com/bcr33d/kattis2canvas"
39
+ Repository = "https://github.com/bcr33d/kattis2canvas"
40
+
41
+ [project.scripts]
42
+ kattis2canvas = "kattis2canvas.cli:top"
43
+
44
+ [tool.setuptools.packages.find]
45
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,3 @@
1
+ """kattis2canvas - CLI tool to integrate Kattis offerings with Canvas LMS courses."""
2
+
3
+ __version__ = "0.1.3"
@@ -0,0 +1,6 @@
1
+ """Entry point for python -m kattis2canvas."""
2
+
3
+ from kattis2canvas.cli import top
4
+
5
+ if __name__ == "__main__":
6
+ top()
@@ -0,0 +1,616 @@
1
+ import collections
2
+ import concurrent.futures
3
+ import configparser
4
+ import datetime
5
+ import os
6
+ import re
7
+ import sys
8
+ from fractions import Fraction
9
+ from typing import NamedTuple, Optional
10
+
11
+ import click
12
+ from dateutil import parser as dateparser
13
+ import pprint
14
+ import requests
15
+ import requests.cookies
16
+ import requests.exceptions
17
+ from bs4 import BeautifulSoup
18
+ from canvasapi import Canvas, module
19
+ from canvasapi.course import Course
20
+ from canvasapi.user import User
21
+
22
+ HEADERS = {'User-Agent': 'kattis-to-canvas'}
23
+
24
+
25
+ class Config(NamedTuple):
26
+ kattis_username: str
27
+ kattis_token: str
28
+ kattis_loginurl: str
29
+ kattis_hostname: str
30
+ canvas_url: str
31
+ canvas_token: str
32
+
33
+
34
+ config: Optional[Config] = None
35
+ login_cookies: Optional[requests.cookies.RequestsCookieJar] = None
36
+
37
+
38
+ class Student(NamedTuple):
39
+ kattis_url: str
40
+ name: str
41
+ email: str
42
+ canvas_id: str
43
+
44
+
45
+ class Submission(NamedTuple):
46
+ user: str
47
+ problem: str
48
+ score: float
49
+ url: str
50
+ date: datetime.datetime
51
+
52
+
53
+ now = datetime.datetime.now(datetime.timezone.utc)
54
+
55
+
56
+ def error(message: str):
57
+ click.echo(click.style(message, fg='red'))
58
+
59
+
60
+ def info(message: str):
61
+ click.echo(click.style(message, fg='blue'))
62
+
63
+
64
+ def warn(message: str):
65
+ click.echo(click.style(message, fg='yellow'))
66
+
67
+
68
+ def check_status(rsp: requests.Response):
69
+ if rsp.status_code != 200:
70
+ error(f"got status {rsp.status_code} for {rsp.url}.")
71
+ exit(6)
72
+
73
+
74
+ # return the last element of a URL
75
+ def extract_last(pathish: str) -> str:
76
+ last_slash = pathish.rindex("/")
77
+ if last_slash:
78
+ pathish = pathish[last_slash + 1:]
79
+ return pathish
80
+
81
+
82
+ # for debugging
83
+ def introspect(o):
84
+ print("class", o.__class__)
85
+ for i in dir(o):
86
+ print(i)
87
+
88
+
89
+ def web_get(url: str) -> requests.Response:
90
+ rsp: requests.Response = requests.get(url, cookies=login_cookies, headers=HEADERS)
91
+ check_status(rsp)
92
+ return rsp
93
+
94
+
95
+ @click.group()
96
+ def top():
97
+ config_ini = click.get_app_dir("kattis2canvas.ini")
98
+ parser = configparser.ConfigParser()
99
+ parser.read([config_ini])
100
+ global config
101
+ try:
102
+ config = Config(
103
+ kattis_username=parser['kattis']['username'],
104
+ kattis_token=parser['kattis']['token'],
105
+ kattis_hostname=parser['kattis']['hostname'],
106
+ kattis_loginurl=parser['kattis']['loginurl'],
107
+ canvas_url=parser['canvas']['url'],
108
+ canvas_token=parser['canvas']['token'],
109
+ )
110
+ except:
111
+ print(f"""problem getting configuration from {config_ini}. should have the following lines:
112
+
113
+ [kattis]
114
+ username=kattis_username
115
+ token=kattis_token
116
+ hostname: something_like_sjsu.kattis.com
117
+ loginurl: https://something_like_sjsu.kattis.com
118
+ [canvas]
119
+ url=https://something_like_sjsu.instructure.com
120
+ token=convas_token
121
+ """)
122
+ exit(2)
123
+
124
+ global login_cookies
125
+ args = {'user': config.kattis_username, 'script': 'true', 'token': config.kattis_token}
126
+ rsp = requests.post(config.kattis_loginurl, data=args, headers=HEADERS)
127
+ if rsp.status_code != 200:
128
+ error(f"Kattis login failed. Status: {rsp.status_code}")
129
+ exit(2)
130
+ login_cookies = rsp.cookies
131
+
132
+
133
+ def get_offerings(offering_pattern: str) -> str:
134
+ rsp = web_get(f"https://{config.kattis_hostname}/")
135
+ bs = BeautifulSoup(rsp.content, 'html.parser')
136
+ for a in bs.find_all('a'):
137
+ h = a.get('href')
138
+ if h and re.match("/courses/[^/]+/[^/]+", h) and offering_pattern in h:
139
+ yield h
140
+
141
+
142
+ @top.command()
143
+ @click.argument("name", default="")
144
+ def list_offerings(name: str):
145
+ """
146
+ list the possible offerings.
147
+ :param name: a substring of the offering name
148
+ """
149
+
150
+ for offering in get_offerings(name):
151
+ info(str(offering))
152
+
153
+
154
+ # Common timezone abbreviations to UTC offsets
155
+ TZINFOS = {
156
+ "UTC": 0,
157
+ "GMT": 0,
158
+ "CET": 3600, # Central European Time (UTC+1)
159
+ "CEST": 7200, # Central European Summer Time (UTC+2)
160
+ "EST": -18000, # Eastern Standard Time (UTC-5)
161
+ "EDT": -14400, # Eastern Daylight Time (UTC-4)
162
+ "CST": -21600, # Central Standard Time (UTC-6)
163
+ "CDT": -18000, # Central Daylight Time (UTC-5)
164
+ "MST": -25200, # Mountain Standard Time (UTC-7)
165
+ "MDT": -21600, # Mountain Daylight Time (UTC-6)
166
+ "PST": -28800, # Pacific Standard Time (UTC-8)
167
+ "PDT": -25200, # Pacific Daylight Time (UTC-7)
168
+ }
169
+
170
+
171
+ # reformat kattis date format to canvas format
172
+ def extract_kattis_date(element: str) -> str:
173
+ if element == "infinity":
174
+ element = "2100-01-01 00:00 UTC"
175
+ dt = dateparser.parse(element, tzinfos=TZINFOS)
176
+ return dt.strftime("%Y-%m-%dT%H:%M:00%z")
177
+
178
+
179
+ # convert canvas UTC to datetime
180
+ def extract_canvas_date(element: str) -> datetime.datetime:
181
+ return datetime.datetime.strptime(element, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=datetime.timezone.utc)
182
+
183
+
184
+ class Assignment(NamedTuple):
185
+ url: str
186
+ assignment_id: str
187
+ title: str
188
+ description: str
189
+ start: str
190
+ end: str
191
+
192
+
193
+ def get_assignments(offering: str) -> [Assignment]:
194
+ rsp = web_get(f"https://{config.kattis_hostname}{offering}")
195
+ bs = BeautifulSoup(rsp.content, 'html.parser')
196
+ for a in bs.find_all('a'):
197
+ h = a.get('href')
198
+ if h and re.search(r"assignments/\w+$", h):
199
+ url = f"https://{config.kattis_hostname}{h}"
200
+ rsp2 = web_get(url)
201
+ bs2 = BeautifulSoup(rsp2.content, 'html.parser')
202
+ description_h2 = bs2.find("h2", string="Description", recursive=True)
203
+ description = None
204
+ if description_h2:
205
+ p = description_h2.find_next_sibling("p")
206
+ if p:
207
+ description = p.text
208
+ all_td = iter(bs2.find_all("td"))
209
+ start = None
210
+ end = None
211
+ for td in all_td:
212
+ if td.get_text(strip=True).casefold() == "start time".casefold():
213
+ start = extract_kattis_date(next(all_td).get_text(strip=True))
214
+ if td.get_text(strip=True).casefold() == "end time".casefold():
215
+ end = extract_kattis_date(next(all_td).get_text(strip=True))
216
+ yield (Assignment(
217
+ url=url, assignment_id=url[url.rindex('/') + 1:], title=a.getText(),
218
+ description=description, start=start, end=end
219
+ ))
220
+
221
+
222
+ @top.command()
223
+ @click.argument("offering", default="")
224
+ def list_assignments(offering):
225
+ """
226
+ list the assignments for the given offering.
227
+ :param offering: a substring of the offering name
228
+ """
229
+ for offering in get_offerings(offering):
230
+ for assignment in get_assignments(offering):
231
+ info(
232
+ f"{assignment.title}: {assignment.start} to {assignment.end} {assignment.description} {assignment.url}")
233
+
234
+
235
+ @top.command()
236
+ @click.argument("offering")
237
+ @click.argument("assignment")
238
+ def download_submissions(offering, assignment):
239
+ """
240
+ download the submissions for an assignment in an offering. offerings and assignments that have the given substring
241
+ will match.
242
+ """
243
+ for o in get_offerings(offering):
244
+ for a in get_assignments(o):
245
+ if assignment in a.title:
246
+ for student, probs in get_best_submissions(o, a.assignment_id).items():
247
+ for problem, submission in probs.items():
248
+ base_path = f"{offering}/{assignment}/{problem}/{student}"
249
+ os.makedirs(base_path, exist_ok=True)
250
+ rsp, name = download_submission(submission.url)
251
+ with open(base_path + "/" + name, "wb") as f:
252
+ f.write(rsp.content)
253
+
254
+
255
+ def download_submission(url):
256
+ rsp = web_get(f"https://{config.kattis_hostname}{url}")
257
+ bs = BeautifulSoup(rsp.content, 'html.parser')
258
+ src_div = bs.find(class_="file_source-content-file", recursive=True)
259
+ a = src_div.find("a", recursive=True)
260
+ h3 = src_div.find("h3")
261
+ name = os.path.basename(h3.get_text().strip())
262
+ sanitize(name)
263
+ return web_get(f"https://{config.kattis_hostname}{a.get('href')}"), name
264
+
265
+
266
+ def sanitize(name):
267
+ return re.sub(r"[^\w.]", "_", name)
268
+
269
+ def get_course(canvas, name, is_active=True) -> Course:
270
+ """ find one course based on partial match """
271
+ course_list = get_courses(canvas, name, is_active)
272
+ if len(course_list) == 0:
273
+ error(f'no courses found that contain {name}. options are:')
274
+ for c in get_courses(canvas, "", is_active):
275
+ error(fr" {c.name}")
276
+ sys.exit(2)
277
+ elif len(course_list) > 1:
278
+ error(f"multiple courses found for {name}:")
279
+ for c in course_list:
280
+ error(f" {c.name}")
281
+ sys.exit(2)
282
+ return course_list[0]
283
+
284
+
285
+ def get_courses(canvas: Canvas, name: str, is_active=True, is_finished=False) -> [Course]:
286
+ """ find the courses based on partial match """
287
+ courses = canvas.get_courses(enrollment_type="teacher")
288
+ course_list = []
289
+ for c in courses:
290
+ start = c.start_at_date if hasattr(c, "start_at_date") else now
291
+ end = c.end_at_date if hasattr(c, "end_at_date") else now
292
+ if is_active and (start > now or end < now):
293
+ continue
294
+ if is_finished and end >= now:
295
+ continue
296
+ if name in c.name:
297
+ c.start = start
298
+ c.end = end
299
+ course_list.append(c)
300
+ return course_list
301
+
302
+
303
+ @top.command()
304
+ @click.argument("offering")
305
+ @click.argument("canvas_course")
306
+ @click.option("--dryrun/--no-dryrun", default=True, help="show planned actions, do not make them happen.")
307
+ @click.option("--force/--no-force", default=False, help="force an update of an assignment if it already exists.")
308
+ @click.option("--add-to-module", help="the module to add the assignment to.")
309
+ @click.option("--assignment-group", default="kattis", help="the canvas assignment group to use (default: kattis).")
310
+ def course2canvas(offering, canvas_course, dryrun, force, add_to_module, assignment_group):
311
+ """
312
+ create assignments in canvas for all the assignments in kattis.
313
+ """
314
+ offerings = list(get_offerings(offering))
315
+ if len(offerings) == 0:
316
+ error(f"no offerings found for {offering}")
317
+ exit(3)
318
+ elif len(offerings) > 1:
319
+ error(f"multiple offerings found for {offering}: {', '.join(offerings)}")
320
+ exit(3)
321
+
322
+ canvas = Canvas(config.canvas_url, config.canvas_token)
323
+ course = get_course(canvas, canvas_course)
324
+
325
+ canvas_group = None
326
+ for ag in course.get_assignment_groups():
327
+ if ag.name == assignment_group:
328
+ canvas_group = ag
329
+ break
330
+ if not canvas_group:
331
+ # create assignment group if not present on canvas
332
+ if dryrun:
333
+ info(f"would create assignment group '{assignment_group}'.")
334
+ else:
335
+ canvas_group = course.create_assignment_group(name=assignment_group)
336
+ info(f"created assignment group {canvas_group}.")
337
+
338
+ if add_to_module:
339
+ modules = {m.name: m for m in course.get_modules()}
340
+ if add_to_module in modules:
341
+ add_to_module = modules[add_to_module]
342
+ else:
343
+ if dryrun:
344
+ info(f"would create and publish {add_to_module}.")
345
+ else:
346
+ args = {"name": add_to_module}
347
+ add_to_module = course.create_module(module=args)
348
+ info(f"created module {add_to_module}.")
349
+
350
+ args = {'published': "true"}
351
+ add_to_module.edit(module=args)
352
+ info(f"published module {add_to_module}.")
353
+
354
+ # In dryrun mode without existing group, get all assignments; otherwise filter by group
355
+ if canvas_group:
356
+ canvas_assignments = {a.name: a for a in course.get_assignments(assignment_group_id=canvas_group.id)}
357
+ else:
358
+ canvas_assignments = {}
359
+
360
+ # make sure assignments are in place
361
+ sorted_assignments = list(get_assignments(offerings[0]))
362
+ sorted_assignments.sort(key=lambda a: a.start)
363
+ for assignment in sorted_assignments:
364
+ description = assignment.description if assignment.description else ""
365
+ if assignment.title in canvas_assignments:
366
+ info(f"{assignment.title} already exists.")
367
+ if force:
368
+ if dryrun:
369
+ info(f"would update {assignment.title}.")
370
+ else:
371
+ canvas_assignments[assignment.title].edit(assignment={
372
+ 'assignment_group_id': canvas_group.id,
373
+ 'name': assignment.title,
374
+ 'description': f'Solve the problems found at <a href="{assignment.url}">{assignment.url}</a>. {description}',
375
+ 'points_possible': 100,
376
+ 'due_at': assignment.end,
377
+ 'lock_at': assignment.end,
378
+ 'unlock_at': assignment.start,
379
+ 'published': True,
380
+ })
381
+ info(f"updated {assignment.title}.")
382
+ else:
383
+ if dryrun:
384
+ info(f"would create {assignment}")
385
+ elif 'late' in assignment.title and assignment.title.replace("-late", "") in canvas_assignments:
386
+ info(f"no new assignment created as --late assignment for {assignment.title.replace('-late', '')}.")
387
+ continue
388
+ else:
389
+ canvas_assignments[assignment.title] = course.create_assignment({
390
+ 'assignment_group_id': canvas_group.id,
391
+ 'name': assignment.title,
392
+ 'description': f'Solve the problems found at <a href="{assignment.url}">{assignment.url}</a>. {description}',
393
+ 'points_possible': 100,
394
+ 'due_at': assignment.end,
395
+ 'lock_at': assignment.end,
396
+ 'unlock_at': assignment.start,
397
+ 'published': True,
398
+ })
399
+ info(f"created {assignment.title}.")
400
+ if add_to_module:
401
+ if assignment.title not in [i.title for i in add_to_module.get_module_items()]:
402
+ add_to_module.create_module_item(module_item={
403
+ 'title': assignment.title,
404
+ 'type': 'Assignment',
405
+ 'content_id': canvas_assignments[assignment.title].id,
406
+ })
407
+ info(f'{assignment.title} added to {add_to_module.name}')
408
+ else:
409
+ info(f'{assignment.title} already in {add_to_module.name}')
410
+
411
+
412
+ def is_student_enrollment(user: User):
413
+ return "StudentEnrollment" in [e['type'] for e in user.enrollments]
414
+
415
+
416
+ def find_kattis_link(profile: dict) -> str:
417
+ kattis_url = None
418
+ for link in profile["links"]:
419
+ if "kattis" in link["title"].lower():
420
+ kattis_url = link["url"]
421
+ return kattis_url
422
+
423
+
424
+ class KattisLink(NamedTuple):
425
+ canvas_user: User
426
+ kattis_user: str
427
+
428
+
429
+ def get_kattis_links(course: Course) -> [KattisLink]:
430
+ # this is so terribly slow because of all the requests, we need threads
431
+ with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:
432
+ futures = []
433
+ for u in course.get_users(include=["enrollments"]):
434
+ if "StudentEnrollment" not in [e['type'] for e in u.enrollments]:
435
+ continue
436
+
437
+ def get_profile(user: User) -> Optional[KattisLink]:
438
+ profile = user.get_profile(include=["links"])
439
+ kattis_url = find_kattis_link(profile)
440
+ kattis_url = extract_last(kattis_url) if kattis_url else None
441
+ return KattisLink(canvas_user=user, kattis_user=kattis_url)
442
+
443
+ futures.append(executor.submit(get_profile, u))
444
+
445
+ links = [f.result() for f in futures if not None]
446
+ links.sort(key=lambda l: l.canvas_user.name)
447
+ return links
448
+
449
+
450
+ @top.command()
451
+ @click.argument("canvas_course")
452
+ def kattislinks(canvas_course):
453
+ """
454
+ list the students in the class with their email and kattis links.
455
+ """
456
+ canvas = Canvas(config.canvas_url, config.canvas_token)
457
+ course = get_course(canvas, canvas_course)
458
+
459
+ for link in get_kattis_links(course):
460
+ if not is_student_enrollment(link.canvas_user):
461
+ continue
462
+ if link.kattis_user:
463
+ info(f"{link.canvas_user.name}\t{link.canvas_user.email}\t{link.kattis_user}")
464
+ else:
465
+ error(f"{link.canvas_user.name}\t{link.canvas_user.email} missing kattis link")
466
+
467
+
468
+ @top.command()
469
+ @click.argument("offering")
470
+ @click.argument("canvas_course")
471
+ @click.option("--dryrun/--no-dryrun", default=True, help="show planned actions, do not make them happen.")
472
+ @click.option("--assignment-group", default="kattis", help="the canvas assignment group to use (default: kattis).")
473
+ def submissions2canvas(offering, canvas_course, dryrun, assignment_group):
474
+ """
475
+ mirror summary of submission from kattis into canvas as a submission comment.
476
+ """
477
+ offerings = list(get_offerings(offering))
478
+ if len(offerings) == 0:
479
+ error(f"no offerings found for {offering}")
480
+ exit(3)
481
+ elif len(offerings) > 1:
482
+ error(f"multiple offerings found for {offering}: {', '.join(offerings)}")
483
+ exit(3)
484
+
485
+ canvas = Canvas(config.canvas_url, config.canvas_token)
486
+ course = get_course(canvas, canvas_course)
487
+
488
+ kattis_user2canvas_id = {}
489
+ canvas_id2kattis_user = {}
490
+ for link in get_kattis_links(course):
491
+ if link.kattis_user:
492
+ kattis_user2canvas_id[link.kattis_user] = link.canvas_user
493
+ canvas_id2kattis_user[link.canvas_user.id] = link.kattis_user
494
+ else:
495
+ warn(f"kattis link missing for {link.canvas_user.name} {link.canvas_user.email}.")
496
+
497
+ canvas_group = None
498
+ for ag in course.get_assignment_groups():
499
+ if ag.name == assignment_group:
500
+ canvas_group = ag
501
+ break
502
+
503
+ if not canvas_group:
504
+ error(f"no '{assignment_group}' assignment group in {canvas_course}")
505
+ exit(4)
506
+
507
+ assignments = {a.name: a for a in course.get_assignments(assignment_group_id=canvas_group.id)}
508
+
509
+ for assignment in get_assignments(offerings[0]):
510
+ if assignment.title.replace("-late", "") not in assignments:
511
+ error(f"{assignment.title.replace('-late', '')} not in canvas {canvas_course}")
512
+ else:
513
+ prefix = "LATE: " if "late" in assignment.title else ""
514
+ best_submissions = get_best_submissions(offering=offerings[0],
515
+ assignment_id=assignment.assignment_id)
516
+ canvas_assignment = assignments[assignment.title.replace("-late", "")]
517
+ # find the last submissions and only add a submission if the best submission is after latest
518
+ submissions_by_user = {}
519
+ for canvas_submission in canvas_assignment.get_submissions(include=["submission_comments"]):
520
+ if canvas_submission.user_id in canvas_id2kattis_user:
521
+ if canvas_submission.user_id in submissions_by_user:
522
+ warn(
523
+ f'duplicate submission for {kattis_user2canvas_id[canvas_submission.user_id]} in {assignment.title}')
524
+ submissions_by_user[canvas_id2kattis_user[canvas_submission.user_id]] = canvas_submission
525
+ last_comment = datetime.datetime.fromordinal(1).replace(tzinfo=datetime.timezone.utc)
526
+ if canvas_submission.submission_comments:
527
+ for comment in canvas_submission.submission_comments:
528
+ created_at = extract_canvas_date(comment['created_at'])
529
+ if created_at > last_comment:
530
+ last_comment = created_at
531
+ canvas_submission.last_comment = last_comment
532
+
533
+ for user, best in best_submissions.items():
534
+ for kattis_submission in best.values():
535
+ if user not in submissions_by_user:
536
+ warn(f"i don't see a canvas submission for {user}")
537
+ elif user not in kattis_user2canvas_id:
538
+ warn(f'skipping submission for unknown user {user}')
539
+ elif kattis_submission.date > submissions_by_user[user].last_comment:
540
+ if dryrun:
541
+ warn(
542
+ f"would update {kattis_user2canvas_id[kattis_submission.user]} on problem {kattis_submission.problem} scored {kattis_submission.score}")
543
+ else:
544
+ submissions_by_user[user].edit(comment={
545
+ 'text_comment': f"{prefix}Submission https://{config.kattis_hostname}{kattis_submission.url} scored {kattis_submission.score} on {kattis_submission.problem}."})
546
+ info(
547
+ f"updated {submissions_by_user[user]} {kattis_user2canvas_id[kattis_submission.user]} for {assignment.title}")
548
+ else:
549
+ info(f"{user} up to date")
550
+
551
+
552
+ def get_best_submissions(offering: str, assignment_id: str) -> {str: {str: Submission}}:
553
+ best_submissions = collections.defaultdict(dict)
554
+ rsp = web_get(f"https://{config.kattis_hostname}{offering}/assignments/{assignment_id}/submissions")
555
+ bs = BeautifulSoup(rsp.content, "html.parser")
556
+ judge_table = bs.find("table", id="judge_table")
557
+ headers = [x.get_text().strip() for x in judge_table.find_all("th")]
558
+ tbody = judge_table.find("tbody")
559
+ for submissions in tbody.find_all("tr", recursive=False):
560
+ if not submissions.get("data-submission-id"):
561
+ continue
562
+ submissions = submissions.find_all("td", recursive=False)
563
+ if not submissions:
564
+ continue
565
+ props = {}
566
+ for index, td in enumerate(submissions):
567
+ a = td.find("a")
568
+ props[headers[index]] = a.get("href") if a else td.get_text().strip()
569
+ date = props["Date"]
570
+ if "-" in date:
571
+ date = datetime.datetime.strptime(date, "%Y-%m-%d %H:%M:%S").replace(tzinfo=now.tzinfo)
572
+ else:
573
+ hms = datetime.datetime.strptime(date, "%H:%M:%S")
574
+ date = now.replace(hour=hms.hour, minute=hms.minute, second=hms.second)
575
+ # it's not clear when the short date version is used. it might be used when it is less than 24 hours,
576
+ # in which case, just setting the time will make the date 24 hours more than it should be
577
+ if date > now:
578
+ date -= datetime.timedelta(days=1)
579
+
580
+ score = 0.0 if props["Test cases"] == "-/-" else float(Fraction(props["Test cases"])) * 100
581
+ submission = Submission(user=extract_last(props["User"]), problem=extract_last(props["Problem"]), date=date,
582
+ score=score, url=props[""])
583
+ if submission.problem not in best_submissions[submission.user]:
584
+ best_submissions[submission.user] = {submission.problem: submission}
585
+ else:
586
+ current_best = best_submissions[submission.user][submission.problem]
587
+ if current_best.score < submission.score or (
588
+ current_best.score == submission.score and current_best.date < submission.date):
589
+ best_submissions[submission.user][submission.problem] = submission
590
+ return best_submissions
591
+
592
+
593
+ @top.command()
594
+ @click.argument("canvas_course")
595
+ def sendemail(canvas_course):
596
+ """
597
+ Email students if they don't have a kattis link in their profile.
598
+ It takes one input argument canvas course name.
599
+ """
600
+ canvas = Canvas(config.canvas_url, config.canvas_token)
601
+ course = get_course(canvas, canvas_course)
602
+
603
+ for link in get_kattis_links(course):
604
+ if not is_student_enrollment(link.canvas_user):
605
+ continue
606
+ if not link.kattis_user:
607
+ canvas.create_conversation(recipients=link.canvas_user.id,
608
+ body="Hello " + link.canvas_user.name + "\n\n\n Please add the missing kattis "
609
+ "link in bio for "
610
+ "course " + canvas_course + ".",
611
+ subject='Reminder: Add kattis link in profile')
612
+ info(f"Able to send conversation to : {link.canvas_user.id}")
613
+
614
+
615
+ if __name__ == "__main__":
616
+ top()
@@ -0,0 +1,107 @@
1
+ Metadata-Version: 2.4
2
+ Name: kattis2canvas
3
+ Version: 0.1.3
4
+ Summary: CLI tool to integrate Kattis offerings with Canvas LMS courses
5
+ Author: bcr33d
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/bcr33d/kattis2canvas
8
+ Project-URL: Repository, https://github.com/bcr33d/kattis2canvas
9
+ Keywords: kattis,canvas,lms,education,grading
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Education
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.8
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Topic :: Education
21
+ Requires-Python: >=3.8
22
+ Description-Content-Type: text/markdown
23
+ Requires-Dist: click>=8.0
24
+ Requires-Dist: requests>=2.25
25
+ Requires-Dist: beautifulsoup4>=4.9
26
+ Requires-Dist: canvasapi>=2.0
27
+ Requires-Dist: python-dateutil>=2.8
28
+
29
+ # kattis2canvas
30
+
31
+ this is a simple python tool that uses the canvasapi toolkit to integrate a kattis offering with a canvas course. the tool was specifically made to work with the commercial kattis (as you will see in a moment). it would take a bit of tweaking on the web scraping to make it work with open.kattis.com.
32
+
33
+ the kattis connection is done using web scraping and thus it is very fragile! at the end, i will highlight where it is most vulnerable.
34
+
35
+ # setting up kattis2canvas
36
+
37
+ ## the config file
38
+
39
+ first you will need to set up the config file. it has all your authorization tokens so DON'T CHECK IT IN. i specificially look for it in the app_dir as defined by click to get it far away from source. on linux this ends up being a file called ~/.config/kattis2canvas.ini. this is how it should be populated:
40
+
41
+ ```
42
+ [kattis]
43
+ username: YOUR_KATTIS_USERNAME_NOT_EMAIL
44
+ token: SOME_RANDOM_CHARACTERS
45
+ hostname: THE_DOMAIN_NAME_OF_YOUR_KATTIS_INSTANCE
46
+ loginurl: THE_URL_TO_LOG_IN_TO_KATTIS
47
+
48
+ [canvas]
49
+ url=URL_OF_YOUR_CANVAS_INSTANCE
50
+ token=SOME_RANDOM_CHARACTERS
51
+ ```
52
+
53
+ you can easily get the kattis section by going to https://\<kattis>/download/kattisrc where \<kattis> is your instance of kattis. you will need to move the lines around slightly. for canvas the url is the one you use to access the main page of canvas. you generate the token in the bottom of the Account -> Settings page.
54
+
55
+ you can check that everything is set up by running:
56
+
57
+ ```
58
+ kattis2canvas list-offerings
59
+ kattis2canvas list-assignments
60
+ ```
61
+
62
+ or if you built the pyz file using make_zipapp.sh
63
+
64
+ ```
65
+ kattis2canvas list-offerings
66
+ kattis2canvas list-assignments
67
+ ```
68
+
69
+ ## mapping student kattis accounts to canvas accounts
70
+
71
+ in canvas, you can associate various URLs with your account in the Links section of Account -> Profile. students need to put the URL of their kattis account in a link with the word "kattis" (in any case) in the title. this ends up being the join key for kattis2canvas.
72
+
73
+ you can check if the students have set up the links properly using
74
+
75
+ ```
76
+ kattis2canvas kattislinks
77
+ ```
78
+
79
+ # using kattis2canvas
80
+
81
+ ## populating kattis assignments in canvas
82
+
83
+ when you create new kattis assignments, you will need to get it mirrored into canvas. currently the **course2canvas** command will put all of the assignments into an assignment group called kattis. the assignment group must be created in your course before **course2canvas**.
84
+
85
+ when you specify the names of offerings in kattis and courses in canvas, you can specify a substring of the name and **kattis2canvas** will be able to use it as long as it matches exactly one name. if it doesn't, it will show it what it found.
86
+
87
+ when creating the assignment in canvas, anything you have put in the description in kattis will also be replicated in canvas along with a link to the kattis assignment.
88
+
89
+ if you have made changes to a kattis assignment that you have already populated in canvas, use the --force option to force an update. (right now there isn't a way to force individual assignments.)
90
+
91
+ if you use modules, you can use the **--add-to-module** flag to add the kattis assignments to a module. at this point, it puts all of the kattis assignments into that one module.
92
+
93
+ ## getting the results to canvas
94
+
95
+ the **submissions2canvas** will replicate results from student submissions to kattis into canvas. it will only replicate results that are either better or the same as or newer than previous results it has replicated. a summary of the problem, score, and link to the submission will be added as a comment for the student in the gradebook for the relevant assignment. the idea is that when it's time to grade, you have easy access to the results and the link to the source from canvas speedgrader.
96
+
97
+ # kattis webscraping
98
+
99
+ unfortuately, scraping the kattis API is very adhoc and it would be naive to think that it wouldn't change in ways that will break this tool. we use BeautifulSoupe (it's pretty beautiful...) so here are the features that the script relies on for kattis webpages: (note the term "assume" is used for things we have to believe because that is the only reasonable way that we can use the information we are given.)
100
+
101
+ * the list of offerings: (HOSTNAME is from the config file above) we assume http://HOSTNAME/ will give us a page will all the offerings and the urls in the href of those offerings will have the form **/courses/[^/]+/[^/]+**
102
+ * the list of assignments: we assume the offering page will have the detail page for assignments in hrefs of anchor tabs of the form "assignments/\w+$".
103
+ * the assignment details: we assume the assignment detail page will have an \<h2> tag with the text "Description" followed by a sibling \<p> tag that entirely contains the description. we also assume that there will be a \<td> for "start time" and another for "end time" we do case insensitve comparisons to find them. we assume that the following \<td> tage will have the time.
104
+ * time: TIME IS HARD! if the time is recent, kattis will drop the date, so if we get a time with no date, we take the current time and up date the HH:MM:SS with the date we get from kattis. we also assume all dates are UTC.
105
+ * getting submissions: we assume the submissions for an assignment are found at https://HOSTNAME/OFFERING/assignments/ASSIGNMENT_ID/submissions it appears that all submissions for the assignment are listed on that page. submissions for a problem outside of the assignment time period will not show up on that page. the submissions are in a table called "judege"table". the headers \<th> that we are looking for are "User" for the user url, "Problem" for the name of the problem, "Test cases" for the score reflected as sucess/count with -/- indicating no tries, and "" indicating the header for the url of the submission. once we know the column numbers we want, we have to look for the \<tbody> child of the table (problems happen if you try to look for \<td> recursively from the table!) then we look for \<tr> children of \<tbody> which have a "data-submission-id" attribute.
106
+
107
+
@@ -0,0 +1,11 @@
1
+ README.md
2
+ pyproject.toml
3
+ src/kattis2canvas/__init__.py
4
+ src/kattis2canvas/__main__.py
5
+ src/kattis2canvas/cli.py
6
+ src/kattis2canvas.egg-info/PKG-INFO
7
+ src/kattis2canvas.egg-info/SOURCES.txt
8
+ src/kattis2canvas.egg-info/dependency_links.txt
9
+ src/kattis2canvas.egg-info/entry_points.txt
10
+ src/kattis2canvas.egg-info/requires.txt
11
+ src/kattis2canvas.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ kattis2canvas = kattis2canvas.cli:top
@@ -0,0 +1,5 @@
1
+ click>=8.0
2
+ requests>=2.25
3
+ beautifulsoup4>=4.9
4
+ canvasapi>=2.0
5
+ python-dateutil>=2.8
@@ -0,0 +1 @@
1
+ kattis2canvas