-
Notifications
You must be signed in to change notification settings - Fork 0
/
OpenTester.py
480 lines (430 loc) · 19.3 KB
/
OpenTester.py
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
# -*- coding: utf-8 -*-
"""
Created on Mon May 14 12:20:07 2018
@author: 1172334950C
This current code will require PyQT 5.6.2! via QtCore.QT_VERSION_STR
"""
import sys
import os
#import pkg_resources
#pkg_resources.require("PyQt5>=5.6.2")
from PyQt5 import QtCore, QtWidgets, uic, QtGui
#from testevalutils import gui
# imports for parser
import docx2txt
import Question
# Path to the directory containing this .py file (same directory as .ui file)
THIS_DIR = os.path.abspath(os.path.dirname(__file__))
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
# Calls the QDialog __init__ method with the given parent
super().__init__(parent)
# Load the ui file (created by Qt Designer)
ui_path = os.path.abspath(os.path.join(THIS_DIR, 'MainWindow.ui'))
uic.loadUi(ui_path, self)
# initialize test variables
self.test = []
self.total_questions = 0
self.currentQuestion = 0
self.displayedQuestion = None
self.navigatorOpened = True
self.answerOpened = False
self.notesOpened = False
self.numberQuestionsWrong = 0
#navigator buttons
self.navigationButtons = []
# elements
self.checkBoxFlag.setText("No Exam Loaded")
self.textBrowserQuestion.setText("Please load an exam within a DOCX format. Check the sample DOCX to see the format that the tester can read")
# menu bar
self.actionNew.triggered.connect(self.MenuNew)
self.actionNavigator.triggered.connect(self.ToggleNavigator)
#disable question elements until something is loaded via NewMenu
self.pushButtonBack.setEnabled(False)
self.pushButtonNext.setEnabled(False)
self.pushButtonFinish.setEnabled(False)
self.pushButtonFinish.hide()
self.checkBoxFlag.setEnabled(False)
self.checkBoxAnswer1.setEnabled(False)
self.checkBoxAnswer2.setEnabled(False)
self.checkBoxAnswer3.setEnabled(False)
self.checkBoxAnswer4.setEnabled(False)
self.pushButtonCheckAnswer.setEnabled(False)
self.pushButtonNotes.setEnabled(False)
self.textBoxNotes.hide()
self.answerLabel.hide()
self.answerLabel.setStyleSheet("color: green")
self.pushButtonEditNotes.hide()
self.pushButtonSaveNotes.hide()
self.pushButtonCancelNotes.hide()
self.flagImage = QtGui.QPixmap('flag.png')
# TODO: Need to make these customizable via settings menu
# set all button shortcuts here
self.actionNew.setShortcut("Ctrl+N")
self.actionNavigator.setShortcut("N")
self.pushButtonBack.setShortcut("A")
self.pushButtonNext.setShortcut("D")
self.pushButtonFinish.setShortcut("D")
# self.pushButtonBack.setShortcut(QtCore.Qt.Key_Left)
# self.pushButtonNext.setShortcut(QtCore.Qt.Key_Right)
# self.pushButtonFinish.setShortcut(QtCore.Qt.Key_Right)
self.pushButtonCheckAnswer.setShortcut("C")
self.pushButtonNotes.setShortcut("H")
# This decorator (@QtCore.Slot) makes it so this method is automatically
# connected to the "clicked" signal of the "pushButton_Add" widget by
# using the naming convention "on_<ObjectName>_<SignalName>"
@QtCore.pyqtSlot()
def on_actionNew_clicked(self):
print('Menu>New clicked')
@QtCore.pyqtSlot()
def on_pushButtonCheckAnswer_clicked(self):
# save answers prior to checking (this does immediate grading)
print("Check answer clicked")
self.saveState()
self.toggleAnswerText()
# first check if they selected anything
if((not self.checkBoxAnswer1.isChecked()) and (not self.checkBoxAnswer2.isChecked()) and (not self.checkBoxAnswer3.isChecked()) and (not self.checkBoxAnswer4.isChecked())):
print("user got this answer wrong")
self.displayedQuestion.IsWrong()
return
self.gradeQuestion(self.displayedQuestion)
@QtCore.pyqtSlot()
def on_pushButtonNotes_clicked(self):
self.toggleNotesView()
@QtCore.pyqtSlot()
def on_pushButtonFinish_clicked(self):
print("Finish button clicked")
self.saveState()
self.gradeTest()
print("Questions wrong: {}".format(self.numberQuestionsWrong))
numberCorrect = (self.total_questions-1) - self.numberQuestionsWrong
percent = numberCorrect / (self.total_questions-1)
print("You Scored: ({}/{}) {:.2%}".format(numberCorrect, self.total_questions, percent))
msg = QtWidgets.QMessageBox()
msg.setIcon(QtWidgets.QMessageBox.Question)
msg.setText("Are you sure you want to grade this session?")
msg.setWindowTitle("Finish?")
msg.setStandardButtons(QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Cancel)
@QtCore.pyqtSlot()
def on_pushButtonNext_clicked(self):
# print('Next pushed')
self.saveState()
# if not at the last question
# print(self.currentQuestion)
# if (self.currentQuestion is self.total_questions-1):
# self.pushButtonFinish.show()
# self.pushButtonFinish.setEnabled(True)
# self.pushButtonNext.hide()
# else:
# self.pushButtonNext.show()
# self.pushButtonFinish.setEnabled(False)
# self.pushButtonFinish.hide()
self.currentQuestion = self.currentQuestion + 1
self.displayQuestion(self.test[self.currentQuestion])
@QtCore.pyqtSlot()
def on_pushButtonBack_clicked(self):
# print('Back pushed')
self.saveState()
# if(self.currentQuestion is self.total_questions-1):
# self.pushButtonFinish.setEnabled(False)
# self.pushButtonNext.setEnabled(True)
# self.pushButtonFinish.hide()
# self.pushButtonNext.show()
# # go to previous question in test array
self.currentQuestion = self.currentQuestion - 1
self.displayQuestion(self.test[self.currentQuestion])
# Saves any user changes with check box selections
# usually called when next or back button is pushed
def saveState(self):
checkBoxState = self.checkBoxFlag.isChecked()
answers = []
answer1State = self.checkBoxAnswer1.isChecked()
answers.append(answer1State)
answer2State = self.checkBoxAnswer2.isChecked()
answers.append(answer2State)
answer3State = self.checkBoxAnswer3.isChecked()
answers.append(answer3State)
answer4State = self.checkBoxAnswer4.isChecked()
answers.append(answer4State)
self.displayedQuestion.SaveState(checkBoxState, answers)
print('Saved Answer State: {} {} {} {}'.format(answer1State,answer2State,answer3State,answer4State))
def disableButton(self, button):
button.setEnabled(False)
### Helper methods ###
def toggleAnswerText(self):
if(self.answerOpened):
self.answerOpened = False
self.answerLabel.hide()
elif(not self.answerOpened):
self.answerOpened = True
self.answerLabel.show()
# Called only if not graded.
def gradeQuestion(self, Question):
if(Question.GotCorrect() is None):
savedAnswers = Question.LoadAnswers()
print('Loaded Answers are {} {} {} {}'.format(savedAnswers[0],savedAnswers[1],savedAnswers[2],savedAnswers[3]))
gradedAnswers = []
gradedAnswers.append(self.checkAnswer(Question, ' A', savedAnswers[0]))
gradedAnswers.append(self.checkAnswer(Question, ' B', savedAnswers[1]))
gradedAnswers.append(self.checkAnswer(Question, ' C', savedAnswers[2]))
gradedAnswers.append(self.checkAnswer(Question, ' D', savedAnswers[3]))
Question.SaveGrade(gradedAnswers)
# iterate through all 4 answers to determine if right or wrong
for x in gradedAnswers:
if x is True:
print("C")
Question.IsRight()
continue
if x is False:
print("W")
Question.IsWrong()
return
print("User got this question correct? {}".format(Question.GotCorrect()))
# Should only be called if question is graded and loads previous answers
def displayGradedAnswers(self, Question):
gradedAnswers = Question.LoadGrade()
# TODO: Need to implement this
# self.checkBoxAnswer1.setChecked(self.gradeToTickLogic(gradedAnswers[0]))
# self.checkBoxAnswer2.setChecked(self.gradeToTickLogic(gradedAnswers[1]))
# self.checkBoxAnswer3.setChecked(self.gradeToTickLogic(gradedAnswers[2]))
# self.checkBoxAnswer4.setChecked(self.gradeToTickLogic(gradedAnswers[3]))
# used to return value of checkbox
def gradeToTickLogic(grade):
if(grade is True):
return True
elif(grade is False):
return False
elif(grade is None):
return False
# Toggles the view of the solution textwindow (bottom text view)
def toggleNotesView(self):
if(self.notesOpened):
self.notesOpened = False
self.textBoxNotes.hide()
self.pushButtonEditNotes.hide()
self.pushButtonSaveNotes.hide()
self.pushButtonCancelNotes.hide()
else:
self.notesOpened = True
self.textBoxNotes.show()
self.pushButtonEditNotes.show()
self.pushButtonSaveNotes.show()
self.pushButtonCancelNotes.show()
# Checks current answers against the user's selection
# Display green for correct and red for incorrect
def checkAnswer(self, Question, filterKeyword, checkBoxState):
if(filterKeyword in Question.ShowAnswer()):
if(not checkBoxState):
# checkBox.toggle()
# checkBox.setStyleSheet("color: red")
return False
elif(checkBoxState):
# checkBox.setStyleSheet("color: green")
return True
if(filterKeyword not in Question.ShowAnswer()):
if(not checkBoxState):
Question.IsRight()
return True
elif(checkBoxState):
# checkBox.toggle()
return False
# Display question elements of the current number by referencing the question object itself and number
def displayQuestion(self, Question):
# display question from object we've parsed
# Add one due to index 0
print(self.currentQuestion)
num = self.currentQuestion + 1
self.checkBoxFlag.setText("Question {} of {}".format(num, len(self.test)))
# if graded display color
self.textBrowserQuestion.setText(Question.question)
self.checkBoxAnswer1.setText(Question.AnswerSetAt(0))
self.checkBoxAnswer2.setText(Question.AnswerSetAt(1))
self.checkBoxAnswer3.setText(Question.AnswerSetAt(2))
self.checkBoxAnswer4.setText(Question.AnswerSetAt(3))
self.textBoxNotes.setPlainText(Question.Explain())
self.answerLabel.setText(Question.ShowAnswer())
# if user has not been graded (userCorrect None) then set to black
if(Question.GotCorrect() is None):
self.checkBoxAnswer1.setStyleSheet("color: black")
self.checkBoxAnswer2.setStyleSheet("color: black")
self.checkBoxAnswer3.setStyleSheet("color: black")
self.checkBoxAnswer4.setStyleSheet("color: black")
self.checkBoxFlag.setChecked(Question.IsFlagged())
self.checkBoxAnswer1.setChecked(Question.LoadAnswer(0))
self.checkBoxAnswer2.setChecked(Question.LoadAnswer(1))
self.checkBoxAnswer3.setChecked(Question.LoadAnswer(2))
self.checkBoxAnswer4.setChecked(Question.LoadAnswer(3))
# if already graded previously, then display the answer
elif(Question.GotCorrect() is not None):
self.displayGradedAnswers(Question)
# Always hide the solutions box whenever we load a question
self.answerOpened = False
self.notesOpened = False
self.answerLabel.hide()
self.textBoxNotes.hide()
self.pushButtonEditNotes.hide()
self.pushButtonSaveNotes.hide()
self.pushButtonCancelNotes.hide()
#if first question disable next button
if(num is 1):
self.pushButtonBack.setEnabled(False)
elif (num is self.total_questions-1):
self.pushButtonNext.setEnabled(False)
self.pushButtonNext.hide()
self.pushButtonFinish.setEnabled(True)
self.pushButtonFinish.show()
else:
self.pushButtonNext.setEnabled(True)
self.pushButtonNext.show()
self.pushButtonFinish.hide()
self.pushButtonBack.setEnabled(True)
self.pushButtonNext.setText("Next")
self.displayedQuestion = self.test[self.currentQuestion]
# Create a txt file "_processed" to read from
def convertDocx(self, filename):
rawtext = docx2txt.process(filename)
f = open(filename[:-5] + '_processed.txt', 'w')
f.write(rawtext)
f.close()
def addToTest(self, Question):
self.test.append(Question)
def clearObjects(self):
self.test = []
self.total_questions = 0
self.currentQuestion = 0
self.displayedQuestion = 1
def MenuNew(self):
# print('clicked on new')
path = QtWidgets.QFileDialog.getOpenFileName(self, "Select a document", "/home", "Word Documents (*.docx *doc)")
file = os.path.basename(path[0])
if(file[0] is not ''):
# print('Change doc')
self.clearObjects()
self.setWindowTitle("OpenTester - " + path[0])
self.convertDocx(file)
self.parse(file)
self.displayQuestion(self.test[0])
# Standard element initialization Enable all except for the Back button
self.pushButtonNext.setEnabled(True)
self.checkBoxFlag.setEnabled(True)
self.checkBoxAnswer1.setEnabled(True)
self.checkBoxAnswer2.setEnabled(True)
self.checkBoxAnswer3.setEnabled(True)
self.checkBoxAnswer4.setEnabled(True)
self.pushButtonCheckAnswer.setEnabled(True)
self.pushButtonNotes.setEnabled(True)
self.numberQuestionsWrong = 0
self.populateNavigator()
# TODO:
# specific only for buttons in the navigator pane
def navigateToQuestion(self, num):
index = num-1
self.saveState()
print("Jumping to question {} of {}".format(num, self.total_questions-1))
self.currentQuestion = index
if(num is self.total_questions-1):
self.pushButtonFinish.show()
self.pushButtonFinish.setEnabled(True)
self.pushButtonNext.hide()
else:
self.pushButtonNext.show()
self.pushButtonFinish.setEnabled(False)
self.pushButtonFinish.hide()
self.displayQuestion(self.test[index])
def populateNavigator(self):
number = 0
for q in self.test:
number += 1
btn = QtWidgets.QPushButton()
btn.setText("Q{}".format(number))
btn.clicked.connect(lambda state, x = number: self.navigateToQuestion(x))
self.navigationButtons.append(btn)
for buttons in self.navigationButtons:
self.navigationLayout.addWidget(buttons)
def ToggleNavigator(self):
print('Toggle Navigator')
if(self.navigatorOpened):
self.navigatorPane.hide()
self.navigatorOpened = False
else:
self.navigatorPane.show()
self.navigatorOpened = True
# called once the user hits the finish button
def gradeTest(self):
print("Grading test")
# loop through all the questions
for q in self.test:
# loop through all question objects where we havent graded
if q.GotCorrect() is None:
self.gradeQuestion(q)
# once graded check if we got it right
# Count if already graded ahead of time (by using check answer button)
if q.GotCorrect() is False:
self.numberQuestionsWrong = self.numberQuestionsWrong + 1
# Parse from the txt file
def parse(self, filename):
question_block = False
answer_block = False
explain_block = False
with open(filename[:-5] + '_processed.txt') as openfileobject:
# set our variable for the question
q_number = None
q_question = ""
q_options = []
q_answer = None
q_explain = ""
for line in openfileobject:
# line.split('\n')
# print(line)
# if only a new line then skip it
if(line == "\n"):
continue
if (not question_block and "QUESTION" in line):
question_block = True
q_number = line
self.total_questions = self.total_questions + 1
# skip to next line to check for its properties
continue
# if found next qustion then get each propertiy and add them
if(question_block):
#keep adding lines until we reach the end
if("?") in line:
question_block = False
answer_block = True
q_question = q_question + line
continue
if(answer_block):
if("A. " in line or "B. " in line or "C. " in line or "D. " in line):
line = line[:-1]
q_options.append(line)
continue
if("Correct Answer:") in line:
q_answer = line
answer_block = False
explain_block = True
continue
if(explain_block):
if("Reference" not in line):
q_explain = q_explain + line
continue
else:
explain_block = False
# Add everything into one question
new_question = Question.Question(q_number, q_question, q_options, q_answer, q_explain)
self.addToTest(new_question)
# Reset our question
q_number = None
q_question = ""
q_options = []
q_answer = None
q_explain = ""
if __name__ == '__main__':
"""Main function that tests the dialog."""
app = QtWidgets.QApplication.instance()
if not app:
app = QtWidgets.QApplication([])
# gui.handle_unhandled()
print(QtCore.QT_VERSION_STR)
w = MainWindow()
w.show()
app.exec_()