-
Notifications
You must be signed in to change notification settings - Fork 0
/
teacheval.py
179 lines (150 loc) · 5.74 KB
/
teacheval.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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
import html
import os.path
import pathlib
import sys
from csvsimple import *
# CONFIGUARATION SETTINGS:
WWW_OUT_DIR = 'd:/www/teaching/'
DATA_DIR = 'data/'
TEMPLATE_DIR = 'templates/'
NO_COMMENT = 'Coming soon...'
# USAGE:
if len(sys.argv) == 1:
print("syntax:")
print(" teacheval.py courseid (do not include the path to data or the .csv)")
print("or teacheval.py all")
exit("missing parameter")
def verify_file(filename):
"""Return filename or gracefully exit if it does not exist"""
if not os.path.isfile(filename):
print("error:")
print(" could not locate required file: " + filename)
exit("required file missing")
return filename
def tag_wrap(lst, tag='td', newline='', escape=True):
"""wrap each item in lst with the html tag, e.g.: <tag>first</tag><tag>second</tag>"""
if escape:
lst = map(html.escape, lst)
return '<' + tag + '>' + ('</' + tag + '>' + newline + '<' + tag + '>').join(lst) + '</' + tag + '>'
def sortkey(s):
"""strip out any initial non-alpha chars and convert to lowercase for sorting"""
return s.lower().lstrip(' -=*!,.:#;@%^&+=_/\\|"\'?()<>[]')
# main program
sections = list()
if sys.argv[1].lower() == 'all':
for f in pathlib.Path(DATA_DIR).glob('*.csv'):
if 'responses' not in f.name and 'export' not in f.name:
sections.append(f.name[:-4])
else:
sections.append(sys.argv[1])
for section_id in sections:
print("processing " + section_id)
data = csv_to_dict(verify_file(DATA_DIR + section_id + '.csv'))
data.update(csv_to_dict(verify_file(TEMPLATE_DIR + data['course'] + '.csv')))
comment_file = DATA_DIR + section_id + '-comments.txt'
if os.path.isfile(comment_file):
with open(comment_file, 'r') as f:
data['comments'] = f.read()
else:
data['comments'] = NO_COMMENT
with open(verify_file(TEMPLATE_DIR + 'base.html'), 'r') as f:
base_html = f.read()
with open(verify_file(TEMPLATE_DIR + data['template'] + '.html'), 'r') as f:
template_html = f.read()
qdata = dict()
if data['template'] != 'comments':
responses = SimpleCSV(verify_file(DATA_DIR + section_id + '-responses.csv'))
questions = csv_to_dict(verify_file(TEMPLATE_DIR + data['template'] + '.csv'))
with open(verify_file(TEMPLATE_DIR + 'mc.html'), 'r') as f:
mc_html = f.read()
with open(verify_file(TEMPLATE_DIR + 'mcex.html'), 'r') as f:
mcex_html = f.read()
with open(verify_file(TEMPLATE_DIR + 'txt.html'), 'r') as f:
txt_html = f.read()
maxtotal = len(responses)
for qid in responses.keys:
if qid.startswith('mc_') or qid.startswith('smc_'): # [SUMMARIZED] MULTIPLE CHOICE
num_choices = 0
counts = list()
percents = list()
choices = list()
while '{}.{}'.format(qid, num_choices + 1) in questions:
num_choices += 1
counts.append(0)
percents.append('')
choices.append(questions[qid + '.{}'.format(num_choices)])
if not num_choices:
continue
if qid.startswith('smc_'): # sumarized
assert num_choices == int(responses[0][qid])
for i in range(0, num_choices):
counts[i] = int(responses[i + 1][qid])
else:
for resp in responses:
r = resp[qid]
if r:
counts[int(r) - 1] += 1
total = sum(counts)
maxtotal = max(maxtotal, total)
if not total:
continue
for i in range(0, num_choices):
if counts[i]:
percents[i] = str(round(100 * counts[i] / total)) + '%'
counts[i] = str(counts[i])
else:
counts[i] = ''
percents[i] = ''
mcdata = {'question_title': html.escape(questions[qid]),
'num_choices': num_choices,
'td_choices': tag_wrap(choices),
'td_counts': tag_wrap(counts),
'td_percents': tag_wrap(percents),
'css_class': ''}
if qid + '.css' in questions:
mcdata['css_class'] = questions[qid + '.css']
qdata[qid] = mc_html.format_map(mcdata)
elif qid.startswith('txt_') or qid.startswith('mcex_'): # TEXT RESPONSE
if qid.startswith('txt_'):
qhtml = txt_html
qtitle = questions[qid]
else:
qhtml = mcex_html
qtitle = questions[qid.replace('ex', '')]
rlist = list()
for resp in responses:
r = resp[qid]
if r and r.strip():
if qid.startswith('mcex_'):
numqid = qid.replace('ex', '')
if resp[numqid]:
numqstr = questions[numqid + '.' + str(resp[numqid])]
else:
numqstr = 'No Answer'
r = '[' + numqstr + '] ' + r
rlist.append(r)
rlist.sort(key=sortkey)
if rlist:
tdata = {'question_title': html.escape(qtitle),
'li_responses': tag_wrap(rlist, 'li', '\n').replace('[nl]', '<br />'),
'css_class': ''}
if qid + '.css' in questions:
tdata['css_class'] = questions[qid + '.css']
qdata[qid] = qhtml.format_map(tdata)
else:
qdata[qid] = ''
else:
print("could not handle question: " + qid)
exit("bad question id")
if 'num-responses' in data:
maxtotal = int(data['num-responses'])
if 'num-expected' in data:
numexp = int(data['num-expected'])
p = round(100 * maxtotal / numexp)
qdata['resp_rate'] = "{} / {} ({}%)".format(maxtotal, numexp, p)
else:
qdata['resp_rate'] = "{} / ???".format(maxtotal)
data['body'] = template_html.format_map(qdata)
page = base_html.format_map(data)
with open(WWW_OUT_DIR + section_id + '.html', 'w', newline='', encoding='utf-8') as f:
f.write(page)