### Install gradescope-tool Package Source: https://github.com/teaching-and-learning-in-computing/gradescope/blob/main/README.md Installs the gradescope-tool Python package using pip. This package is a dependency for using the Gradescope wrapper functionalities. ```bash pip install gradescope-tool ``` -------------------------------- ### Error Handling for API and Authentication - Python Source: https://context7.com/teaching-and-learning-in-computing/gradescope/llms.txt Provides examples of how to handle common errors when interacting with the Gradescope API, such as `LoginError`, `NotLoggedInError`, and `ResponseError`. It also includes a utility function `safe_login` that implements a retry mechanism for login attempts. ```python from gradescope import Gradescope, Role from gradescope.errors import LoginError, NotLoggedInError, ResponseError try: # Attempt login gs = Gradescope('invalid@example.com', 'wrong_password') # Try to get courses without login courses = gs.get_courses(role=Role.INSTRUCTOR) except LoginError as e: print(f"Login failed: {e}") # Output: Login failed: Invalid credentials except NotLoggedInError as e: print(f"Not authenticated: {e}") # Output: Not authenticated: User is not logged in except ResponseError as e: print(f"API error: {e}") # Output: API error: Failed to fetch the webpage. Status code: 403 except Exception as e: print(f"Unexpected error: {e}") # Proper error handling with retry logic def safe_login(username, password, max_retries=3): for attempt in range(max_retries): try: gs = Gradescope(username, password, verbose=False) if gs.logged_in: print(f"Login successful on attempt {attempt + 1}") return gs except LoginError: print(f"Attempt {attempt + 1} failed") if attempt < max_retries - 1: print("Retrying...") return None gs = safe_login('user@example.com', 'password') if gs: courses = gs.get_courses(role=Role.INSTRUCTOR) ``` -------------------------------- ### Get Course Members using Gradescope API Source: https://context7.com/teaching-and-learning-in-computing/gradescope/llms.txt Retrieves all members (students, TAs, instructors) for a given course. It requires an active Gradescope client instance and a course object. The output includes member names, emails, SIDs, and member IDs. ```python from gradescope import Gradescope # Assuming 'gs' is an authenticated Gradescope instance and 'course' is a valid course object # gs = Gradescope('instructor@example.com', 'password') # courses = gs.get_courses(role=Role.INSTRUCTOR) # course = courses[0] members = gs.get_members(course) print(f"Total members: {len(members)}") for member in members[:5]: # Print first 5 print(f"{member.full_name}") print(f" Email: {member.email}") print(f" SID: {member.sid}") print(f" Member ID: {member.member_id}") ``` -------------------------------- ### Retrieve Student Gradebook with Gradescope API Source: https://context7.com/teaching-and-learning-in-computing/gradescope/llms.txt Gets the complete gradebook for a specific student across all assignments in a course. It requires a Gradescope instance, course, and student objects. The retrieved gradebook can be saved to a JSON file using `save_json` and its contents can be iterated to display assignment titles, scores, and maximum points. ```python from gradescope import Gradescope, Role, save_json, EnhancedJSONEncoder # Assuming 'gs' is an authenticated Gradescope instance and course, student objects are valid # gs = Gradescope('instructor@example.com', 'password') # courses = gs.get_courses(role=Role.INSTRUCTOR) # course = courses[0] # members = gs.get_members(course) # student = members[0] gradebook = gs.get_gradebook(course, student) # Save gradebook to JSON file save_json('./gradebook.json', gradebook, encoder=EnhancedJSONEncoder) # Access gradebook data print(f"Gradebook for {student.full_name}:") for item in gradebook[:3]: # Print first 3 assignments assignment_info = item.get('assignment', {}) submission_info = item.get('submission', {}) print(f" {assignment_info.get('title')}: {submission_info.get('score')} / {assignment_info.get('total_points')}") ``` -------------------------------- ### Initialize Gradescope and Export Courses Source: https://context7.com/teaching-and-learning-in-computing/gradescope/llms.txt Loads credentials from a JSON file, initializes the Gradescope client with verbose logging, creates a timestamped output directory, and exports all instructor courses to a JSON file. It then prints the number of exported courses. ```python import json import os from datetime import datetime from datascope import Gradescope, Role # Assuming EnhancedJSONEncoder and save_json are defined elsewhere def save_json(filename, data, encoder): with open(filename, 'w') as f: json.dump(data, f, cls=encoder, indent=2) # Load credentials from file with open('./credentials.json', 'r') as f: creds = json.load(f) # Initialize with verbose logging gs = Gradescope(creds['username'], creds['password'], verbose=True) # Create output directory with timestamp timestamp = datetime.now().strftime('%Y%m%d_%H%M%S') output_dir = f"./gradescope_export_{timestamp}" os.makedirs(output_dir, exist_ok=True) # Get all instructor courses courses = gs.get_courses(role=Role.INSTRUCTOR) save_json(f"{output_dir}/courses.json", courses, encoder=EnhancedJSONEncoder) print(f"Exported {len(courses)} courses") ``` -------------------------------- ### Gradescope Authentication and Initialization Source: https://context7.com/teaching-and-learning-in-computing/gradescope/llms.txt Demonstrates how to initialize the Gradescope wrapper and authenticate using email and password. It supports both automatic login and manual login after initialization, returning a success status. ```python from gradescope import Gradescope, Role # Initialize with automatic login gs = Gradescope('your_email@example.com', 'your_password', verbose=True) # Manual login after initialization gs = Gradescope() success = gs.login('your_email@example.com', 'your_password') if success: print("Login successful") else: print("Login failed") ``` -------------------------------- ### Python Gradescope API Interaction and Data Retrieval Source: https://github.com/teaching-and-learning-in-computing/gradescope/blob/main/README.md Demonstrates initializing the Gradescope wrapper with credentials and retrieving various data types like courses, assignments, members, and submissions. It also shows how to save data to JSON and CSV files, and download files. ```python from gradescope import * gs = Gradescope('username', 'password') courses = gs.get_courses(role=Role.INSTRUCTOR) # courses: ... assignments = gs.get_assignments(courses[0]) # assignments: ... members = gs.get_members(courses[0]) # members: ... past_submissions = gs.get_past_submissions(courses[0], assignments[0], members[0]) # past_submissions: ... gradebook = gs.get_gradebook(courses[0], members[0]) save_json('./gradebook.json', gradebook, encoder=EnhancedJSONEncoder) grades_csv = gs.get_assignment_grades(assignments[0]) save_csv('./assignment_grades.csv', grades_csv) gs.download_file('./submission.zip', past_submission[-1].get_file_url()) ``` -------------------------------- ### Download All Submissions in Batch - Python Source: https://context7.com/teaching-and-learning-in-computing/gradescope/llms.txt This Python script automates the process of downloading all submissions for a given assignment from Gradescope. It includes error handling for individual student submissions and provides a summary report of successful and failed downloads. It iterates through members, retrieves past submissions, downloads the latest submission file, and saves a JSON report. ```python from gradescope import Gradescope, Role, save_json, EnhancedJSONEncoder import os gs = Gradescope('instructor@example.com', 'password') courses = gs.get_courses(role=Role.INSTRUCTOR) course = courses[0] assignments = gs.get_assignments(course) members = gs.get_members(course) assignment = assignments[0] download_dir = f"./submissions_{assignment.assignment_id}" os.makedirs(download_dir, exist_ok=True) successful_downloads = [] failed_downloads = [] for i, student in enumerate(members, 1): try: print(f"[{i}/{len(members)}] Processing {student.full_name}...") # Get submissions past_submissions = gs.get_past_submissions(course, assignment, student) if past_submissions and len(past_submissions) > 0: latest = past_submissions[-1] filename = f"{download_dir}/{student.sid}_{student.last_name}.zip" # Download file gs.download_file(filename, latest.get_file_url()) successful_downloads.append({ 'student': student.full_name, 'sid': student.sid, 'filename': filename, 'score': latest.score, 'submitted_at': latest.created_at }) print(f" ✓ Downloaded (Score: {latest.score})") else: failed_downloads.append({ 'student': student.full_name, 'reason': 'No submissions found' }) print(f" ✗ No submissions") except Exception as e: failed_downloads.append({ 'student': student.full_name, 'reason': str(e) }) print(f" ✗ Error: {e}") # Save summary report save_json(f"{download_dir}/download_report.json", { 'successful': successful_downloads, 'failed': failed_downloads, 'summary': { 'total': len(members), 'successful': len(successful_downloads), 'failed': len(failed_downloads) } }, encoder=EnhancedJSONEncoder) print(f"\nSummary: {len(successful_downloads)}/{len(members)} successful") ``` -------------------------------- ### Process Courses: Export Assignments and Members Source: https://context7.com/teaching-and-learning-in-computing/gradescope/llms.txt Iterates through each instructor course, creating a specific directory for each. It then exports the assignments and members of the course to separate JSON files and prints the counts. ```python import os import json # Assuming EnhancedJSONEncoder and save_json are defined elsewhere def save_json(filename, data, encoder): with open(filename, 'w') as f: json.dump(data, f, cls=encoder, indent=2) # Process each course (assuming 'courses' and 'gs' are defined from previous step) for course in courses: print(f"\nProcessing: {course.short_name}") course_dir = f"{output_dir}/{course.course_id}_{course.short_name}" os.makedirs(course_dir, exist_ok=True) # Export assignments assignments = gs.get_assignments(course) save_json(f"{course_dir}/assignments.json", assignments, encoder=EnhancedJSONEncoder) print(f" - {len(assignments)} assignments") # Export members members = gs.get_members(course) save_json(f"{course_dir}/members.json", members, encoder=EnhancedJSONEncoder) print(f" - {len(members)} members") ``` -------------------------------- ### Data Export Utilities - JSON and CSV - Python Source: https://context7.com/teaching-and-learning-in-computing/gradescope/llms.txt Demonstrates the use of built-in Gradescope utilities for exporting and importing data in JSON and CSV formats. It covers saving and loading course and assignment data to JSON, including the use of `EnhancedJSONEncoder` for dataclasses, and exporting/loading assignment grades to CSV. ```python from gradescope import Gradescope, Role from gradescope import save_json, load_json, save_csv, load_csv, EnhancedJSONEncoder gs = Gradescope('instructor@example.com', 'password') courses = gs.get_courses(role=Role.INSTRUCTOR) course = courses[0] # Export courses to JSON (with EnhancedJSONEncoder for dataclasses) save_json('./courses.json', courses, indent=2, encoder=EnhancedJSONEncoder) # Load courses from JSON courses_data = load_json('./courses.json') print(f"Loaded {len(courses_data)} courses") # Get and export assignments assignments = gs.get_assignments(course) save_json('./assignments.json', assignments, encoder=EnhancedJSONEncoder) # Export grades to CSV assignment = assignments[0] grades_df = gs.get_assignment_grades(assignment) save_csv('./grades.csv', grades_df, index=False) # Load and analyze CSV loaded_df = load_csv('./grades.csv') print(f"Loaded {len(loaded_df)} grade records") print(f"Mean score: {loaded_df['Total Score'].mean():.2f}") ``` -------------------------------- ### Export Individual Gradebooks Source: https://context7.com/teaching-and-learning-in-computing/gradescope/llms.txt For the first five members of a course, this code retrieves their individual gradebook data and saves it as a JSON file. It includes error handling for potential issues during retrieval. ```python import json # Assuming EnhancedJSONEncoder and save_json are defined elsewhere def save_json(filename, data, encoder): with open(filename, 'w') as f: json.dump(data, f, cls=encoder, indent=2) # Export individual gradebooks (first 5 students - within the course loop) for member in members[:5]: try: gradebook = gs.get_gradebook(course, member) filename = f"{course_dir}/gradebook_{member.member_id}.json" save_json(filename, gradebook, encoder=EnhancedJSONEncoder) except Exception as e: print(f" - Failed to export gradebook for {member.full_name}: {e}") ``` -------------------------------- ### Download Submission Files using Gradescope API Source: https://context7.com/teaching-and-learning-in-computing/gradescope/llms.txt Downloads student submission files, typically as ZIP archives. This function requires a Gradescope instance, course, assignment, and student objects to identify the specific submission. It creates a directory for downloads if it doesn't exist and saves the file with a unique name based on student SID and assignment ID. ```python from gradescope import Gradescope, Role import os # Assuming 'gs' is an authenticated Gradescope instance and course, assignment, student objects are valid # gs = Gradescope('instructor@example.com', 'password') # courses = gs.get_courses(role=Role.INSTRUCTOR) # course = courses[0] # assignments = gs.get_assignments(course) # members = gs.get_members(course) # assignment = assignments[0] # student = members[0] # Get most recent submission past_submissions = gs.get_past_submissions(course, assignment, student) if past_submissions: latest_submission = past_submissions[-1] # Create download directory os.makedirs('./submissions', exist_ok=True) # Download submission file filename = f"./submissions/{student.sid}_{assignment.assignment_id}.zip" gs.download_file(filename, latest_submission.get_file_url()) print(f"Downloaded submission to {filename}") print(f"File size: {os.path.getsize(filename)} bytes") ``` -------------------------------- ### Retrieve Courses by Role (Python) Source: https://context7.com/teaching-and-learning-in-computing/gradescope/llms.txt Shows how to fetch courses associated with a specific role (instructor or student). It can return a list of courses or a dictionary keyed by course ID. Useful for filtering and accessing course-specific data. ```python from gradescope import Gradescope, Role gs = Gradescope('your_email@example.com', 'your_password') # Get courses as instructor (returns list) instructor_courses = gs.get_courses(role=Role.INSTRUCTOR) print(f"Found {len(instructor_courses)} instructor courses") for course in instructor_courses: print(f"{course.short_name}: {course.full_name} ({course.term})") # Output: CS50: Introduction to Computer Science (Fall 2024) # Get courses as dictionary keyed by course_id student_courses_dict = gs.get_courses(role=Role.STUDENT, as_dict=True) if 123456 in student_courses_dict: course = student_courses_dict[123456] print(f"Course URL: {course.get_url()}") # Output: Course URL: https://www.gradescope.com/courses/123456 ``` -------------------------------- ### Retrieve Assignments for Instructor (Python) Source: https://context7.com/teaching-and-learning-in-computing/gradescope/llms.txt Retrieves all assignments for a given course from an instructor's perspective. Includes detailed metadata such as assignment ID, points, due date, submission count, grading progress, and publication status. ```python from gradescope import Gradescope, Role gs = Gradescope('instructor@example.com', 'password') courses = gs.get_courses(role=Role.INSTRUCTOR) course = courses[0] # Get all assignments for the course assignments = gs.get_assignments(course) for assignment in assignments: print(f"Title: {assignment.title}") print(f" Assignment ID: {assignment.assignment_id}") print(f" Points: {assignment.total_points}") print(f" Due: {assignment.due_date}") print(f" Active Submissions: {assignment.active_submissions}") print(f" Grading Progress: {assignment.grading_progress}%") print(f" Published: {assignment.published}") print(f" URL: {assignment.get_url()}") # Output: # Title: Homework 1 # Assignment ID: 654321 # Points: 100.0 # Due: 2024-04-07T23:59 # Active Submissions: 250 # Grading Progress: 85 # Published: True # URL: https://www.gradescope.com/courses/123456/assignments/654321 ``` -------------------------------- ### Retrieve Assignments for Student (Python) Source: https://context7.com/teaching-and-learning-in-computing/gradescope/llms.txt Fetches assignments from a student's perspective, including submission status, score, and due date. This function is useful for students to track their progress and view assignment details. ```python from gradescope import Gradescope, Role gs = Gradescope('student@example.com', 'password') courses = gs.get_courses(role=Role.STUDENT) course = courses[0] # Get assignments as student student_assignments = gs.get_assignments_as_student(course) for assignment in student_assignments: status = "Submitted" if assignment.submitted else "Not Submitted" print(f"{assignment.title}") print(f" Status: {status}") print(f" Score: {assignment.score if assignment.score else 'Not graded'}") print(f" Due: {assignment.due_date}") if assignment.template_url: print(f" Template: {assignment.template_url}") # Output: # Lab 1: Python Basics # Status: Submitted # Score: 95 / 100 # Due: 2024-04-07T23:59:00 # Template: /courses/123456/assignments/654321/template ``` -------------------------------- ### Download Assignment Grades as CSV using Gradescope API Source: https://context7.com/teaching-and-learning-in-computing/gradescope/llms.txt Exports assignment grades for all students in a course as a pandas DataFrame. This method requires a Gradescope instance and an assignment object. The DataFrame can then be saved to a CSV file using `save_csv` and analyzed for statistics like total students, average scores, and column names. ```python from gradescope import Gradescope, Role, save_csv # Assuming 'gs' is an authenticated Gradescope instance and assignment object is valid # gs = Gradescope('instructor@example.com', 'password') # courses = gs.get_courses(role=Role.INSTRUCTOR) # course = courses[0] # assignments = gs.get_assignments(course) # assignment = assignments[0] # Download grades as DataFrame grades_df = gs.get_assignment_grades(assignment) # Save to CSV save_csv('./assignment_grades.csv', grades_df) # Work with the DataFrame print(f"Total students: {len(grades_df)}") print(f"Average score: {grades_df['Total Score'].mean():.2f}") print(f"Columns: {list(grades_df.columns)}") # Filter students with score > 90 high_scorers = grades_df[grades_df['Total Score'] > 90] print(f"Students with >90: {len(high_scorers)}") ``` -------------------------------- ### Retrieve Student Submission History with Gradescope API Source: https://context7.com/teaching-and-learning-in-computing/gradescope/llms.txt Fetches all past submissions for a specific student on a particular assignment. This function requires a Gradescope instance, course, assignment, and student objects. It outputs submission details like ID, creation time, score, and URLs for viewing or downloading. ```python from gradescope import Gradescope, Role # Assuming 'gs' is an authenticated Gradescope instance and course, assignment, student objects are valid # gs = Gradescope('instructor@example.com', 'password') # courses = gs.get_courses(role=Role.INSTRUCTOR) # course = courses[0] # assignments = gs.get_assignments(course) # members = gs.get_members(course) # assignment = assignments[0] # student = members[0] past_submissions = gs.get_past_submissions(course, assignment, student) if past_submissions: print(f"Submissions for {student.full_name} on {assignment.title}:") for submission in past_submissions: print(f" Submission ID: {submission.submission_id}") print(f" Submitted at: {submission.created_at}") print(f" Score: {submission.score}") print(f" URL: {submission.get_url()}") print(f" Download: {submission.get_file_url()}") else: print(f"No submissions found for {student.full_name}") ``` -------------------------------- ### Export Assignment Grades Source: https://context7.com/teaching-and-learning-in-computing/gradescope/llms.txt For each assignment within a course, this code attempts to retrieve the grades as a pandas DataFrame and save them to a CSV file. It includes error handling for failed exports. ```python import pandas as pd # Assuming save_csv is defined elsewhere def save_csv(filename, df): df.to_csv(filename, index=False) # Export grades for each assignment (within the course loop) for assignment in assignments: try: grades_df = gs.get_assignment_grades(assignment) filename = f"{course_dir}/grades_{assignment.assignment_id}.csv" save_csv(filename, grades_df) print(f" - Exported grades for '{assignment.title}'") except Exception as e: print(f" - Failed to export grades for '{assignment.title}': {e}") ``` -------------------------------- ### Retrieve Course Members (Python) Source: https://context7.com/teaching-and-learning-in-computing/gradescope/llms.txt Fetches the roster of all students and instructors within a specific course. This function is essential for managing course participants and obtaining class lists. ```python from gradescope import Gradescope, Role gs = Gradescope('instructor@example.com', 'password') courses = gs.get_courses(role=Role.INSTRUCTOR) course = courses[0] ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.