Last active
November 10, 2023 10:46
-
-
Save hogru/58611270e82db2fbe923ccfbbd6402a1 to your computer and use it in GitHub Desktop.
Open a random submission file during JKU's Python I exercise (UE)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding=utf-8 | |
"""Open a random submission file during JKU's Python I exercise (UE). | |
This script has the following features: | |
- selects only files from students who are listed in a students file (defaults to './students.csv'). | |
- uses a file search pattern to find submission files in a given directory. | |
- randomly selects from the candidate files / submissions. | |
- asks for confirmation before opening the file, unless the --quiet flag is given. | |
Pre-requisites: | |
- a students file in CSV format, with (at least) columns 'Vorname', 'Nachname', separated by ';'. | |
- Hint: KUSSS can export the students of a course in that format. | |
- Hint: I could not figure out the encoding of the KUSSS output and had to change 'Umlaute (äöü...)' manually. | |
- The submission files in a (local) directory, i.e. manually downloaded from the Moodle course page. | |
- a "correct" setting of the VIEWER variable for your preferred code viewer. | |
- Hint: the command to open the file works on macOS, should work on Linux, but might not work on Windows. | |
- python >= 3.10 (because of the "match" statement, could easily be replaced by "if" statements). | |
- the pandas package. | |
Example usage: | |
- python select_submission.py ../../submissions/a4 --pattern '*a4_ex1.py' | |
Changes in the submission file name format or the students file format will probably require changes to the code. | |
""" | |
import argparse | |
import os | |
from collections.abc import Callable | |
from pathlib import Path | |
from random import randint | |
from typing import Final, Iterable, Optional, Sequence | |
import pandas as pd | |
STUDENTS_FILE: Final[Path] = Path("./students.csv") # default students file | |
SUBMISSION_FILE_PATTERN: Final[str] = "*.py" # default file pattern to search for | |
VIEWER: Final[ | |
Optional[str] | |
] = "/Applications/BBEdit.app" # app to open submission in, assign None for default application | |
def parse_args() -> argparse.Namespace: | |
parser = argparse.ArgumentParser(description="Open a random submission") | |
parser.add_argument( | |
"directory", type=Path, help="The directory to search for submissions" | |
) | |
parser.add_argument( | |
"-p", | |
"--pattern", | |
type=str, | |
default=SUBMISSION_FILE_PATTERN, | |
help="The file name pattern to search for, default: %(default)s", | |
) | |
parser.add_argument( | |
"-s", | |
"--students", | |
type=Path, | |
default=STUDENTS_FILE, | |
help="The file name that holds the students names,: %(default)s", | |
) | |
parser.add_argument( | |
"-q", "--quiet", action="store_true", help="Don't print anything" | |
) | |
parser.add_argument( | |
"-r", "--recursive", action="store_true", help="Do a recursive search" | |
) | |
return parser.parse_args() | |
# noinspection PyUnusedLocal | |
def do_not_print(*args, **kwargs) -> None: # type: ignore | |
... | |
def read_students_file(students_file: Path) -> set[str]: | |
# Change this function if the (KUSSS) file format changes | |
students_file = Path(students_file).resolve() | |
df = pd.read_csv(students_file, sep=";") | |
df["name"] = df["Vorname"] + " " + df["Nachname"] | |
return set(df["name"]) | |
def get_submission_files( | |
directory: Path, | |
*, | |
file_pattern: str = SUBMISSION_FILE_PATTERN, | |
recursive: bool = False, | |
) -> list[Path]: | |
pattern = f"**/{file_pattern}" if recursive else file_pattern | |
return [file_name for file_name in directory.glob(pattern) if file_name.is_file()] | |
def select_submission_file( | |
submission_files: Sequence[Path], students: Optional[Iterable[str]] = None | |
) -> Path: | |
# This is definitely _not_ the most efficient way to do this | |
# Came later when I found out that I get _all_ submissions (from all exercises) | |
# Don't care for this one-off script | |
for _ in range(100): # make sure that we don't get stuck in an infinite loop | |
submission_file = submission_files[randint(0, len(submission_files) - 1)] | |
if students is None: | |
return submission_file | |
elif students is not None and parse_author(submission_file) in students: | |
return submission_file | |
raise RuntimeError("Could not find a submission file") | |
def parse_author(submission_file: Path) -> str: | |
# Change this function if the file naming convention changes | |
# try: | |
return submission_file.stem.split("_")[0] | |
# except IndexError as e: | |
# raise ValueError(f"Could not parse author from {submission_file}") from e | |
def open_submission(submission_file: Path, viewer: Optional[str] = VIEWER) -> None: | |
if viewer is not None and isinstance(viewer, str) and Path(viewer).exists(): | |
os.system( | |
f"open -a {VIEWER} '{submission_file.as_posix()}'" | |
) # might not work in Windows | |
else: | |
os.system(f"open '{submission_file.as_posix()}'") # might not work in Windows | |
def main() -> None: | |
args = parse_args() | |
if not args.directory.is_dir(): | |
raise FileNotFoundError(f"{args.directory} is not a valid directory") | |
if not args.students.is_file(): | |
raise FileNotFoundError(f"{args.students} is not a valid file") | |
print_: Callable = do_not_print if args.quiet else print # type: ignore | |
print_(f"Reading students from file {args.students.resolve()}...") | |
students = read_students_file(args.students) | |
print_(f"Found {len(students)} student(s)") | |
print_( | |
f"Searching for submissions in directory {args.directory.resolve()} with pattern {args.pattern}..." | |
) | |
submission_files = get_submission_files( | |
args.directory, file_pattern=args.pattern, recursive=args.recursive | |
) | |
if not submission_files: | |
raise FileNotFoundError("No submission files found") | |
print_(f"Found {len(submission_files)} submission(s)") | |
while True: | |
submission_file = select_submission_file(submission_files, students) | |
print_(f"Select submission file {submission_file.name}") | |
submission_author = parse_author(submission_file) | |
print_(f"\nThe submission author is {submission_author.upper()}\n") | |
if not args.quiet: | |
inp = ( | |
input( | |
"Enter 'n' to select another submission, 'x' to cancel or ENTER to open: " | |
) | |
.strip() | |
.lower() | |
) | |
match inp: | |
case "n": | |
continue | |
case "x": | |
break | |
case _: | |
pass | |
print_(f"Opening {submission_file.name}...") | |
open_submission(submission_file) | |
break | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment