File size: 4,344 Bytes
4581c90
 
 
 
 
 
 
 
 
573538a
 
 
 
 
 
06b74c7
a39de4a
327d778
ffc804b
573538a
 
 
4581c90
573538a
4581c90
573538a
 
 
 
 
 
 
4581c90
136b1dc
573538a
 
 
4581c90
573538a
 
 
 
 
 
7e09f8c
573538a
cc010e0
 
573538a
 
 
 
 
 
 
 
 
7e09f8c
 
573538a
 
 
 
 
 
ae9da43
573538a
71c5936
573538a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b720c3
 
573538a
 
5cac5ae
7b720c3
573538a
c664af0
5cac5ae
7b720c3
573538a
5cac5ae
573538a
5cac5ae
573538a
6c47b98
573538a
71c5936
4581c90
573538a
 
 
 
 
4581c90
 
573538a
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

import gradio as gr
import transformers

import os
import sys
import openai
from openai import Completion as complete

qa_gen_prompt = str("""You are a highly intelligent & complex question-answer generative model. 
  You take a passage as an input and generate 5 high-quality and diverse multiple-choice questions 
  with four choices each from the given passage by imitating the way a human asks questions and give answers. 
  Your output format is only 
    [{\"Q\": Question, \"A1\": Answer, \"A2\": Answer,\"A3\": Answer, \"A4\": Answer}, ...]\") }} form, no other form. \n The passage: """)
end_prompt = "the QA pairs:"

openai.api_key = os.environ["openai_api_key"]
access_code = os.environ["access_code"]

def convert_questions_to_html(qapairs):
  qapairs_template = []
  for qapair in qapairs:

    result = "<problem>\n<choiceresponse>  \n<label>" + qapair['Q'] + "</label>\n<checkboxgroup>"

    for key, value in qapair.items():
        if key != "Q":
            result += "\n    <choice correct=\"false\">" + value + "</choice>"
    result+="\n"
    result += "  </checkboxgroup>\n</choiceresponse>\n</problem>"
    qapairs_template.append(result)
  return "".join([qa + "\n\n" for qa in qapairs_template])


def convert_questions_to_template(qapairs):
  qapairs_template = []
  for qapair in qapairs:

    result = ">>" + qapair['Q'] + " <<\n\n"
    choices = [qapair['A1'], qapair['A2'], qapair['A3'], qapair['A4']]
    for i, choice in enumerate(choices):
      result += "[ ] " + choice + "\n"
      
    qapairs_template.append(result)

  return "".join([qa + "\n\n" for qa in qapairs_template])


def list_of_dicts_to_str(qapairs, indent=0):
    result = ''
    for d in qapairs:
        for key, value in d.items():
            if key.startswith("A"):
                result += ' ' * (indent + 4) + str(key) + ': ' + str(value) + '\n'
            else:
                result += ' ' * indent + str(key) + ': ' + str(value) + '\n'
    return result


def generate_questions(context, credentials):
    """
    Generate questions by calling davinci-003.
    """
    if credentials != access_code:
        return "Code d'accès incorrect. Veuillez réessayer.", "Code d'accès incorrect. Veuillez réessayer.", "Code d'accès incorrect. Veuillez réessayer."

    prompt = qa_gen_prompt + context + end_prompt
    
    try:
        completion = complete.create(model="text-davinci-003", prompt=prompt, max_tokens=1875)
        q_dict = eval(completion.choices[0].text)
        return list_of_dicts_to_str(q_dict), convert_questions_to_html(q_dict), convert_questions_to_template(q_dict)
    except Exception as e:
        # return str(e)
        # return python version
        return str(sys.version)


with gr.Blocks() as demo:

    # with gr.Row():
        
    #     with gr.Column():


    with gr.Row():
        
        with gr.Column():   
            gr.Markdown("## Générateur de questions à choix multiples")    
            gr.Markdown("Pour créer des questions à choix multiples, insérez un texte dans la boîte à gauche, puis cliquez sur 'Générer des questions.' Attention! N'oubliez pas le code d'accès.")

        with gr.Column():

            quiz_button = gr.Button("Générer cinq questions.", variant="primary")   
            credentials = gr.Textbox(placeholder="Code d'accès", lines=1, label="")
            

    with gr.Row():
        context = gr.Textbox(placeholder="insérez le texte ici.", lines=8, label="Texte")
        
        with gr.Tab("brut"):
            qa_pairs = gr.Textbox(placeholder="Les questions apparaîtront ici.", lines=19, label="Paires question-réponse")
        with gr.Tab("format html"):
            qa_pairs_html = gr.Textbox(placeholder="Les questions apparaîtront ici.", lines=19, label="Paires question-réponse, format html")
        with gr.Tab("format edulib"):
            qa_pairs_edulib = gr.Textbox(placeholder="Les questions apparaîtront ici.", lines=19, label="Paires question-réponse, format edulib")

        #todo: test generating with just one phrase for one MCQ with smaller models

    quiz_button.click(fn= generate_questions,
                          inputs=[context, credentials],	
                          outputs=[qa_pairs, qa_pairs_html, qa_pairs_edulib]
                     )
    

if __name__ == "__main__":
    demo.launch()