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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -77
app.py CHANGED
@@ -1,15 +1,18 @@
1
  import os
 
2
  from dotenv import load_dotenv
3
  from groq import Groq
4
- import streamlit as st
5
 
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.
@@ -33,85 +36,75 @@ def generate_mcqs_from_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}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
+ import streamlit as st
3
  from dotenv import load_dotenv
4
  from groq import Groq
 
5
 
6
+ # Load environment variables from .env file
7
  load_dotenv()
8
 
9
+ # Get the API key from the environment variables
10
+ api_key = os.getenv("GROQ_API_KEY")
11
 
12
+ # Initialize Groq client with the API key
13
+ client = Groq(api_key=api_key)
14
+
15
+ # Function to generate MCQs based on the input text
16
  def generate_mcqs_from_text(user_text):
17
  prompt = f"""
18
  You are a 35-year experienced educator specializing in crafting challenging and insightful MCQs.
 
36
  """
37
  chat_completion = client.chat.completions.create(
38
  messages=[{"role": "user", "content": prompt}],
39
+ model="Llama-3.3-70b", # Replace with a valid Groq model
40
  )
41
+ response = chat_completion.choices[0].message.content
42
+ print("API Response:\n", response) # Debugging: Inspect the raw response
43
+ return response
44
 
45
+ # Function to parse the MCQs and correct answers from the API response
46
  def parse_mcqs_and_answers(mcqs_and_answers):
47
  try:
48
+ # Try splitting on "Correct Answers:"
49
+ parts = mcqs_and_answers.split("Correct Answers:")
50
+ if len(parts) != 2:
51
+ raise ValueError("Could not find 'Correct Answers:' in the response.")
52
+
53
+ # Separate MCQs and correct answers
54
+ mcqs = parts[0].strip()
55
+ correct_answers = {}
56
+ for line in parts[1].strip().splitlines():
57
+ if line.startswith("Question"):
58
+ q, ans = line.split(":")
59
+ correct_answers[q.strip()] = ans.strip()
60
+
61
+ return mcqs, correct_answers
62
+ except Exception as e:
63
+ st.error(f"Failed to parse response: {e}")
64
+ st.write("Raw response:", mcqs_and_answers) # Display raw output for troubleshooting
65
  return None, None
66
 
67
  # Streamlit app
68
+ def main():
69
+ st.title("MCQ Generator and Evaluator")
70
+
71
+ # Input text from the user
72
+ user_text = st.text_area("Enter the text for MCQ generation:", height=150)
73
+
74
+ if st.button("Generate MCQs"):
75
+ if user_text:
76
+ # Generate MCQs from the input text
77
  mcqs_and_answers = generate_mcqs_from_text(user_text)
 
78
 
79
+ # Parse the MCQs and correct answers
80
+ mcqs, correct_answers = parse_mcqs_and_answers(mcqs_and_answers)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
82
+ if mcqs:
83
+ # Display MCQs one by one and evaluate answers
84
+ mcq_list = mcqs.splitlines()
85
+ correct_count = 0
86
+ for idx, mcq in enumerate(mcq_list):
87
+ question = mcq.split("\n")[0]
88
+ options = mcq.split("\n")[1:5]
89
+ st.write(question)
90
+ for option in options:
91
+ st.write(option)
92
+
93
+ user_answer = st.radio("Select your answer", options=["A", "B", "C", "D"], key=idx)
94
+
95
+ if user_answer:
96
+ # Evaluate the user's answer
97
+ correct_answer = correct_answers.get(f"Question {idx+1}")
98
+ if user_answer == correct_answer:
99
+ st.success(f"Correct! The answer is {correct_answer}.")
100
+ correct_count += 1
101
+ else:
102
+ st.error(f"Incorrect. The correct answer is {correct_answer}.")
103
+
104
+ # Display final score
105
+ st.write(f"Your final score is {correct_count}/{len(mcq_list)}.")
106
+ else:
107
+ st.error("Please enter some text to generate MCQs.")
108
+
109
+ if __name__ == "__main__":
110
+ main()