WAQASCHANNA commited on
Commit
047d4a1
·
verified ·
1 Parent(s): 8508fef

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +112 -130
app.py CHANGED
@@ -1,144 +1,126 @@
1
  import os
2
  import streamlit as st
3
  from openai import OpenAI
4
- import random
5
- import json
6
- import re
 
 
7
 
8
  class QuizEngine:
9
  def __init__(self, api_key):
10
- self.client = OpenAI(
11
- api_key=api_key,
12
- base_url="https://api.x.ai/v1"
13
- )
14
- self.subject = ""
15
- self.difficulty = ""
16
- self.num_questions = 0
17
- self.questions = []
18
 
19
- def parse_quiz_response(self, response_text):
 
 
20
  """
21
- Parse the quiz response text into a structured format with enhanced debugging
 
 
 
 
 
 
 
 
 
 
 
 
22
  """
23
- st.write("Raw Response Text:")
24
- st.code(response_text)
25
 
26
- # Multiple parsing strategies
27
- parsing_strategies = [
28
- # Strategy 1: Detailed regex parsing
29
- r'(\d+)\.\s*(.+?)\n+A\.\s*(.+?)\n+B\.\s*(.+?)\n+C\.\s*(.+?)\n+D\.\s*(.+?)\n+Correct\s*[Aa]nswer:\s*([ABCD])',
30
 
31
- # Strategy 2: More flexible parsing
32
- r'(Question:)\s*(.+?)\n+(?:Options:)?\s*A\.\s*(.+?)\n+B\.\s*(.+?)\n+C\.\s*(.+?)\n+D\.\s*(.+?)\n+(?:Correct\s*[Aa]nswer:)?\s*([ABCD])',
33
- ]
34
-
35
- questions = []
36
- for pattern in parsing_strategies:
37
- matches = re.findall(pattern, response_text, re.DOTALL | re.IGNORECASE)
 
 
38
 
39
- if matches:
40
- for match in matches:
41
- # Handling different match lengths based on regex capture groups
42
- if len(match) == 7:
43
- question = {
44
- "question": match[1].strip(),
45
- "options": [match[2].strip(), match[3].strip(), match[4].strip(), match[5].strip()],
46
- "correct_answer": match[6].strip()
47
- }
48
- elif len(match) == 6:
49
- question = {
50
- "question": match[1].strip(),
51
- "options": [match[2].strip(), match[3].strip(), match[4].strip(), match[5].strip()],
52
- "correct_answer": "A" # Default if not specified
53
- }
54
-
55
- questions.append(question)
56
-
57
- break # Stop if we find any matches
58
-
59
- st.write("Parsed Questions:")
60
- st.json(questions)
61
-
62
- return questions
63
-
64
- def generate_quiz(self, subject, difficulty, num_questions):
65
- """
66
- Generate a quiz using Grok AI with multiple prompt strategies
67
- """
68
- self.subject = subject
69
- self.difficulty = difficulty
70
- self.num_questions = num_questions
71
-
72
- # Multiple prompt strategies
73
- prompt_strategies = [
74
- f"""
75
- Create a {difficulty} level educational quiz about {subject}.
76
- Generate {num_questions} multiple-choice questions.
77
-
78
- For each question, provide:
79
- Question: [Question text]
80
- A. [Option A]
81
- B. [Option B]
82
- C. [Option C]
83
- D. [Option D]
84
- Correct Answer: [A/B/C/D]
85
-
86
- Ensure questions test deep understanding and are challenging.
87
- """,
88
 
89
- f"""
90
- Design a comprehensive {difficulty} level quiz on {subject}.
91
- Create {num_questions} thought-provoking multiple-choice questions.
92
-
93
- Format:
94
- 1. [Question number]
95
- Question: [Detailed question text]
96
- Options:
97
- A. [First option]
98
- B. [Second option]
99
- C. [Third option]
100
- D. [Fourth option]
101
- Answer: [Correct option letter]
102
- """,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
 
104
- f"""
105
- Develop an educational quiz covering {subject} at {difficulty} level.
106
- Number of questions: {num_questions}
107
-
108
- Quiz Structure:
109
- - Varied, challenging questions
110
- - 4 multiple-choice options per question
111
- - Clear indication of correct answer
112
- - Focus on comprehensive understanding
113
- """
114
- ]
115
-
116
- # Try different prompt strategies
117
- for prompt in prompt_strategies:
118
- try:
119
- response = self.client.chat.completions.create(
120
- model="grok-beta",
121
- messages=[
122
- {"role": "system", "content": "You are an expert educational quiz generator."},
123
- {"role": "user", "content": prompt}
124
- ]
125
- )
126
-
127
- # Extract response text
128
- response_text = response.choices[0].message.content
129
-
130
- # Parse the response
131
- self.questions = self.parse_quiz_response(response_text)
132
-
133
- if self.questions:
134
- return self.questions
135
-
136
- except Exception as e:
137
- st.error(f"Error with prompt strategy: {e}")
138
-
139
- st.error("Could not generate quiz with any prompt strategy.")
140
- return []
141
-
142
- # ... [Rest of the code remains the same as in the previous version]
143
-
144
- # The main() function and other parts of the code remain unchanged
 
