Spaces:
Sleeping
Sleeping
Download generate_demo_data.py from mohitlahoti2002/djangoServer: direct link, hf CLI and curl.
- Browser
- Download file 23.3 kB
-
https://huggingface.co/spaces/mohitlahoti2002/djangoServer/resolve/main/generate_demo_data.py
- Command line
-
hf download hf://spaces/mohitlahoti2002/djangoServer/generate_demo_data.py
-
curl -L -o generate_demo_data.py https://huggingface.co/spaces/mohitlahoti2002/djangoServer/resolve/main/generate_demo_data.py
23.3 kB
| """ | |
| Demo Data Generation Script for Education Platform | |
| This script generates realistic demo data including: | |
| - 30 teachers | |
| - 40 students | |
| - 10-15 tests with questions | |
| - Classroom enrollments | |
| - Test assignments | |
| - Completed test results with AI-generated feedback | |
| """ | |
| import os | |
| import sys | |
| import django | |
| import random | |
| from datetime import datetime, timedelta | |
| from django.utils import timezone | |
| # Setup Django environment | |
| sys.path.append(os.path.dirname(os.path.abspath(__file__))) | |
| os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangoServer.settings') | |
| django.setup() | |
| from authService.models import User | |
| from classroomService.models import Classroom, Enrollment | |
| from questionService.models import Test, Question, Choice, TestAssignment, TestResult | |
| # Sample data | |
| TEACHER_NAMES = [ | |
| "Dr. Sarah Johnson", "Prof. Michael Chen", "Ms. Emily Rodriguez", "Mr. David Kim", | |
| "Dr. Jennifer Williams", "Prof. Robert Martinez", "Ms. Lisa Anderson", "Mr. James Taylor", | |
| "Dr. Maria Garcia", "Prof. Christopher Lee", "Ms. Amanda White", "Mr. Daniel Brown", | |
| "Dr. Patricia Davis", "Prof. Matthew Wilson", "Ms. Jessica Moore", "Mr. Andrew Jackson", | |
| "Dr. Linda Thompson", "Prof. Kevin Harris", "Ms. Michelle Martin", "Mr. Brian Clark", | |
| "Dr. Nancy Lewis", "Prof. Steven Walker", "Ms. Karen Hall", "Mr. Paul Allen", | |
| "Dr. Betty Young", "Prof. Mark King", "Ms. Sandra Wright", "Mr. Donald Scott", | |
| "Dr. Helen Green", "Prof. George Adams" | |
| ] | |
| STUDENT_NAMES = [ | |
| "Alex Turner", "Emma Watson", "Noah Smith", "Olivia Johnson", "Liam Brown", | |
| "Ava Davis", "Ethan Wilson", "Sophia Martinez", "Mason Anderson", "Isabella Taylor", | |
| "Lucas Thomas", "Mia Jackson", "Logan White", "Charlotte Harris", "Oliver Martin", | |
| "Amelia Thompson", "Elijah Garcia", "Harper Rodriguez", "James Lee", "Evelyn Walker", | |
| "Benjamin Hall", "Abigail Allen", "William Young", "Emily King", "Michael Wright", | |
| "Elizabeth Scott", "Alexander Green", "Sofia Adams", "Daniel Baker", "Avery Nelson", | |
| "Matthew Carter", "Ella Mitchell", "Joseph Perez", "Scarlett Roberts", "David Turner", | |
| "Grace Phillips", "Jackson Campbell", "Chloe Parker", "Samuel Evans", "Aria Edwards" | |
| ] | |
| SUBJECTS = [ | |
| "Mathematics", "Physics", "Chemistry", "Biology", "English Literature", | |
| "History", "Geography", "Computer Science", "Economics", "Psychology" | |
| ] | |
| CLASS_LEVELS = [ | |
| "Grade 9", "Grade 10", "Grade 11", "Grade 12", "AP Level", "IB Level" | |
| ] | |
| # Question templates by subject | |
| QUESTION_TEMPLATES = { | |
| "Mathematics": [ | |
| {"stem": "What is the derivative of xΒ² + 3x + 2?", "answer": "2x + 3", "type": "short"}, | |
| {"stem": "Solve for x: 2x + 5 = 15", "answer": "x = 5", "type": "short"}, | |
| {"stem": "What is the value of Ο (pi) approximately?", "choices": ["3.14159", "2.71828", "1.41421", "1.61803"], "correct": 0, "type": "mcq"}, | |
| {"stem": "Is the square root of 16 equal to 4?", "answer": "True", "type": "true_false"}, | |
| {"stem": "Calculate the area of a circle with radius 5 cm.", "answer": "78.54 square cm", "type": "short"}, | |
| {"stem": "What is 15% of 200?", "choices": ["30", "25", "35", "20"], "correct": 0, "type": "mcq"}, | |
| {"stem": "The sum of angles in a triangle is 180 degrees.", "answer": "True", "type": "true_false"}, | |
| {"stem": "Simplify: (x + 2)(x - 2)", "answer": "xΒ² - 4", "type": "short"}, | |
| ], | |
| "Physics": [ | |
| {"stem": "What is Newton's Second Law of Motion?", "answer": "F = ma (Force equals mass times acceleration)", "type": "long"}, | |
| {"stem": "What is the speed of light in vacuum?", "choices": ["3 Γ 10βΈ m/s", "3 Γ 10βΆ m/s", "3 Γ 10β· m/s", "3 Γ 10βΉ m/s"], "correct": 0, "type": "mcq"}, | |
| {"stem": "Energy can be created or destroyed.", "answer": "False", "type": "true_false"}, | |
| {"stem": "What is the SI unit of force?", "answer": "Newton (N)", "type": "short"}, | |
| {"stem": "Which law states that for every action there is an equal and opposite reaction?", "choices": ["First Law", "Second Law", "Third Law", "Law of Gravitation"], "correct": 2, "type": "mcq"}, | |
| {"stem": "Explain the concept of potential energy.", "answer": "Potential energy is stored energy that depends on the position of an object", "type": "long"}, | |
| ], | |
| "Chemistry": [ | |
| {"stem": "What is the chemical formula for water?", "answer": "HβO", "type": "short"}, | |
| {"stem": "What is the atomic number of Carbon?", "choices": ["6", "12", "8", "14"], "correct": 0, "type": "mcq"}, | |
| {"stem": "Acids have a pH value less than 7.", "answer": "True", "type": "true_false"}, | |
| {"stem": "What is the process of a solid turning directly into a gas called?", "answer": "Sublimation", "type": "short"}, | |
| {"stem": "Which element has the symbol 'Au'?", "choices": ["Silver", "Gold", "Aluminum", "Argon"], "correct": 1, "type": "mcq"}, | |
| {"stem": "Explain the difference between ionic and covalent bonds.", "answer": "Ionic bonds involve transfer of electrons while covalent bonds involve sharing of electrons", "type": "long"}, | |
| ], | |
| "Biology": [ | |
| {"stem": "What is the powerhouse of the cell?", "answer": "Mitochondria", "type": "short"}, | |
| {"stem": "What is the process by which plants make food?", "choices": ["Respiration", "Photosynthesis", "Digestion", "Fermentation"], "correct": 1, "type": "mcq"}, | |
| {"stem": "DNA stands for Deoxyribonucleic Acid.", "answer": "True", "type": "true_false"}, | |
| {"stem": "How many chambers does the human heart have?", "answer": "4 (four)", "type": "short"}, | |
| {"stem": "Describe the process of mitosis.", "answer": "Mitosis is cell division resulting in two identical daughter cells with the same number of chromosomes", "type": "long"}, | |
| {"stem": "Which blood type is known as the universal donor?", "choices": ["A", "B", "AB", "O"], "correct": 3, "type": "mcq"}, | |
| ], | |
| "English Literature": [ | |
| {"stem": "Who wrote 'Romeo and Juliet'?", "answer": "William Shakespeare", "type": "short"}, | |
| {"stem": "What is a metaphor?", "choices": ["Direct comparison using like/as", "Implied comparison", "Exaggeration", "Sound repetition"], "correct": 1, "type": "mcq"}, | |
| {"stem": "A sonnet typically has 14 lines.", "answer": "True", "type": "true_false"}, | |
| {"stem": "Explain the theme of 'To Kill a Mockingbird'.", "answer": "The novel explores themes of racial injustice, moral growth, and the loss of innocence", "type": "long"}, | |
| {"stem": "What literary device uses 'like' or 'as' for comparison?", "answer": "Simile", "type": "short"}, | |
| ], | |
| "History": [ | |
| {"stem": "In what year did World War II end?", "answer": "1945", "type": "short"}, | |
| {"stem": "Who was the first President of the United States?", "choices": ["Thomas Jefferson", "George Washington", "John Adams", "Benjamin Franklin"], "correct": 1, "type": "mcq"}, | |
| {"stem": "The Renaissance began in Italy.", "answer": "True", "type": "true_false"}, | |
| {"stem": "Discuss the causes of the French Revolution.", "answer": "Causes included economic hardship, social inequality, Enlightenment ideas, and weak leadership", "type": "long"}, | |
| {"stem": "What ancient civilization built the pyramids?", "answer": "Ancient Egyptians", "type": "short"}, | |
| ], | |
| "Computer Science": [ | |
| {"stem": "What does CPU stand for?", "answer": "Central Processing Unit", "type": "short"}, | |
| {"stem": "Which programming language is known for web development?", "choices": ["Python", "JavaScript", "C++", "Assembly"], "correct": 1, "type": "mcq"}, | |
| {"stem": "Binary code uses only 0s and 1s.", "answer": "True", "type": "true_false"}, | |
| {"stem": "Explain what an algorithm is.", "answer": "An algorithm is a step-by-step procedure or formula for solving a problem", "type": "long"}, | |
| {"stem": "What does HTML stand for?", "answer": "HyperText Markup Language", "type": "short"}, | |
| ], | |
| } | |
| # AI feedback templates | |
| STRENGTHS_TEMPLATES = [ | |
| "Strong understanding of fundamental concepts", | |
| "Excellent problem-solving approach", | |
| "Clear and concise explanations", | |
| "Good grasp of theoretical knowledge", | |
| "Demonstrates critical thinking skills", | |
| "Shows attention to detail", | |
| "Applies concepts effectively", | |
| "Well-structured answers", | |
| ] | |
| WEAKNESSES_TEMPLATES = [ | |
| "Could improve on time management", | |
| "Needs more practice with complex problems", | |
| "Should review basic concepts", | |
| "Could provide more detailed explanations", | |
| "Needs to work on accuracy", | |
| "Should focus on understanding rather than memorization", | |
| "Could benefit from more examples", | |
| "Needs to improve calculation speed", | |
| ] | |
| SUGGESTIONS_TEMPLATES = [ | |
| "Practice more problems daily", | |
| "Review class notes regularly", | |
| "Focus on understanding core concepts", | |
| "Work on time management during tests", | |
| "Seek help from teacher for difficult topics", | |
| "Form study groups with classmates", | |
| "Use online resources for additional practice", | |
| "Create summary notes for quick revision", | |
| ] | |
| def clear_existing_data(): | |
| """Clear existing demo data""" | |
| print("Clearing existing data...") | |
| TestResult.objects.all().delete() | |
| TestAssignment.objects.all().delete() | |
| Question.objects.all().delete() | |
| Test.objects.all().delete() | |
| Enrollment.objects.all().delete() | |
| Classroom.objects.all().delete() | |
| User.objects.filter(email__contains='demo').delete() | |
| print("β Existing data cleared") | |
| def create_users(): | |
| """Create teachers and students""" | |
| print("\nCreating users...") | |
| teachers = [] | |
| students = [] | |
| # Create teachers | |
| print(" Creating teachers...", end=" ", flush=True) | |
| for i, name in enumerate(TEACHER_NAMES, 1): | |
| email = f"teacher{i}@demo.com" | |
| teacher = User.objects.create_user( | |
| email=email, | |
| password="demo123", | |
| full_name=name, | |
| phone=f"+1555{i:04d}", | |
| role="teacher", | |
| is_verified=True | |
| ) | |
| teachers.append(teacher) | |
| print(f"β Created {len(teachers)} teachers") | |
| # Create students | |
| print(" Creating students...", end=" ", flush=True) | |
| for i, name in enumerate(STUDENT_NAMES, 1): | |
| email = f"student{i}@demo.com" | |
| student = User.objects.create_user( | |
| email=email, | |
| password="demo123", | |
| full_name=name, | |
| phone=f"+1666{i:04d}", | |
| role="student", | |
| is_verified=True | |
| ) | |
| students.append(student) | |
| print(f"β Created {len(students)} students") | |
| return teachers, students | |
| def create_classrooms(teachers, students): | |
| """Create classrooms and enroll students""" | |
| print("\nCreating classrooms...") | |
| classrooms = [] | |
| for teacher in teachers[:15]: # Each of first 15 teachers gets 1-2 classrooms | |
| num_classrooms = random.randint(1, 2) | |
| for _ in range(num_classrooms): | |
| subject = random.choice(SUBJECTS) | |
| class_level = random.choice(CLASS_LEVELS) | |
| classroom = Classroom.objects.create( | |
| teacher=teacher, | |
| name=f"{class_level} - {subject}", | |
| subject=subject, | |
| description=f"Learn {subject} concepts for {class_level}" | |
| ) | |
| classrooms.append(classroom) | |
| # Enroll 5-10 random students | |
| num_students = random.randint(5, 10) | |
| enrolled_students = random.sample(students, num_students) | |
| for student in enrolled_students: | |
| Enrollment.objects.create( | |
| student=student, | |
| classroom=classroom, | |
| status='approved', | |
| approval_date=timezone.now() - timedelta(days=random.randint(1, 30)) | |
| ) | |
| print(f"β Created {len(classrooms)} classrooms with enrollments") | |
| return classrooms | |
| def create_tests(teachers): | |
| """Create tests with questions""" | |
| print("\nCreating tests...") | |
| tests = [] | |
| num_tests = random.randint(12, 15) | |
| for i in range(num_tests): | |
| teacher = random.choice(teachers[:15]) | |
| subject = random.choice(SUBJECTS) | |
| class_level = random.choice(CLASS_LEVELS) | |
| test_type = random.choice(['Written', 'Oral', 'Mixed']) | |
| test = Test.objects.create( | |
| user=teacher, | |
| title=f"{subject} {test_type} Test {i+1}", | |
| description=f"Comprehensive {test_type.lower()} test covering {subject} topics for {class_level}", | |
| subject=subject, | |
| class_level=class_level, | |
| test_type=test_type, | |
| status='published' | |
| ) | |
| # Add questions | |
| question_pool = QUESTION_TEMPLATES.get(subject, QUESTION_TEMPLATES["Mathematics"]) | |
| num_questions = random.randint(5, 8) | |
| selected_questions = random.sample(question_pool, min(num_questions, len(question_pool))) | |
| for order, q_template in enumerate(selected_questions): | |
| difficulty = random.choice(['easy', 'medium', 'hard']) | |
| question = Question.objects.create( | |
| test=test, | |
| stem=q_template['stem'], | |
| question_type=q_template['type'], | |
| difficulty=difficulty, | |
| answer=q_template.get('answer', ''), | |
| rationale=f"This tests understanding of {subject} concepts", | |
| order=order | |
| ) | |
| # Add choices for MCQ | |
| if q_template['type'] == 'mcq' and 'choices' in q_template: | |
| for choice_order, choice_text in enumerate(q_template['choices']): | |
| Choice.objects.create( | |
| question=question, | |
| content=choice_text, | |
| is_correct=(choice_order == q_template['correct']), | |
| order=choice_order | |
| ) | |
| # Add choices for True/False | |
| elif q_template['type'] == 'true_false': | |
| correct_answer = q_template.get('answer', 'True') | |
| Choice.objects.create( | |
| question=question, | |
| content="True", | |
| is_correct=(correct_answer == "True"), | |
| order=0 | |
| ) | |
| Choice.objects.create( | |
| question=question, | |
| content="False", | |
| is_correct=(correct_answer == "False"), | |
| order=1 | |
| ) | |
| test.items = test.questions.count() | |
| test.save() | |
| tests.append(test) | |
| print(f"β Created {len(tests)} tests with questions") | |
| return tests | |
| def create_assignments_and_results(tests, classrooms, students): | |
| """Create test assignments and some completed results""" | |
| print("\nCreating test assignments and results...") | |
| assignments_created = 0 | |
| results_created = 0 | |
| for test in tests: | |
| # Find classrooms that match the test subject | |
| matching_classrooms = [c for c in classrooms if c.subject == test.subject] | |
| if not matching_classrooms: | |
| matching_classrooms = random.sample(classrooms, min(2, len(classrooms))) | |
| else: | |
| matching_classrooms = random.sample(matching_classrooms, min(2, len(matching_classrooms))) | |
| for classroom in matching_classrooms: | |
| # Get enrolled students | |
| enrolled_students = [e.student for e in classroom.enrollments.filter(status='approved')] | |
| if not enrolled_students: | |
| continue | |
| # Assign to some students | |
| num_to_assign = random.randint(3, min(8, len(enrolled_students))) | |
| assigned_students = random.sample(enrolled_students, num_to_assign) | |
| for student in assigned_students: | |
| # Create assignment | |
| start_date = timezone.now() - timedelta(days=random.randint(1, 20)) | |
| end_date = start_date + timedelta(days=random.randint(3, 14)) | |
| duration = random.randint(30, 90) | |
| # 70% chance of completion | |
| is_completed = random.random() < 0.7 | |
| status = 'completed' if is_completed else random.choice(['pending', 'in_progress']) | |
| assignment = TestAssignment.objects.create( | |
| test=test, | |
| student=student, | |
| classroom=classroom, | |
| created_by=test.user, | |
| start_date=start_date, | |
| end_date=end_date, | |
| duration=duration, | |
| status=status, | |
| started_at=start_date + timedelta(hours=random.randint(1, 48)) if is_completed else None, | |
| completed_at=start_date + timedelta(days=random.randint(1, 7)) if is_completed else None | |
| ) | |
| assignments_created += 1 | |
| # Create result if completed | |
| if is_completed: | |
| num_questions = test.questions.count() | |
| if num_questions == 0: | |
| continue | |
| # Generate realistic score distribution | |
| score_range = random.choice([ | |
| (85, 100), # Excellent | |
| (70, 84), # Good | |
| (50, 69), # Average | |
| (30, 49), # Below average | |
| ]) | |
| score = random.uniform(*score_range) | |
| correct_answers = int((score / 100) * num_questions) | |
| time_taken = random.randint(duration - 20, duration) | |
| # Generate answers | |
| answers = {} | |
| for idx, question in enumerate(test.questions.all()): | |
| is_correct = idx < correct_answers | |
| answer_score = 1 if is_correct else random.uniform(0, 0.5) | |
| # Generate answer based on question type | |
| if question.question_type == 'mcq': | |
| choices = list(question.choices.all()) | |
| if is_correct: | |
| selected = next((c for c in choices if c.is_correct), choices[0]) | |
| else: | |
| selected = random.choice([c for c in choices if not c.is_correct] or choices) | |
| transcript = selected.content | |
| elif question.question_type == 'true_false': | |
| choices = list(question.choices.all()) | |
| if is_correct: | |
| selected = next((c for c in choices if c.is_correct), choices[0]) | |
| else: | |
| selected = next((c for c in choices if not c.is_correct), choices[1]) | |
| transcript = selected.content | |
| else: | |
| transcript = question.answer if is_correct else "Student's answer here" | |
| answers[f"q{idx}"] = { | |
| "questionIndex": idx, | |
| "questionText": question.stem, | |
| "transcript": transcript, | |
| "score": answer_score, | |
| "feedback": { | |
| "summary": "Correct answer!" if is_correct else "Needs improvement", | |
| "details": "Well done" if is_correct else "Review this topic" | |
| } | |
| } | |
| # Select random strengths, weaknesses, suggestions | |
| strengths = random.sample(STRENGTHS_TEMPLATES, random.randint(2, 4)) | |
| weaknesses = random.sample(WEAKNESSES_TEMPLATES, random.randint(2, 3)) | |
| suggestions = random.sample(SUGGESTIONS_TEMPLATES, random.randint(2, 4)) | |
| TestResult.objects.create( | |
| assignment=assignment, | |
| student=student, | |
| test=test, | |
| score=score, | |
| total_questions=num_questions, | |
| correct_answers=correct_answers, | |
| time_taken=time_taken, | |
| strengths=strengths, | |
| weaknesses=weaknesses, | |
| suggestions=suggestions, | |
| answers=answers | |
| ) | |
| results_created += 1 | |
| # Update test statistics | |
| for test in tests: | |
| test.assigned = test.assignments.count() | |
| test.completed = test.assignments.filter(status='completed').count() | |
| test.save() | |
| print(f"β Created {assignments_created} test assignments") | |
| print(f"β Created {results_created} test results") | |
| def print_summary(teachers, students, classrooms, tests): | |
| """Print summary of generated data""" | |
| print("\n" + "="*60) | |
| print("DEMO DATA GENERATION COMPLETE!") | |
| print("="*60) | |
| print(f"\nπ Summary:") | |
| print(f" β’ Teachers: {len(teachers)}") | |
| print(f" β’ Students: {len(students)}") | |
| print(f" β’ Classrooms: {len(classrooms)}") | |
| print(f" β’ Tests: {len(tests)}") | |
| print(f" β’ Total Questions: {Question.objects.count()}") | |
| print(f" β’ Test Assignments: {TestAssignment.objects.count()}") | |
| print(f" β’ Completed Tests: {TestResult.objects.count()}") | |
| print(f" β’ Enrollments: {Enrollment.objects.count()}") | |
| print(f"\nπ Login Credentials:") | |
| print(f" Teachers: teacher1@demo.com to teacher30@demo.com") | |
| print(f" Students: student1@demo.com to student40@demo.com") | |
| print(f" Password: demo123") | |
| print(f"\nπ‘ Sample Accounts:") | |
| print(f" Teacher: {teachers[0].email} ({teachers[0].full_name})") | |
| print(f" Student: {students[0].email} ({students[0].full_name})") | |
| print("\n" + "="*60) | |
| def main(): | |
| """Main execution function""" | |
| print("="*60) | |
| print("EDUCATION PLATFORM - DEMO DATA GENERATOR") | |
| print("="*60) | |
| try: | |
| # Clear existing data | |
| clear_existing_data() | |
| # Create users | |
| teachers, students = create_users() | |
| # Create classrooms and enrollments | |
| classrooms = create_classrooms(teachers, students) | |
| # Create tests with questions | |
| tests = create_tests(teachers) | |
| # Create assignments and results | |
| create_assignments_and_results(tests, classrooms, students) | |
| # Print summary | |
| print_summary(teachers, students, classrooms, tests) | |
| print("\nβ Demo data generation completed successfully!") | |
| except Exception as e: | |
| print(f"\nβ Error during data generation: {str(e)}") | |
| import traceback | |
| traceback.print_exc() | |
| sys.exit(1) | |
| if __name__ == "__main__": | |
| main() | |