Amelia-James commited on
Commit
1ad69d1
·
verified ·
1 Parent(s): 523c362

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -88
app.py CHANGED
@@ -1,19 +1,11 @@
1
- import os
2
- from dotenv import load_dotenv
3
  import streamlit as st
4
  from groq import Groq
5
- import re
6
 
7
- # Load environment variables from .env file
8
- load_dotenv()
9
-
10
- # Get the API key from the environment variables
11
- api_key = os.getenv("GROQ_API_KEY")
12
-
13
- # Initialize Groq client with the API key
14
  client = Groq(api_key=api_key)
15
 
16
- # Function to generate MCQs from the user text
17
  def generate_mcqs_from_text(user_text):
18
  prompt = f"""
19
  You are a 35-year experienced educator specializing in crafting challenging and insightful MCQs.
@@ -28,8 +20,8 @@ def generate_mcqs_from_text(user_text):
28
  B. [Option 2]
29
  C. [Option 3]
30
  D. [Option 4]
31
-
32
- Correct Answers:
33
  Question 1: [Correct Option]
34
  Question 2: [Correct Option], etc.
35
 
@@ -39,94 +31,64 @@ def generate_mcqs_from_text(user_text):
39
  messages=[{"role": "user", "content": prompt}],
40
  model="gemma2-9b-it", # Replace with a valid Groq model
41
  )
42
- response = chat_completion.choices[0].message.content
43
- print("API Response:\n", response) # Debugging: Inspect the raw response
44
- return response
45
-
46
- # Function to parse MCQs and answers with a flexible approach
47
- def parse_mcqs_and_answers(mcqs_and_answers):
48
- try:
49
- # Regular expression to match MCQs and answers
50
- mcq_pattern = r"(Question \d+:.+?)(?=Question \d+|$)"
51
- answer_pattern = r"(Question \d+: .+?)\n(A|B|C|D)\. .+"
52
-
53
- # Extract questions
54
- questions = re.findall(mcq_pattern, mcqs_and_answers)
55
- # Extract answers
56
- answers = re.findall(answer_pattern, mcqs_and_answers)
57
-
58
- if len(questions) == 0 or len(answers) == 0:
59
- raise ValueError("Failed to extract questions or answers.")
60
-
61
- # Parse questions and answers
62
- mcqs = {}
63
- for q, ans in zip(questions, answers):
64
- question_text = q.strip()
65
- answer_text = ans.strip()
66
- mcqs[question_text] = answer_text
67
-
68
- return mcqs
69
- except Exception as e:
70
- st.error(f"Failed to parse response: {e}")
71
- st.write("Raw response:", mcqs_and_answers) # Display raw output for troubleshooting
72
- return None
73
 
74
  # Function to evaluate user answers
75
- def evaluate_answers(mcqs, user_answers):
76
- # Here we assume the user_answers is a dictionary of answers for each question
77
  prompt = f"""
78
- Here are the user's answers to the following multiple-choice questions.
79
- Please evaluate them as an experienced teacher, providing feedback on correctness,
80
- and explain why each answer is right or wrong.
 
 
81
 
82
  MCQs: {mcqs}
83
 
 
 
84
  User Answers: {user_answers}
85
  """
86
-
87
- # Make the API call to evaluate the answers
88
  chat_completion = client.chat.completions.create(
89
  messages=[{"role": "user", "content": prompt}],
90
  model="gemma2-9b-it", # Replace with a valid Groq model
91
  )
92
-
93
- # Return the evaluation result
94
  return chat_completion.choices[0].message.content
95
 
96
- # Streamlit UI
97
- st.title("MCQ Generator and Evaluator")
98
-
99
- # User input
100
- user_text = st.text_area("Enter text to generate MCQs:")
101
-
102
- if st.button("Generate MCQs"):
103
- # Generate MCQs from user-provided text
104
- mcqs_and_answers = generate_mcqs_from_text(user_text)
105
-
106
- # Parse the MCQs and correct answers
107
- mcqs = parse_mcqs_and_answers(mcqs_and_answers)
108
-
109
- if mcqs:
110
- # Display the first MCQ question
111
- questions = list(mcqs.keys())
112
- question = questions[0]
113
-
114
- # Show question options (Here we assume options are A, B, C, D)
115
- st.write(f"Question: {question}")
116
-
117
- options = ["A", "B", "C", "D"] # Example options, you may adjust according to your response
118
- user_answer = st.radio("Choose your answer:", options)
119
 
120
- if st.button("Submit Answer"):
121
- # Evaluate the answer
122
- result = evaluate_answers(mcqs, {question: user_answer})
123
- st.write(result)
124
-
125
- # Show next question if available
126
- if len(questions) > 1:
127
- next_question = questions[1]
128
- st.write(f"Next Question: {next_question}")
129
- else:
130
- st.write("You have completed all the questions!")
131
  else:
132
- st.error("Could not parse MCQs or answers.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
  from groq import Groq
 
3
 
4
+ # Initialize Groq client with API key
5
+ api_key = "your-groq-api-key-here"
 
 
 
 
 
6
  client = Groq(api_key=api_key)
7
 
8
+ # Function to generate MCQs without showing answers
9
  def generate_mcqs_from_text(user_text):
10
  prompt = f"""
