Spaces:
Sleeping
Sleeping
Update contin_gen.py
Browse files- contin_gen.py +210 -210
contin_gen.py
CHANGED
@@ -1,211 +1,211 @@
|
|
1 |
-
import time
|
2 |
-
import logging
|
3 |
-
import openai
|
4 |
-
import re
|
5 |
-
from models import get_db_connection, add_ques_llm, create_quiz_by_id
|
6 |
-
import os
|
7 |
-
|
8 |
-
logging.basicConfig(
|
9 |
-
level=logging.INFO,
|
10 |
-
format="%(asctime)s - %(levelname)s - %(message)s",
|
11 |
-
|
12 |
-
|
13 |
-
logging.StreamHandler()
|
14 |
-
]
|
15 |
-
)
|
16 |
-
client = openai.OpenAI(
|
17 |
-
base_url="https://api.groq.com/openai/v1",
|
18 |
-
api_key=os.getenv("GROQ_API_KEY")
|
19 |
-
)
|
20 |
-
|
21 |
-
|
22 |
-
def generate_question_random(theme):
|
23 |
-
ques_prompt = (
|
24 |
-
f"Generate only one unique, factually accurate quiz question on the theme of {theme}. \n "
|
25 |
-
"Make sure each time the question generated is very unique and from a new topic. Make the question as innovative as possible so that it doesn't get repeated."
|
26 |
-
"Generate question on a different theme each time involve literature, sports, science, mathematics, technology and other themes"
|
27 |
-
"Question generated in each chat has to be a new question. Don't generate even a similar question to previous one."
|
28 |
-
"Ensure that:\n"
|
29 |
-
"1. The question is unique.\n"
|
30 |
-
"2. Options: A, B, C, D.\n"
|
31 |
-
"3. Correct answer should be marked.\n"
|
32 |
-
"4. Difficulty: Easy, Medium, Hard.\n"
|
33 |
-
"Provide response in this format:\n"
|
34 |
-
"Theme: [Theme]\n"
|
35 |
-
"Question: [Your question here]\n"
|
36 |
-
"A) [Option A]\n"
|
37 |
-
"B) [Option B]\n"
|
38 |
-
"C) [Option C]\n"
|
39 |
-
"D) [Option D]\n"
|
40 |
-
"Correct answer: [Correct option letter]\n"
|
41 |
-
"Difficulty level: [Easy/Medium/Hard]"
|
42 |
-
)
|
43 |
-
|
44 |
-
response = client.chat.completions.create(
|
45 |
-
model="llama-3.3-70b-versatile",
|
46 |
-
messages=[
|
47 |
-
{"role": "system", "content": "You are a helpful assistant who generates quizzes."},
|
48 |
-
{"role": "user", "content": ques_prompt}
|
49 |
-
],
|
50 |
-
temperature=0.5,
|
51 |
-
max_tokens=1024
|
52 |
-
)
|
53 |
-
return response.choices[0].message.content
|
54 |
-
|
55 |
-
def parse_question(response_text):
|
56 |
-
"""Extracts theme, question, options, correct answer, and difficulty from LLM response."""
|
57 |
-
|
58 |
-
question_data = {}
|
59 |
-
|
60 |
-
question_match = re.search(r'Question:\s*(.*)', response_text)
|
61 |
-
options_matches = re.findall(r'([A-D])\)\s*(.*)', response_text)
|
62 |
-
correct_answer_match = re.search(r'Correct answer:\s*([A-D])', response_text)
|
63 |
-
difficulty_match = re.search(r'Difficulty level:\s*(.*)', response_text)
|
64 |
-
|
65 |
-
if question_match and options_matches and correct_answer_match:
|
66 |
-
question = question_match.group(1).strip()
|
67 |
-
question_data["question"] = question
|
68 |
-
options = [f"{opt[0]}) {opt[1].strip()}" for opt in options_matches]
|
69 |
-
question_data["options"] = options
|
70 |
-
correct_option = correct_answer_match.group(1).strip().upper()
|
71 |
-
question_data["correct_answer"] = correct_option
|
72 |
-
difficulty = difficulty_match.group(1).strip()
|
73 |
-
question_data["difficulty"] = difficulty
|
74 |
-
|
75 |
-
logging.debug("Parsed question: %s", question)
|
76 |
-
logging.debug("Parsed options: %s", options)
|
77 |
-
logging.debug("Parsed correct option: %s", correct_option)
|
78 |
-
logging.debug("Parsed difficulty: %s", difficulty)
|
79 |
-
|
80 |
-
|
81 |
-
if correct_option not in ['A', 'B', 'C', 'D']:
|
82 |
-
raise ValueError("The correct option is invalid.")
|
83 |
-
|
84 |
-
return question_data if "question" in question_data else None
|
85 |
-
|
86 |
-
|
87 |
-
else:
|
88 |
-
raise ValueError("Question format is incorrect or missing correct option.")
|
89 |
-
|
90 |
-
|
91 |
-
def generate_quiz_daily():
|
92 |
-
connection = get_db_connection()
|
93 |
-
if not connection:
|
94 |
-
logging.error("Failed to connect to DB in generate_quiz_daily")
|
95 |
-
return
|
96 |
-
|
97 |
-
try:
|
98 |
-
cursor = connection.cursor()
|
99 |
-
cursor.execute("SELECT theme FROM themes")
|
100 |
-
themes = [row[0] for row in cursor.fetchall()]
|
101 |
-
|
102 |
-
for theme in themes:
|
103 |
-
theme = theme.lower()
|
104 |
-
try:
|
105 |
-
logging.info("Creating daily quiz from bank for theme: %s", theme)
|
106 |
-
result = create_quiz_by_id(theme, 5)
|
107 |
-
logging.info("Quiz created: %s", result)
|
108 |
-
except Exception as e:
|
109 |
-
logging.error("Failed to create quiz for theme %s: %s", theme, e)
|
110 |
-
finally:
|
111 |
-
cursor.close()
|
112 |
-
connection.close()
|
113 |
-
|
114 |
-
|
115 |
-
def continuous_generation():
|
116 |
-
generation_count = 0
|
117 |
-
last_quiz_creation = 0
|
118 |
-
|
119 |
-
while True:
|
120 |
-
logging.info("Generating a new quiz question...")
|
121 |
-
connection = get_db_connection()
|
122 |
-
if not connection:
|
123 |
-
logging.error("Failed to connect to DB in generate_quiz_daily")
|
124 |
-
return
|
125 |
-
|
126 |
-
try:
|
127 |
-
cursor = connection.cursor()
|
128 |
-
cursor.execute("SELECT theme FROM themes")
|
129 |
-
themes = [row[0] for row in cursor.fetchall()]
|
130 |
-
|
131 |
-
for theme in themes:
|
132 |
-
theme = theme.lower()
|
133 |
-
try:
|
134 |
-
logging.info("Creating daily question from bank for theme: %s", theme)
|
135 |
-
question_text = generate_question_random(theme)
|
136 |
-
|
137 |
-
if question_text:
|
138 |
-
try:
|
139 |
-
question_data = parse_question(question_text)
|
140 |
-
if question_data:
|
141 |
-
# theme = question_data["theme"].lower()
|
142 |
-
# added = add_theme_if_not_exists(theme)
|
143 |
-
|
144 |
-
logging.info(
|
145 |
-
"Storing Question - Theme: %s | Question: %s | Answer: %s | Difficulty: %s",
|
146 |
-
theme,
|
147 |
-
question_data["question"],
|
148 |
-
question_data["correct_answer"],
|
149 |
-
question_data["difficulty"]
|
150 |
-
)
|
151 |
-
result = add_ques_llm(
|
152 |
-
theme,
|
153 |
-
question_data["question"],
|
154 |
-
question_data["options"],
|
155 |
-
question_data["correct_answer"],
|
156 |
-
question_data["difficulty"]
|
157 |
-
)
|
158 |
-
if result == "True":
|
159 |
-
logging.info("New quiz question added successfully.")
|
160 |
-
else:
|
161 |
-
logging.warning("Failed to add question to DB.")
|
162 |
-
continue
|
163 |
-
else:
|
164 |
-
logging.warning("Could not parse generated question.")
|
165 |
-
except Exception as e:
|
166 |
-
logging.error("Error processing quiz data: %s", e)
|
167 |
-
|
168 |
-
logging.info("Question created")
|
169 |
-
except Exception as e:
|
170 |
-
logging.error("Failed to generate question for theme %s: %s", theme, e)
|
171 |
-
finally:
|
172 |
-
cursor.close()
|
173 |
-
connection.close()
|
174 |
-
|
175 |
-
generation_count += 1
|
176 |
-
|
177 |
-
if time.time() - last_quiz_creation >= 86400:
|
178 |
-
logging.info("Running daily quiz creation for all themes...")
|
179 |
-
generate_quiz_daily()
|
180 |
-
last_quiz_creation = time.time()
|
181 |
-
|
182 |
-
time.sleep(20)
|
183 |
-
|
184 |
-
if __name__ == '__main__':
|
185 |
-
import time
|
186 |
-
import traceback
|
187 |
-
|
188 |
-
while True:
|
189 |
-
try:
|
190 |
-
continuous_generation()
|
191 |
-
except Exception as e:
|
192 |
-
print("continuous_generation crashed:", e)
|
193 |
-
traceback.print_exc()
|
194 |
-
print("Restarting in 5 seconds...")
|
195 |
-
time.sleep(5)
|
196 |
-
|
197 |
-
# from app import app
|
198 |
-
|
199 |
-
# if __name__ == '__main__':
|
200 |
-
# import time
|
201 |
-
# import traceback
|
202 |
-
|
203 |
-
# with app.app_context():
|
204 |
-
# while True:
|
205 |
-
# try:
|
206 |
-
# continuous_generation()
|
207 |
-
# except Exception as e:
|
208 |
-
# print("continuous_generation crashed:", e)
|
209 |
-
# traceback.print_exc()
|
210 |
-
# print("Restarting in 5 seconds...")
|
211 |
# time.sleep(5)
|
|
|
1 |
+
import time
|
2 |
+
import logging
|
3 |
+
import openai
|
4 |
+
import re
|
5 |
+
from models import get_db_connection, add_ques_llm, create_quiz_by_id
|
6 |
+
import os
|
7 |
+
|
8 |
+
logging.basicConfig(
|
9 |
+
level=logging.INFO,
|
10 |
+
format="%(asctime)s - %(levelname)s - %(message)s",
|
11 |
+
filename=os.path.join('/tmp', 'app.log'),
|
12 |
+
handlers=[
|
13 |
+
logging.StreamHandler()
|
14 |
+
]
|
15 |
+
)
|
16 |
+
client = openai.OpenAI(
|
17 |
+
base_url="https://api.groq.com/openai/v1",
|
18 |
+
api_key=os.getenv("GROQ_API_KEY")
|
19 |
+
)
|
20 |
+
|
21 |
+
|
22 |
+
def generate_question_random(theme):
|
23 |
+
ques_prompt = (
|
24 |
+
f"Generate only one unique, factually accurate quiz question on the theme of {theme}. \n "
|
25 |
+
"Make sure each time the question generated is very unique and from a new topic. Make the question as innovative as possible so that it doesn't get repeated."
|
26 |
+
"Generate question on a different theme each time involve literature, sports, science, mathematics, technology and other themes"
|
27 |
+
"Question generated in each chat has to be a new question. Don't generate even a similar question to previous one."
|
28 |
+
"Ensure that:\n"
|
29 |
+
"1. The question is unique.\n"
|
30 |
+
"2. Options: A, B, C, D.\n"
|
31 |
+
"3. Correct answer should be marked.\n"
|
32 |
+
"4. Difficulty: Easy, Medium, Hard.\n"
|
33 |
+
"Provide response in this format:\n"
|
34 |
+
"Theme: [Theme]\n"
|
35 |
+
"Question: [Your question here]\n"
|
36 |
+
"A) [Option A]\n"
|
37 |
+
"B) [Option B]\n"
|
38 |
+
"C) [Option C]\n"
|
39 |
+
"D) [Option D]\n"
|
40 |
+
"Correct answer: [Correct option letter]\n"
|
41 |
+
"Difficulty level: [Easy/Medium/Hard]"
|
42 |
+
)
|
43 |
+
|
44 |
+
response = client.chat.completions.create(
|
45 |
+
model="llama-3.3-70b-versatile",
|
46 |
+
messages=[
|
47 |
+
{"role": "system", "content": "You are a helpful assistant who generates quizzes."},
|
48 |
+
{"role": "user", "content": ques_prompt}
|
49 |
+
],
|
50 |
+
temperature=0.5,
|
51 |
+
max_tokens=1024
|
52 |
+
)
|
53 |
+
return response.choices[0].message.content
|
54 |
+
|
55 |
+
def parse_question(response_text):
|
56 |
+
"""Extracts theme, question, options, correct answer, and difficulty from LLM response."""
|
57 |
+
|
58 |
+
question_data = {}
|
59 |
+
|
60 |
+
question_match = re.search(r'Question:\s*(.*)', response_text)
|
61 |
+
options_matches = re.findall(r'([A-D])\)\s*(.*)', response_text)
|
62 |
+
correct_answer_match = re.search(r'Correct answer:\s*([A-D])', response_text)
|
63 |
+
difficulty_match = re.search(r'Difficulty level:\s*(.*)', response_text)
|
64 |
+
|
65 |
+
if question_match and options_matches and correct_answer_match:
|
66 |
+
question = question_match.group(1).strip()
|
67 |
+
question_data["question"] = question
|
68 |
+
options = [f"{opt[0]}) {opt[1].strip()}" for opt in options_matches]
|
69 |
+
question_data["options"] = options
|
70 |
+
correct_option = correct_answer_match.group(1).strip().upper()
|
71 |
+
question_data["correct_answer"] = correct_option
|
72 |
+
difficulty = difficulty_match.group(1).strip()
|
73 |
+
question_data["difficulty"] = difficulty
|
74 |
+
|
75 |
+
logging.debug("Parsed question: %s", question)
|
76 |
+
logging.debug("Parsed options: %s", options)
|
77 |
+
logging.debug("Parsed correct option: %s", correct_option)
|
78 |
+
logging.debug("Parsed difficulty: %s", difficulty)
|
79 |
+
|
80 |
+
|
81 |
+
if correct_option not in ['A', 'B', 'C', 'D']:
|
82 |
+
raise ValueError("The correct option is invalid.")
|
83 |
+
|
84 |
+
return question_data if "question" in question_data else None
|
85 |
+
|
86 |
+
|
87 |
+
else:
|
88 |
+
raise ValueError("Question format is incorrect or missing correct option.")
|
89 |
+
|
90 |
+
|
91 |
+
def generate_quiz_daily():
|
92 |
+
connection = get_db_connection()
|
93 |
+
if not connection:
|
94 |
+
logging.error("Failed to connect to DB in generate_quiz_daily")
|
95 |
+
return
|
96 |
+
|
97 |
+
try:
|
98 |
+
cursor = connection.cursor()
|
99 |
+
cursor.execute("SELECT theme FROM themes")
|
100 |
+
themes = [row[0] for row in cursor.fetchall()]
|
101 |
+
|
102 |
+
for theme in themes:
|
103 |
+
theme = theme.lower()
|
104 |
+
try:
|
105 |
+
logging.info("Creating daily quiz from bank for theme: %s", theme)
|
106 |
+
result = create_quiz_by_id(theme, 5)
|
107 |
+
logging.info("Quiz created: %s", result)
|
108 |
+
except Exception as e:
|
109 |
+
logging.error("Failed to create quiz for theme %s: %s", theme, e)
|
110 |
+
finally:
|
111 |
+
cursor.close()
|
112 |
+
connection.close()
|
113 |
+
|
114 |
+
|
115 |
+
def continuous_generation():
|
116 |
+
generation_count = 0
|
117 |
+
last_quiz_creation = 0
|
118 |
+
|
119 |
+
while True:
|
120 |
+
logging.info("Generating a new quiz question...")
|
121 |
+
connection = get_db_connection()
|
122 |
+
if not connection:
|
123 |
+
logging.error("Failed to connect to DB in generate_quiz_daily")
|
124 |
+
return
|
125 |
+
|
126 |
+
try:
|
127 |
+
cursor = connection.cursor()
|
128 |
+
cursor.execute("SELECT theme FROM themes")
|
129 |
+
themes = [row[0] for row in cursor.fetchall()]
|
130 |
+
|
131 |
+
for theme in themes:
|
132 |
+
theme = theme.lower()
|
133 |
+
try:
|
134 |
+
logging.info("Creating daily question from bank for theme: %s", theme)
|
135 |
+
question_text = generate_question_random(theme)
|
136 |
+
|
137 |
+
if question_text:
|
138 |
+
try:
|
139 |
+
question_data = parse_question(question_text)
|
140 |
+
if question_data:
|
141 |
+
# theme = question_data["theme"].lower()
|
142 |
+
# added = add_theme_if_not_exists(theme)
|
143 |
+
|
144 |
+
logging.info(
|
145 |
+
"Storing Question - Theme: %s | Question: %s | Answer: %s | Difficulty: %s",
|
146 |
+
theme,
|
147 |
+
question_data["question"],
|
148 |
+
question_data["correct_answer"],
|
149 |
+
question_data["difficulty"]
|
150 |
+
)
|
151 |
+
result = add_ques_llm(
|
152 |
+
theme,
|
153 |
+
question_data["question"],
|
154 |
+
question_data["options"],
|
155 |
+
question_data["correct_answer"],
|
156 |
+
question_data["difficulty"]
|
157 |
+
)
|
158 |
+
if result == "True":
|
159 |
+
logging.info("New quiz question added successfully.")
|
160 |
+
else:
|
161 |
+
logging.warning("Failed to add question to DB.")
|
162 |
+
continue
|
163 |
+
else:
|
164 |
+
logging.warning("Could not parse generated question.")
|
165 |
+
except Exception as e:
|
166 |
+
logging.error("Error processing quiz data: %s", e)
|
167 |
+
|
168 |
+
logging.info("Question created")
|
169 |
+
except Exception as e:
|
170 |
+
logging.error("Failed to generate question for theme %s: %s", theme, e)
|
171 |
+
finally:
|
172 |
+
cursor.close()
|
173 |
+
connection.close()
|
174 |
+
|
175 |
+
generation_count += 1
|
176 |
+
|
177 |
+
if time.time() - last_quiz_creation >= 86400:
|
178 |
+
logging.info("Running daily quiz creation for all themes...")
|
179 |
+
generate_quiz_daily()
|
180 |
+
last_quiz_creation = time.time()
|
181 |
+
|
182 |
+
time.sleep(20)
|
183 |
+
|
184 |
+
if __name__ == '__main__':
|
185 |
+
import time
|
186 |
+
import traceback
|
187 |
+
|
188 |
+
while True:
|
189 |
+
try:
|
190 |
+
continuous_generation()
|
191 |
+
except Exception as e:
|
192 |
+
print("continuous_generation crashed:", e)
|
193 |
+
traceback.print_exc()
|
194 |
+
print("Restarting in 5 seconds...")
|
195 |
+
time.sleep(5)
|
196 |
+
|
197 |
+
# from app import app
|
198 |
+
|
199 |
+
# if __name__ == '__main__':
|
200 |
+
# import time
|
201 |
+
# import traceback
|
202 |
+
|
203 |
+
# with app.app_context():
|
204 |
+
# while True:
|
205 |
+
# try:
|
206 |
+
# continuous_generation()
|
207 |
+
# except Exception as e:
|
208 |
+
# print("continuous_generation crashed:", e)
|
209 |
+
# traceback.print_exc()
|
210 |
+
# print("Restarting in 5 seconds...")
|
211 |
# time.sleep(5)
|