Spaces:
Build error
Build error
update remote
Browse files- pages/2_Text_prompt.py +4 -390
- pdfutils.py +152 -4
- users.db +0 -0
pages/2_Text_prompt.py
CHANGED
|
@@ -14,12 +14,12 @@ import re
|
|
| 14 |
from reportlab.platypus import Paragraph, Frame, Spacer
|
| 15 |
from reportlab.lib.styles import getSampleStyleSheet
|
| 16 |
import shutil
|
|
|
|
| 17 |
|
| 18 |
MODEL_ID = "gemini-2.0-flash-exp"
|
| 19 |
api_key = os.getenv("GEMINI_API_KEY")
|
| 20 |
model_id = MODEL_ID
|
| 21 |
genai.configure(api_key=api_key)
|
| 22 |
-
enable_stream = False
|
| 23 |
|
| 24 |
if "model" not in st.session_state:
|
| 25 |
st.session_state.model = genai.GenerativeModel(MODEL_ID)
|
|
@@ -48,392 +48,6 @@ def save_user_prompt(username, prompt_time, prompt_type):
|
|
| 48 |
conn.commit()
|
| 49 |
conn.close()
|
| 50 |
|
| 51 |
-
def merge_json_strings(json_str1, json_str2):
|
| 52 |
-
"""
|
| 53 |
-
Merges two JSON strings into one, handling potential markdown tags.
|
| 54 |
-
|
| 55 |
-
Args:
|
| 56 |
-
json_str1: The first JSON string, potentially with markdown tags.
|
| 57 |
-
json_str2: The second JSON string, potentially with markdown tags.
|
| 58 |
-
|
| 59 |
-
Returns:
|
| 60 |
-
A cleaned JSON string representing the merged JSON objects.
|
| 61 |
-
"""
|
| 62 |
-
|
| 63 |
-
# Clean the JSON strings by removing markdown tags
|
| 64 |
-
cleaned_json_str1 = _clean_markdown(json_str1)
|
| 65 |
-
cleaned_json_str2 = _clean_markdown(json_str2)
|
| 66 |
-
|
| 67 |
-
try:
|
| 68 |
-
# Parse the cleaned JSON strings into Python dictionaries
|
| 69 |
-
data1 = json.loads(cleaned_json_str1)
|
| 70 |
-
data2 = json.loads(cleaned_json_str2)
|
| 71 |
-
|
| 72 |
-
# Merge the dictionaries
|
| 73 |
-
merged_data = _merge_dicts(data1, data2)
|
| 74 |
-
|
| 75 |
-
# Convert the merged dictionary back into a JSON string
|
| 76 |
-
return json.dumps(merged_data, indent=2)
|
| 77 |
-
except json.JSONDecodeError as e:
|
| 78 |
-
return f"Error decoding JSON: {e}"
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
def _clean_markdown(text):
|
| 82 |
-
"""
|
| 83 |
-
Removes markdown tags from a string if they exist.
|
| 84 |
-
Otherwise, returns the original string unchanged.
|
| 85 |
-
|
| 86 |
-
Args:
|
| 87 |
-
text: The input string.
|
| 88 |
-
|
| 89 |
-
Returns:
|
| 90 |
-
The string with markdown tags removed, or the original string
|
| 91 |
-
if no markdown tags were found.
|
| 92 |
-
"""
|
| 93 |
-
try:
|
| 94 |
-
# Check if the string contains markdown
|
| 95 |
-
if re.match(r"^```json\s*", text) and re.search(r"\s*```$", text):
|
| 96 |
-
# Remove leading ```json
|
| 97 |
-
text = re.sub(r"^```json\s*", "", text)
|
| 98 |
-
# Remove trailing ```
|
| 99 |
-
text = re.sub(r"\s*```$", "", text)
|
| 100 |
-
return text
|
| 101 |
-
except Exception as e:
|
| 102 |
-
# Log the error
|
| 103 |
-
st.error(f"Error cleaning markdown: {e}")
|
| 104 |
-
return None
|
| 105 |
-
|
| 106 |
-
def _merge_dicts(data1, data2):
|
| 107 |
-
"""
|
| 108 |
-
Recursively merges two data structures.
|
| 109 |
-
|
| 110 |
-
Handles merging of dictionaries and lists.
|
| 111 |
-
For dictionaries, if a key exists in both and both values are dictionaries
|
| 112 |
-
or lists, they are merged recursively. Otherwise, the value from data2 is used.
|
| 113 |
-
For lists, the lists are concatenated.
|
| 114 |
-
|
| 115 |
-
Args:
|
| 116 |
-
data1: The first data structure (dictionary or list).
|
| 117 |
-
data2: The second data structure (dictionary or list).
|
| 118 |
-
|
| 119 |
-
Returns:
|
| 120 |
-
The merged data structure.
|
| 121 |
-
|
| 122 |
-
Raises:
|
| 123 |
-
ValueError: If the data types are not supported for merging.
|
| 124 |
-
"""
|
| 125 |
-
if isinstance(data1, dict) and isinstance(data2, dict):
|
| 126 |
-
for key, value in data2.items():
|
| 127 |
-
if key in data1 and isinstance(data1[key], (dict, list)) and isinstance(value, type(data1[key])):
|
| 128 |
-
_merge_dicts(data1[key], value)
|
| 129 |
-
else:
|
| 130 |
-
data1[key] = value
|
| 131 |
-
return data1
|
| 132 |
-
elif isinstance(data1, list) and isinstance(data2, list):
|
| 133 |
-
return data1 + data2
|
| 134 |
-
else:
|
| 135 |
-
raise ValueError("Unsupported data types for merging")
|
| 136 |
-
|
| 137 |
-
def create_json(metadata, content):
|
| 138 |
-
"""
|
| 139 |
-
Creates a JSON string combining metadata and content.
|
| 140 |
-
|
| 141 |
-
Args:
|
| 142 |
-
metadata: A dictionary containing metadata information.
|
| 143 |
-
content: A dictionary containing the quiz content.
|
| 144 |
-
|
| 145 |
-
Returns:
|
| 146 |
-
A string representing the combined JSON data.
|
| 147 |
-
"""
|
| 148 |
-
|
| 149 |
-
# Create metadata with timestamp
|
| 150 |
-
metadata = {
|
| 151 |
-
"subject": metadata.get("subject", ""),
|
| 152 |
-
"topic": metadata.get("topic", ""),
|
| 153 |
-
"num_questions": metadata.get("num_questions", 0),
|
| 154 |
-
"exam_type": metadata.get("exam_type", ""),
|
| 155 |
-
"timestamp": datetime.datetime.now().isoformat()
|
| 156 |
-
}
|
| 157 |
-
|
| 158 |
-
# Combine metadata and content
|
| 159 |
-
combined_data = {"metadata": metadata, "content": content}
|
| 160 |
-
|
| 161 |
-
# Convert to JSON string
|
| 162 |
-
json_string = json.dumps(combined_data, indent=4)
|
| 163 |
-
|
| 164 |
-
return json_string
|
| 165 |
-
|
| 166 |
-
def create_pdf(data):
|
| 167 |
-
"""
|
| 168 |
-
Creates a PDF file with text wrapping for quiz content, supporting multiple question types.
|
| 169 |
-
"""
|
| 170 |
-
try:
|
| 171 |
-
# Load the JSON data
|
| 172 |
-
data = json.loads(data)
|
| 173 |
-
|
| 174 |
-
if 'metadata' not in data or 'content' not in data:
|
| 175 |
-
st.error("Error: Invalid data format. Missing 'metadata' or 'content' keys.")
|
| 176 |
-
return None
|
| 177 |
-
|
| 178 |
-
metadata = data['metadata']
|
| 179 |
-
content = data['content']
|
| 180 |
-
|
| 181 |
-
# Validate metadata
|
| 182 |
-
required_metadata_keys = ['subject', 'topic', 'exam_type', 'num_questions']
|
| 183 |
-
if not all(key in metadata for key in required_metadata_keys):
|
| 184 |
-
st.error("Error: Invalid metadata format. Missing required keys.")
|
| 185 |
-
return None
|
| 186 |
-
|
| 187 |
-
# Create a unique filename with timestamp
|
| 188 |
-
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 189 |
-
pdf_filename = f"quiz_output_{timestamp}.pdf"
|
| 190 |
-
temp_dir = tempfile.gettempdir()
|
| 191 |
-
pdf_path = os.path.join(temp_dir, pdf_filename)
|
| 192 |
-
|
| 193 |
-
c = canvas.Canvas(pdf_path, pagesize=A4)
|
| 194 |
-
c.setFont("Helvetica", 10)
|
| 195 |
-
|
| 196 |
-
styles = getSampleStyleSheet()
|
| 197 |
-
text_style = styles['Normal']
|
| 198 |
-
|
| 199 |
-
# Starting position
|
| 200 |
-
margin_left = 50
|
| 201 |
-
y_position = 750
|
| 202 |
-
line_height = 12 # Adjusted for tighter spacing
|
| 203 |
-
frame_width = 500
|
| 204 |
-
first_page = True
|
| 205 |
-
|
| 206 |
-
def wrap_text_draw(text, x, y):
|
| 207 |
-
"""
|
| 208 |
-
Wraps and draws text using ReportLab's Paragraph for automatic line breaks.
|
| 209 |
-
"""
|
| 210 |
-
p = Paragraph(text, text_style)
|
| 211 |
-
width, height = p.wrap(frame_width, y)
|
| 212 |
-
p.drawOn(c, x, y - height)
|
| 213 |
-
return height
|
| 214 |
-
|
| 215 |
-
# Print metadata once on the first page
|
| 216 |
-
if first_page:
|
| 217 |
-
for key, label in [("subject", "Subject"), ("topic", "Topic"),
|
| 218 |
-
("exam_type", "Type"), ("num_questions", "Number of Questions")]:
|
| 219 |
-
c.drawString(margin_left, y_position, f"{label}: {metadata[key]}")
|
| 220 |
-
y_position -= line_height
|
| 221 |
-
y_position -= line_height
|
| 222 |
-
first_page = False
|
| 223 |
-
|
| 224 |
-
# Render questions and options
|
| 225 |
-
for idx, q in enumerate(content):
|
| 226 |
-
if not isinstance(q, dict):
|
| 227 |
-
st.error(f"Error: Invalid question format at index {idx}. Skipping...")
|
| 228 |
-
continue
|
| 229 |
-
|
| 230 |
-
question_text = f"{idx + 1}. {q.get('question', q.get('statement', ''))}"
|
| 231 |
-
height = wrap_text_draw(question_text, margin_left, y_position)
|
| 232 |
-
y_position -= (height + line_height)
|
| 233 |
-
|
| 234 |
-
if y_position < 50:
|
| 235 |
-
c.showPage()
|
| 236 |
-
c.setFont("Helvetica", 10)
|
| 237 |
-
y_position = 750
|
| 238 |
-
|
| 239 |
-
# Handle specific exam types
|
| 240 |
-
exam_type = metadata['exam_type']
|
| 241 |
-
|
| 242 |
-
if exam_type == "Multiple Choice":
|
| 243 |
-
for option_idx, option in enumerate(q['options'], ord('a')):
|
| 244 |
-
option_text = f"{chr(option_idx)}) {option}"
|
| 245 |
-
height = wrap_text_draw(option_text, margin_left + 20, y_position)
|
| 246 |
-
y_position -= (height + line_height)
|
| 247 |
-
|
| 248 |
-
if y_position < 50:
|
| 249 |
-
c.showPage()
|
| 250 |
-
c.setFont("Helvetica", 10)
|
| 251 |
-
y_position = 750
|
| 252 |
-
|
| 253 |
-
# Print correct answer
|
| 254 |
-
correct_answer_text = f"Correct Answer: {q['correct_answer']}"
|
| 255 |
-
height = wrap_text_draw(correct_answer_text, margin_left + 20, y_position)
|
| 256 |
-
y_position -= (height + line_height)
|
| 257 |
-
|
| 258 |
-
elif exam_type == "True or False":
|
| 259 |
-
for option in q['options']:
|
| 260 |
-
height = wrap_text_draw(option, margin_left + 20, y_position)
|
| 261 |
-
y_position -= (height + line_height)
|
| 262 |
-
|
| 263 |
-
if y_position < 50:
|
| 264 |
-
c.showPage()
|
| 265 |
-
c.setFont("Helvetica", 10)
|
| 266 |
-
y_position = 750
|
| 267 |
-
|
| 268 |
-
correct_answer_text = f"Correct Answer: {q['correct_answer']}"
|
| 269 |
-
height = wrap_text_draw(correct_answer_text, margin_left + 20, y_position)
|
| 270 |
-
y_position -= (height + line_height)
|
| 271 |
-
|
| 272 |
-
elif exam_type in ["Short Response", "Essay Type"]:
|
| 273 |
-
answer_text = f"Correct Answer: {q['correct_answer']}"
|
| 274 |
-
height = wrap_text_draw(answer_text, margin_left + 20, y_position)
|
| 275 |
-
y_position -= (height + line_height)
|
| 276 |
-
|
| 277 |
-
if y_position < 50:
|
| 278 |
-
c.showPage()
|
| 279 |
-
c.setFont("Helvetica", 10)
|
| 280 |
-
y_position = 750
|
| 281 |
-
|
| 282 |
-
# Add a footer
|
| 283 |
-
notice = "This exam was generated by the WVSU Exam Maker (c) 2025 West Visayas State University"
|
| 284 |
-
c.drawString(margin_left, y_position, notice)
|
| 285 |
-
|
| 286 |
-
c.save()
|
| 287 |
-
return pdf_path
|
| 288 |
-
|
| 289 |
-
except Exception as e:
|
| 290 |
-
st.error(f"Error creating PDF: {e}")
|
| 291 |
-
return None
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
def generate_quiz_content(data):
|
| 295 |
-
"""
|
| 296 |
-
Separates the metadata and content from a JSON string containing exam data.
|
| 297 |
-
Creates a markdown formatted text that contains the exam metadata and
|
| 298 |
-
enumerates the questions, options and answers nicely formatted for readability.
|
| 299 |
-
|
| 300 |
-
Args:
|
| 301 |
-
data: A JSON string containing the exam data.
|
| 302 |
-
|
| 303 |
-
Returns:
|
| 304 |
-
A markdown formatted string.
|
| 305 |
-
"""
|
| 306 |
-
data = json.loads(data)
|
| 307 |
-
metadata = data["metadata"]
|
| 308 |
-
content = data["content"]
|
| 309 |
-
exam_type = metadata["exam_type"]
|
| 310 |
-
if exam_type == "Multiple Choice":
|
| 311 |
-
md_text = f"""# {metadata['subject']} - {metadata['topic']}
|
| 312 |
-
|
| 313 |
-
**Exam Type:** {metadata['exam_type']}
|
| 314 |
-
**Number of Questions:** {metadata['num_questions']}
|
| 315 |
-
**Timestamp:** {metadata['timestamp']}
|
| 316 |
-
|
| 317 |
-
---
|
| 318 |
-
|
| 319 |
-
"""
|
| 320 |
-
for i, q in enumerate(content):
|
| 321 |
-
md_text += f"""Question {i+1}:
|
| 322 |
-
{q['question']}
|
| 323 |
-
|
| 324 |
-
"""
|
| 325 |
-
for j, option in enumerate(q['options'], ord('a')):
|
| 326 |
-
md_text += f"""{chr(j)}. {option}
|
| 327 |
-
|
| 328 |
-
"""
|
| 329 |
-
md_text += f"""**Correct Answer:** {q['correct_answer']}
|
| 330 |
-
|
| 331 |
-
---
|
| 332 |
-
|
| 333 |
-
"""
|
| 334 |
-
md_text += """This exam was generated by the WVSU Exam Maker
|
| 335 |
-
(c) 2025 West Visayas State University
|
| 336 |
-
"""
|
| 337 |
-
|
| 338 |
-
elif exam_type == "True or False":
|
| 339 |
-
md_text = f"""# {metadata['subject']} - {metadata['topic']}
|
| 340 |
-
|
| 341 |
-
**Exam Type:** {metadata['exam_type']}
|
| 342 |
-
**Number of Questions:** {metadata['num_questions']}
|
| 343 |
-
**Timestamp:** {metadata['timestamp']}
|
| 344 |
-
|
| 345 |
-
---
|
| 346 |
-
|
| 347 |
-
"""
|
| 348 |
-
|
| 349 |
-
for i, q in enumerate(content):
|
| 350 |
-
md_text += f"""Statement {i+1}:
|
| 351 |
-
|
| 352 |
-
{q['statement']}
|
| 353 |
-
|
| 354 |
-
"""
|
| 355 |
-
for j, option in enumerate(q['options'], ord('a')):
|
| 356 |
-
md_text += f"""{option}
|
| 357 |
-
"""
|
| 358 |
-
|
| 359 |
-
md_text += f"""**Correct Answer:** {q['correct_answer']}
|
| 360 |
-
|
| 361 |
-
---
|
| 362 |
-
"""
|
| 363 |
-
md_text += """This exam was generated by the WVSU Exam Maker
|
| 364 |
-
(c) 2025 West Visayas State University"""
|
| 365 |
-
|
| 366 |
-
elif exam_type == "Short Response" or exam_type == "Essay Type":
|
| 367 |
-
md_text = f"""# {metadata['subject']} - {metadata['topic']}
|
| 368 |
-
|
| 369 |
-
**Exam Type:** {metadata['exam_type']}
|
| 370 |
-
**Number of Questions:** {metadata['num_questions']}
|
| 371 |
-
**Timestamp:** {metadata['timestamp']}
|
| 372 |
-
|
| 373 |
-
---
|
| 374 |
-
|
| 375 |
-
"""
|
| 376 |
-
|
| 377 |
-
for i, q in enumerate(content):
|
| 378 |
-
md_text += f"""Question {i+1}:
|
| 379 |
-
|
| 380 |
-
{q['question']}
|
| 381 |
-
|
| 382 |
-
"""
|
| 383 |
-
md_text += f"""**Correct Answer:** {q['correct_answer']}
|
| 384 |
-
|
| 385 |
-
---
|
| 386 |
-
"""
|
| 387 |
-
md_text += """This exam was generated by the WVSU Exam Maker
|
| 388 |
-
(c) 2025 West Visayas State University"""
|
| 389 |
-
|
| 390 |
-
return md_text
|
| 391 |
-
|
| 392 |
-
def generate_metadata(subject, topic, num_questions, exam_type):
|
| 393 |
-
"""Generates quiz metadata as a dictionary combining num_questions,
|
| 394 |
-
exam_type, and timestamp.
|
| 395 |
-
|
| 396 |
-
Args:
|
| 397 |
-
num_questions: The number of questions in the exam (int).
|
| 398 |
-
exam_type: The type of exam (str).
|
| 399 |
-
|
| 400 |
-
Returns:
|
| 401 |
-
A dictionary containing the quiz metadata.
|
| 402 |
-
"""
|
| 403 |
-
|
| 404 |
-
# Format the timestamp
|
| 405 |
-
timestamp = datetime.datetime.now()
|
| 406 |
-
formatted_timestamp = timestamp.strftime("%Y-%m-%d %H:%M:%S")
|
| 407 |
-
|
| 408 |
-
metadata = {
|
| 409 |
-
"subject": subject,
|
| 410 |
-
"topic": topic,
|
| 411 |
-
"num_questions": num_questions,
|
| 412 |
-
"exam_type": exam_type,
|
| 413 |
-
"timestamp": formatted_timestamp
|
| 414 |
-
}
|
| 415 |
-
|
| 416 |
-
return metadata
|
| 417 |
-
|
| 418 |
-
def generate_text(prompt):
|
| 419 |
-
"""Generates text based on the prompt."""
|
| 420 |
-
try:
|
| 421 |
-
|
| 422 |
-
# Send a text prompt to Gemini API
|
| 423 |
-
chat = st.session_state.chat
|
| 424 |
-
response = chat.send_message(
|
| 425 |
-
[
|
| 426 |
-
prompt
|
| 427 |
-
],
|
| 428 |
-
stream=enable_stream
|
| 429 |
-
)
|
| 430 |
-
|
| 431 |
-
return response.text
|
| 432 |
-
|
| 433 |
-
except Exception as e:
|
| 434 |
-
st.error(f"An error occurred while generating text: {e}")
|
| 435 |
-
return None
|
| 436 |
-
|
| 437 |
def show_text_prompt():
|
| 438 |
st.subheader("Text Prompt")
|
| 439 |
|
|
@@ -537,14 +151,14 @@ def show_text_prompt():
|
|
| 537 |
if question_type == "Essay Type":
|
| 538 |
#prompt once
|
| 539 |
with st.spinner('Generating questions...'):
|
| 540 |
-
full_quiz =
|
| 541 |
|
| 542 |
else:
|
| 543 |
if num_questions == 10:
|
| 544 |
|
| 545 |
#prompt once
|
| 546 |
with st.spinner('Generating questions...'):
|
| 547 |
-
full_quiz =
|
| 548 |
else:
|
| 549 |
#prompt multiple times
|
| 550 |
times = num_questions//10
|
|
@@ -553,7 +167,7 @@ def show_text_prompt():
|
|
| 553 |
response = generate_text(prompt)
|
| 554 |
|
| 555 |
if i==0:
|
| 556 |
-
full_quiz =
|
| 557 |
else:
|
| 558 |
full_quiz = merge_json_strings(full_quiz, response)
|
| 559 |
|
|
|
|
| 14 |
from reportlab.platypus import Paragraph, Frame, Spacer
|
| 15 |
from reportlab.lib.styles import getSampleStyleSheet
|
| 16 |
import shutil
|
| 17 |
+
from pdfutils import generate_quiz_content, create_pdf, create_json, generate_metadata, merge_json_strings, generate_text, clean_markdown
|
| 18 |
|
| 19 |
MODEL_ID = "gemini-2.0-flash-exp"
|
| 20 |
api_key = os.getenv("GEMINI_API_KEY")
|
| 21 |
model_id = MODEL_ID
|
| 22 |
genai.configure(api_key=api_key)
|
|
|
|
| 23 |
|
| 24 |
if "model" not in st.session_state:
|
| 25 |
st.session_state.model = genai.GenerativeModel(MODEL_ID)
|
|
|
|
| 48 |
conn.commit()
|
| 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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
def show_text_prompt():
|
| 52 |
st.subheader("Text Prompt")
|
| 53 |
|
|
|
|
| 151 |
if question_type == "Essay Type":
|
| 152 |
#prompt once
|
| 153 |
with st.spinner('Generating questions...'):
|
| 154 |
+
full_quiz = clean_markdown(generate_text(prompt))
|
| 155 |
|
| 156 |
else:
|
| 157 |
if num_questions == 10:
|
| 158 |
|
| 159 |
#prompt once
|
| 160 |
with st.spinner('Generating questions...'):
|
| 161 |
+
full_quiz = clean_markdown(generate_text(prompt))
|
| 162 |
else:
|
| 163 |
#prompt multiple times
|
| 164 |
times = num_questions//10
|
|
|
|
| 167 |
response = generate_text(prompt)
|
| 168 |
|
| 169 |
if i==0:
|
| 170 |
+
full_quiz = clean_markdown(response)
|
| 171 |
else:
|
| 172 |
full_quiz = merge_json_strings(full_quiz, response)
|
| 173 |
|
pdfutils.py
CHANGED
|
@@ -3,9 +3,14 @@ import re
|
|
| 3 |
from reportlab.platypus import Paragraph, Frame, Spacer
|
| 4 |
from reportlab.lib.styles import getSampleStyleSheet
|
| 5 |
import datetime
|
| 6 |
-
from reportlab.platypus import Paragraph, Frame, Spacer
|
| 7 |
from reportlab.lib.styles import getSampleStyleSheet
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
|
|
|
| 9 |
|
| 10 |
def merge_json_strings(json_str1, json_str2):
|
| 11 |
"""
|
|
@@ -20,8 +25,8 @@ def merge_json_strings(json_str1, json_str2):
|
|
| 20 |
"""
|
| 21 |
|
| 22 |
# Clean the JSON strings by removing markdown tags
|
| 23 |
-
cleaned_json_str1 =
|
| 24 |
-
cleaned_json_str2 =
|
| 25 |
|
| 26 |
try:
|
| 27 |
# Parse the cleaned JSON strings into Python dictionaries
|
|
@@ -36,7 +41,7 @@ def merge_json_strings(json_str1, json_str2):
|
|
| 36 |
except json.JSONDecodeError as e:
|
| 37 |
return f"Error decoding JSON: {e}"
|
| 38 |
|
| 39 |
-
def
|
| 40 |
"""
|
| 41 |
Removes markdown tags from a string if they exist.
|
| 42 |
Otherwise, returns the original string unchanged.
|
|
@@ -247,3 +252,146 @@ def create_pdf(data):
|
|
| 247 |
except Exception as e:
|
| 248 |
st.error(f"Error creating PDF: {e}")
|
| 249 |
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
from reportlab.platypus import Paragraph, Frame, Spacer
|
| 4 |
from reportlab.lib.styles import getSampleStyleSheet
|
| 5 |
import datetime
|
|
|
|
| 6 |
from reportlab.lib.styles import getSampleStyleSheet
|
| 7 |
+
import streamlit as st
|
| 8 |
+
import tempfile
|
| 9 |
+
import os
|
| 10 |
+
from reportlab.pdfgen import canvas
|
| 11 |
+
from reportlab.lib.pagesizes import A4, letter
|
| 12 |
|
| 13 |
+
ENABLE_STREAM = False
|
| 14 |
|
| 15 |
def merge_json_strings(json_str1, json_str2):
|
| 16 |
"""
|
|
|
|
| 25 |
"""
|
| 26 |
|
| 27 |
# Clean the JSON strings by removing markdown tags
|
| 28 |
+
cleaned_json_str1 = clean_markdown(json_str1)
|
| 29 |
+
cleaned_json_str2 = clean_markdown(json_str2)
|
| 30 |
|
| 31 |
try:
|
| 32 |
# Parse the cleaned JSON strings into Python dictionaries
|
|
|
|
| 41 |
except json.JSONDecodeError as e:
|
| 42 |
return f"Error decoding JSON: {e}"
|
| 43 |
|
| 44 |
+
def clean_markdown(text):
|
| 45 |
"""
|
| 46 |
Removes markdown tags from a string if they exist.
|
| 47 |
Otherwise, returns the original string unchanged.
|
|
|
|
| 252 |
except Exception as e:
|
| 253 |
st.error(f"Error creating PDF: {e}")
|
| 254 |
return None
|
| 255 |
+
|
| 256 |
+
def generate_quiz_content(data):
|
| 257 |
+
"""
|
| 258 |
+
Separates the metadata and content from a JSON string containing exam data.
|
| 259 |
+
Creates a markdown formatted text that contains the exam metadata and
|
| 260 |
+
enumerates the questions, options and answers nicely formatted for readability.
|
| 261 |
+
|
| 262 |
+
Args:
|
| 263 |
+
data: A JSON string containing the exam data.
|
| 264 |
+
|
| 265 |
+
Returns:
|
| 266 |
+
A markdown formatted string.
|
| 267 |
+
"""
|
| 268 |
+
data = json.loads(data)
|
| 269 |
+
metadata = data["metadata"]
|
| 270 |
+
content = data["content"]
|
| 271 |
+
exam_type = metadata["exam_type"]
|
| 272 |
+
if exam_type == "Multiple Choice":
|
| 273 |
+
md_text = f"""# {metadata['subject']} - {metadata['topic']}
|
| 274 |
+
|
| 275 |
+
**Exam Type:** {metadata['exam_type']}
|
| 276 |
+
**Number of Questions:** {metadata['num_questions']}
|
| 277 |
+
**Timestamp:** {metadata['timestamp']}
|
| 278 |
+
|
| 279 |
+
---
|
| 280 |
+
|
| 281 |
+
"""
|
| 282 |
+
for i, q in enumerate(content):
|
| 283 |
+
md_text += f"""Question {i+1}:
|
| 284 |
+
{q['question']}
|
| 285 |
+
|
| 286 |
+
"""
|
| 287 |
+
for j, option in enumerate(q['options'], ord('a')):
|
| 288 |
+
md_text += f"""{chr(j)}. {option}
|
| 289 |
+
|
| 290 |
+
"""
|
| 291 |
+
md_text += f"""**Correct Answer:** {q['correct_answer']}
|
| 292 |
+
|
| 293 |
+
---
|
| 294 |
+
|
| 295 |
+
"""
|
| 296 |
+
md_text += """This exam was generated by the WVSU Exam Maker
|
| 297 |
+
(c) 2025 West Visayas State University
|
| 298 |
+
"""
|
| 299 |
+
|
| 300 |
+
elif exam_type == "True or False":
|
| 301 |
+
md_text = f"""# {metadata['subject']} - {metadata['topic']}
|
| 302 |
+
|
| 303 |
+
**Exam Type:** {metadata['exam_type']}
|
| 304 |
+
**Number of Questions:** {metadata['num_questions']}
|
| 305 |
+
**Timestamp:** {metadata['timestamp']}
|
| 306 |
+
|
| 307 |
+
---
|
| 308 |
+
|
| 309 |
+
"""
|
| 310 |
+
|
| 311 |
+
for i, q in enumerate(content):
|
| 312 |
+
md_text += f"""Statement {i+1}:
|
| 313 |
+
|
| 314 |
+
{q['statement']}
|
| 315 |
+
|
| 316 |
+
"""
|
| 317 |
+
for j, option in enumerate(q['options'], ord('a')):
|
| 318 |
+
md_text += f"""{option}
|
| 319 |
+
"""
|
| 320 |
+
|
| 321 |
+
md_text += f"""**Correct Answer:** {q['correct_answer']}
|
| 322 |
+
|
| 323 |
+
---
|
| 324 |
+
"""
|
| 325 |
+
md_text += """This exam was generated by the WVSU Exam Maker
|
| 326 |
+
(c) 2025 West Visayas State University"""
|
| 327 |
+
|
| 328 |
+
elif exam_type == "Short Response" or exam_type == "Essay Type":
|
| 329 |
+
md_text = f"""# {metadata['subject']} - {metadata['topic']}
|
| 330 |
+
|
| 331 |
+
**Exam Type:** {metadata['exam_type']}
|
| 332 |
+
**Number of Questions:** {metadata['num_questions']}
|
| 333 |
+
**Timestamp:** {metadata['timestamp']}
|
| 334 |
+
|
| 335 |
+
---
|
| 336 |
+
|
| 337 |
+
"""
|
| 338 |
+
|
| 339 |
+
for i, q in enumerate(content):
|
| 340 |
+
md_text += f"""Question {i+1}:
|
| 341 |
+
|
| 342 |
+
{q['question']}
|
| 343 |
+
|
| 344 |
+
"""
|
| 345 |
+
md_text += f"""**Correct Answer:** {q['correct_answer']}
|
| 346 |
+
|
| 347 |
+
---
|
| 348 |
+
"""
|
| 349 |
+
md_text += """This exam was generated by the WVSU Exam Maker
|
| 350 |
+
(c) 2025 West Visayas State University"""
|
| 351 |
+
|
| 352 |
+
return md_text
|
| 353 |
+
|
| 354 |
+
def generate_metadata(subject, topic, num_questions, exam_type):
|
| 355 |
+
"""Generates quiz metadata as a dictionary combining num_questions,
|
| 356 |
+
exam_type, and timestamp.
|
| 357 |
+
|
| 358 |
+
Args:
|
| 359 |
+
num_questions: The number of questions in the exam (int).
|
| 360 |
+
exam_type: The type of exam (str).
|
| 361 |
+
|
| 362 |
+
Returns:
|
| 363 |
+
A dictionary containing the quiz metadata.
|
| 364 |
+
"""
|
| 365 |
+
|
| 366 |
+
# Format the timestamp
|
| 367 |
+
timestamp = datetime.datetime.now()
|
| 368 |
+
formatted_timestamp = timestamp.strftime("%Y-%m-%d %H:%M:%S")
|
| 369 |
+
|
| 370 |
+
metadata = {
|
| 371 |
+
"subject": subject,
|
| 372 |
+
"topic": topic,
|
| 373 |
+
"num_questions": num_questions,
|
| 374 |
+
"exam_type": exam_type,
|
| 375 |
+
"timestamp": formatted_timestamp
|
| 376 |
+
}
|
| 377 |
+
|
| 378 |
+
return metadata
|
| 379 |
+
|
| 380 |
+
def generate_text(prompt):
|
| 381 |
+
"""Generates text based on the prompt."""
|
| 382 |
+
try:
|
| 383 |
+
|
| 384 |
+
# Send a text prompt to Gemini API
|
| 385 |
+
chat = st.session_state.chat
|
| 386 |
+
response = chat.send_message(
|
| 387 |
+
[
|
| 388 |
+
prompt
|
| 389 |
+
],
|
| 390 |
+
stream=ENABLE_STREAM
|
| 391 |
+
)
|
| 392 |
+
|
| 393 |
+
return response.text
|
| 394 |
+
|
| 395 |
+
except Exception as e:
|
| 396 |
+
st.error(f"An error occurred while generating text: {e}")
|
| 397 |
+
return None
|
users.db
CHANGED
|
Binary files a/users.db and b/users.db differ
|
|
|