Amelia-James commited on
Commit
78d1477
·
verified ·
1 Parent(s): 0f0ccd9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -64
app.py CHANGED
@@ -6,88 +6,112 @@ import streamlit as st
6
  # Load environment variables
7
  load_dotenv()
8
 
9
- # Get API key
10
- api_key = os.getenv("GROQ_API_KEY")
11
- client = Groq(api_key=api_key)
12
 
13
- # Function to generate MCQs from text
14
  def generate_mcqs_from_text(user_text):
15
  prompt = f"""
16
- Based on the following text, generate between 30 to 50 multiple-choice questions.
17
- Each question should have four answer options, with one correct answer and three distractors.
18
- Format each question as:
19
-
20
- Question: [Your question here]
21
- A. [Option 1]
22
- B. [Option 2]
23
- C. [Option 3]
 
 
 
24
  D. [Option 4]
25
- Correct Answer: [Correct Option]
 
 
 
26
 
27
  Text: {user_text}
28
  """
29
- response = client.chat.completions.create(
30
- messages=[
31
- {"role": "user", "content": prompt}
32
- ],
33
- model="Llama-3.3-70b",
34
  )
35
- return response.choices[0].message.content
36
 
37
- # Function to parse MCQs and answers
38
- def parse_mcqs(mcq_text):
39
- questions = []
40
- correct_answers = []
41
- mcqs = mcq_text.split("\n\n")
42
- for mcq in mcqs:
43
- if "Correct Answer:" in mcq:
44
- question, answer = mcq.split("Correct Answer:")
45
- questions.append(question.strip())
46
- correct_answers.append(answer.strip())
47
- return questions, correct_answers
 
48
 
49
- # Initialize Streamlit app
50
- st.title("MCQs Generator and Evaluator")
51
- st.sidebar.header("Upload Text Data")
52
- user_text = st.sidebar.text_area("Paste your text here:")
53
 
54
- if "current_question" not in st.session_state:
55
- st.session_state.current_question = 0
56
- if "questions" not in st.session_state:
57
- st.session_state.questions = []
58
- if "correct_answers" not in st.session_state:
59
- st.session_state.correct_answers = []
60
 
61
- # Generate MCQs
62
  if st.sidebar.button("Generate MCQs"):
63
- if user_text:
64
- st.session_state.mcq_data = generate_mcqs_from_text(user_text)
65
- st.session_state.questions, st.session_state.correct_answers = parse_mcqs(st.session_state.mcq_data)
66
- st.session_state.current_question = 0
 
 
 
 
 
 
 
 
 
 
67
  else:
68
- st.sidebar.error("Please provide text data to generate MCQs.")
69
 
70
- # Display and Evaluate MCQs
71
- if st.session_state.questions:
72
- current_index = st.session_state.current_question
73
- question = st.session_state.questions[current_index]
74
- correct_answer = st.session_state.correct_answers[current_index]
75
-
76
- st.write(question)
77
- options = ["A", "B", "C", "D"]
78
- user_answer = st.radio("Choose your answer:", options)
79
 
80
- if st.button("Submit Answer"):
81
- if user_answer:
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  if user_answer == correct_answer:
83
- st.success(f"Correct! The correct answer is {correct_answer}.")
 
84
  else:
85
  st.error(f"Incorrect. The correct answer is {correct_answer}.")
86
 
87
  # Move to the next question
88
- if current_index + 1 < len(st.session_state.questions):
89
- st.session_state.current_question += 1
90
- else:
91
- st.write("You have completed all the questions!")
92
- else:
93
- st.warning("Please select an answer.")
 
 
 
 
 
 
 
6
  # Load environment variables
7
  load_dotenv()
8
 
9
+ # Initialize the Groq client with API key
10
+ client = Groq(api_key=os.getenv("GROQ_API_KEY"))
 
11
 
12
+ # Function to generate MCQs from the user text
13
  def generate_mcqs_from_text(user_text):
