Repository navigation
Expand file tree
/
Copy pathextract.py
More file actions
137 lines (115 loc) · 4.64 KB
/
Copy pathextract.py
File metadata and controls
137 lines (115 loc) · 4.64 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
# Minerva assignment submission extractor
import re
import sys
import textwrap
from argparse import ArgumentParser, Namespace, RawDescriptionHelpFormatter
from datetime import datetime
from pathlib import Path
from zipfile import ZipFile, is_zipfile
try:
from rich.progress import track
except ImportError:
# Allow tool to run even if Rich is unavailable
def track(names: list, description: str) -> list:
return names
DEFAULT_LATE_FILE = "late.txt"
class AssignmentExtractor:
"""
Submission extractor for Minerva Assignments.
"""
# regexp for the names of archive members
NAME_FORMAT = re.compile(
r"(.+)_(\w+)_attempt_(\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2}).(.+)"
)
SPACES = re.compile(r"\s+")
def __init__(self, zpath: str, deadline: str = None, verbose: bool = False) -> None:
"""
Creates an AssignmentExtractor for a Zip archive with the given path.
The assignment deadline can optionally be specified, in YYYY-MM-DD:hh:mm
format. If this is done, the extractor will collect information on late
submissions as part of the extraction process.
"""
if not is_zipfile(zpath):
raise FileNotFoundError(
f"'{zpath}' does not exist or is not a valid Zip archive"
)
self.zip_path = zpath
if deadline:
self.deadline = datetime.strptime(deadline, "%Y-%m-%d:%H:%M")
else:
self.deadline = None
self.verbose = verbose
self.usernames = set()
self.late = {}
def extract(self) -> None:
"""
Runs the extraction process on an Assignment Zip archive.
"""
with ZipFile(self.zip_path) as zfile:
names = zfile.namelist()
for name in track(names, description="Extracting:"):
if match := self.NAME_FORMAT.match(name):
assignment, username, time, filename = match.groups()
self.usernames.add(username)
submitted = datetime.strptime(time, "%Y-%m-%d-%H-%M-%S")
if self.deadline and submitted > self.deadline:
self.late[username] = submitted - self.deadline
basedir = self.SPACES.sub("_", assignment.lower())
dirpath = Path(basedir) / username
dirpath.mkdir(parents=True, exist_ok=True)
filepath = dirpath / filename
filepath.write_bytes(zfile.read(name))
if self.verbose:
print()
print(f"{len(self.usernames)} submitters processed")
def write_lateness(self, filename: str) -> None:
"""
Writes information on late submissions to the given file, if such
information was collected during extraction.
"""
if self.late:
with open(filename, "wt") as outfile:
for username, lateness in sorted(self.late.items()):
print(f"{username:>8s}: {lateness}", file=outfile)
if self.verbose:
print(f"{len(self.late)} late submissions")
print(f"Lateness information written to {filename}")
def parse_command_line() -> Namespace:
parser = ArgumentParser(
formatter_class=RawDescriptionHelpFormatter,
description=textwrap.dedent("""
Extracts submissions from an Assignment Zip archive.
A destination directory is created, named after the assignment. Within
this directory are subdirectories, one for each student, containing that
student's submitted files. Student usernames are used as the names
of these subdirectories.
If a deadline is specified, information on late submissions will be
collected and written to a file.
"""),
)
parser.add_argument("zip_path", help="path to Zip archive containing submissions")
parser.add_argument(
"-v",
"--verbose",
action="store_true",
default=False,
help="provide more information on submission extraction",
)
parser.add_argument(
"--deadline", metavar="TIME", help="assignment deadline (YYYY-MM-DD:hh:mm)"
)
parser.add_argument(
"--latefile",
default=DEFAULT_LATE_FILE,
metavar="FILE",
help="name of lateness file (default: %(default)s)",
)
return parser.parse_args()
if __name__ == "__main__":
args = parse_command_line()
try:
extractor = AssignmentExtractor(args.zip_path, args.deadline, args.verbose)
extractor.extract()
extractor.write_lateness(args.latefile)
except Exception as error:
sys.exit(f"Error: {error}")