qa_gen / app.py
AndrewRWilliams's picture
Update app.py
6c47b98
raw
history blame
4.34 kB
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()