14
  prompt = f"""
15
+ You are a 35-year experienced educator specializing in crafting challenging and insightful MCQs.
16
+ Based on the following text, generate between 30 to 50 multiple-choice questions (MCQs).
17
+ Each question should:
18
+ 1. Test critical thinking and understanding of the content.
19
+ 2. Include four options (A, B, C, D).
20
+ 3. Format the output as follows:
21
+
22
+ Question: [Your question here]
23
+ A. [Option 1]
24
+ B. [Option 2]
25
+ C. [Option 3]
26
  D. [Option 4]
27
+
28
+ Additionally, provide the correct answers in a separate section titled "Correct Answers" in the format:
29
+ Question 1: [Correct Option]
30
+ Question 2: [Correct Option], etc.
31
 
32
  Text: {user_text}
33
  """
34
+ chat_completion = client.chat.completions.create(
35
+ messages=[{"role": "user", "content": prompt}],
36
+ model="gemma2-9b-it", # Replace with a valid Groq model
 
 
37
  )
38
+ return chat_completion.choices[0].message.content
39
 
40
+ # Function to parse MCQs and correct answers
41
+ def parse_mcqs_and_answers(mcqs_and_answers):
42
+ try:
43
+ mcqs, correct_answers_section = mcqs_and_answers.split("Correct Answers:")
44
+ correct_answers = {
45
+ f"Question {i+1}": answer.strip()
46
+ for i, answer in enumerate(correct_answers_section.splitlines() if correct_answers_section else [])
47
+ }
48
+ return mcqs.strip(), correct_answers
49
+ except ValueError:
50
+ st.error("The API response is not in the expected format. Please check the output or adjust the prompt.")
51
+ return None, None
52
 
53
+ # Streamlit app
54
+ st.title("Experienced Teacher's MCQ Generator & Interactive Evaluator")
 
 
55
 
56
+ # Sidebar for text input
57
+ user_text = st.sidebar.text_area("Enter the text for generating MCQs:")
 
 
 
 
58
 
59
+ # Generate MCQs and answers
60
  if st.sidebar.button("Generate MCQs"):
61
+ if user_text.strip():
62
+ with st.spinner("Generating MCQs..."):
63
+ mcqs_and_answers = generate_mcqs_from_text(user_text)
64
+ mcqs, correct_answers = parse_mcqs_and_answers(mcqs_and_answers)
65
+
66
+ if mcqs and correct_answers:
67
+ st.session_state["mcqs"] = mcqs.split("\n\n") # Split into individual questions
68
+ st.session_state["correct_answers"] = correct_answers
69
+ st.session_state["current_index"] = 0
70
+ st.session_state["score"] = 0
71
+ st.session_state["finished"] = False
72
+ st.success("MCQs generated successfully!")
73
+ else:
74
+ st.error("Failed to parse the MCQs or answers. Please check the output format.")
75
  else:
76
+ st.error("Please enter text for generating MCQs.")
77
 
78
+ # Display current MCQ
79
+ if "mcqs" in st.session_state and not st.session_state.get("finished", False):
80
+ current_index = st.session_state["current_index"]
81
+ mcqs = st.session_state["mcqs"]
82
+ correct_answers = st.session_state["correct_answers"]
 
 
 
 
83
 
84
+ if current_index < len(mcqs):
85
+ st.subheader(f"Question {current_index + 1}")
86
+ current_question = mcqs[current_index]
87
+ st.text(current_question)
88
+
89
+ # User selects their answer
90
+ user_answer = st.radio(
91
+ "Choose your answer:",
92
+ ["A", "B", "C", "D"],
93
+ key=f"question_{current_index}",
94
+ )
95
+
96
+ # Submit button to evaluate the answer
97
+ if st.button("Submit Answer"):
98
+ correct_answer = correct_answers.get(f"Question {current_index + 1}", "Unknown")
99
  if user_answer == correct_answer:
100
+ st.session_state["score"] += 1
101
+ st.success("Correct!")
102
  else:
103
  st.error(f"Incorrect. The correct answer is {correct_answer}.")
104
 
105
  # Move to the next question
106
+ st.session_state["current_index"] += 1
107
+ if st.session_state["current_index"] >= len(mcqs):
108
+ st.session_state["finished"] = True
109
+ else:
110
+ st.session_state["finished"] = True
111
+
112
+ # Final score display
113
+ if st.session_state.get("finished", False):
114
+ st.subheader("Quiz Completed!")
115
+ total_questions = len(st.session_state["mcqs"])
116
+ score = st.session_state["score"]
117
+ st.success(f"Your score: {score}/{total_questions}")