Spaces:
Runtime error
Runtime error
import streamlit as st | |
import google.generativeai as genai | |
import random | |
import re | |
# Configure the Gemini API with your API key | |
genai.configure(api_key='AIzaSyAjDT14MAn93D1xJMsBtHeaNThaFIYeLbs') | |
# Initialize the generative model | |
model = genai.GenerativeModel('gemini-pro') | |
def generate_mcqs(context): | |
prompt = f""" | |
Based on the following context, generate 10 multiple-choice questions (MCQs). | |
You can use data without the context too if needed, but all the topics within the context should be included. | |
Generate valid MCQs too. | |
Each MCQ should have 4 options with only one correct answer. | |
Format each question exactly as follows: | |
**Question X:** [Question text] | |
A) [Option A] | |
B) [Option B] | |
C) [Option C] | |
D) [Option D] | |
Correct Answer: [A/B/C/D] | |
Context: | |
{context} | |
""" | |
try: | |
response = model.generate_content(prompt) | |
raw_text = response.text | |
# Debug: Print raw response | |
# st.text("Raw API Response:") | |
# st.text(raw_text) | |
# Parse the raw text into a structured format | |
questions = re.split(r'\*\*Question \d+:\*\*', raw_text)[1:] # Split by question number | |
mcqs = [] | |
for q in questions: | |
try: | |
# Extract question text | |
question_text = q.split('A)')[0].strip() | |
# Extract options | |
options = re.findall(r'([A-D]\).*?)(?=[A-D]\)|Correct Answer:)', q, re.DOTALL) | |
options = [opt.strip() for opt in options] | |
# Extract correct answer | |
correct_answer = re.search(r'Correct Answer:\s*([A-D])', q).group(1) | |
if len(options) == 4 and correct_answer in ['A', 'B', 'C', 'D']: | |
mcqs.append({ | |
"question": question_text, | |
"options": options, | |
"correct_answer": correct_answer | |
}) | |
else: | |
st.warning(f"Skipped question due to incorrect format: {q}") | |
except Exception as e: | |
st.warning(f"Skipped a malformed question: {str(e)}\nQuestion: {q}") | |
if not mcqs: | |
raise ValueError("No valid MCQs were generated") | |
return mcqs | |
except Exception as e: | |
st.error(f"An error occurred while generating MCQs: {str(e)}") | |
return None | |
def main(): | |
st.title("MCQ Generator and Exam") | |
# Input section | |
st.header("Generate MCQs") | |
context = st.text_area("Enter the context or data for generating MCQs:") | |
if st.button("Generate MCQs"): | |
if context: | |
with st.spinner("Generating MCQs..."): | |
mcqs = generate_mcqs(context) | |
if mcqs: | |
st.session_state.mcqs = mcqs | |
st.success(f"Generated {len(mcqs)} MCQs successfully!") | |
else: | |
st.error("Failed to generate valid MCQs. Please try again with a different or more detailed context.") | |
else: | |
st.warning("Please enter some context to generate MCQs.") | |
# Exam section | |
st.header("Take Exam") | |
if 'mcqs' in st.session_state and st.session_state.mcqs: | |
user_answers = [] | |
for i, question in enumerate(st.session_state.mcqs): | |
st.subheader(f"Question {i + 1}") | |
st.write(question['question']) | |
user_answer = st.radio("Select your answer:", question['options'], key=f"q{i}") | |
user_answers.append(user_answer) | |
if st.button("Submit Exam"): | |
score = sum(1 for q, a in zip(st.session_state.mcqs, user_answers) | |
if a == q['options'][ord(q['correct_answer']) - ord('A')]) | |
st.subheader("Exam Completed!") | |
st.write(f"Your score: {score}/{len(st.session_state.mcqs)}") | |
# Display correct answers | |
st.subheader("Correct Answers:") | |
for i, (question, user_answer) in enumerate(zip(st.session_state.mcqs, user_answers)): | |
st.write(f"Q{i+1}: {question['question']}") | |
st.write(f"Your answer: {user_answer}") | |
correct_answer = question['options'][ord(question['correct_answer']) - ord('A')] | |
st.write(f"Correct answer: {correct_answer}") | |
st.write("---") | |
else: | |
st.info("Generate MCQs first to take the exam.") | |
if __name__ == "__main__": | |
main() |