1
  import os
2
  import streamlit as st
3
  from openai import OpenAI
4
+ import traceback
5
+ import logging
6
+
7
+ # Configure logging
8
+ logging.basicConfig(level=logging.DEBUG)
9
 
10
  class QuizEngine:
11
  def __init__(self, api_key):
12
+ try:
13
+ self.client = OpenAI(
14
+ api_key=api_key,
15
+ base_url="https://api.x.ai/v1"
16
+ )
17
+ except Exception as e:
18
+ st.error(f"Error initializing OpenAI client: {e}")
19
+ logging.error(f"Client initialization error: {traceback.format_exc()}")
20
 
21
+ def generate_quiz(self, subject, difficulty, num_questions):
22
+ """
23
+ Simplified quiz generation with extensive error handling
24
  """
25
+ st.write("Starting quiz generation...")
26
+
27
+ # Simplified prompt
28
+ prompt = f"""
29
+ Create a {difficulty} level quiz about {subject} with {num_questions} multiple-choice questions.
30
+
31
+ For each question, provide:
32
+ Question: [Question text]
33
+ A) [Option A]
34
+ B) [Option B]
35
+ C) [Option C]
36
+ D) [Option D]
37
+ Correct Answer: [A/B/C/D]
38
  """
 
 
39
 
40
+ try:
41
+ st.write("Sending request to Grok API...")
 
 
42
 
43
+ # Use a more basic API call
44
+ response = self.client.chat.completions.create(
45
+ model="grok-beta",
46
+ messages=[
47
+ {"role": "system", "content": "You are a quiz generator."},
48
+ {"role": "user", "content": prompt}
49
+ ],
50
+ max_tokens=1000 # Limit response length
51
+ )
52
 
53
+ # Extract and display full response
54
+ full_response = response.choices[0].message.content
55
+ st.write("API Response:")
56
+ st.code(full_response)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
+ return full_response
59
+
60
+ except Exception as e:
61
+ st.error(f"Error generating quiz: {e}")
62
+ logging.error(f"Quiz generation error: {traceback.format_exc()}")
63
+ return None
64
+
65
+ def main():
66
+ # Set page configuration
67
+ st.set_page_config(page_title="Grok Quiz Generator", page_icon="🧠")
68
+
69
+ # Main title
70
+ st.title("🤖 Grok AI Quiz Generator")
71
+
72
+ # Add debug information about environment
73
+ st.write("### System Diagnostics")
74
+
75
+ try:
76
+ # OpenAI version check
77
+ import openai
78
+ st.write(f"OpenAI Library Version: {openai.__version__}")
79
+ except Exception as e:
80
+ st.error(f"Error checking OpenAI version: {e}")
81
+
82
+ # Sidebar for configuration
83
+ st.sidebar.title("Quiz Configuration")
84
+
85
+ # API Key input
86
+ api_key = st.sidebar.text_input("Enter Grok API Key", type="password")
87
+
88
+ # Subject and difficulty selection
89
+ subjects = [
90
+ "Mathematics", "Science", "History",
91
+ "Computer Science", "Literature", "Geography"
92
+ ]
93
+ subject = st.sidebar.selectbox("Select Subject", subjects)
94
+
95
+ difficulties = ["Easy", "Medium", "Hard"]
96
+ difficulty = st.sidebar.selectbox("Select Difficulty", difficulties)
97
+
98
+ # Number of questions
99
+ num_questions = st.sidebar.slider("Number of Questions", 3, 10, 5)
100
+
101
+ # Generate Quiz Button
102
+ if st.sidebar.button("Generate Quiz"):
103
+ # Validate API Key
104
+ if not api_key:
105
+ st.error("Please enter your Grok API Key")
106
+ return
107
+
108
+ try:
109
+ # Initialize Quiz Engine
110
+ quiz_engine = QuizEngine(api_key)
111
 
112
+ # Generate Quiz
113
+ quiz_content = quiz_engine.generate_quiz(subject, difficulty, num_questions)
114
+
115
+ if quiz_content:
116
+ st.write("### Generated Quiz")
117
+ st.text_area("Quiz Content", quiz_content, height=300)
118
+ else:
119
+ st.error("Failed to generate quiz. Check the error messages above.")
120
+
121
+ except Exception as e:
122
+ st.error(f"Unexpected error: {e}")
123
+ logging.error(f"Unexpected error: {traceback.format_exc()}")
124
+
125
+ if __name__ == "__main__":
126
+ main()