GeneXam / app.py
Rathapoom's picture
Update app.py
6d71955 verified
raw
history blame
5.32 kB
import streamlit as st
import openai
import time
# Set your OpenAI API key from Hugging Face Secrets
openai.api_key = st.secrets["OPENAI_API_KEY"]
# Initialize OpenAI client
client = openai.OpenAI(api_key=openai.api_key)
# Function to generate exam questions using OpenAI API with retry logic
def generate_questions_with_retry(knowledge_material, question_type, cognitive_level, extra_instructions, max_retries=3):
# Adjust the number of questions based on the type
if question_type == "Multiple Choice":
num_questions = 3
elif question_type == "Fill in the Blank":
num_questions = 10
else: # Open-ended
num_questions = 3
prompt = f"Generate {num_questions} {question_type.lower()} exam questions based on {cognitive_level.lower()} level from the following material: {knowledge_material}. {extra_instructions}"
if question_type != "Fill in the Blank":
prompt += " Provide answers with short explanations."
retries = 0
while retries < max_retries:
try:
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are a helpful assistant for generating exam questions."},
{"role": "user", "content": prompt}
]
)
return response.choices[0].message.content
except openai.error.APIConnectionError:
retries += 1
time.sleep(2) # Wait for 2 seconds before retrying
if retries == max_retries:
st.error("Failed to connect to OpenAI API after several attempts.")
return None
# Login page
if 'username' not in st.session_state:
# Show the login form if the username is not set
st.title("Login")
username_input = st.text_input("Enter your username:")
if st.button("Login"):
if username_input:
st.session_state['username'] = username_input
st.success(f"Welcome, {username_input}!")
else:
st.warning("Please enter a valid username.")
else:
# Main App after login
st.title(f"Welcome, {st.session_state['username']}! Generate your exam questions")
# Input field for knowledge material (text)
knowledge_material = st.text_area("Enter knowledge material to generate exam questions:")
# Extra input field for additional instructions
extra_instructions = st.text_area("Enter additional instructions (e.g., how you want the questions to be phrased):")
# File uploader for PDFs (Optional: Only if you want to implement PDF input later)
uploaded_file = st.file_uploader("Upload a file (PDF)", type="pdf")
# Select question type
question_type = st.selectbox("Select question type:",
["Multiple Choice", "Fill in the Blank", "Open-ended"])
# Select cognitive level
cognitive_level = st.selectbox("Select cognitive level:",
["Recall", "Understanding", "Application", "Analysis", "Synthesis", "Evaluation"])
# Generate questions button
if 'previous_questions' not in st.session_state:
st.session_state['previous_questions'] = []
if st.button("Generate Questions"):
if knowledge_material:
# Generate questions with retry logic
questions = generate_questions_with_retry(knowledge_material, question_type, cognitive_level, extra_instructions)
if questions:
st.write("Generated Exam Questions:")
st.write(questions)
# Avoid showing repeated content in future requests
st.session_state['previous_questions'].append(questions)
# Option to download the questions as a text file
st.download_button(
label="Download Questions",
data=questions,
file_name='generated_questions.txt',
mime='text/plain'
)
else:
st.warning("Please enter the knowledge material.")
# Button to generate more questions based on the same material
if st.button("Generate More Questions"):
if knowledge_material:
# Regenerate new questions, trying to avoid repeated content
questions = generate_questions_with_retry(knowledge_material, question_type, cognitive_level, extra_instructions)
# Check if the new set of questions is not the same as the previous set
if questions and questions not in st.session_state['previous_questions']:
st.write("Generated More Exam Questions:")
st.write(questions)
# Append the new questions to the session state
st.session_state['previous_questions'].append(questions)
# Option to download the new set of questions
st.download_button(
label="Download More Questions",
data=questions,
file_name='more_generated_questions.txt',
mime='text/plain'
)
else:
st.warning("New questions seem to overlap with the previous ones. Try adjusting the instructions.")