File size: 32,924 Bytes
abd0aa3 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 |
# import streamlit as st
# from datetime import datetime
# from pymongo import MongoClient
# import os
# from openai import OpenAI
# from dotenv import load_dotenv
# from bson import ObjectId
# load_dotenv()
# # MongoDB setup
# MONGO_URI = os.getenv('MONGO_URI')
# client = MongoClient(MONGO_URI)
# db = client["novascholar_db"]
# subjective_tests_collection = db["subjective_tests"]
# subjective_test_evaluation_collection = db["subjective_test_evaluation"]
# resources_collection = db["resources"]
# students_collection = db["students"]
# def evaluate_subjective_answers(session_id, student_id, test_id):
# """
# Generate evaluation and analysis for subjective test answers
# """
# try:
# # Fetch test and student submission
# test = subjective_tests_collection.find_one({"_id": test_id})
# if not test:
# return None
# # Find student's submission
# submission = next(
# (sub for sub in test.get('submissions', [])
# if sub['student_id'] == str(student_id)),
# None
# )
# if not submission:
# return None
# # Fetch pre-class materials
# pre_class_materials = resources_collection.find({"session_id": session_id})
# pre_class_content = ""
# for material in pre_class_materials:
# if 'text_content' in material:
# pre_class_content += material['text_content'] + "\n"
# # Default rubric (can be customized later)
# default_rubric = """
# 1. Content Understanding (1-4):
# - Demonstrates comprehensive understanding of core concepts
# - Accurately applies relevant theories and principles
# - Provides specific examples and evidence
# 2. Critical Analysis (1-4):
# - Shows depth of analysis
# - Makes meaningful connections
# - Demonstrates original thinking
# 3. Organization & Clarity (1-4):
# - Clear structure and flow
# - Well-developed arguments
# - Effective use of examples
# """
# # Initialize OpenAI client
# client = OpenAI(api_key=os.getenv('OPENAI_KEY'))
# evaluations = []
# for i, (question, answer) in enumerate(zip(test['questions'], submission['answers'])):
# analysis_content = f"""
# Question: {question['question']}
# Student Answer: {answer}
# """
# prompt_template = f"""As an educational assessor, evaluate this student's answer based on the provided rubric criteria and pre-class materials. Follow these assessment guidelines:
# 1. Evaluation Process:
# - Use each rubric criterion (scored 1-4) for internal assessment
# - Compare response with pre-class materials
# - Check alignment with all rubric requirements
# - Calculate final score: sum of criteria scores converted to 10-point scale
# Pre-class Materials:
# {pre_class_content[:1000]} # Truncate to avoid token limits
# Rubric Criteria:
# {default_rubric}
# Question and Answer:
# {analysis_content}
# Provide your assessment in the following format:
# **Score and Evidence**
# - Score: [X]/10
# - Evidence for deduction: [One-line reference to most significant gap or inaccuracy]
# **Key Areas for Improvement**
# - [Concise improvement point 1]
# - [Concise improvement point 2]
# - [Concise improvement point 3]
# """
# # Generate evaluation using OpenAI
# response = client.chat.completions.create(
# model="gpt-4o-mini",
# messages=[{"role": "user", "content": prompt_template}],
# max_tokens=500,
# temperature=0.4
# )
# evaluations.append({
# "question_number": i + 1,
# "question": question['question'],
# "answer": answer,
# "evaluation": response.choices[0].message.content
# })
# # Store evaluation in MongoDB
# evaluation_doc = {
# "test_id": test_id,
# "student_id": student_id,
# "session_id": session_id,
# "evaluations": evaluations,
# "evaluated_at": datetime.utcnow()
# }
# subjective_test_evaluation_collection.insert_one(evaluation_doc)
# return evaluation_doc
# except Exception as e:
# print(f"Error in evaluate_subjective_answers: {str(e)}")
# return None
# def display_evaluation_to_faculty(session_id, student_id, course_id):
# """
# Display interface for faculty to generate and view evaluations
# """
# st.header("Evaluate Subjective Tests")
# try:
# # Fetch available tests
# tests = list(subjective_tests_collection.find({
# "session_id": str(session_id),
# "status": "active"
# }))
# if not tests:
# st.info("No subjective tests found for this session.")
# return
# # Select test
# test_options = {
# f"{test['title']} (Created: {test['created_at'].strftime('%Y-%m-%d %H:%M')})" if 'created_at' in test else test['title']: test['_id']
# for test in tests
# }
# if test_options:
# selected_test = st.selectbox(
# "Select Test to Evaluate",
# options=list(test_options.keys())
# )
# if selected_test:
# test_id = test_options[selected_test]
# test = subjective_tests_collection.find_one({"_id": test_id})
# if test:
# submissions = test.get('submissions', [])
# if not submissions:
# st.warning("No submissions found for this test.")
# return
# # Create a dropdown for student submissions
# student_options = {
# f"{students_collection.find_one({'_id': ObjectId(sub['student_id'])})['full_name']} (Submitted: {sub['submitted_at'].strftime('%Y-%m-%d %H:%M')})": sub['student_id']
# for sub in submissions
# }
# selected_student = st.selectbox(
# "Select Student Submission",
# options=list(student_options.keys())
# )
# if selected_student:
# student_id = student_options[selected_student]
# submission = next(sub for sub in submissions if sub['student_id'] == student_id)
# st.markdown(f"**Submission Date:** {submission.get('submitted_at', 'No submission date')}")
# st.markdown("---")
# # Display questions and answers
# st.subheader("Submission Details")
# for i, (question, answer) in enumerate(zip(test['questions'], submission['answers'])):
# st.markdown(f"**Question {i+1}:** {question['question']}")
# st.markdown(f"**Answer:** {answer}")
# st.markdown("---")
# # Check for existing evaluation
# existing_eval = subjective_test_evaluation_collection.find_one({
# "test_id": test_id,
# "student_id": student_id,
# "session_id": str(session_id)
# })
# if existing_eval:
# st.subheader("Evaluation Results")
# for eval_item in existing_eval['evaluations']:
# st.markdown(f"### Evaluation for Question {eval_item['question_number']}")
# st.markdown(eval_item['evaluation'])
# st.markdown("---")
# st.success("✓ Evaluation completed")
# if st.button("Regenerate Evaluation", key=f"regenerate_{student_id}_{test_id}"):
# with st.spinner("Regenerating evaluation..."):
# evaluation = evaluate_subjective_answers(
# str(session_id),
# student_id,
# test_id
# )
# if evaluation:
# st.success("Evaluation regenerated successfully!")
# st.rerun()
# else:
# st.error("Error regenerating evaluation.")
# else:
# st.subheader("Generate Evaluation")
# if st.button("Generate Evaluation", key=f"evaluate_{student_id}_{test_id}"):
# with st.spinner("Generating evaluation..."):
# evaluation = evaluate_subjective_answers(
# str(session_id),
# student_id,
# test_id
# )
# if evaluation:
# st.success("Evaluation generated successfully!")
# st.markdown("### Generated Evaluation")
# for eval_item in evaluation['evaluations']:
# st.markdown(f"#### Question {eval_item['question_number']}")
# st.markdown(eval_item['evaluation'])
# st.markdown("---")
# st.rerun()
# else:
# st.error("Error generating evaluation.")
# except Exception as e:
# st.error(f"An error occurred while loading the evaluations: {str(e)}")
# print(f"Error in display_evaluation_to_faculty: {str(e)}")
import streamlit as st
from datetime import datetime
from pymongo import MongoClient
import os
from openai import OpenAI
from dotenv import load_dotenv
from bson import ObjectId
load_dotenv()
# MongoDB setup
MONGO_URI = os.getenv("MONGO_URI")
client = MongoClient(MONGO_URI)
db = client["novascholar_db"]
subjective_tests_collection = db["subjective_tests"]
subjective_test_evaluation_collection = db["subjective_test_evaluation"]
pre_subjective_tests_collection = db["pre_subjective_tests"]
resources_collection = db["resources"]
students_collection = db["students"]
pre_subjective_test_evaluation_collection = db["pre_subjective_test_evaluation"]
def evaluate_subjective_answers(session_id, student_id, test_id):
"""
Generate evaluation and analysis for subjective test answers
"""
try:
# Fetch test and student submission
test = subjective_tests_collection.find_one({"_id": test_id})
if not test:
return None
# Find student's submission
submission = next(
(
sub
for sub in test.get("submissions", [])
if sub["student_id"] == str(student_id)
),
None,
)
if not submission:
return None
# Fetch pre-class materials
pre_class_materials = resources_collection.find({"session_id": session_id})
pre_class_content = ""
for material in pre_class_materials:
if "text_content" in material:
pre_class_content += material["text_content"] + "\n"
# Default rubric (can be customized later)
default_rubric = """
1. Content Understanding (1-4):
- Demonstrates comprehensive understanding of core concepts
- Accurately applies relevant theories and principles
- Provides specific examples and evidence
2. Critical Analysis (1-4):
- Shows depth of analysis
- Makes meaningful connections
- Demonstrates original thinking
3. Organization & Clarity (1-4):
- Clear structure and flow
- Well-developed arguments
- Effective use of examples
"""
# Initialize OpenAI client
client = OpenAI(api_key=os.getenv("OPENAI_KEY"))
evaluations = []
for i, (question, answer) in enumerate(
zip(test["questions"], submission["answers"])
):
analysis_content = f"""
Question: {question['question']}
Student Answer: {answer}
"""
prompt_template = f"""As an educational assessor, evaluate this student's answer based on the provided rubric criteria and pre-class materials. Follow these assessment guidelines:
1. Evaluation Process:
- Use each rubric criterion (scored 1-4) for internal assessment
- Compare response with pre-class materials
- Check alignment with all rubric requirements
- Calculate final score: sum of criteria scores converted to 10-point scale
Pre-class Materials:
{pre_class_content[:1000]} # Truncate to avoid token limits
Rubric Criteria:
{default_rubric}
Question and Answer:
{analysis_content}
Provide your assessment in the following format:
**Score and Evidence**
- Score: [X]/10
- Evidence for deduction: [One-line reference to most significant gap or inaccuracy]
**Key Areas for Improvement**
- [Concise improvement point 1]
- [Concise improvement point 2]
- [Concise improvement point 3]
"""
# Generate evaluation using OpenAI
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": prompt_template}],
max_tokens=500,
temperature=0.4,
)
evaluations.append(
{
"question_number": i + 1,
"question": question["question"],
"answer": answer,
"evaluation": response.choices[0].message.content,
}
)
# Store evaluation in MongoDB
evaluation_doc = {
"test_id": test_id,
"student_id": student_id,
"session_id": session_id,
"evaluations": evaluations,
"evaluated_at": datetime.utcnow(),
}
subjective_test_evaluation_collection.insert_one(evaluation_doc)
return evaluation_doc
except Exception as e:
print(f"Error in evaluate_subjective_answers: {str(e)}")
return None
def pre_evaluate_subjective_answers(session_id, student_id, test_id):
"""
Generate evaluation and analysis for subjective test answers
"""
try:
# Fetch test and student submission
test = pre_subjective_tests_collection.find_one({"_id": test_id})
if not test:
return None
# Find student's submission
submission = next(
(
sub
for sub in test.get("submissions", [])
if sub["student_id"] == str(student_id)
),
None,
)
if not submission:
return None
# Fetch pre-class materials
pre_class_materials = resources_collection.find({"session_id": session_id})
pre_class_content = ""
for material in pre_class_materials:
if "text_content" in material:
pre_class_content += material["text_content"] + "\n"
# Default rubric (can be customized later)
default_rubric = """
1. Content Understanding (1-4):
- Demonstrates comprehensive understanding of core concepts
- Accurately applies relevant theories and principles
- Provides specific examples and evidence
2. Critical Analysis (1-4):
- Shows depth of analysis
- Makes meaningful connections
- Demonstrates original thinking
3. Organization & Clarity (1-4):
- Clear structure and flow
- Well-developed arguments
- Effective use of examples
"""
# Initialize OpenAI client
client = OpenAI(api_key=os.getenv("OPENAI_KEY"))
evaluations = []
for i, (question, answer) in enumerate(
zip(test["questions"], submission["answers"])
):
analysis_content = f"""
Question: {question['question']}
Student Answer: {answer}
"""
prompt_template = f"""As an educational assessor, evaluate this student's answer based on the provided rubric criteria and pre-class materials. Follow these assessment guidelines:
1. Evaluation Process:
- Use each rubric criterion (scored 1-4) for internal assessment
- Compare response with pre-class materials
- Check alignment with all rubric requirements
- Calculate final score: sum of criteria scores converted to 10-point scale
Pre-class Materials:
{pre_class_content[:1000]} # Truncate to avoid token limits
Rubric Criteria:
{default_rubric}
Question and Answer:
{analysis_content}
Provide your assessment in the following format:
**Score and Evidence**
- Score: [X]/10
- Evidence for deduction: [One-line reference to most significant gap or inaccuracy]
**Key Areas for Improvement**
- [Concise improvement point 1]
- [Concise improvement point 2]
- [Concise improvement point 3]
"""
# Generate evaluation using OpenAI
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": prompt_template}],
max_tokens=500,
temperature=0.4,
)
evaluations.append(
{
"question_number": i + 1,
"question": question["question"],
"answer": answer,
"evaluation": response.choices[0].message.content,
}
)
# Store evaluation in MongoDB
evaluation_doc = {
"test_id": test_id,
"student_id": student_id,
"session_id": session_id,
"evaluations": evaluations,
"evaluated_at": datetime.utcnow(),
}
pre_subjective_test_evaluation_collection.insert_one(evaluation_doc)
return evaluation_doc
except Exception as e:
print(f"Error in evaluate_subjective_answers: {str(e)}")
return None
def display_evaluation_to_faculty(session_id, student_id, course_id):
"""
Display interface for faculty to generate and view evaluations
"""
st.header("Evaluate Subjective Tests")
try:
# Fetch available tests
print("session_id", session_id, "student_id", student_id, "course_id", course_id)
tests = list(
subjective_tests_collection.find(
{"session_id": str(session_id), "status": "active"}
)
)
print("tests" ,tests)
if not tests:
st.info("No subjective tests found for this session.")
return
# Select test
test_options = {
(
f"{test['title']} (Created: {test['created_at'].strftime('%Y-%m-%d %H:%M')})"
if "created_at" in test
else test["title"]
): test["_id"]
for test in tests
}
if test_options:
selected_test = st.selectbox(
"Select Test to Evaluate", options=list(test_options.keys())
)
if selected_test:
test_id = test_options[selected_test]
test = subjective_tests_collection.find_one({"_id": test_id})
if test:
submissions = test.get("submissions", [])
if not submissions:
st.warning("No submissions found for this test.")
return
# Create a dropdown for student submissions
student_options = {
f"{students_collection.find_one({'_id': ObjectId(sub['student_id'])})['full_name']} (Submitted: {sub['submitted_at'].strftime('%Y-%m-%d %H:%M')})": sub[
"student_id"
]
for sub in submissions
}
selected_student = st.selectbox(
"Select Student Submission",
options=list(student_options.keys()),
)
if selected_student:
student_id = student_options[selected_student]
submission = next(
sub
for sub in submissions
if sub["student_id"] == student_id
)
st.markdown(
f"**Submission Date:** {submission.get('submitted_at', 'No submission date')}"
)
st.markdown("---")
# Display questions and answers
st.subheader("Submission Details")
for i, (question, answer) in enumerate(
zip(test["questions"], submission["answers"])
):
st.markdown(f"**Question {i+1}:** {question['question']}")
st.markdown(f"**Answer:** {answer}")
st.markdown("---")
# Check for existing evaluation
existing_eval = subjective_test_evaluation_collection.find_one(
{
"test_id": test_id,
"student_id": student_id,
"session_id": str(session_id),
}
)
if existing_eval:
st.subheader("Evaluation Results")
for eval_item in existing_eval["evaluations"]:
st.markdown(
f"### Evaluation for Question {eval_item['question_number']}"
)
st.markdown(eval_item["evaluation"])
st.markdown("---")
st.success("✓ Evaluation completed")
if st.button(
"Regenerate Evaluation",
key=f"regenerate_{student_id}_{test_id}",
):
with st.spinner("Regenerating evaluation..."):
evaluation = evaluate_subjective_answers(
str(session_id), student_id, test_id
)
if evaluation:
st.success(
"Evaluation regenerated successfully!"
)
st.rerun()
else:
st.error("Error regenerating evaluation.")
else:
st.subheader("Generate Evaluation")
if st.button(
"Generate Evaluation",
key=f"evaluate_{student_id}_{test_id}",
):
with st.spinner("Generating evaluation..."):
evaluation = evaluate_subjective_answers(
str(session_id), student_id, test_id
)
if evaluation:
st.success("Evaluation generated successfully!")
st.markdown("### Generated Evaluation")
for eval_item in evaluation["evaluations"]:
st.markdown(
f"#### Question {eval_item['question_number']}"
)
st.markdown(eval_item["evaluation"])
st.markdown("---")
st.rerun()
else:
st.error("Error generating evaluation.")
except Exception as e:
st.error(f"An error occurred while loading the evaluations: {str(e)}")
print(f"Error in display_evaluation_to_faculty: {str(e)}")
return None
def pre_display_evaluation_to_faculty(session_id, student_id, course_id):
"""
Display interface for faculty to generate and view evaluations
"""
st.header("Evaluate Pre Subjective Tests")
try:
# Fetch available tests
tests = list(
pre_subjective_tests_collection.find(
{"session_id": str(session_id), "status": "active"}
)
)
if not tests:
st.info("No subjective tests found for this session.")
return
# Select test
test_options = {
(
f"{test['title']} (Created: {test['created_at'].strftime('%Y-%m-%d %H:%M')})"
if "created_at" in test
else test["title"]
): test["_id"]
for test in tests
}
if test_options:
selected_test = st.selectbox(
"Select Test to Evaluate", options=list(test_options.keys())
)
if selected_test:
test_id = test_options[selected_test]
test = pre_subjective_tests_collection.find_one({"_id": test_id})
if test:
submissions = test.get("submissions", [])
if not submissions:
st.warning("No submissions found for this test.")
return
# Create a dropdown for student submissions
student_options = {
f"{students_collection.find_one({'_id': ObjectId(sub['student_id'])})['full_name']} (Submitted: {sub['submitted_at'].strftime('%Y-%m-%d %H:%M')})": sub[
"student_id"
]
for sub in submissions
}
selected_student = st.selectbox(
"Select Student Submission",
options=list(student_options.keys()),
)
if selected_student:
student_id = student_options[selected_student]
submission = next(
sub
for sub in submissions
if sub["student_id"] == student_id
)
st.markdown(
f"**Submission Date:** {submission.get('submitted_at', 'No submission date')}"
)
st.markdown("---")
# Display questions and answers
st.subheader("Submission Details")
for i, (question, answer) in enumerate(
zip(test["questions"], submission["answers"])
):
st.markdown(f"**Question {i+1}:** {question['question']}")
st.markdown(f"**Answer:** {answer}")
st.markdown("---")
# Check for existing evaluation
existing_eval = (
pre_subjective_test_evaluation_collection.find_one(
{
"test_id": test_id,
"student_id": student_id,
"session_id": str(session_id),
}
)
)
if existing_eval:
st.subheader("Evaluation Results")
for eval_item in existing_eval["evaluations"]:
st.markdown(
f"### Evaluation for Question {eval_item['question_number']}"
)
st.markdown(eval_item["evaluation"])
st.markdown("---")
st.success("✓ Evaluation completed")
if st.button(
"Regenerate Evaluation",
key=f"regenerate_{student_id}_{test_id}",
):
with st.spinner("Regenerating evaluation..."):
evaluation = pre_evaluate_subjective_answers(
str(session_id), student_id, test_id
)
if evaluation:
st.success(
"Evaluation regenerated successfully!"
)
st.rerun()
else:
st.error("Error regenerating evaluation.")
else:
st.subheader("Generate Evaluation")
if st.button(
"Generate Evaluation",
key=f"pre_evaluate_{student_id}_{test_id}",
):
with st.spinner("Generating evaluation..."):
print("session_id", session_id, "student_id", student_id, "test_id", test_id)
evaluation = pre_evaluate_subjective_answers(
str(session_id), student_id, test_id
)
if evaluation:
st.success("Evaluation generated successfully!")
st.markdown("### Generated Evaluation")
for eval_item in evaluation["evaluations"]:
st.markdown(
f"#### Question {eval_item['question_number']}"
)
st.markdown(eval_item["evaluation"])
st.markdown("---")
st.rerun()
else:
st.error("Error generating evaluation.")
except Exception as e:
st.error(f"An error occurred while loading the evaluations: {str(e)}")
print(f"Error in display_evaluation_to_faculty: {str(e)}")
|