11
  You are a 35-year experienced educator specializing in crafting challenging and insightful MCQs.
 
20
  B. [Option 2]
21
  C. [Option 3]
22
  D. [Option 4]
23
+
24
+ Additionally, provide the correct answers in a separate section titled "Correct Answers" in the format:
25
  Question 1: [Correct Option]
26
  Question 2: [Correct Option], etc.
27
 
 
31
  messages=[{"role": "user", "content": prompt}],
32
  model="gemma2-9b-it", # Replace with a valid Groq model
33
  )
34
+ return chat_completion.choices[0].message.content
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
  # Function to evaluate user answers
37
+ def evaluate_answers(mcqs, correct_answers, user_answers):
 
38
  prompt = f"""
39
+ You are a 35-year experienced educator evaluating student answers.
40
+ Here are the generated MCQs, the correct answers, and the student's responses. Please:
41
+ 1. Check the correctness of each answer.
42
+ 2. Provide feedback for each question, explaining why the student's choice is correct or incorrect.
43
+ 3. Assign an overall score and include suggestions for improvement.
44
 
45
  MCQs: {mcqs}
46
 
47
+ Correct Answers: {correct_answers}
48
+
49
  User Answers: {user_answers}
50
  """
 
 
51
  chat_completion = client.chat.completions.create(
52
  messages=[{"role": "user", "content": prompt}],
53
  model="gemma2-9b-it", # Replace with a valid Groq model
54
  )
 
 
55
  return chat_completion.choices[0].message.content
56
 
57
+ # Streamlit App
58
+ st.title("Experienced Educator MCQ Generator & Evaluator")
59
+ st.sidebar.header("Input Settings")
60
+
61
+ # Input text from user
62
+ user_text = st.sidebar.text_area("Enter the text for generating MCQs:", height=200)
63
+
64
+ if st.sidebar.button("Generate MCQs"):
65
+ if user_text.strip():
66
+ with st.spinner("Generating MCQs..."):
67
+ mcqs_and_answers = generate_mcqs_from_text(user_text)
68
+ # Split the output into MCQs and correct answers
69
+ mcqs, correct_answers = mcqs_and_answers.split("Correct Answers:")
70
+ st.session_state["mcqs"] = mcqs.strip()
71
+ st.session_state["correct_answers"] = correct_answers.strip()
 
 
 
 
 
 
 
 
72
 
73
+ st.subheader("Generated MCQs:")
74
+ st.text_area("MCQs", value=st.session_state["mcqs"], height=400)
 
 
 
 
 
 
 
 
 
75
  else:
76
+ st.error("Please enter text for generating MCQs.")
77
+
78
+ # Input user answers for evaluation
79
+ if "mcqs" in st.session_state and "correct_answers" in st.session_state:
80
+ st.subheader("Solve the MCQs")
81
+ user_answers = st.text_area("Enter your answers (e.g., A, B, C, D for each question):", height=100)
82
+
83
+ if st.button("Evaluate Answers"):
84
+ if user_answers.strip():
85
+ with st.spinner("Evaluating answers..."):
86
+ evaluation_result = evaluate_answers(
87
+ st.session_state["mcqs"],
88
+ st.session_state["correct_answers"],
89
+ user_answers
90
+ )
91
+ st.subheader("Evaluation Result:")
92
+ st.text_area("Evaluation", value=evaluation_result, height=400)
93
+ else:
94
+ st.error("Please enter your answers for evaluation.")