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