-
Notifications
You must be signed in to change notification settings - Fork 0
/
gradesculptor.py
165 lines (123 loc) · 4.74 KB
/
gradesculptor.py
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
import argparse
import os
import sys
import logging
import pandas as pd
def configure_logging() -> None:
"""
Configures logging settings.
Sets the logging level to INFO, configures the message format, and sets the handler to output to stdout.
"""
# Configure logging
logging.basicConfig(
level=logging.INFO,
format="%(message)s",
handlers=[logging.StreamHandler(sys.stdout)],
)
def clean_answers(
filename: str = "submission_metadata.csv",
submission_id_column: str = "Submission ID",
output_dir="submissions",
) -> None:
"""
Reads student submission data from a CSV file and writes each submission's answers to a separate text file.
Parameters:
filename (str): The name of the CSV file from which to read student submissions.
submission_id_column (str): The name of the column in the CSV file that contains the submission IDs. Defaults to "Submission ID".
output_dir (str): The path to the directory where the output files will be written. Defaults to "submissions".
"""
# Read CSV
df = pd.read_csv(filename, dtype={submission_id_column: str}, na_values=None)
# Filter rows to submitted
df = df[df[submission_id_column].notna()]
logging.info(f"Number of submissions to parse: {len(df)}")
# Filter columns to those with answer content and submission ID
df = df.filter(
regex=rf"(?:^Question \d\d?(?:\.\d\d?)? Response$)|(?:{submission_id_column})",
axis=1,
)
# Define length of question header for .txt file
header_length = longest_column_length(df.columns) + 20
# Write submissions to .txt files
for _, student_submission in df.iterrows():
# Create directory for file
submission_id = student_submission[submission_id_column]
os.makedirs(f"{output_dir}/{submission_id}", exist_ok=True)
# Write submission
with open(f"{output_dir}/{submission_id}/written_answers.txt", "w") as f:
def write_to_txt(column_name, value) -> None:
f.write(build_header(column_name, header_length))
f.write(str(value) + "\n")
f.write(("-" * header_length) + "\n\n")
for column_name, value in student_submission.items():
write_to_txt(column_name, value)
def build_header(column_name: str, header_length: int) -> str:
"""
Constructs a header string of a given length, with the column name centered and surrounded by dashes.
Parameters:
column_name (str): The name of the column to center in the header.
header_length (int): The total length of the header string.
Returns:
str: The constructed header string.
"""
# Calculate number of dashes
num_dashes = header_length - len(column_name)
first_dash_length = num_dashes // 2
# Odd or even number of dashes
if num_dashes % 2 == 0:
second_dash_length = first_dash_length
else:
second_dash_length = first_dash_length + 1
# Define header
header = ("-" * first_dash_length) + column_name + ("-" * second_dash_length) + "\n"
return header
def longest_column_length(columns: list[str]) -> int:
"""
Determines the length of the longest column name in a list of column names.
Parameters:
columns (list[str]): A list of column names.
Returns:
int: The length of the longest column name.
"""
max_column_name_length = 0
for column_name in columns:
if len(column_name) > max_column_name_length:
max_column_name_length = len(column_name)
return max_column_name_length
def csv_filename(filename: str) -> bool:
if not filename.endswith(".csv"):
return False
return True
def main():
configure_logging()
# Configure command-line arguments
parser = argparse.ArgumentParser(description="Parse and clean student submissions.")
parser.add_argument(
"--filename",
type=argparse.FileType("r"),
default="submission_metadata.csv",
help="The filename of the CSV file to read data from.",
)
parser.add_argument(
"--id-column",
type=str,
default="Submission ID",
help="The name of the column in the CSV file that contains the submission IDs.",
)
parser.add_argument(
"-o",
"--output",
type=str,
default="submissions",
help="The path to the directory where the output files will be written.",
)
# Parse arguments
args = parser.parse_args()
if not csv_filename(str(args.filename.name)):
logging.info(f"Must read from a CSV file.")
return
logging.info(f"Cleaning answers.")
clean_answers(args.filename.name, args.id_column, args.output)
logging.info(f"Done.")
if __name__ == "__main__":
main()