348 lines
14 KiB
Python
348 lines
14 KiB
Python
from os.path import isfile
|
|
from os import listdir, remove
|
|
import sys
|
|
import subprocess
|
|
|
|
import matplotlib.pyplot as plt
|
|
import pandas
|
|
import argparse
|
|
|
|
|
|
def read_moodle_csv(moodle_csv):
|
|
try:
|
|
moodle_list = pandas.read_csv(moodle_csv, sep=";")
|
|
except pandas.errors.ParserError:
|
|
sys.stderr.write("cannot parse csv file from moodle")
|
|
sys.exit(1)
|
|
return moodle_list
|
|
|
|
|
|
def create_jack_lists(moodle_csv, jack_prefix):
|
|
print("creating list with matriculation numbers for JACK")
|
|
moodle_list = read_moodle_csv(moodle_csv)
|
|
days = moodle_list["Datum"].unique()
|
|
frames_by_day = []
|
|
for day in days:
|
|
frames_by_day.append(moodle_list[:][moodle_list.Datum == day])
|
|
for frame in frames_by_day:
|
|
numbers = frame['Teilnehmer-ID'].tolist()
|
|
output = ""
|
|
for n in numbers:
|
|
try:
|
|
n = int(n)
|
|
output = output + str(n) + "\n"
|
|
except ValueError:
|
|
sys.stderr.write("cannot parse matriculation number '" + str(n) + "', please add it manually")
|
|
with open(jack_prefix+(frame["Datum"].tolist())[0].split(",")[0]+".txt", "w") as text_file:
|
|
text_file.write(output)
|
|
|
|
|
|
def split_tables(moodle_csv):
|
|
print("splitting moodle registrations by appointment")
|
|
moodle_list = read_moodle_csv(moodle_csv)
|
|
days = moodle_list["Datum"].unique()
|
|
frames_by_day = []
|
|
for day in days:
|
|
frames_by_day.append(moodle_list[:][moodle_list.Datum == day])
|
|
frames_by_time = []
|
|
for frame in frames_by_day:
|
|
times = frame["Startzeit"].unique()
|
|
for t in times:
|
|
frames_by_time.append(frame[:][frame.Startzeit == t])
|
|
|
|
for frame in frames_by_time:
|
|
frame.sort_values("Nachname", inplace=True, key=lambda col: col.str.lower().str.normalize('NFD'))
|
|
seats = list(range(1, len(frame)+1))
|
|
rows = [int((s-1) / 20) + 1 for s in seats]
|
|
frame["Reihe"] = rows
|
|
frame["Platz"] = seats
|
|
full_place_info = []
|
|
for index, row in frame.iterrows():
|
|
full_place_info.append("Datum: " + str(row["Datum"]) + ": " + str(row["Startzeit"]) + " - "
|
|
+ str(row["Endzeit"]) + " --- Platz: Raum " + str(row["Ort"])
|
|
+ " Reihe " + str(row["Reihe"]) + " Platz " + str(row["Platz"]))
|
|
frame["Sitzplatz"] = full_place_info
|
|
|
|
return frames_by_time
|
|
|
|
|
|
def create_info_for_moodle(tables: list[pandas.DataFrame], moodle_upload):
|
|
print("creating file for moodle upload")
|
|
new_frame = pandas.DataFrame()
|
|
vornamen = []
|
|
nachnamen = []
|
|
ids = []
|
|
sitzplaetze = []
|
|
for frame in tables:
|
|
vornamen.extend(frame["Vorname"].tolist())
|
|
nachnamen.extend(frame["Nachname"].tolist())
|
|
ids.extend(frame["Teilnehmer-ID"].tolist())
|
|
sitzplaetze.extend(frame["Sitzplatz"].tolist())
|
|
new_frame["Vorname"] = vornamen
|
|
new_frame["Nachname"] = nachnamen
|
|
new_frame["Teilnehmer-ID"] = ids
|
|
new_frame["Sitzplatz"] = sitzplaetze
|
|
new_frame.to_csv(moodle_upload, sep=";")
|
|
|
|
|
|
def create_students_tables(tables: list[pandas.DataFrame], login_file, tan_prefix):
|
|
print("creating entry lists csv files")
|
|
jack_tans = pandas.DataFrame()
|
|
files = [f for f in listdir(".") if isfile(f)]
|
|
for f in files:
|
|
if f.startswith(tan_prefix):
|
|
tans = pandas.read_csv(f, sep=",", header=None)
|
|
jack_tans = pandas.concat([jack_tans, tans])
|
|
if not isfile(login_file):
|
|
sys.stderr.write("PC login list does not exist")
|
|
return
|
|
jack_tans = dict(zip(jack_tans[0], jack_tans[1]))
|
|
pc_logins: pandas.DataFrame
|
|
try:
|
|
pc_logins = pandas.read_csv(login_file, sep=",", header=None)
|
|
except pandas.errors.ParserError:
|
|
sys.stderr.write("cannot parse pc login file")
|
|
sys.exit(1)
|
|
extended_tables = []
|
|
filenames = []
|
|
logins = pc_logins[0].tolist()
|
|
pw = pc_logins[1].tolist()
|
|
for frame in tables:
|
|
tag = str(frame["Datum"].tolist()[0]).split(",")[0]
|
|
zeit = str(frame["Startzeit"].tolist()[0]).replace(":", "")
|
|
new_frame = pandas.DataFrame()
|
|
new_frame["Vorname"] = frame["Vorname"].tolist()
|
|
new_frame["Nachname"] = frame["Nachname"].tolist()
|
|
new_frame["Matrikelnummer"] = frame["Teilnehmer-ID"].tolist()
|
|
tan_list = []
|
|
for matnumber in [int(n) for n in new_frame["Matrikelnummer"]]:
|
|
if matnumber in jack_tans.keys():
|
|
tan_list.append(jack_tans[matnumber])
|
|
else:
|
|
sys.stderr.write("Student '" + str(matnumber) + "' is not registered in JACK\n")
|
|
tan_list.append("")
|
|
new_frame["TAN"] = tan_list
|
|
new_frame["Kennung"] = logins[0:len(tan_list)]
|
|
new_frame["Passwort"] = pw[0:len(tan_list)]
|
|
logins = logins[len(tan_list):]
|
|
pw = pw[len(tan_list):]
|
|
new_frame["Reihe"] = frame["Reihe"].tolist()
|
|
new_frame["Platz"] = frame["Platz"].tolist()
|
|
new_frame.to_csv("_Teilnehmer_"+tag+"_"+zeit+".csv", sep=";")
|
|
|
|
# add some more fields for later
|
|
new_frame["Datum"] = frame["Datum"].tolist()
|
|
new_frame["Startzeit"] = frame["Startzeit"].tolist()
|
|
new_frame["Endzeit"] = frame["Endzeit"].tolist()
|
|
tasks = ["A" if str(datum).startswith("Montag") else "B" for datum in frame["Datum"].tolist()]
|
|
new_frame["Task"] = tasks
|
|
extended_tables.append(new_frame)
|
|
filenames.append(("_Teilnehmer_"+tag+"_"+zeit+".csv",
|
|
str(frame["Datum"].tolist()[0]) + ", "
|
|
+ str(frame["Startzeit"].tolist()[0]) + " - " + str(frame["Endzeit"].tolist()[0])
|
|
+ " - " + str(len(new_frame)) + " Teilnehmer"))
|
|
return extended_tables, filenames
|
|
|
|
|
|
def create_extra_logins(tables: list[pandas.DataFrame], login_file):
|
|
print("collecting unused login information")
|
|
length = sum([len(table) for table in tables])
|
|
pc_logins: pandas.DataFrame
|
|
try:
|
|
pc_logins = pandas.read_csv(login_file, sep=",", header=None)
|
|
except pandas.errors.ParserError:
|
|
sys.stderr.write("cannot parse pc login file")
|
|
sys.exit(1)
|
|
kennungen = pc_logins[0].tolist()[length:]
|
|
passwords = pc_logins[1].tolist()[length:]
|
|
output = "KennungA;PasswortA;KennungB;PasswortB;KennungC;PasswortC"
|
|
for i in range(0, len(kennungen)-3, 3):
|
|
output = (output + "\n" + kennungen[i] + ";" + passwords[i] + ";"
|
|
+ kennungen[i+1] + ";" + passwords[i+1] + ";"
|
|
+ kennungen[i+2] + ";" + passwords[i+2])
|
|
with open("_extra_logins.csv", "w") as csvfile:
|
|
csvfile.write(output)
|
|
|
|
|
|
def create_super_csv_for_pdf(tables: list[pandas.DataFrame]):
|
|
print("creating csv for testat pdf")
|
|
firstnames = []
|
|
lastnames = []
|
|
matnumbers = []
|
|
rows = []
|
|
seats = []
|
|
usernames = []
|
|
userpws = []
|
|
tans = []
|
|
timeslots = []
|
|
tasks = []
|
|
|
|
for table in tables:
|
|
firstnames.extend(table["Vorname"].tolist())
|
|
lastnames.extend(table["Nachname"].tolist())
|
|
matnumbers.extend(table["Matrikelnummer"].tolist())
|
|
rows.extend(table["Reihe"].tolist())
|
|
seats.extend(table["Platz"].tolist())
|
|
usernames.extend(table["Kennung"].tolist())
|
|
userpws.extend(table["Passwort"].tolist())
|
|
tans.extend(table["TAN"].tolist())
|
|
timeslots.extend(
|
|
[str(time[0]) + ": " + str(time[1]) + " - " + str(time[2]) for time in
|
|
zip(table["Datum"].tolist(), table["Startzeit"].tolist(), table["Endzeit"].tolist())]
|
|
)
|
|
tasks.extend(table["Task"])
|
|
supertable = pandas.DataFrame()
|
|
supertable["Vorname"] = firstnames
|
|
supertable["Nachname"] = lastnames
|
|
supertable["Matrikelnummer"] = matnumbers
|
|
supertable["Reihe"] = rows
|
|
supertable["Platz"] = seats
|
|
supertable["Kennung"] = usernames
|
|
supertable["Passwort"] = userpws
|
|
supertable["TAN"] = tans
|
|
supertable["Zeit"] = timeslots
|
|
supertable["Aufgabe"] = tasks
|
|
supertable.to_csv("_Teilnehmerliste.csv", sep=";")
|
|
|
|
|
|
def create_serienbrief():
|
|
print("creating testat pdf")
|
|
result = subprocess.run(["pdflatex", "Serienbrief.tex"], capture_output=True, text=True)
|
|
if result.returncode != 0:
|
|
sys.stderr.write("pdflatex exited with error code " + str(result.returncode))
|
|
|
|
|
|
def create_teilnehmerlisten(filenames):
|
|
print("creating entry lists pdfs")
|
|
output = "File;Title"
|
|
for file, title in filenames:
|
|
output = output + "\n" + file + ";" + title
|
|
with open("_table_info.csv", "w") as csvfile:
|
|
csvfile.write(output)
|
|
result = subprocess.run(["pdflatex", "Teilnehmerlisten.tex"], capture_output=True, text=True)
|
|
if result.returncode != 0:
|
|
sys.stderr.write("pdflatex exited with error code " + str(result.returncode))
|
|
|
|
|
|
def create_extra_kennungen():
|
|
print("creating extra login information pdf")
|
|
result = subprocess.run(["pdflatex", "ExtraKennungen.tex"], capture_output=True, text=True)
|
|
if result.returncode != 0:
|
|
sys.stderr.write("pdflatex exited with error code " + str(result.returncode))
|
|
|
|
|
|
def cleanup_files():
|
|
print("deleting temporary files")
|
|
files = [f for f in listdir(".")]
|
|
for f in files:
|
|
if f.endswith(".aux"):
|
|
remove(f)
|
|
if f.endswith(".log"):
|
|
remove(f)
|
|
if f.startswith("_"):
|
|
remove(f)
|
|
|
|
|
|
def merge_results(results, moodle_output, tables):
|
|
def sort_function(col: pandas.Series):
|
|
if col.name == "Nachname":
|
|
return col.str.lower().str.normalize('NFD')
|
|
else:
|
|
return col.map(lambda v: ("A" if v.split("-")[0] == "Montag" else "B") + v.split("-")[1])
|
|
|
|
if moodle_output == "":
|
|
return
|
|
|
|
print("checking results")
|
|
mat_numbers = []
|
|
scores = []
|
|
status = []
|
|
first_names = []
|
|
last_names = []
|
|
slot = []
|
|
for r in results:
|
|
frame = pandas.read_excel(r)
|
|
mat_numbers.extend(frame["Matrikelnummer"].tolist())
|
|
scores.extend(frame["Punktzahl"].tolist())
|
|
status.extend(frame["Status"].tolist())
|
|
if len(mat_numbers) != len(set(mat_numbers)):
|
|
raise RuntimeError("There are duplicate matriculation numbers in JACK")
|
|
for m in mat_numbers:
|
|
row = [r for r in [t.loc[t['Teilnehmer-ID'] == m] for t in tables] if len(r) > 0]
|
|
if len(row) > 1:
|
|
raise RuntimeError("found multiple students with the same matriculation number '" + str(m) + "'")
|
|
if len(row) == 0:
|
|
raise RuntimeError("student '" + str(m) + "' did not participate in the testat, but has a result")
|
|
row = row[0]
|
|
if len(row) > 1:
|
|
raise RuntimeError("found multiple students with the same matriculation number '" + str(m) + "'")
|
|
if len(row) == 0:
|
|
raise RuntimeError("student '" + str(m) + "' did not participate in the testat, but has a result")
|
|
first_names.append(row["Vorname"].tolist()[0])
|
|
last_names.append(row["Nachname"].tolist()[0])
|
|
slot.append(row["Datum"].tolist()[0].split(",")[0] + "-" + row["Startzeit"].tolist()[0])
|
|
results_frame = pandas.DataFrame()
|
|
results_frame["Slot"] = slot
|
|
results_frame["Vorname"] = first_names
|
|
results_frame["Nachname"] = last_names
|
|
results_frame["Matrikelnummer"] = mat_numbers
|
|
results_frame["Punktzahl"] = scores
|
|
results_frame["Status"] = status
|
|
|
|
results_frame.sort_values(["Slot", "Nachname"], inplace=True, key=sort_function)
|
|
fig, ax = plt.subplots()
|
|
results_frame.hist(column="Punktzahl", ax=ax)
|
|
fig.savefig('histogram.png')
|
|
|
|
if moodle_output.endswith(".csv"):
|
|
results_frame.to_csv(moodle_output, sep=";")
|
|
elif moodle_output.endswith(".xls") or moodle_output.endswith("xlsx"):
|
|
results_frame.to_excel(moodle_output, index=False)
|
|
else:
|
|
sys.stderr.write("unsupported file format")
|
|
sys.exit(1)
|
|
|
|
|
|
def start(moodle_input: str, moodle_output: str = "", logins: str = "",
|
|
jack: bool = False, jack_prefix: str = "JACK_", tan_prefix: str = "examTans",
|
|
results_prefix: str = "Jack-Report"):
|
|
if jack:
|
|
create_jack_lists(moodle_input, jack_prefix)
|
|
tables = split_tables(moodle_input)
|
|
results = [f for f in listdir(".") if f.startswith(results_prefix) and f.endswith(".xls")]
|
|
if moodle_output != "" and len(results) == 0:
|
|
create_info_for_moodle(tables, moodle_output)
|
|
if logins != "":
|
|
extended_tables, filenames = create_students_tables(tables, logins, tan_prefix)
|
|
create_extra_logins(extended_tables, logins)
|
|
create_super_csv_for_pdf(extended_tables)
|
|
create_serienbrief()
|
|
create_teilnehmerlisten(filenames)
|
|
create_extra_kennungen()
|
|
if len(results) > 0:
|
|
merge_results(results, moodle_output, tables)
|
|
cleanup_files()
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("-i", "--input", type=str, required=True,
|
|
help='the csv file downloaded from moodle', action='store')
|
|
parser.add_argument("-j", "--jack", help='output matriculation numbers for JACK?', action='store_true')
|
|
parser.add_argument("-p", "--jack_prefix", type=str,
|
|
help='prefix for output files for JACK, default: JACK_', action='store', default="JACK_")
|
|
parser.add_argument("-t", "--tan_prefix", type=str,
|
|
help='prefix for tan files from JACK, default: examTans', action='store', default="examTans")
|
|
parser.add_argument("-o", "--output", type=str, default="", help='the output file', action='store')
|
|
parser.add_argument("-l", "--logins", type=str, default="",
|
|
help='file with login information', action='store')
|
|
parser.add_argument("-r", "--results_prefix", type=str, action='store', default="Jack-Report",
|
|
help="prefix for files from JACK with the results of the testat")
|
|
args = parser.parse_args()
|
|
start(args.input, args.output, args.logins, args.jack,
|
|
args.jack_prefix, args.tan_prefix, args.results_prefix)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|