-
Notifications
You must be signed in to change notification settings - Fork 0
/
pygrade.pyw
1672 lines (1222 loc) · 77 KB
/
pygrade.pyw
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
tkinter-based application for creating/recording assessment feedback
"""
import os
import re
import json
import base64
from datetime import datetime
import itertools
import pandas as pd
import numpy as np
import tkinter as tk
from tkinter import filedialog as fd
from tkinter import messagebox, StringVar
from tkinter.ttk import Scrollbar, Notebook, Combobox
import tkinter.scrolledtext as scrolledtext
from commentbankwidget import commentbank
#pip install pandastable
from pandastable import Table
#conda install -c conda-forge pyperclip
import pyperclip as pc
#conda install -c conda-forge fpdf
from fpdf import FPDF
#Integration with canvas
#pip install canvasapi
from canvasapi import Canvas as cvs
#Turn off warning for now
pd.options.mode.chained_assignment = None
#------------------------------------------------------------------------------
class PDF(FPDF):
def header(self):
title = self.title
# Arial bold 15
self.set_font('Arial', 'B', 15)
# Calculate width of title and position
w = self.get_string_width(title) + 6
self.set_x((210 - w) / 2)
# Colors of frame, background and text
self.set_draw_color(85, 0, 5)
self.set_fill_color(214, 0, 13)
self.set_text_color(255, 255, 255)
# Thickness of frame (1 mm)
self.set_line_width(1)
# Title
self.cell(w, 9, title, 1, 1, 'C', 1)
# Line break
self.ln(5)
def footer(self):
# Position at 1.5 cm from bottom
self.set_y(-15)
# Arial italic 8
self.set_font('Arial', 'I', 8)
# Text color in gray
self.set_text_color(128)
# Page number
self.cell(0, 10, 'Page ' + str(self.page_no()), 0, 0, 'C')
def chapter_title(self, num, label):
# Arial 12
self.set_font('Arial', '', 12)
# Background color
self.set_fill_color(255, 150, 150)
# Title
self.cell(0, 6, 'Chapter %d : %s' % (num, label), 0, 1, 'L', 1)
# Line break
self.ln(4)
def chapter_body(self, name):
# Read text file
with open(name, 'rb') as fh:
txt = fh.read().decode('latin-1')
# Times 12
self.set_font('Times', '', 12)
# Output justified text
self.multi_cell(0, 5, txt)
# Line break
self.ln()
# Mention in italics
self.set_font('', 'I')
self.cell(0, 5, '(end of excerpt)')
def print_chapter(self, num, title, name):
self.add_page()
self.chapter_title(num, title)
self.chapter_body(name)
def print_subheader(self, text):
# Arial bold 15
self.set_font('Arial', 'B', 12)
# Calculate width of title and position
w = self.get_string_width(text) + 6
self.set_x((210 - w) / 2)
# Colors of frame, background and text
self.set_draw_color(255, 255, 255)
self.set_fill_color(255, 255, 255)
self.set_text_color(50, 50, 50)
# Thickness of frame (1 mm)
self.set_line_width(1)
# Title
self.cell(w, 9, text, 1, 1, 'C', 1)
# Line break
self.ln(5)
def print_question(self, question):
# Arial 12
self.set_font('Arial', '', 12)
# Background color
self.set_fill_color(255, 200, 200)
# Title
self.cell(0, 6, question, 0, 1, 'L', 1)
# Line break
self.ln(1)
def print_feedback(self, txt):
# Times 12
self.set_font('Times', '', 12)
# Output justified text
self.multi_cell(0, 5, txt)
# Line break
self.ln()
def print_bold(self, txt):
self.set_font('Times', '', 12)
# Mention in italics
self.set_font('', 'B')
self.multi_cell(0, 5, txt)
def print_major(self, question, score, available, feedback):
if score == "":
self.print_question(question)
elif int(available)>0:
self.print_question(question + f" ({score}/{available})")
else:
self.print_question(question + f" ({score})")
self.print_feedback(feedback)
def print_minor(self, question, score, available, feedback):
if score == "":
self.print_question(question)
elif int(available)>0:
self.print_bold(question + f" ({score}/{available})")
else:
self.print_bold(question + f" ({score})")
self.print_feedback(feedback)
#------------------------------------------------------------------------------
#Helper functions
def clean(text):
"""convert to string or strip"""
try:
if isinstance(text,str):
return text.strip()
except:
return str(text)
def numericcolumn(dfcol):
"""Convert to dataframe column to numeric values"""
return pd.to_numeric(dfcol, errors='coerce')
def flatten(t):
"""Flatten a list of lists"""
return [item for sublist in t for item in sublist]
def extractid(filename, n=8):
"""Extract digits from file matching student id"""
x = re.findall('[0-9]+', filename)
return [y for y in x if len(y)==n]
def shortstrnum(value):
"""Convert to string but truncate for integers"""
if float(value).is_integer():
return str(int(value))
else:
return str(value)
#------------------------------------------------------------------------------
#Widget for questions and feedback
class CustomWidget(tk.Frame):
def __init__(self, parent, owner):
tk.Frame.__init__(self, parent)
self.owner = owner
bgcolor = self.owner.config.config["bgcolor"]
self.f1 = tk.Frame(self, bg=bgcolor, bd=0)
self.f1.grid(row=0, column=0, padx=10, pady=5, sticky='nsew')
self.keys = self.owner.config.classlist['key'].tolist()
self.idcombo = Combobox(self.f1, values = self.keys, height=10, state="readonly")
self.idcombo.grid(row=0, column=0, columnspan =2, padx=5, sticky='nsew')
self.idcombo.bind("<<ComboboxSelected>>", lambda event: self.idcomboselect())
self.f1.columnconfigure(0, weight=1)
#Select first value
self.idcombo.current(0)
self.btnpdf = tk.Button(self.f1, text="pdf", anchor='e')
self.btnpdf.grid(row=0, column=3, padx=5, sticky='nsew')
self.btnpdf.bind("<Button-1>", self.pdf)
self.btnpdf.columnconfigure(3, weight=0)
self.btnsave = tk.Button(self.f1, text="save", anchor='e')
self.btnsave.grid(row=0, column=4, padx=5, sticky='nsew')
self.btnsave.bind("<Button-1>", self.save)
self.btnsave.columnconfigure(4, weight=0)
self.feedbacktext = tk.Button(self.f1, text="...", anchor='e')
self.feedbacktext.grid(row=0, column=5, padx=5, sticky='nsew')
self.feedbacktext.bind("<Button-1>", self.feedbackpopup)
self.feedbacktext.columnconfigure(5, weight=0)
self.previousstudent = tk.Button(self.f1, text="<", anchor='e')
self.previousstudent.grid(row=0, column=6, padx=5, sticky='nsew')
self.previousstudent.bind("<Button-1>", self.moveback)
self.previousstudent.columnconfigure(6, weight=0)
self.nextstudent = tk.Button(self.f1, text=">", anchor='e')
self.nextstudent.grid(row=0, column=7, padx=5, sticky='nsew')
self.nextstudent.bind("<Button-1>", self.moveforward)
self.nextstudent.columnconfigure(7, weight=0)
self.total = tk.Label(self.f1, text='0', anchor='e', borderwidth=2, width=5, relief="groove", justify='center')
self.total.grid(row=0, column=8, padx=0, sticky='ne')
self.total.config(font=("Arial", 20))
self.f1.columnconfigure(8, weight=0)
self.f2 = tk.Frame(self, bg=bgcolor, bd=0)
self.f2.grid(row=1, column=0, padx=5, pady=5, sticky='nsew')
self.canvas = tk.Canvas(self.f2, bg=bgcolor, highlightthickness=0)
self.canvas.grid(row=0, column=0, padx=5, pady=5, sticky='nsew')
self.f2.columnconfigure(0, weight=1)
self.f2.rowconfigure(0, weight=1)
self.rowconfigure(0, weight=0)
self.rowconfigure(1, weight=1)
self.columnconfigure(0, weight=1)
#Now second frame for the components
self.frame_components = tk.Frame(self.canvas, bg=bgcolor)
self.frame_components.grid(row=0, column=0, padx=5, sticky='nsew')
self.frame_components.columnconfigure(0, weight=1)
self.frame_components.rowconfigure(0, weight=1)
#Need for the scroll bar
self.canvas.create_window((0, 0), window=self.frame_components, anchor='nw', tags="frame")
self.canvas.grid(row=0, column=0, padx=5, sticky='nsew')
self.canvas.columnconfigure(0, weight=0)
df = self.owner.config.questions
self.n = len(df)
self.scrollbaron = (self.n>self.owner.config.config["maxquestionsonscreen"])
self.nonscoringquestion = [np.isnan(self.owner.config.questions.marks.iloc[i]) for i in range(self.n)]
#Dictionary to match id to question index
self.index = df.question.tolist()
self.hint = []
self.hintlabel = []
self.combo = []
self.score = []
self.scoresv = []
self.text = []
for i in range(self.n):
if pd.isnull(df.iloc[i,2]):
label = f'{str(df.iloc[i,0])}. {df.iloc[i,1]}'
else:
label = f'{str(df.iloc[i,0])}. {df.iloc[i,1]} [{df.iloc[i,2]}]'
x = tk.Label(self.frame_components, text=label, anchor='w')
h = StringVar()
y = tk.Label(self.frame_components, text="<>", anchor='e', textvariable=h)
self.hint.append(h)
self.hintlabel.append(y)
s = StringVar()
self.scoresv.append(s)
s.trace("w", lambda name, index, mode, var=s, i=i: self.entryupdate(var, i))
z = tk.Entry(self.frame_components, width=5, justify='center', textvariable=s)
qid = str(df.iloc[i,0])
values = self.owner.config.combinedfeedback[self.owner.config.combinedfeedback.question==qid].feedback.tolist()
values.insert(0,"")
w = Combobox(self.frame_components, values = values, height=10, state="readonly")
self.combo.append(w)
#Stop frame scroll rolling combo boxes?!
w.unbind_class("TCombobox", "<MouseWheel>")
#Configure event handler
w.bind("<<ComboboxSelected>>", lambda event, k=i: self.comboselect(k))
if self.nonscoringquestion[i]:
t = scrolledtext.ScrolledText(self.frame_components, undo=True, height = int(self.owner.config.config["feedbacklines"])*2, background =self.owner.config.config["feedbackbgcolor"])
else:
t = scrolledtext.ScrolledText(self.frame_components, undo=True, height = int(self.owner.config.config["feedbacklines"]), background =self.owner.config.config["feedbackbgcolor"])
t['font'] = (self.owner.config.config["fontface"], self.owner.config.config["fontsize"])
self.text.append(t)
t.bind("<Key>", lambda event, k=i: self.textupdate(k))
x.grid(row = 3*i+0, column = 0, sticky = 'nsew', pady=5, padx = 2)
#Keep hidden for null feedback (i.e. overall)
if not self.nonscoringquestion[i]:
y.grid(row = 3*i+0, column = 1, sticky = 'nsew', pady=5, padx = 2)
z.grid(row = 3*i+0, column = 2, sticky = 'nsew', pady=5, padx = 2)
w.grid(row = 3*i+1, column = 0, columnspan=2, sticky = 'nsew', pady=2, padx = 5)
t.grid(row = 3*i+2, column = 0, columnspan=2, sticky = 'nsew', pady=3, padx = 5)
self.frame_components.columnconfigure(0, weight=1)
self.frame_components.rowconfigure(tuple(range(0,3*self.n,3)), weight=1)
self.frame_components.rowconfigure(tuple(range(1,3*self.n,3)), weight=1)
self.frame_components.rowconfigure(tuple(range(2,3*self.n,3)), weight=20)
self.sid = self.owner.config.classlist.id.iloc[0]
self.loadstudent(self.sid)
if self.scrollbaron:
self.scrollbar = Scrollbar(self, orient='vertical', command=self.canvas.yview)
self.scrollbar.grid(row=1, column=1, rowspan=1, sticky='ns')
self.canvas.configure(yscrollcommand=self.scrollbar.set)
#Update frame idle tasks to let tkinter calculate sizes
self.frame_components.update_idletasks()
self.canvas.config(scrollregion=self.canvas.bbox("all"))
self.canvas.bind('<Configure>', self._configure_canvas)
self.canvas.bind("<Enter>", self._bind_mouse)
self.canvas.bind("<Leave>", self._unbind_mouse)
def feedbackpopup(self, event=None):
win = tk.Toplevel()
win.wm_title("Feedback for " + self.idcombo.get())
t = scrolledtext.ScrolledText(win, undo=True, background =self.owner.config.config["feedbackbgcolor"])
t['font'] = (self.owner.config.config["fontface"], self.owner.config.config["fontsize"])
t.grid(row = 0, column = 0, sticky = 'nsew', pady=3, padx = 3)
win.columnconfigure(0, weight=1)
win.rowconfigure(0, weight=1)
df = self.owner.config.questions
firstname = self.owner.config.classlist.loc[self.owner.config.classlist.id == self.sid, 'first'][0]
feedback = ""
for i in range(self.n):
feedback += f'{str(df.iloc[i,0])}. {df.iloc[i,1]} '
if not pd.isnull(df.iloc[i,2]):
score = clean(self.scoresv[i].get())
feedback += f'[{score}/{df.iloc[i,2]}]\n\n'
txt = clean(self.text[i].get("1.0", "end"))
feedback += txt.replace("<name>", firstname)
feedback += "\n\n"
t.insert('0.0', feedback)
pc.copy(feedback)
def moveback(self, event=None):
i = self.idcombo.current()
if i>0:
self.idcombo.current(i-1)
self.idcomboselect()
def moveforward(self, event=None):
i = self.idcombo.current()
if i<len(self.keys)-1:
self.idcombo.current(i+1)
self.idcomboselect()
def loadstudent(self, studentid):
df = self.owner.config.outcomes[self.owner.config.outcomes.id == studentid]
for i, q in enumerate(self.index):
try:
score = df[df.question==q].score.iloc[0]
feedback = df[(df.question==q)].feedback.iloc[0]
except:
score = ""
feedback = ""
if isinstance(score,str):
self.scoresv[i].set("")
elif np.isnan(score):
self.scoresv[i].set("")
else:
x = float(score)
if x.is_integer():
self.scoresv[i].set(int(x))
elif np.isnan(x):
self.scoresv[i].set("")
else:
self.scoresv[i].set(score)
self.text[i].delete('0.0', 'end')
self.text[i].insert('0.0', feedback)
self.updatehint(i)
try:
k = self.combo[i]['values'].index(feedback)
self.combo[i].current(k)
self.updatehint(i)
except:
self.combo[i].current(0)
self.updatehint(i)
self.owner.sb.settext("")
def save(self, event=None):
self.savestudent()
#Reload to refresh ranges
self.loadstudent(self.sid)
def pdf(self, event=None):
self.savestudent()
self.pdfonestudent()
def pdfonestudent(self):
#load and export to pdf
#calling functions to take case of saving if necessary
df = self.owner.config.questions
outcomes = self.owner.config.outcomes[self.owner.config.outcomes.id == self.sid]
outcomes["major"] = [x.split('.',1)[0] for x in outcomes.question]
#Ignore any students who have no feedbacks or no marks
if outcomes.score.sum(skipna=True)==0 and len([x for x in outcomes.feedback if x!=""])==0:
return False
firstname = self.owner.config.classlist.loc[self.owner.config.classlist.id == self.sid, 'first'].iat[0]
name = self.idcombo.get()
pdf = PDF()
if ("module" in self.owner.config.config) and ("assessment" in self.owner.config.config):
title = f'{self.owner.config.config["module"]} {self.owner.config.config["assessment"]}'
else:
title = ""
pdf.set_title(title)
pdf.add_page()
subtitle = "Feedback report for " + name
pdf.print_subheader(subtitle)
if len(df.major.unique())==len(df):
for i in range(self.n):
question = f'{str(df.iloc[i,0])}. {df.iloc[i,1]}'
score = clean(self.scoresv[i].get())
feedback = clean(self.text[i].get("1.0", "end"))
feedback = feedback.replace("<name>", firstname)
#Question with marks available?
if pd.isnull(self.owner.config.questions.iloc[i,2]):
available = ""
else:
available = shortstrnum(self.owner.config.questions.iloc[i,2])
pdf.print_major(question, score, available, feedback)
else:
#Track question change
major = ""
for i in range(self.n):
score = clean(self.scoresv[i].get())
feedback = clean(self.text[i].get("1.0", "end"))
feedback = feedback.replace("<name>", firstname)
#Question with marks available?
if pd.isnull(self.owner.config.questions.iloc[i,2]):
available = ""
else:
available = shortstrnum(self.owner.config.questions.iloc[i,2])
if df.minor[i]=="" and (available=="" or int(available)==0):
question = f'{df.description[i]}'
pdf.print_major(question, score, available, feedback)
elif df.minor[i]=="":
question = f'Question {str(df.major[i])}: {df.description[i]}'
pdf.print_major(question, score, available, feedback)
#Multipart question
else:
if major != df.major[i]:
temp = outcomes[outcomes.major==df.major[i]]
subscore = shortstrnum(sum(temp.score))
temp = df[df.major==df.major[i]]
subtotal = shortstrnum(sum(temp.marks))
question = f'Question {str(df.major[i])} ({subscore}/{subtotal})'
pdf.print_question(question)
question = f'{str(df.iloc[i,0])}. {df.iloc[i,1]}'
pdf.print_minor(question, score, available, feedback)
major = df.major[i]
total = self.total.cget("text")
pdf.print_bold(f"\nTotal mark awarded: {total}")
pdf.output(name + '.pdf', 'F')
return True
def savestudent(self):
q = []
f = []
s = []
for i in range(self.n):
q.append(clean(self.index[i]))
f.append(clean(self.text[i].get("1.0", "end")))
s.append(clean(self.scoresv[i].get()))
df = pd.DataFrame({"id" : [self.sid]* self.n , "question" : q, "score" : s, "feedback" : f})
df['score'] = numericcolumn(df['score'])
#delete existing entries
self.owner.config.outcomes.drop(self.owner.config.outcomes[self.owner.config.outcomes.id == self.sid].index, inplace = True)
#merge updates
self.owner.config.outcomes = pd.concat([self.owner.config.outcomes, df], ignore_index=True)
self.owner.refresh()
self.owner.sb.settext("")
def entryupdate(self, sv, i):
self.owner.sb.settext("Unsaved changes", True)
self.updatetotal()
def textupdate(self, i):
self.owner.sb.settext("Unsaved changes", True)
def updatetotal(self):
total = 0
for sv in self.scoresv:
try:
value = float(sv.get())
total += value
except:
pass
self.total.config(text=total)
self.total.update_idletasks()
def idcomboselect(self):
self.savestudent()
stext = self.idcombo.get()
#This approach worked when the student id was numeric
#self.sid = int("".join([x for x in stext if x.isdigit()]))
self.sid = stext.split("[")[1].split("]")[0]
self.refreshlists()
self.loadstudent(self.sid)
def refreshlists(self):
df = self.owner.config.combinedfeedback
for i in range(self.n):
qid = self.owner.config.questions.iloc[i,0]
values = df[df.question==qid].feedback.tolist()
values.insert(0,"")
self.combo[i]['values'] = values
def updatehint(self, index):
try:
if self.nonscoringquestion[index]:
return
q = self.index[index]
stext = str(self.text[index].get('1.0', 'end-1c'))
stext = clean(stext)
df = self.owner.config.outcomes
df = df[(df.question==q) & (df.feedback==stext)]
values = df.score
values = [x for x in values if isinstance(x,(int,float)) and not np.isnan(x)]
self.hintlabel[index].config(fg="black")
maxscore = self.owner.config.questions.marks[index]
if len(values)==0:
self.hint[index].set("[?]")
else:
a = min(values)
b = max(values)
if b>maxscore:
self.hint[index].set("["+str(a)+"-"+str(b)+"] max exceeded!")
self.hintlabel[index].config(fg="red")
elif a==b:
self.hint[index].set("["+str(a)+"]")
else:
self.hint[index].set("["+str(a)+"-"+str(b)+"]")
except Exception as e:
self.hint[index].set("[??]")
print("error in updatehint:",e)
def comboselect(self, index):
try:
#Update text
stext = self.combo[index].get()
if self.nonscoringquestion[index]:
existing = clean(self.text[index].get("1.0", "end"))
if len(existing)>0:
stext = existing+"\n"+stext
self.text[index].delete('0.0', 'end')
self.text[index].insert('0.0', stext)
#Update other components
try:
#Nothing to update for a pure feedback (no score) box
if not(self.nonscoringquestion[index]):
#Find question from index
df = self.owner.config.questions
#look up question name in class index variable
q = self.index[index]
#Look up and set feedback score
df = self.owner.config.combinedfeedback
score = df.score[(df.question==q) & (df.feedback==stext)].values[0]
score = shortstrnum(score)
self.scoresv[index].set(score)
self.updatehint(index)
self.owner.sb.settext("Unsaved changes", True)
except:
#not found
self.scoresv[index].set(score)
self.hint[index].set("?")
self.owner.sb.settext("Unsaved changes", True)
self.updatetotal()
except:
print("combo select exception")
self.owner.sb.settext("Unsaved changes", True)
self.updatetotal()
def exportAllPDFs(self):
#Save changes for current student just in case
self.save()
self.owner.config.logmessage("\nExporting PDFs (students with feedback only)", True )
#Export all students with outcomes to PDF
count = 0
for i, row in self.owner.config.classlist.iterrows():
sid = row.id
if sid in self.owner.config.outcomes.id.unique():
try:
self.sid = sid
self.idcombo.current(i)
self.loadstudent(sid)
if self.pdfonestudent():
self.owner.config.logmessage(f"PDF exported for {self.idcombo.get()}")
count += 1
else:
self.owner.config.logmessage(f"Skipping {sid}: no feedback recorded")
except:
self.owner.config.logmessage(f"Error exporting PDF for {sid}", alert = True)
else:
self.owner.config.logmessage(f"Skipping {sid}: no feedback recorded")
self.owner.config.logmessage(f"Exported {count} files")
def _configure_canvas(self, event=None):
if self.scrollbaron: #if self.n>self.owner.config.config["maxquestionsonscreen"]:
self.canvas.itemconfig('frame', width=self.canvas.winfo_width())
self.canvas.config(scrollregion=self.canvas.bbox("all"))
else:
self.canvas.itemconfig('frame', width=self.canvas.winfo_width(), height=self.canvas.winfo_height())
def _bind_mouse(self, event=None):
self.canvas.bind_all("<4>", self._on_mousewheel)
self.canvas.bind_all("<5>", self._on_mousewheel)
self.canvas.bind_all("<MouseWheel>", self._on_mousewheel)
def _unbind_mouse(self, event=None):
self.canvas.unbind_all("<4>")
self.canvas.unbind_all("<5>")
self.canvas.unbind_all("<MouseWheel>")
def _on_mousewheel(self, event):
"""Linux uses event.num; Windows / Mac uses event.delta"""
self.canvas.config(scrollregion=self.canvas.bbox("all"))
if event.num == 4 or event.delta > 0:
self.canvas.yview_scroll(-1, "units" )
elif event.num == 5 or event.delta < 0:
self.canvas.yview_scroll(1, "units" )
#------------------------------------------------------------------------------
class Config(tk.Frame):
def __init__(self, parent, owner, configfile = ""):
tk.Frame.__init__(self, parent)
self.owner = owner
self.configfile = configfile
self.config = dict()
self.questioncount = None
self.defaultconfig()
self.btnselect = tk.Button(self, text="Select Config File", anchor='nw')
self.btnselect.bind("<Button-1>", lambda event: self.selectconfigfile())
self.btnselect.grid(row = 0, column = 0, sticky = 'nw', padx=5, pady=5)
self.btncreate = tk.Button(self, text="Create Config File", anchor='n')
self.btncreate.bind("<Button-1>", lambda event: self.createconfigfile())
self.btncreate.grid(row = 1, column = 0, sticky = 'nw', padx=5, pady=5)
self.lblfile = tk.Label(self, text="", anchor="w")
self.lblfile.grid(row = 0, column = 1, sticky = 'new', padx=5, pady=5)
self.btnTotals = tk.Button(self, text="Export Totals CSV", anchor='nw')
self.btnTotals.bind("<Button-1>", lambda event: self.exporttotals())
self.btnTotals.grid(row = 2, column = 0, sticky = 'nw', padx=5, pady=5)
self.btnPDFs = tk.Button(self, text="Export PDFs", anchor='nw')
self.btnPDFs.bind("<Button-1>", lambda event: self.exportAllPDFs())
self.btnPDFs.grid(row = 2, column = 1, sticky = 'nw', padx=5, pady=5)
self.log = scrolledtext.ScrolledText(self, undo=False, height = 20)
self.log.tag_config("highlight", foreground="red")
self.log.grid(row = 3, column = 0, columnspan=2, sticky = 'news', padx=5, pady=5)
self.log.configure(state='disabled')
self.columnconfigure(1, weight=1)
self.rowconfigure(3, weight=1)
#Default data
self.config["outcomes"] = "outcomes.txt"
self.config["sep"] = ","
self.questions = pd.DataFrame({"question":["1","2"], "description":["Introduction", "Analysis"], "marks":[50.0,50.0]})
self.classlist = pd.DataFrame({"id":["888","999"], "first":["john", "jane"], "last":['dear','doe']})
self.feedback = pd.DataFrame({"question":["1","2"], "score":[4,7], "feedback":["good", "bad"]})
self.outcomes = pd.DataFrame({"id":["888","888"], "question":["1","2"], "score":[4,7], "feedback":["good", "bad"]})
#Comment bank is now independent
self.dummydata = True
self.postloaddatafresh()
def postloaddatafresh(self):
self.config["buckets"][-1] = self.config["buckets"][-1] + 10**-10
#Whether defaulted or loaded, ensure data is a consistent state
#canvas permits non-integer ids so don't enforce this
#self.classlist['id'] = pd.to_numeric(self.classlist['id'])
self.classlist['key'] = self.classlist.apply(lambda x: x['last'] + ", " + x['first'] + " [" + str(x['id']) + "]", axis=1)
#canvas permits non-integer ids so don't enforce this
#self.outcomes['id'] = pd.to_numeric(self.outcomes['id'])
self.outcomes.id = self.outcomes.id.apply(str)
self.classlist.id = self.classlist.id.apply(str)
#Convert float columns to avoid strings
self.outcomes['score'] = numericcolumn(self.outcomes['score'])
self.feedback['score'] = numericcolumn(self.feedback['score'])
self.questions['major']=""
self.questions['minor']=""
for i, row in self.questions.iterrows():
temp = row.question.split(".",1)
if len(temp)==1:
self.questions.major[i] = row.question
else:
self.questions.major[i] = temp[0]
self.questions.minor[i] = temp[1]
self.preparesummarytables()
def preparesummarytables(self):
#Start by saving the latest results
filename = self.config["outcomes"]
if not(self.dummydata):
self.outcomes.sort_values(by=['id', 'question'], inplace=True)
self.outcomes.to_csv(filename, sep=self.config["sep"], index = False, header=False)
self.display = self.outcomes.merge(self.classlist, left_on='id', right_on='id', right_index=False, how="left")
self.display = self.display[['id', 'last', 'first', 'question', 'score', 'feedback']]
self.display['score'] = numericcolumn(self.display['score'])
#take copy for merge below
df = self.display[['question','score','feedback']].copy()
#replace returns so all lines visible in summary
self.display.feedback = self.display.feedback.apply(lambda x: x.replace("\n", " "))
f = lambda x: x.iloc[0]
nc = lambda x: len(x.dropna())
tc = lambda x: len([y for y in x if y!=""])
self.totals = self.display.groupby(['id']).agg({'id':f, 'last':f, 'first':f, 'score': 'sum'})
#Create combined table for generic and custom feedback
self.combinedfeedback = self.feedback.copy()
self.scoring = self.questions.question[~np.isnan(self.questions.marks)].tolist()
self.nonscoring = self.questions.question[np.isnan(self.questions.marks)].tolist()
df1 = df[df.question.isin(self.scoring)]
df2 = df[df.question.isin(self.nonscoring)]
if len(df2)>0:
small_dfs = [df1]
for q in df2.question.unique():
values = df2.feedback[df2.question==q].tolist()
values = [str(x).split(chr(10)) for x in values if x != np.nan]
values = flatten(values)
values = [clean(x) for x in values]
small_dfs.append(pd.DataFrame({'question':[q]*len(values),'score':[np.nan]*len(values),'feedback':values}))
df1 = pd.concat(small_dfs, ignore_index=True)
#Merge in a way so that the generic feedback stays at the top
df1.sort_values(['question','feedback'], ascending=True, inplace=True)
df1.drop_duplicates(inplace=True)
#Depricated pandas method
#self.combinedfeedback = self.combinedfeedback.append(df1)
self.combinedfeedback = pd.concat([self.combinedfeedback, df1])
self.combinedfeedback.drop_duplicates(['question','feedback'],inplace=True)
self.combinedfeedback = self.combinedfeedback[self.combinedfeedback.feedback!=""]
#Create dataframe to summarise marks per question and overall totals
#df = self.display.merge(self.questions, left_on='question', right_on='question')
df = pd.merge(self.display.assign(question=self.display.question.astype(str)),
self.questions.assign(question=self.questions.question.astype(str)),
how='left', on='question')
df = df[['question','description', 'score', 'marks','feedback']]
#Extract rows that represent student totals
totals = self.totals[['id', 'last', 'score','score']].copy()
totals['feedback'] = ""
totals.columns = df.columns
totals['question'] = "Total"
totals['description'] = "Sum of marks"
totals['marks'] = self.questions.marks.sum()
#Depricated pandas method
#df = df.append(totals)
df = pd.concat([df, totals])
#Create group by column to aggregate by question not question component
#Need to sum by question before applying summary metrics
#df['q']=df.question.str.split(".", n=1, expand=True)[0]
self.summary = df.groupby(['question']).agg(question=('question', f),
description=('description',f),
available=('marks',f),
mean=('score',np.nanmean),
std=('score',np.nanstd),
low=('score',min),
high=('score',max),
numcount=('score',nc),
textcount=('feedback',tc))
#Drop first column (a duplicate)
#self.display.drop(self.display.columns[0], axis=1, inplace=True)
#Sort
self.display = self.display.sort_values(["last", "first"], ascending = (True, True))
self.totals = self.totals.sort_values(["last", "first"], ascending = (True, True))
df = pd.DataFrame({"score":totals['score'].values})
df.dropna(inplace=True)
df['bin'] = pd.cut(df['score'], self.config["buckets"], right=False).astype(str)
self.distribution = df.groupby('bin').agg(interval = ('bin',f),
count=('bin',len))
def setdefault(self, key, defaultvalue):
if not (key in self.config):
self.config[key] = defaultvalue
def defaultconfig(self):
self.setdefault("sep", ",")
self.setdefault("module", "XXX9999")
self.setdefault("assessment", "Assignment X")
self.setdefault("fontface", "arial")
self.setdefault("fontsize", 12)
self.setdefault("bgcolor", "#f0f0f0")
self.setdefault("feedbackbgcolor", "#fdfdde")
self.setdefault("maxquestionsonscreen", 8)
self.setdefault("feedbacklines", 4)
self.setdefault("questions", "questions.txt")
self.setdefault("feedback", "feedback.txt")
self.setdefault("classlist", "classlist.txt")
self.setdefault("outcomes", "outcomes.txt")
self.setdefault("commentbank", "commentbank.txt")
self.setdefault("apiurl", "https://canvas.qub.ac.uk/")
self.setdefault("apikey", "")
self.setdefault("courseid", "")
self.setdefault("assignmentid", "")
try:
if ("buckets" in self.config):
text = str(self.config["buckets"])
text.replace("[","")
text.replace("]","")
buckets = text.split(",")