1
1
"""Short answers Xblock with AI evaluation."""
2
2
3
+ import chardet
3
4
import logging
4
5
import traceback
5
6
import urllib .parse
@@ -144,6 +145,15 @@ def validate_field_data(self, validation, data):
144
145
)
145
146
)
146
147
148
+ try :
149
+ self ._get_attachments (data .attachment_urls )
150
+ except Exception :
151
+ validation .add (
152
+ ValidationMessage (
153
+ ValidationMessage .ERROR , _ ("Error downloading attachments" ),
154
+ )
155
+ )
156
+
147
157
def student_view (self , context = None ):
148
158
"""
149
159
The primary view of the ShortAnswerAIEvalXBlock, shown to students
@@ -180,15 +190,17 @@ def student_view(self, context=None):
180
190
181
191
def _download_attachment (self , url ):
182
192
with urllib .request .urlopen (url ) as f :
183
- return f .read ().decode ('utf-8' )
193
+ data = f .read ()
194
+ encoding = chardet .detect (data )['encoding' ]
195
+ return data .decode (encoding )
184
196
185
197
def _filename_for_url (self , url ):
186
198
return urllib .parse .urlparse (url ).path .split ('/' )[- 1 ]
187
199
188
- def _get_attachments (self ):
200
+ def _get_attachments (self , attachment_urls ):
189
201
pool = Pool (self .ATTACHMENT_PARALLEL_DOWNLOADS )
190
- attachments = pool .map (self ._download_attachment , self . attachment_urls )
191
- filenames = map (self ._filename_for_url , self . attachment_urls )
202
+ attachments = pool .map (self ._download_attachment , attachment_urls )
203
+ filenames = map (self ._filename_for_url , attachment_urls )
192
204
return zip (filenames , attachments )
193
205
194
206
@XBlock .json_handler
@@ -197,7 +209,7 @@ def get_response(self, data, suffix=""): # pylint: disable=unused-argument
197
209
user_submission = str (data ["user_input" ])
198
210
199
211
attachments = []
200
- for filename , contents in self ._get_attachments ():
212
+ for filename , contents in self ._get_attachments (self . attachment_urls ):
201
213
attachments .append (f"""
202
214
<attachment>
203
215
<filename>{ saxutils .escape (filename )} </filename>
0 commit comments