-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQAPI.py
More file actions
1529 lines (1300 loc) · 69.9 KB
/
QAPI.py
File metadata and controls
1529 lines (1300 loc) · 69.9 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
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
import json
import fitz, docx2txt
from pptx import Presentation
from cryptography.fernet import Fernet
from tkinter import filedialog
import Levenshtein as lev
from openai import OpenAI
import requests
from prompts import *
from keys import CONTEXT_CRYPTO_KEY
from tkinter import messagebox, Tk
import random
import threading
import time
CONTEXT_CUTOFF = 150
THREAD_TIMEOUT_TIME = 20
MAX_THREADS = 5
class StopThread(Exception):
pass
def call_gpt(domain, context, api_key, model, system, request, image_embed):
return_response = []
# create a background function to make the api call
def internal_gpt_call():
# initalize client and domain/context segments
client = OpenAI(api_key=api_key)
domain_c = "Domain: " + domain + "\n"
context_c = "Context: " + get_random_context_segment(context, CONTEXT_CUTOFF) + "\n"
model_c = determine_model_str_from_index(model)
try:
response = client.chat.completions.create (
model = model_c,
messages = [
{"role": "system", "content": system},
{
"role":"user",
"content": [
{"type": "text", "text": domain_c + context_c + request},
{"type": "image_url", "image_url": {
"url": image_embed
}}
] if image_embed != "" else [
{"type": "text", "text": domain_c + context_c + request}
]
}
]
)
return_response.append(response.choices[0].message.content)
except Exception as e:
return_response.append(f"Error: {str(e)}")
# push the response to a thread and wait for it using a timeout length
thread = threading.Thread(target=internal_gpt_call)
thread.start()
thread.join(THREAD_TIMEOUT_TIME)
# check if the thread timed out
if thread.is_alive():
raise TimeoutError("GPT call timed out!")
return return_response[0]
def determine_model_str_from_index(model):
return "gpt-4o-mini" if model == 0 else ("gpt-4o" if model == 1 else "o1-mini")
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
def all_at_once_numaric_comparision_grading(answers, correct_answers):
# get a list of similarities and copy the collections
similarities = []
ans = answers.copy()
cor_ans = correct_answers.copy()
# iterate through the numbers in the ans list
for answer in ans:
# check if this answer is numaric
if not is_number(answer):
similarities.append(0.0)
continue
most_similar = ""
best_similarity = 0.0
# iterate through the cor_ans list
for correct in cor_ans:
# get the percent distance from this answer
distance = abs(float(answer) - float(correct)) / float(correct)
# get a ratio of value with a 5% confidence
similarity = 1 - min(distance / 0.05, 1)
# compare with the score already logged for this answer
if similarity > best_similarity:
# save as best, remember with what string
best_similarity = similarity
most_similar = correct
# check if a record was found to be similar
if best_similarity == 0.0:
# append a score of 0
similarities.append(0.0)
# continue
continue
# record this similarity and remove the most similar string from answer collection
similarities.append(best_similarity)
cor_ans.remove(most_similar)
# return results
return similarities
def all_at_once_answer_comparision_grading(answers, correct_answers):
# get a list of similarities and copy the lowercase conversion collections
similarities = []
ans = [ans.lower() for ans in answers]
cor_ans = [ans.lower() for ans in correct_answers]
# iterate through the strings in the ans list
for answer in ans:
most_similar = ""
best_similarity = 0.0
best_diff = 0.0
# iterate through the cor_ans list
for correct in cor_ans:
# get the Levenshtein similarity score between these 2 strinsg
distance = lev.distance(answer, correct)
max_length = max(len(answer), len(correct))
difference = (distance / max_length)
# get a ratio of value with 25% confidence
similarity = 1 - min(difference/.25, 1)
# compare with the score already logged for this answer
if similarity > best_similarity:
# save as best, remember with what string
best_similarity = similarity
most_similar = correct
best_diff = difference
# check if a record was found to be similar
if best_similarity == 0.0:
# append a score of 0
similarities.append(0.0)
# continue
continue
# record this similarity and remove the most similar string from answer collection and this answer
similarities.append(best_similarity)
cor_ans.remove(most_similar)
# return results
return similarities
def answer_comparision_grading(answer, correct_answer):
# get the Levenshtein similarity score between these 2 strinsg
distance = lev.distance(answer, correct_answer)
max_length = max(len(answer), len(correct_answer))
difference = (distance / max_length)
# get a ratio of value with 25% confidence
similarity = 1 - min(difference/.25, 1)
# return this similarity
return similarity
def validate_question_object(object):
# ensure we have a question text and q_index, otherwise fail immediately
if not 'Question' in object or not 'Q' in object:
print("@FAIL (???): Object too corrupted to be a valid question object. Terminating...")
messagebox.showerror("Failure @?", "Unable to parse question header. File might be corrupted!")
return False
# for debugging, grab the question's index
q_index = object['Q']
# determine the question's type
try:
if not 'Type' in object:
print(f'@WARN ({q_index}): Question missing its type, defaulting to MC!')
object['Type'] = 'MC'
match object['Type']:
case "MC":
# count the incorrect and correct answers and ensure they enumerate correctly
num_cor = 0
max_cor = 0
num_incor = 0
max_incor = 0
# iterate over the keys
for key, ___ in object.items():
if not key.startswith(("C", "A")):
continue
k_prefix = key[0]
k_val = int(key[1:])
# check for a correct key
if k_prefix == "C":
# count this key and log if this key is the largest found so far
num_cor += 1
max_cor = max(max_cor, k_val)
# check for a incorrect key
if k_prefix == "A":
# count this key and log if this key is the largest found so far
num_incor += 1
max_incor = max(max_incor, k_val)
# check if we are missing correct answers or incorrect answers entirely
if num_cor == 0:
print(f'@FAIL ({q_index}): Question missing correct answers. Terminating...')
messagebox.showerror(f"Failure @{q_index}", "Question missing correct answers, unable to import!")
return False
if num_incor == 0:
print(f'@FAIL ({q_index}): Question missing incorrect answers. Terminating...')
messagebox.showerror(f"Failure @{q_index}", "Question missing incorrect answers, unable to import!")
return False
# check if the counts match
if num_cor != max_cor:
print(f'@FAIL ({q_index}): Question correct answer count does not match maximal index. Terminating...')
messagebox.showerror(f"Failure @{q_index}", "Correct answers are incorrectly indexed, unable to import!")
return False
if num_incor != max_incor:
print(f'@FAIL ({q_index}): Question incorrect answer count does not match maximal index. Terminating...')
messagebox.showerror(f"Failure @{q_index}", "Incorrect answers are incorrectly indexed, unable to import!")
return False
# check for a forced state, default to "Either" (0)
if not "Forced" in object:
print(f'@WARN ({q_index}): Question lacking "Forced" flag, defaulting to Either (0)!')
object["Forced"] = "0"
# check for illegal keys
for key, ___ in object.items():
if key == "Type":
continue
if key.startswith(("T", "D", "Guidelines", "Format", "Language")):
print(f'@FAIL ({q_index}): MC question contains illegal key: "{key}" Terminating...')
messagebox.showerror(f"Failure @{q_index}", f"Multiple choice question contains illegal key {key}, unable to import!")
return False
case "TD":
# count the terms and definitions and ensure they enumerate correctly
num_terms = 0
max_terms = 0
num_defines = 0
max_defines = 0
# iterate over the keys
for key, ___ in object.items():
if not key.startswith(("T", "D")) or key.startswith("Ty"):
continue
k_prefix = key[0]
k_val = int(key[1:])
# check for a term key
if k_prefix == "T":
# count this key and log if this key is the largest found so far
num_terms += 1
max_terms = max(max_terms, k_val)
# check for a definition key
if k_prefix == "D":
# count this key and log if this key is the largest found so far
num_defines += 1
max_defines = max(max_defines, k_val)
# check if we are missing terms or definitions entirely
if num_terms == 0:
print(f'@FAIL ({q_index}): Question missing terms. Terminating...')
messagebox.showerror(f"Failure @{q_index}", "Question is missing term keys, unable to import!")
return False
if num_defines == 0:
print(f'@FAIL ({q_index}): Question missing definitions. Terminating...')
messagebox.showerror(f"Failure @{q_index}", "Question is missing definition keys, unable to import!")
return False
# check if the counts match
if num_terms != max_terms:
print(f'@FAIL ({q_index}): Question term count does not match maximal index. Terminating...')
messagebox.showerror(f"Failure @{q_index}", "Terms are incorrectly indexed, unable to import!")
return False
if num_defines != max_defines:
print(f'@FAIL ({q_index}): Question definition count does not match maximal index. Terminating...')
messagebox.showerror(f"Failure @{q_index}", "Definitions are incorrectly indexed, unable to import!")
return False
# check for a forced state, default to "Either" (0)
if not "Forced" in object:
print(f'@WARN ({q_index}): Question lacking "Forced" flag, defaulting to Either (0)!')
object["Forced"] = "0"
# check for illegal keys
for key, ___ in object.items():
if key == "Type":
continue
if key.startswith(("C", "A", "Guidelines", "Format", "Language")):
print(f'@FAIL ({q_index}): TD question contains illegal key: "{key}" Terminating...')
messagebox.showerror(f"Failure @{q_index}", f"Term-definition question contains illegal key {key}, unable to import!")
return False
case "Ess":
# fail if we lack guidelines
if not "Guidelines" in object:
print(f'@FAIL ({q_index}): Essay question missing guidelines. Terminating...')
messagebox.showerror(f"Failure @{q_index}", "Question is missing grading guidelines, unable to import!")
return False
# check for format specification, and default to "0" if missing
if not "Format" in object:
print(f'@WARN ({q_index}): Essay question missing format, defaulting to Explaination (0)!')
object["Format"] = "0"
# check for difficulty specification, and default to "1" if missing
if not "UseGL" in object:
print(f'@WARN ({q_index}): Essay question missing toggle on if it uses guidelines, defaulting to Does not (0)!')
object["UseGL"] = "0"
# fail if format is "Code" and the language is not specified
if not "Language" in object or (object["Format"] == "1" and object["Language"] == "N/A"):
print(f'@FAIL ({q_index}): Essay question missing language when "Code" was specified. Terminating...')
messagebox.showerror(f"Failure @{q_index}", "Question is missing a language specification when 'Code' was specified, unable to import!")
return False
# check for illegal keys
for key, ___ in object.items():
if key == "Type":
continue
if key.startswith(("T", "D", "A", "C")) and key != "Difficulty":
print(f'@FAIL ({q_index}): Essay question contains illegal key: "{key}" Terminating...')
messagebox.showerror(f"Failure @{q_index}", f"Essay question contains illegal key {key}, unable to import!")
return False
case _:
# fail for invalid type
print(f'@FAIL ({q_index}): Question failed validation due to corrupted type: "{object["Type"]}". Terminating...')
messagebox.showerror(f"Failure @{q_index}", f"{object["Type"]} is not a valid question type, unable to import!")
return False
except Exception as e:
print(f'@FAIL ({q_index}): Question failed validation due to exception: "{e}". Terminating...')
messagebox.showerror(f"Failure @{q_index}", f"Importing this question generated the following exception: {e}, unable to import!")
return False
# check for an explaination, default to "No explaination was provided :("
if not "Explaination" in object:
print(f'@WARN ({q_index}): Question lacks explaination field, default provided!')
object["Explaination"] = "No explaination was provided :("
# if we make it here, then this question must be valid!
return True
def get_random_context_segment(context, cutoff):
# split the context segment into words and randomly choose a segment of those words based on the cuttoff
context_words = context.split(" ")
start_point = random.choice(range(0, max(len(context_words) - cutoff, 1)))
return " ".join(context_words[start_point:min(start_point+cutoff, len(context_words))]) + "\n"
def remove_backticked_imbeds(s):
# split the input based on backticked imbeds
imbeds = s.split('```')
result = ""
# iterate through the imbeds
for i, chunk, in enumerate(imbeds):
if i % 2 == 0:
# not an embed, skip
result += chunk
else:
# readd if not an image embed
if not chunk.startswith("img:"):
result += "```" + chunk + "```"
return result
def get_image_embed_links_if_any(question):
# Split the question content into chunks to search for the first img embed
imbeds = question.split('```')
for i, chunk in enumerate(imbeds):
if i % 2 != 0:
# determine what imbed we are using
header = chunk.split(':')[0]
if header == "img":
# we are imbedding an image, remove header from string
link = chunk[4:]
# fetch the image using a request
response = requests.get(link)
# check if successful
if response.status_code == 200:
# return link
return link
else:
# return blank
return ""
# return blank if no link is found
return ""
def grade_multiple_choice_question(question, answers, frqComp):
# collect the correct answers of the question
correct_answers = []
for key, val in question.items():
if key.startswith("C"):
correct_answers += [val]
# determine if we are doing numaric comparision grading
is_numaric = all([is_number(ans) for ans in correct_answers])
# determine if this question is prosed as a FRQ
if frqComp:
max_weighted_score = len(correct_answers)
score = 0
# compare each answer choice against all possible correct answers and take the one with the best score (answers are written and thus may partially match)
if is_numaric:
# get the best matching answer-score pair
results = all_at_once_numaric_comparision_grading(answers, correct_answers)
# add the results sum to the total score
score += sum(results)
else:
# get the best matching answer-score pair
results = all_at_once_answer_comparision_grading(answers, correct_answers)
# add the results sum to the total score
score += sum(results)
# scale the score out of 1
score = score / max_weighted_score
else:
# answers must absolutely match, so we can simply just do a symmetric difference of the 2 sets
missing_matches = [x for x in list(set(answers).symmetric_difference(set(correct_answers))) if x != "NanX"]
print(answers)
print(correct_answers)
print(missing_matches)
# the score is the inverse of the ratio of missing matches over total correct answers
score = 1 - (min(len(missing_matches), len(correct_answers)) / len(correct_answers))
return int(score * 10)
def grade_matching_question(question, answers, frqComp):
# collect the terms in the order that they appear from the question
matchings = sum(1 for key in question if key.startswith("D"))
terms = []
for i in range(matchings):
terms += [question["T" + str(i + 1)]]
# determine if this question is prosed as a FRQ
max_weighted_score = len(terms)
score = 0
if frqComp:
# iterate over the answers and compare them to their respective term, where score can be partial if the provided answer is close
score = sum([answer_comparision_grading(ans, term) for ans, term in zip(answers, terms)]) / max_weighted_score
else:
# iterate over the answers and just check if they are equal, no partial credit
score = sum([1 if ans == term else 0 for ans, term in zip(answers, terms)]) / max_weighted_score
return int(score * 10)
def grade_question(question, Q_index, answers, frqComp, domain, context, api_key, model):
# grade this question differently depending on its type
match question['Type']:
case "MC":
score = grade_multiple_choice_question(question, answers, frqComp)
case "TD":
score = grade_matching_question(question, answers, frqComp)
case "Ess":
# score is completely determined by prompt through assessing the answer that the user typed in and how it adheres to the question guidelines
score = grade_essay_question(question, answers[0], domain, context, api_key, model)
# scale the score to 10 points and return the result
return int(score * 10)
def grade_essay_question(question, answer, domain, context, api_key, model):
# First retrieve an image embed if it exists
img_link = get_image_embed_links_if_any(question["Question"])
# determine how the student response will be graded
match question['Format']:
case "0": # Explaination
format = "Graded as an explaination; "
case "1": # Code
format = "Graded as code written in " + question['Language'] + "; "
case "2": # Proof
format = "Graded as a proof; "
# Get the response from the GPT
try:
system_content = SYSTEM_INTRO + ((REQUEST_EXAMPLE_GRADE_ESSAY_GUIDELINES) if question["UseGL"] else (REQUEST_EXAMPLE_GRADE_ESSAY)) + SYSTEM_CONCLUSION + (IMG_SPECIFICATION if img_link != "" else "")
response_content = format + "Question: "+ remove_backticked_imbeds(question["Question"]) + (("Guidelines: " + question["Guidelines"] + "\n" + REQUEST_GRADE_ESSAY_GUIDELINES) if question["UseGL"] else (REQUEST_GRADE_ESSAY)) + "\nInput Response: " + answer
response = call_gpt(domain, context, api_key, model, system_content, response_content, img_link)
# split the response into the grade and explaination
result = response.strip().replace('\\\\', '\\')
grade = int(result.split("~")[0])
explaination = result.split("~")[1]
# override the question's explaination with the one the AI cooked up
question["Explaination"] = explaination
except TimeoutError:
# fail to grade
messagebox.showerror("GPT Call Fail!", "A call to ChatGPT to grade an essay question timed out! So it will unfortunately not be graded.")
grade = 10
# return the score
return int(grade)
def generate_permutation_from_question(question, domain, context, api_key, model, t_results = None):
# create a new question object
new_question = {}
# seed the question text with generated permutations (permutation questions dont have an index as they are not saved)
new_question['Q'] = str(-1)
new_question['Forced'] = str(1)
new_question['Question'] = seed_permutations_in_question(question["Question"], domain, context, api_key, model)
new_question['Type'] = question['Type']
# from the new question header text, generate new answer choices that emulate the same pattern as the input
match new_question['Type']:
case "MC":
fill_multiple_choice_options(new_question, domain, context, api_key, model)
case 'TD':
fill_matching_options(new_question, False, domain, context, api_key, model)
case 'Ess':
fill_essay_guidelines(new_question, domain, context, api_key, model)
# finally, generate the explaination for the question.
generate_explaination_for_question(new_question, domain, context, api_key, model)
# push results to threads, otherwise return
if t_results is None:
return new_question
else:
t_results.append(new_question)
def unscramble_matching(question, domain, context, api_key, model):
# First retrieve an image embed if it exists
img_link = get_image_embed_links_if_any(question["Question"])
# get the list of terms and definitions for appropriate matching
pair_count = sum(1 for key in question if key.startswith("D"))
terms = []
definitions = []
for i in range(pair_count):
terms += [question["T" + str(i + 1)]]
definitions += [question["D" + str(i + 1)]]
# Get the response from the GPT
try:
system_content = SYSTEM_INTRO + REQUEST_EXAMPLE_UNSCRAMBLE + SYSTEM_CONCLUSION + (IMG_SPECIFICATION if img_link != "" else "")
response_content = REQUEST_UNSCRAMBLE + "Question: " + remove_backticked_imbeds(question["Question"]) + "Terms: " + "\n".join([f"{i + 1}. {term}" for i, term in enumerate(terms)]) + "\nDefinitions: " + "\n".join([f"{i + 1}. {defin}" for i, defin in enumerate(definitions)])
response = call_gpt(domain, context, api_key, model, system_content, response_content, img_link)
# the result is a list of definition indexes in the order of how they are supposed to match with the term indexes
try:
# using the list, simply iterate in the order of the definitions and update them according to our array of numbers
matchings = [int(num) for num in response.split(",")]
for i in range(pair_count):
question['D' + str(i + 1)] = definitions[matchings[i] - 1]
except Exception as e:
# report if this generates an exception when parsing
messagebox.showerror("GPT Error!", "ChatGPT was unable to unscrable these terms and definitions.")
print("GPT failed the matching: " + str(e))
return
except TimeoutError:
# fail to unscramble
messagebox.showerror("GPT Call Fail!", "The call to unscramble these terms and definitions timed out, so they were not unscrambled!")
return
def parallelized_blank_fill(question, banned_items, id, domain, context, api_key, model):
# First retrieve an image embed if it exists
img_link = get_image_embed_links_if_any(question["Question"])
# convert the banned items into a stringed list
banned_list = ", ".join(banned_items)
if question["T" + str(id)] == "" and question["D" + str(id)] != "":
# Get the response from the GPT
try:
system_content = SYSTEM_INTRO + REQUEST_EXAMPLE_GENERATE_TERM.replace("{X}", banned_list) + SYSTEM_CONCLUSION + (IMG_SPECIFICATION if img_link != "" else "")
response_content = REQUEST_GENERATE_TERM + "Question: "+ remove_backticked_imbeds(question["Question"]) + "Definition: " + question["D" + str(id)]
response = call_gpt(domain, context, api_key, model, system_content, response_content, img_link)
# idealy, the response should just be as simple as the term to use here, so we can 1-to-1 use it without any further parsing!
# regardless, at least sanitize the response a little bit.
question["T" + str(id)] = response.strip().replace('\\\\', '\\')
# add to term log to make sure we dont see this term again as a duplicate!
banned_items += [question["T" + str(id)]]
except TimeoutError:
# fail
messagebox.showerror("GPT Call Fail!", "The call to ChatGPT to fill in the term timed out!")
return
if question["D" + str(id)] == "" and question["T" + str(id)] != "":
# Get the response from the GPT
try:
system_content = SYSTEM_INTRO + REQUEST_EXAMPLE_GENERATE_DEFINITION.replace("{X}", banned_list) + SYSTEM_CONCLUSION + (IMG_SPECIFICATION if img_link != "" else "")
response_content = REQUEST_GENERATE_DEFINITION + "Question: "+ remove_backticked_imbeds(question["Question"]) + "Term: " + question["T" + str(id)]
response = call_gpt(domain, context, api_key, model, system_content, response_content, img_link)
# idealy, the response should just be as simple as the term to use here, so we can 1-to-1 use it without any further parsing!
question["D" + str(id)] = response.strip().replace('\\\\', '\\')
# add to term log to make sure we dont see this term again as a duplicate!
banned_items += [question["D" + str(id)]]
except TimeoutError:
# fail
messagebox.showerror("GPT Call Fail!", "The call to ChatGPT to fill in the definition timed out!")
return
def fill_matching_options(question, scrambled, domain, context, api_key, model):
# iterate through the term definition pairs of the question
matchings = sum(1 for key in question if key.startswith("D"))
terms = []
definitions = []
for i in range(matchings):
if question["T" + str(i + 1)] != "":
terms += [question["T" + str(i + 1)]]
elif question["D" + str(i + 1)] != "":
definitions += [question["D" + str(i + 1)]]
# if we have no content, generate some terms relating to the question content, then populate those terms with definitions later on.
if matchings == 0:
# First retrieve an image embed if it exists
img_link = get_image_embed_links_if_any(question["Question"])
# Get the response from the GPT
try:
system_content = SYSTEM_INTRO + REQUEST_EXAMPLE_INITAL_TERMS + SYSTEM_CONCLUSION + (IMG_SPECIFICATION if img_link != "" else "")
response_content = REQUEST_INITAL_TERMS + remove_backticked_imbeds(question["Question"])
response = call_gpt(domain, context, api_key, model, system_content, response_content, img_link)
# Split the response and use that as our new defacto term list
terms = [term.strip() for term in response.split(',')]
# Create keys in our question according to the number of terms that we have
for i in range(len(terms)):
question["T" + str(i + 1)] = terms[i]
question["D" + str(i + 1)] = ""
matchings = len(terms)
except TimeoutError:
# fail
messagebox.showerror("GPT Call Fail!", "The call to ChatGPT to generate terms timed out!")
return
# fill the blanks in parallel based on what component is missing:
failsafe = 0
while any(question[f"T{i}"] == "" for i in range(1, matchings + 1)) or any(question[f"D{i}"] == "" for i in range(1, matchings + 1)) and failsafe < 5:
threads = []
t_gen = []
d_gen = []
for i in range(matchings):
if question["T" + str(i + 1)] == "" and question["D" + str(i + 1)] != "":
t_gen.append(i)
threads.append(threading.Thread(target=parallelized_blank_fill, args=(question, terms, i+1, domain, context, api_key, model)))
threads[-1].start()
elif question["D" + str(i + 1)] == "" and question["T" + str(i + 1)] != "":
d_gen.append(i)
threads.append(threading.Thread(target=parallelized_blank_fill, args=(question, definitions, i+1, domain, context, api_key, model)))
threads[-1].start()
for thread in threads:
thread.join(THREAD_TIMEOUT_TIME)
# check if the thread timed out
if thread.is_alive():
raise TimeoutError("GPT call timed out!")
threads.clear()
# check for duplicates and "remove" them if necessary
if len(terms) != len(set(terms)):
dupe_terms = [item for item in set(terms) if terms.count(item) > 1 for _ in range(terms.count(item) - 1)]
print("Duplicate terms! " + str(dupe_terms))
for i in range(matchings):
if question["T" + str(i + 1)] in dupe_terms and i + 1 in t_gen:
dupe_terms.remove(question["T" + str(i + 1)])
question["T" + str(i + 1)] = ""
if len(definitions) != len(set(definitions)):
dupe_terms = [item for item in set(definitions) if definitions.count(item) > 1 for _ in range(definitions.count(item) - 1)]
print("Duplicate definitions! " + str(dupe_terms))
for i in range(matchings):
if question["D" + str(i + 1)] in dupe_terms and i + 1 in d_gen:
dupe_terms.remove(question["D" + str(i + 1)])
question["D" + str(i + 1)] = ""
t_gen.clear()
d_gen.clear()
failsafe += 1
if failsafe == 5:
print("FAILSAFE TRIGGERED! TOO MANY LOOPS!")
# once the terms and definitions are populated, if prompeted unscramble them to be the correct matchings
if(scrambled):
unscramble_matching(question, domain, context, api_key, model)
def fill_essay_guidelines(question, domain, context, api_key, model):
# First retrieve an image embed if it exists
img_link = get_image_embed_links_if_any(question["Question"])
# determine how the student response will be graded
match question['Format']:
case "0": # Explaination
format = "Graded as an explaination; "
case "1": # Code
format = "Graded as code written in " + question['Language'] + "; "
case "2": # Proof
format = "Graded as a proof; "
# Check if we are missing the guidelines to the question
if question["Guidelines"] == "":
# Get the response from the GPT
try:
system_content = SYSTEM_INTRO + REQUEST_EXAMPLE_GENERATE_ESSAY_GUIDELINES + SYSTEM_CONCLUSION + (IMG_SPECIFICATION if img_link != "" else "")
response_content = REQUEST_GENERATE_ESSAY_GUIDELINES + format + "Question: "+ remove_backticked_imbeds(question["Question"])
response = call_gpt(domain, context, api_key, model, system_content, response_content, img_link)
# idealy, the response should just be as simple as the guidelines for which we follow, so we just sanitize and use it directly
question["Guidelines"] = response.strip().replace('\\\\', '\\')
except TimeoutError:
# fail
messagebox.showerror("GPT Call Fail!", "The call to ChatGPT to generate essay guidelines timed out!")
return
def fill_multiple_choice_options(question, domain, context, api_key, model):
# First retrieve an image embed if it exists
img_link = get_image_embed_links_if_any(question["Question"])
# Determine what parts of the question we are missing
# Generate the correct answer(s) and incorrect answer(s) if both are (effectively) missing
if not "C1" in question.keys() and (not "A1" in question.keys() or ("A1" in question.keys() and not "A2" in question.keys())) :
# Get the response from the GPT
try:
system_content = SYSTEM_INTRO + REQUEST_EXAMPLE_ALL_CHOICES + SYSTEM_CONCLUSION + (IMG_SPECIFICATION if img_link != "" else "")
response_content = REQUEST_ALL_CHOICES + remove_backticked_imbeds(question["Question"])
response = call_gpt(domain, context, api_key, model, system_content, response_content, img_link)
# Parse to get the correct and incorrect answers generated
try:
# iterate through the output
lines = response.split('\n')
cur_key = ""
num_cor = 0
num_incor = 0 if not "A1" in question.keys() else 1
for line in lines:
# check if this line contains a correct answer
if line.strip().startswith('C~'):
# get the new key
num_cor += 1
cur_key = "C" + str(num_cor)
# set this line into the question dictionary
question[cur_key] = line[2:].strip()
# check if this line contains a incorrect answer
elif line.strip().startswith('I~'):
# get the new key
num_incor += 1
cur_key = "A" + str(num_incor)
# set this line into the question dictionary
question[cur_key] = line[2:].strip()
# otherwise is continuation of previous line
else:
# if we enter here without a key, something went wrong
if cur_key == "":
raise Exception()
# append this line to the previous on a newline
question[cur_key] = "\n" + line.strip()
except Exception as e:
# prompt error and prevent submit
messagebox.showerror("GPT Failed!", "The call to ChatGPT to generate the multiple choice options failed: " + str(e))
print("Failed call to GPT!")
return
except TimeoutError:
# fail
messagebox.showerror("GPT Call Fail!", "The call to ChatGPT to generate the multiple choice options timed out!")
return
# generate several incorrect answers if they are missing for several correct answers
elif "C2" in question.keys() and not "A1" in question.keys():
# get the required content for the prompt
correct_answers_c = "Correct Answers: "
correct_count = 0
for key, value in question.items():
if "C" in key:
correct_answers_c += value + ", "
correct_count += 1
content = "Question: " + remove_backticked_imbeds(question['Question']) + "\n" + remove_backticked_imbeds(correct_answers_c) + "\n"
# Get the response from the GPT
try:
system_content = SYSTEM_INTRO + REQUEST_EXAMPLE_INCORRECT_CHOICES_MULTIPLE_CORRECT + SYSTEM_CONCLUSION + (IMG_SPECIFICATION if img_link != "" else "")
response_content = REQUEST_INCORRECT_CHOICES_MULTIPLE_CORRECT.replace("{X}", str(correct_count)) + content
response = call_gpt(domain, context, api_key, model, system_content, response_content, img_link)
# Parse to get the correct and incorrect answers generated
try:
# iterate through the output
lines = response.split('\n')
cur_key = ""
num_cor = 0
num_incor = 0
for line in lines:
# check if this line contains a incorrect answer
if line.strip().startswith('I~'):
# get the new key
num_incor += 1
cur_key = "A" + str(num_incor)
# set this line into the question dictionary
question[cur_key] = line[2:].strip()
# otherwise is continuation of previous line
else:
# if we enter here without a key, something went wrong
if cur_key == "":
raise Exception()
# append this line to the previous on a newline
question[cur_key] = "\n" + line.strip()
except Exception as e:
# prompt error and prevent submit
messagebox.showerror("GPT Failed!", "The call to ChatGPT to generate the multiple choice options failed: " + str(e))
print("Failed call to GPT!")
return
except TimeoutError:
# fail
messagebox.showerror("GPT Call Fail!", "The call to ChatGPT to generate the multiple choice options timed out!")
return
# select a correct answer from the incorrect answers if enough incorrect answers are given.
elif not "C1" in question.keys() and "A2" in question.keys():
# First, generate the additional content
answer_choices_c = "Answer Choices:\n"
choice_num = 1
for key, value in question.items():
if "A" in key:
answer_choices_c += "A" + str(choice_num) + "~ " + value + "\n"
choice_num += 1
content = "Question: " + remove_backticked_imbeds(question['Question']) + "\n" + answer_choices_c + "\n"
# Get the response from the GPT
try:
system_content = SYSTEM_INTRO + REQUEST_EXAMPLE_SELECT_CORRECT_CHOICE + SYSTEM_CONCLUSION + (IMG_SPECIFICATION if img_link != "" else "")
response_content = REQUEST_SELECT_CORRECT_CHOICE + content
response = call_gpt(domain, context, api_key, model, system_content, response_content, img_link)
choices = []
# parse
print(response.split('\n'))
choice_num = 0
for key, value in question.items():
if "A" in key:
choices.append(value)
choice_num += 1
while choice_num > 0:
del question["A" + str(choice_num)]
choice_num -= 1
# Parse to get the correct and incorrect answers generated
try:
# iterate through the output
lines = response.split(',')
cur_key = ""
choice_num = len(lines)
for i in range(len(lines) - 1, -1, -1):
line = lines[i]
# validate this choice
if line.strip().startswith('A'):
# get the new key
cur_key = "C" + str(choice_num)
choice_num -= 1
# set this line into the question dictionary
answer = int(line.strip()[1])
question[cur_key] = choices.pop(answer - 1)
# otherwise is continuation of previous line
else:
# if we enter here, we have a problem
raise Exception()
except Exception as e:
# prompt error and prevent submit
messagebox.showerror("GPT Failed!", "The call to ChatGPT to generate the multiple choice options failed: " + str(e))
print("Failed call to GPT!")
return
# push the remainder of the list as incorrect answer choices
choice_num = 1
for item in choices:
question["A" + str(choice_num)] = item
choice_num += 1
except TimeoutError:
# fail
messagebox.showerror("GPT Call Fail!", "The call to ChatGPT to generate the multiple choice options timed out!")
return
# generate incorrect answers if they are missing for a single correct answer
elif "C1" in question.keys() and not "A1" in question.keys():
# first, generate additional content
content = "Question: " + remove_backticked_imbeds(question["Question"]) + "\nCorrect Answer: " + remove_backticked_imbeds(question["C1"]) + "\n"
# Get the response from the GPT
try:
system_content = SYSTEM_INTRO + REQUEST_EXAMPLE_INCORRECT_CHOICES_SINGLE_CORRECT + SYSTEM_CONCLUSION + (IMG_SPECIFICATION if img_link != "" else "")
response_content = REQUEST_INCORRECT_CHOICES_SINGLE_CORRECT + content
response = call_gpt(domain, context, api_key, model, system_content, response_content, img_link)
# Parse to get the correct and incorrect answers generated
try:
# iterate through the output
lines = response.split('\n')
cur_key = ""
num_cor = 0
num_incor = 0
for line in lines:
# check if this line contains a incorrect answer
if line.strip().startswith('I~'):
# get the new key
num_incor += 1
cur_key = "A" + str(num_incor)
# set this line into the question dictionary
question[cur_key] = line[2:].strip()
# otherwise is continuation of previous line
else:
# if we enter here without a key, something went wrong
if cur_key == "":
raise Exception()
# append this line to the previous on a newline
question[cur_key] = "\n" + line.strip()
except Exception as e:
# prompt error and prevent submit
messagebox.showerror("GPT Failed!", "The call to ChatGPT to generate the multiple choice options failed: " + str(e))
print("Failed call to GPT!")
return
except TimeoutError:
# fail
messagebox.showerror("GPT Call Fail!", "The call to ChatGPT to generate the multiple choice options timed out!")
return
def get_question_sample(bank):
# get the proportionate amounts of each question type in the bank, while also currating lists for each of the 3 question types
mc_questions = []
td_questions = []
ess_questions = []
for question in bank:
match question["Type"]:
case "MC":
mc_questions += [question]
case "TD":
td_questions += [question]
case "Ess":
ess_questions += [question]
proportions = (len(mc_questions) / len(bank), len(td_questions) / len(bank), len(ess_questions) / len(bank))
# using those proportions, select a type to generate a sample of
sel_type = ""
selection = random.random()
if selection < proportions[0]:
sel_type = "MC"
elif selection < proportions[0] + proportions[1]:
sel_type = "TD"
else:
sel_type = "Ess"
# choose the appropriate number of questions to create the sample
match sel_type:
case "MC":
sample = random.sample(mc_questions, min(3, len(mc_questions)))
case "TD":
sample = random.sample(td_questions, 1)
case "Ess":
sample = random.sample(ess_questions, 1)
# return the sample
return sample
def kill_thread(thread, timeout):
try: