Newer
Older
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
# -*- coding: utf-8 -*-
from __future__ import division
__copyright__ = "Copyright (C) 2014 Andreas Kloeckner"
__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import django.forms as forms
import re
from course.validation import validate_struct, ValidationError
from courseflow.utils import StyledForm, Struct
class PageContext(object):
"""
.. attribute:: course
.. attribute:: repo
.. attribute:: commit_sha
.. attribute:: flow_session
May be None.
Note that this is different from :class:`course.utils.FlowPageContext`,
which is used internally by the flow views.
"""
def __init__(self, course, repo, commit_sha, flow_session):
self.course = course
self.repo = repo
self.commit_sha = commit_sha
self.flow_session = flow_session
def markup_to_html(page_context, text):
from course.content import markup_to_html
return markup_to_html(
page_context.course,
page_context.repo,
page_context.commit_sha,
text)
# {{{ answer feedback type
class NoNormalizedAnswerAvailable(object):
pass
def get_auto_feedback(correctness):
if correctness == 0:
return "Your answer is not correct."
elif correctness == 1:
return "Your answer is correct."
elif correctness > 0.5:
return "Your answer is mostly correct. (%.1f %%)" \
% (100*correctness)
elif correctness is None:
return "(No information on correctness of answer.)"
else:
return "Your answer is somewhat correct. (%.1f %%)" \
% (100*correctness)
class AnswerFeedback(object):
"""
.. attribute:: correctness
A :class:`float` between 0 and 1 (inclusive),
indicating the degree of correctness of the
answer. May be *None*.
.. attribute:: feedback
Text (at least as a full sentence, or even multi-paragraph HTML)
providing feedback to the student about the provided answer. Should not
reveal the correct answer.
May be None, in which case generic feedback
is generated from :attr:`correctness`.
.. attribute:: normalized_answer
An HTML-formatted answer to be shown in analytics,
or a :class:`NoNormalizedAnswerAvailable`, or *None*
if no answer was provided.
"""
def __init__(self, correctness, feedback=None,
normalized_answer=NoNormalizedAnswerAvailable()):
if correctness is not None:
if correctness < 0 or correctness > 1:
raise ValueError("Invalid correctness value")
if feedback is None:
feedback = get_auto_feedback(correctness)
self.correctness = correctness
self.feedback = feedback
self.normalized_answer = normalized_answer
def as_json(self):
result = {
"correctness": self.correctness,
"feedback": self.feedback,
}
if not isinstance(self.normalized_answer, NoNormalizedAnswerAvailable):
result["normalized_answer"] = self.normalized_answer
return result
@staticmethod
def from_json(json):
return AnswerFeedback(
correctness=json["correctness"],
feedback=json["feedback"],
normalized_answer=json.get("normalized_answer",
NoNormalizedAnswerAvailable())
)
def percentage(self):
if self.correctness is not None:
return 100*self.correctness
else:
return None
# }}}
# {{{ abstract page base class
class PageBase(object):
"""The abstract interface of a flow page.
.. attribute:: location
A string 'location' for reporting errors.
.. attribute:: id
The page identifier.
.. automethod:: required_attrs
.. automethod:: allowed_attrs
.. automethod:: get_modified_permissions_for_page
.. automethod:: make_page_data
.. automethod:: title
.. automethod:: body
.. automethod:: expects_answer
.. automethod:: max_points
.. rubric:: Student Input
.. automethod:: answer_data
.. automethod:: make_form
.. automethod:: post_form
.. automethod:: form_to_html
.. rubric:: Grader Input
.. automethod:: make_grading_form
.. automethod:: post_grading_form
.. automethod:: update_grade_data_from_grading_form
.. automethod:: grading_form_to_html
.. rubric:: Grading/Feedback
.. automethod:: grade
.. automethod:: correct_answer
"""
def __init__(self, vctx, location, page_desc):
"""
:arg vctx: a :class:`course.validation.ValidationContext`, or None
if no validation is desired
"""
self.location = location
if isinstance(page_desc, Struct):
if vctx is not None:
validate_struct(
vctx,
location,
page_desc,
required_attrs=self.required_attrs(),
allowed_attrs=self.allowed_attrs())
# {{{ validate access_rules
if hasattr(page_desc, "access_rules"):
ar_loc = "%s: access rules" % location
validate_struct(
vctx,
ar_loc,
page_desc.access_rules,
required_attrs=(),
allowed_attrs=(
("add_permissions", list),
("remove_permissions", list),
))
from course.validation import validate_flow_permission
for attr in ["add_permissions", "remove_permissions"]:
if hasattr(page_desc.access_rules, attr):
for perm in page_desc.access_rules.add_permissions:
validate_flow_permission(
vctx,
"%s: %s" % (ar_loc, attr),
perm)
# }}}
self.page_desc = page_desc
else:
from warnings import warn
warn("Not passing page_desc to PageBase.__init__ is deprecated",
DeprecationWarning)
id = page_desc
del page_desc
self.id = id
def required_attrs(self):
"""Required attributes, as accepted by
:func:`course.validation.validate_struct`.
Subclasses should only add to, not remove entries from this.
"""
return (
("id", str),
("type", str),
)
def allowed_attrs(self):
"""Allowed attributes, as accepted by
:func:`course.validation.validate_struct`.
Subclasses should only add to, not remove entries from this.
"""
return (
("access_rules", Struct),
)
def get_modified_permissions_for_page(self, permissions):
permissions = set(permissions)
if hasattr(self.page_desc, "access_rules"):
if hasattr(self.page_desc.access_rules, "add_permissions"):
for perm in self.page_desc.access_rules.add_permissions:
permissions.add(perm)
if hasattr(self.page_desc.access_rules, "remove_permissions"):
for perm in self.page_desc.access_rules.remove_permissions:
if perm in permissions:
permissions.remove(perm)
return permissions
def make_page_data(self):
"""Return (possibly randomly generated) data that is used to generate
the content on this page. This is passed to methods below as the *page_data*
argument. One possible use for this argument would be a random permutation
of choices that is generated once (at flow setup) and then used whenever
this page is shown.
"""
return {}
def title(self, page_context, page_data):
"""Return the (non-HTML) title of this page."""
raise NotImplementedError()
def body(self, page_context, page_data):
"""Return the (HTML) body of the page."""
raise NotImplementedError()
def expects_answer(self):
"""
:return: a :class:`bool` indicating whether this page lets the
user provide an answer of some type.
"""
raise NotImplementedError()
def max_points(self, page_data):
"""
:return: a :class:`int` or :class:`float` indicating how many points
are achievable on this page.
"""
raise NotImplementedError()
# {{{ student input
def answer_data(self, page_context, page_data, form, files_data):
"""Return a JSON-persistable object reflecting the user's answer on the
form. This will be passed to methods below as *answer_data*.
"""
raise NotImplementedError()
def make_form(self, page_context, page_data,
answer_data, answer_is_final):
"""
:arg answer_data: value returned by :meth:`answer_data`.
May be *None*.
:return:
a :class:`django.forms.Form` instance with *answer_data* prepopulated.
If *answer_is_final* is *True*, the form should be read-only.
"""
raise NotImplementedError()
def post_form(self, page_context, page_data, post_data, files_data):
"""Return a form with the POST response from *post_data* and *files_data*
filled in.
:return: a
:class:`django.forms.Form` instance with *answer_data* prepopulated.
If *answer_is_final* is *True*, the form should be read-only.
"""
raise NotImplementedError()
def form_to_html(self, request, page_context, form, answer_data):
"""Returns an HTML rendering of *form*."""
from crispy_forms.utils import render_crispy_form
from django.template import RequestContext
context = RequestContext(request, {})
return render_crispy_form(form, context=context)
# }}}
# {{{ grader input
def make_grading_form(self, page_context, page_data, grade_data):
"""
:arg grade_data: value returned by
:meth:`update_grade_data_from_grading_form`. May be *None*.
:return:
a :class:`django.forms.Form` instance with *grade_data* prepopulated.
"""
return None
def post_grading_form(self, page_context, page_data, grade_data,
post_data, files_data):
"""Return a form with the POST response from *post_data* and *files_data*
filled in.
:return: a
:class:`django.forms.Form` instance with *grade_data* prepopulated.
"""
raise NotImplementedError()
def update_grade_data_from_grading_form(self, page_context, page_data,
grade_data, grading_form, files_data):
"""Return an updated version of *grade_data*, which is a
JSON-persistable object reflecting data on grading of this response.
This will be passed to other methods as *grade_data*.
"""
return grade_data
def grading_form_to_html(self, request, page_context, grading_form, grade_data):
"""Returns an HTML rendering of *grading_form*."""
from crispy_forms.utils import render_crispy_form
from django.template import RequestContext
context = RequestContext(request, {})
return render_crispy_form(grading_form, context=context)
# }}}
# {{{ grading/feedback
def grade(self, page_context, page_data, answer_data, grade_data):
"""Grade the answer contained in *answer_data*.
:arg answer_data: value returned by :meth:`answer_data`,
or *None*, which means that no answer was supplied.
:arg grade_data: value updated by
:meth:`update_grade_data_from_grading_form`
:return: a :class:`AnswerFeedback` instanstance, or *None* if the
grade is not yet available.
"""
raise NotImplementedError()
def correct_answer(self, page_context, page_data, answer_data, grade_data):
"""The correct answer to this page's interaction, formatted as HTML,
or *None*.
"""
return None
# }}}
# }}}
# {{{ utility base classes
TITLE_RE = re.compile(ur"^\#\s*(\w.*)", re.UNICODE)
def extract_title_from_markup(markup_text):
lines = markup_text.split("\n")
for l in lines[:5]:
match = TITLE_RE.match(l)
if match is not None:
return match.group(1)
return None
class PageBaseWithTitle(PageBase):
def __init__(self, vctx, location, page_desc):
super(PageBaseWithTitle, self).__init__(vctx, location, page_desc)
title = None
try:
title = self.page_desc.title
except AttributeError:
pass
if title is None:
try:
md_body = self.markup_body_for_title()
except NotImplementedError:
from warnings import warn
warn("PageBaseWithTitle subclass '%s' does not implement "
"markdown_body_for_title()"
% type(self).__name__)
else:
title = extract_title_from_markup(md_body)
if title is None:
raise ValidationError(
"%s: no title found in body or title attribute"
% (location))
self._title = title
def allowed_attrs(self):
return super(PageBaseWithTitle, self).allowed_attrs() + (
("title", str),
)
def markup_body_for_title(self):
raise NotImplementedError()
def title(self, page_context, page_data):
return self._title
class PageBaseWithValue(PageBase):
def allowed_attrs(self):
return super(PageBaseWithValue, self).allowed_attrs() + (
("value", (int, float)),
)
def expects_answer(self):
return True
def max_points(self, page_data):
return getattr(self.page_desc, "value", 1)
# {{{ human text feedback page base
class HumanTextFeedbackForm(StyledForm):
released = forms.BooleanField(
initial=False, required=False,
help_text="Whether the grade and feedback below are to be shown "
"to student")
grade_percent = forms.FloatField(
min_value=0,
max_value=1000, # allow excessive extra credit
help_text="Grade assigned, in percent",
required=False)
feedback_text = forms.CharField(
widget=forms.Textarea(),
required=False,
help_text="Feedback to be shown to student, using "
"CourseFlow-flavored Markdown")
notify = forms.BooleanField(
initial=False, required=False,
help_text="Checking this box and submitting the form "
"will notify the participant "
"with a generic message containing the feedback text")
notes = forms.CharField(
widget=forms.Textarea(),
help_text="Internal notes, not shown to student",
required=False)
def __init__(self, *args, **kwargs):
super(HumanTextFeedbackForm, self).__init__(*args, **kwargs)
class PageBaseWithHumanTextFeedback(PageBase):
grade_data_attrs = ["released", "grade_percent", "feedback_text", "notes"]
def required_attrs(self):
return super(PageBaseWithHumanTextFeedback, self).required_attrs() + (
("rubric", "markup"),
)
def make_grading_form(self, page_context, page_data, grade_data):
if grade_data is not None:
form_data = {}
for k in self.grade_data_attrs:
form_data[k] = grade_data[k]
return HumanTextFeedbackForm(form_data)
else:
return HumanTextFeedbackForm()
def post_grading_form(self, page_context, page_data, grade_data,
post_data, files_data):
return HumanTextFeedbackForm(post_data, files_data)
def update_grade_data_from_grading_form(self, page_context, page_data,
grade_data, grading_form, files_data):
if grade_data is None:
grade_data = {}
for k in self.grade_data_attrs:
grade_data[k] = grading_form.cleaned_data[k]
if grading_form.cleaned_data["notify"] and page_context.flow_session:
from django.template.loader import render_to_string
message = render_to_string("course/grade-notify.txt", {
"page_title": self.title(page_context, page_data),
"course": page_context.course,
"participation": page_context.flow_session.participation,
"feedback_text": grade_data["feedback_text"],
"flow_session": page_context.flow_session,
})
from django.core.mail import send_mail
from django.conf import settings
send_mail("[%s:%s] New notification"
% (page_context.course.identifier,
page_context.flow_session.flow_id),
message,
settings.ROBOT_EMAIL_FROM,
recipient_list=[
page_context.flow_session.participation.user.email])
return grade_data
def grading_form_to_html(self, request, page_context, grading_form, grade_data):
ctx = {
"form": grading_form,
"rubric": markup_to_html(page_context, self.page_desc.rubric)
}
from django.template import RequestContext
from django.template.loader import render_to_string
return render_to_string(
"course/human-feedback-form.html",
RequestContext(request, ctx))
def grade(self, page_context, page_data, answer_data, grade_data):
"""This method is appropriate if the grade consists *only* of the
feedback provided by humans. If more complicated/combined feedback
is desired, a subclass would likely override this.
"""
if answer_data is None:
return AnswerFeedback(correctness=0,
feedback="No answer provided.")
if grade_data is None:
return None
if not grade_data["released"]:
return None
if grade_data["grade_percent"] is not None:
correctness = grade_data["grade_percent"]/100
feedback_text = "<p>%s</p>" % get_auto_feedback(correctness)
if grade_data["feedback_text"]:
feedback_text += (
"<p>The following feedback was provided:<p>"
+ markup_to_html(page_context, grade_data["feedback_text"]))
return AnswerFeedback(
correctness=correctness,
feedback=feedback_text)
else:
return None
class PageBaseWithCorrectAnswer(PageBase):
def allowed_attrs(self):
return super(PageBaseWithCorrectAnswer, self).allowed_attrs() + (
("correct_answer", "markup"),
)
def correct_answer(self, page_context, page_data, answer_data, grade_data):
if hasattr(self.page_desc, "correct_answer"):
return markup_to_html(page_context, self.page_desc.correct_answer)
else:
return None
# }}}
# }}}
# vim: foldmethod=marker