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
@@ -128,6 +129,15 @@ def validate_field_data(self, validation, data):
128
129
)
129
130
)
130
131
132
+ try :
133
+ self ._get_attachments (data .attachment_urls )
134
+ except Exception :
135
+ validation .add (
136
+ ValidationMessage (
137
+ ValidationMessage .ERROR , _ ("Error downloading attachments" ),
138
+ )
139
+ )
140
+
131
141
def student_view (self , context = None ):
132
142
"""
133
143
The primary view of the ShortAnswerAIEvalXBlock, shown to students
@@ -164,15 +174,17 @@ def student_view(self, context=None):
164
174
165
175
def _download_attachment (self , url ):
166
176
with urllib .request .urlopen (url ) as f :
167
- return f .read ().decode ('utf-8' )
177
+ data = f .read ()
178
+ encoding = chardet .detect (data )['encoding' ]
179
+ return data .decode (encoding )
168
180
169
181
def _filename_for_url (self , url ):
170
182
return urllib .parse .urlparse (url ).path .split ('/' )[- 1 ]
171
183
172
- def _get_attachments (self ):
184
+ def _get_attachments (self , attachment_urls ):
173
185
pool = Pool (self .ATTACHMENT_PARALLEL_DOWNLOADS )
174
- attachments = pool .map (self ._download_attachment , self . attachment_urls )
175
- filenames = map (self ._filename_for_url , self . attachment_urls )
186
+ attachments = pool .map (self ._download_attachment , attachment_urls )
187
+ filenames = map (self ._filename_for_url , attachment_urls )
176
188
return zip (filenames , attachments )
177
189
178
190
@XBlock .json_handler
@@ -182,7 +194,7 @@ def get_response(self, data, suffix=""): # pylint: disable=unused-argument
182
194
183
195
attachments = []
184
196
attachment_hash_inputs = []
185
- for filename , contents in self ._get_attachments ():
197
+ for filename , contents in self ._get_attachments (self . attachment_urls ):
186
198
# Build system prompt attachment section (HTML-like) as before
187
199
attachments .append (f"""
188
200
<attachment>
0 commit comments