We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Internal server error for API call
This URL currently gives an internal server error: http://rsr.akvo.org/rest/v1/project_extra/787/.json

Part of the stacktrace:

```
IOError Root Cause
image file is truncated (48 bytes not processed)

...
akvo/rest/fields.py ? in to_native
    default_thumb = get_thumbnail(value, default_width, quality=99)
sorl/thumbnail/shortcuts.py ? in get_thumbnail
    return default.backend.get_thumbnail(file_, geometry_string, **options)
sorl/thumbnail/base.py ? in get_thumbnail
    thumbnail)
sorl/thumbnail/base.py ? in _create_thumbnail
    image = default.engine.create(source_image, geometry, options)
sorl/thumbnail/engines/base.py ? in create
    image = self.colorspace(image, geometry, options)
sorl/thumbnail/engines/base.py ? in colorspace
    return self._colorspace(image, colorspace)
sorl/thumbnail/engines/pil_engine.py ? in _colorspace
    return image.convert('RGB')
PIL/Image.py ? in convert
    self.load()
PIL/ImageFile.py ? in load
    "(%d bytes not processed)" % len(b))
```


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `akvo/rest/fields.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 
3 # Akvo RSR is covered by the GNU Affero General Public License.
4 # See more details in the license.txt file located at the root folder of the Akvo RSR module.
5 # For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >.
6 
7 
8 import base64
9 import imghdr
10 import six
11 import uuid
12 
13 from django.core.files.base import ContentFile
14 from django.utils.encoding import smart_text
15 from django.utils.translation import ugettext_lazy as _
16 
17 from rest_framework import serializers
18 from rest_framework.fields import ImageField
19 from sorl.thumbnail import get_thumbnail
20 from sorl.thumbnail.parsers import ThumbnailParseError
21 
22 
23 class NonNullCharField(serializers.CharField):
24     """ Fix fo CharField so that '' is returned if the field value is None
25         see https://github.com/tomchristie/django-rest-framework/pull/1665
26     """
27     def from_native(self, value):
28         if isinstance(value, six.string_types):
29             return value
30         if value is None:
31             return u''
32         return smart_text(value)
33 
34 
35 class NonNullURLField(NonNullCharField, serializers.URLField):
36     pass
37 
38 
39 class Base64ImageField(ImageField):
40     """ A django-rest-framework field for handling image-uploads through raw post data.
41         It uses base64 for en-/decoding the contents of the file.
42         Now also supports thumbnails of different sizes. See to_native() for more info.
43     """
44     ALLOWED_IMAGE_TYPES = (
45         'gif',
46         'jpeg',
47         'jpg',
48         'png',
49     )
50     def from_native(self, base64_data):
51         # Check if this is a base64 string
52         if isinstance(base64_data, basestring):
53             # Try to decode the file. Return validation error if it fails.
54             try:
55                 decoded_file = base64.b64decode(base64_data)
56             except TypeError:
57                 raise serializers.ValidationError(_(u"Please upload a valid image."))
58 
59             # Generate file name:
60             file_name = str(uuid.uuid4())[:12] # 12 characters are more than enough.
61             # Get the file name extension:
62             file_extension = self.get_file_extension(file_name, decoded_file)
63             if file_extension not in self.ALLOWED_IMAGE_TYPES:
64                 raise serializers.ValidationError(
65                     _(u"The type of the image couldn't been determined.")
66                 )
67             complete_file_name = file_name + "." + file_extension
68             data = ContentFile(decoded_file, name=complete_file_name)
69         else:
70             data = base64_data
71 
72         return super(Base64ImageField, self).from_native(data)
73 
74     def to_native(self, value):
75         """
76         :param value: A Base64ImageField object
77         :return: a path to a thumbnail with a predetermined size, the default thumb
78         OR
79         a dict with a number of thumbnails, one of which is the default, the others being generated
80         from the query string parameters, and finally the path to the original image keyed to
81         "original".
82 
83         The extended functionality, allowing the generation of one or more thumbnails from the
84         original image is triggered by including "image_thumb_name" in the query string. The value
85         for image_thumb_name is a comma separated list of identifiers for the generated thumbs.
86         The names must not be "default" or "original".
87 
88         For each thumb thus specified a size must be supplied as a query param on the form
89             image_thumb_<name>_<dimension>
90         where <name> is the name of the thumb specified as one of the values for image_thumb_name
91         and <dimension> is one of "width, "height" or "max_size". width and height must be an integer
92         specifying that dimension in pixels. The image will be scaled correctly in the other
93         dimension. max_size is width and height concatenated with an "x" and sets the maximum size
94         allowed for the respective dimensions, while still maintaining the correct aspect ratio of
95         the image.
96 
97         Example:
98         the querystring
99             ?image_thumb_name=big,small&image_thumb_small_width=90&image_thumb_big_max_size=300x200
100         results in the following dict being returned:
101         {
102             'original': '/full/path/to/original/image.png',
103             'default': '/full/path/to/default/thumbnail/image.png',
104             'small': '/full/path/to/small/thumbnail/image.png',
105             'big': '/full/path/to/big/thumbnail/image.png',
106         }
107         This dict will be converted as appropriate to JSON or XML
108 
109         NOTE: This special functionality works best when there is only one image field in a model.
110         If there are more, things will still work (I think), but for each image all thumbs returned
111         will have the same dimensions
112         """
113         def get_thumb(request, name):
114             if name not in [u'original', u'default']:
115                 try:
116                     width = request.GET.get('image_thumb_{}_width'.format(name))
117                     if width:
118                         return get_thumbnail(value, '{}'.format(width), quality=99)
119                     height = request.GET.get('image_thumb_{}_height'.format(name))
120                     if height:
121                         return get_thumbnail(value, 'x{}'.format(height), quality=99)
122                     # yes this is redundant...code is nearly identical with the width code above
123                     # but for clarity of function we keep them separate
124                     max_size = request.GET.get('image_thumb_{}_max_size'.format(name))
125                     if max_size:
126                         return get_thumbnail(value, '{}'.format(max_size), quality=99)
127                 except ThumbnailParseError:
128                     return None
129             # no size specification matching the name found; give up
130             return None
131 
132         if value:
133             default_width = '191' # width of update images on akvo.org/seeithappen
134             default_thumb = get_thumbnail(value, default_width, quality=99)
135             try:
136                 request = self.context['request']
137             except KeyError:
138                 return None
139             # look for name(s) of thumb(s)
140             image_thumb_name = request.GET.get('image_thumb_name')
141             if image_thumb_name:
142                 names = image_thumb_name.split(',')
143                 thumbs = {u'original': value.url, u'default': default_thumb.url}
144                 for name in names:
145                     thumb = get_thumb(request, name)
146                     if thumb is not None:
147                         thumbs[name] = thumb.url
148                 return thumbs
149             return default_thumb.url
150 
151     def get_file_extension(self, filename, decoded_file):
152         extension = imghdr.what(filename, decoded_file)
153         extension = "jpg" if extension == "jpeg" else extension
154         return extension
155
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/akvo/rest/fields.py b/akvo/rest/fields.py
--- a/akvo/rest/fields.py
+++ b/akvo/rest/fields.py
@@ -124,18 +124,20 @@
                     max_size = request.GET.get('image_thumb_{}_max_size'.format(name))
                     if max_size:
                         return get_thumbnail(value, '{}'.format(max_size), quality=99)
-                except ThumbnailParseError:
+                except (ThumbnailParseError, IOError):
                     return None
+
             # no size specification matching the name found; give up
             return None
 
         if value:
             default_width = '191' # width of update images on akvo.org/seeithappen
-            default_thumb = get_thumbnail(value, default_width, quality=99)
             try:
+                default_thumb = get_thumbnail(value, default_width, quality=99)
                 request = self.context['request']
-            except KeyError:
+            except (ThumbnailParseError, IOError, KeyError):
                 return None
+
             # look for name(s) of thumb(s)
             image_thumb_name = request.GET.get('image_thumb_name')
             if image_thumb_name:

{"golden_diff": "diff --git a/akvo/rest/fields.py b/akvo/rest/fields.py\n--- a/akvo/rest/fields.py\n+++ b/akvo/rest/fields.py\n@@ -124,18 +124,20 @@\n                     max_size = request.GET.get('image_thumb_{}_max_size'.format(name))\n                     if max_size:\n                         return get_thumbnail(value, '{}'.format(max_size), quality=99)\n-                except ThumbnailParseError:\n+                except (ThumbnailParseError, IOError):\n                     return None\n+\n             # no size specification matching the name found; give up\n             return None\n \n         if value:\n             default_width = '191' # width of update images on akvo.org/seeithappen\n-            default_thumb = get_thumbnail(value, default_width, quality=99)\n             try:\n+                default_thumb = get_thumbnail(value, default_width, quality=99)\n                 request = self.context['request']\n-            except KeyError:\n+            except (ThumbnailParseError, IOError, KeyError):\n                 return None\n+\n             # look for name(s) of thumb(s)\n             image_thumb_name = request.GET.get('image_thumb_name')\n             if image_thumb_name:\n", "issue": "Internal server error for API call\nThis URL currently gives an internal server error: http://rsr.akvo.org/rest/v1/project_extra/787/.json\n\nPart of the stacktrace:\n\n```\nIOError Root Cause\nimage file is truncated (48 bytes not processed)\n\n...\nakvo/rest/fields.py ? in to_native\n    default_thumb = get_thumbnail(value, default_width, quality=99)\nsorl/thumbnail/shortcuts.py ? in get_thumbnail\n    return default.backend.get_thumbnail(file_, geometry_string, **options)\nsorl/thumbnail/base.py ? in get_thumbnail\n    thumbnail)\nsorl/thumbnail/base.py ? in _create_thumbnail\n    image = default.engine.create(source_image, geometry, options)\nsorl/thumbnail/engines/base.py ? in create\n    image = self.colorspace(image, geometry, options)\nsorl/thumbnail/engines/base.py ? in colorspace\n    return self._colorspace(image, colorspace)\nsorl/thumbnail/engines/pil_engine.py ? in _colorspace\n    return image.convert('RGB')\nPIL/Image.py ? in convert\n    self.load()\nPIL/ImageFile.py ? in load\n    \"(%d bytes not processed)\" % len(b))\n```\n\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n\n# Akvo RSR is covered by the GNU Affero General Public License.\n# See more details in the license.txt file located at the root folder of the Akvo RSR module.\n# For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >.\n\n\nimport base64\nimport imghdr\nimport six\nimport uuid\n\nfrom django.core.files.base import ContentFile\nfrom django.utils.encoding import smart_text\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom rest_framework import serializers\nfrom rest_framework.fields import ImageField\nfrom sorl.thumbnail import get_thumbnail\nfrom sorl.thumbnail.parsers import ThumbnailParseError\n\n\nclass NonNullCharField(serializers.CharField):\n    \"\"\" Fix fo CharField so that '' is returned if the field value is None\n        see https://github.com/tomchristie/django-rest-framework/pull/1665\n    \"\"\"\n    def from_native(self, value):\n        if isinstance(value, six.string_types):\n            return value\n        if value is None:\n            return u''\n        return smart_text(value)\n\n\nclass NonNullURLField(NonNullCharField, serializers.URLField):\n    pass\n\n\nclass Base64ImageField(ImageField):\n    \"\"\" A django-rest-framework field for handling image-uploads through raw post data.\n        It uses base64 for en-/decoding the contents of the file.\n        Now also supports thumbnails of different sizes. See to_native() for more info.\n    \"\"\"\n    ALLOWED_IMAGE_TYPES = (\n        'gif',\n        'jpeg',\n        'jpg',\n        'png',\n    )\n    def from_native(self, base64_data):\n        # Check if this is a base64 string\n        if isinstance(base64_data, basestring):\n            # Try to decode the file. Return validation error if it fails.\n            try:\n                decoded_file = base64.b64decode(base64_data)\n            except TypeError:\n                raise serializers.ValidationError(_(u\"Please upload a valid image.\"))\n\n            # Generate file name:\n            file_name = str(uuid.uuid4())[:12] # 12 characters are more than enough.\n            # Get the file name extension:\n            file_extension = self.get_file_extension(file_name, decoded_file)\n            if file_extension not in self.ALLOWED_IMAGE_TYPES:\n                raise serializers.ValidationError(\n                    _(u\"The type of the image couldn't been determined.\")\n                )\n            complete_file_name = file_name + \".\" + file_extension\n            data = ContentFile(decoded_file, name=complete_file_name)\n        else:\n            data = base64_data\n\n        return super(Base64ImageField, self).from_native(data)\n\n    def to_native(self, value):\n        \"\"\"\n        :param value: A Base64ImageField object\n        :return: a path to a thumbnail with a predetermined size, the default thumb\n        OR\n        a dict with a number of thumbnails, one of which is the default, the others being generated\n        from the query string parameters, and finally the path to the original image keyed to\n        \"original\".\n\n        The extended functionality, allowing the generation of one or more thumbnails from the\n        original image is triggered by including \"image_thumb_name\" in the query string. The value\n        for image_thumb_name is a comma separated list of identifiers for the generated thumbs.\n        The names must not be \"default\" or \"original\".\n\n        For each thumb thus specified a size must be supplied as a query param on the form\n            image_thumb_<name>_<dimension>\n        where <name> is the name of the thumb specified as one of the values for image_thumb_name\n        and <dimension> is one of \"width, \"height\" or \"max_size\". width and height must be an integer\n        specifying that dimension in pixels. The image will be scaled correctly in the other\n        dimension. max_size is width and height concatenated with an \"x\" and sets the maximum size\n        allowed for the respective dimensions, while still maintaining the correct aspect ratio of\n        the image.\n\n        Example:\n        the querystring\n            ?image_thumb_name=big,small&image_thumb_small_width=90&image_thumb_big_max_size=300x200\n        results in the following dict being returned:\n        {\n            'original': '/full/path/to/original/image.png',\n            'default': '/full/path/to/default/thumbnail/image.png',\n            'small': '/full/path/to/small/thumbnail/image.png',\n            'big': '/full/path/to/big/thumbnail/image.png',\n        }\n        This dict will be converted as appropriate to JSON or XML\n\n        NOTE: This special functionality works best when there is only one image field in a model.\n        If there are more, things will still work (I think), but for each image all thumbs returned\n        will have the same dimensions\n        \"\"\"\n        def get_thumb(request, name):\n            if name not in [u'original', u'default']:\n                try:\n                    width = request.GET.get('image_thumb_{}_width'.format(name))\n                    if width:\n                        return get_thumbnail(value, '{}'.format(width), quality=99)\n                    height = request.GET.get('image_thumb_{}_height'.format(name))\n                    if height:\n                        return get_thumbnail(value, 'x{}'.format(height), quality=99)\n                    # yes this is redundant...code is nearly identical with the width code above\n                    # but for clarity of function we keep them separate\n                    max_size = request.GET.get('image_thumb_{}_max_size'.format(name))\n                    if max_size:\n                        return get_thumbnail(value, '{}'.format(max_size), quality=99)\n                except ThumbnailParseError:\n                    return None\n            # no size specification matching the name found; give up\n            return None\n\n        if value:\n            default_width = '191' # width of update images on akvo.org/seeithappen\n            default_thumb = get_thumbnail(value, default_width, quality=99)\n            try:\n                request = self.context['request']\n            except KeyError:\n                return None\n            # look for name(s) of thumb(s)\n            image_thumb_name = request.GET.get('image_thumb_name')\n            if image_thumb_name:\n                names = image_thumb_name.split(',')\n                thumbs = {u'original': value.url, u'default': default_thumb.url}\n                for name in names:\n                    thumb = get_thumb(request, name)\n                    if thumb is not None:\n                        thumbs[name] = thumb.url\n                return thumbs\n            return default_thumb.url\n\n    def get_file_extension(self, filename, decoded_file):\n        extension = imghdr.what(filename, decoded_file)\n        extension = \"jpg\" if extension == \"jpeg\" else extension\n        return extension\n", "path": "akvo/rest/fields.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n\n# Akvo RSR is covered by the GNU Affero General Public License.\n# See more details in the license.txt file located at the root folder of the Akvo RSR module.\n# For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >.\n\n\nimport base64\nimport imghdr\nimport six\nimport uuid\n\nfrom django.core.files.base import ContentFile\nfrom django.utils.encoding import smart_text\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom rest_framework import serializers\nfrom rest_framework.fields import ImageField\nfrom sorl.thumbnail import get_thumbnail\nfrom sorl.thumbnail.parsers import ThumbnailParseError\n\n\nclass NonNullCharField(serializers.CharField):\n    \"\"\" Fix fo CharField so that '' is returned if the field value is None\n        see https://github.com/tomchristie/django-rest-framework/pull/1665\n    \"\"\"\n    def from_native(self, value):\n        if isinstance(value, six.string_types):\n            return value\n        if value is None:\n            return u''\n        return smart_text(value)\n\n\nclass NonNullURLField(NonNullCharField, serializers.URLField):\n    pass\n\n\nclass Base64ImageField(ImageField):\n    \"\"\" A django-rest-framework field for handling image-uploads through raw post data.\n        It uses base64 for en-/decoding the contents of the file.\n        Now also supports thumbnails of different sizes. See to_native() for more info.\n    \"\"\"\n    ALLOWED_IMAGE_TYPES = (\n        'gif',\n        'jpeg',\n        'jpg',\n        'png',\n    )\n    def from_native(self, base64_data):\n        # Check if this is a base64 string\n        if isinstance(base64_data, basestring):\n            # Try to decode the file. Return validation error if it fails.\n            try:\n                decoded_file = base64.b64decode(base64_data)\n            except TypeError:\n                raise serializers.ValidationError(_(u\"Please upload a valid image.\"))\n\n            # Generate file name:\n            file_name = str(uuid.uuid4())[:12] # 12 characters are more than enough.\n            # Get the file name extension:\n            file_extension = self.get_file_extension(file_name, decoded_file)\n            if file_extension not in self.ALLOWED_IMAGE_TYPES:\n                raise serializers.ValidationError(\n                    _(u\"The type of the image couldn't been determined.\")\n                )\n            complete_file_name = file_name + \".\" + file_extension\n            data = ContentFile(decoded_file, name=complete_file_name)\n        else:\n            data = base64_data\n\n        return super(Base64ImageField, self).from_native(data)\n\n    def to_native(self, value):\n        \"\"\"\n        :param value: A Base64ImageField object\n        :return: a path to a thumbnail with a predetermined size, the default thumb\n        OR\n        a dict with a number of thumbnails, one of which is the default, the others being generated\n        from the query string parameters, and finally the path to the original image keyed to\n        \"original\".\n\n        The extended functionality, allowing the generation of one or more thumbnails from the\n        original image is triggered by including \"image_thumb_name\" in the query string. The value\n        for image_thumb_name is a comma separated list of identifiers for the generated thumbs.\n        The names must not be \"default\" or \"original\".\n\n        For each thumb thus specified a size must be supplied as a query param on the form\n            image_thumb_<name>_<dimension>\n        where <name> is the name of the thumb specified as one of the values for image_thumb_name\n        and <dimension> is one of \"width, \"height\" or \"max_size\". width and height must be an integer\n        specifying that dimension in pixels. The image will be scaled correctly in the other\n        dimension. max_size is width and height concatenated with an \"x\" and sets the maximum size\n        allowed for the respective dimensions, while still maintaining the correct aspect ratio of\n        the image.\n\n        Example:\n        the querystring\n            ?image_thumb_name=big,small&image_thumb_small_width=90&image_thumb_big_max_size=300x200\n        results in the following dict being returned:\n        {\n            'original': '/full/path/to/original/image.png',\n            'default': '/full/path/to/default/thumbnail/image.png',\n            'small': '/full/path/to/small/thumbnail/image.png',\n            'big': '/full/path/to/big/thumbnail/image.png',\n        }\n        This dict will be converted as appropriate to JSON or XML\n\n        NOTE: This special functionality works best when there is only one image field in a model.\n        If there are more, things will still work (I think), but for each image all thumbs returned\n        will have the same dimensions\n        \"\"\"\n        def get_thumb(request, name):\n            if name not in [u'original', u'default']:\n                try:\n                    width = request.GET.get('image_thumb_{}_width'.format(name))\n                    if width:\n                        return get_thumbnail(value, '{}'.format(width), quality=99)\n                    height = request.GET.get('image_thumb_{}_height'.format(name))\n                    if height:\n                        return get_thumbnail(value, 'x{}'.format(height), quality=99)\n                    # yes this is redundant...code is nearly identical with the width code above\n                    # but for clarity of function we keep them separate\n                    max_size = request.GET.get('image_thumb_{}_max_size'.format(name))\n                    if max_size:\n                        return get_thumbnail(value, '{}'.format(max_size), quality=99)\n                except (ThumbnailParseError, IOError):\n                    return None\n\n            # no size specification matching the name found; give up\n            return None\n\n        if value:\n            default_width = '191' # width of update images on akvo.org/seeithappen\n            try:\n                default_thumb = get_thumbnail(value, default_width, quality=99)\n                request = self.context['request']\n            except (ThumbnailParseError, IOError, KeyError):\n                return None\n\n            # look for name(s) of thumb(s)\n            image_thumb_name = request.GET.get('image_thumb_name')\n            if image_thumb_name:\n                names = image_thumb_name.split(',')\n                thumbs = {u'original': value.url, u'default': default_thumb.url}\n                for name in names:\n                    thumb = get_thumb(request, name)\n                    if thumb is not None:\n                        thumbs[name] = thumb.url\n                return thumbs\n            return default_thumb.url\n\n    def get_file_extension(self, filename, decoded_file):\n        extension = imghdr.what(filename, decoded_file)\n        extension = \"jpg\" if extension == \"jpeg\" else extension\n        return extension\n", "path": "akvo/rest/fields.py"}]}