Spaces:
Runtime error
Runtime error
import gradio as gr | |
import openai | |
# Replace with your OpenAI API key | |
openai.api_key = "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" | |
# Global variables to store the state | |
current_step = "question_generation" | |
current_question = "" | |
correct_answer = "" | |
def reset_state(): | |
global current_step, current_question, correct_answer | |
current_step = "question_generation" | |
current_question = "" | |
correct_answer = "" | |
def generate_question_and_answer(text): | |
global current_question, correct_answer | |
response = openai.Completion.create( | |
engine="gpt-3.5-turbo-0301", | |
prompt=f"Create a question based on the following text: \"{text}\".\nQuestion: ", | |
max_tokens=50, | |
n=1, | |
) | |
current_question = response.choices[0].text.strip() | |
response = openai.Completion.create( | |
engine="gpt-3.5-turbo-0301", | |
prompt=f"What is the answer to the following question based on the text: \"{text}\"?\nQuestion: {current_question}\nAnswer: ", | |
max_tokens=50, | |
n=1, | |
) | |
correct_answer = response.choices[0].text.strip() | |
def get_feedback(text, user_answer=None, continue_quiz='Yes'): | |
global current_step, current_question, correct_answer | |
if current_step == "question_generation": | |
if text: | |
generate_question_and_answer(text) | |
current_step = "answer_checking" | |
return f"Question: {current_question}", "", "hidden" | |
else: | |
return "Please input text to generate a question.", "", "hidden" | |
elif current_step == "answer_checking": | |
if user_answer is not None: | |
feedback = "Correct!" if user_answer.lower() == correct_answer.lower() else f"Incorrect! The correct answer was: {correct_answer}" | |
current_step = "continue_prompt" | |
return f"Feedback: {feedback}", "Do you want to answer another question?", "text" | |
else: | |
return f"Question: {current_question}", "", "hidden" | |
elif current_step == "continue_prompt": | |
if continue_quiz.lower() == 'no': | |
reset_state() | |
return "Quiz ended. Thank you for participating!", "", "hidden" | |
else: | |
current_step = "question_generation" | |
return "Please input text to generate a new question.", "", "hidden" | |
iface = gr.Interface( | |
fn=get_feedback, | |
inputs=[ | |
gr.inputs.Textbox(lines=5, label="Input Text"), | |
gr.inputs.Textbox(lines=1, label="Your Answer"), | |
gr.inputs.Radio(choices=["Yes", "No"], label="Continue?") | |
], | |
outputs=[ | |
gr.outputs.Textbox(label="Model Output"), | |
gr.outputs.Textbox(label="Prompt"), | |
], | |
live=True | |
) | |
iface.launch() | |