Exemplo n.º 1
0
def _make_object_json(application, search_key, object_key, obj):
    '''Convert an object attribute dict into a dict suitable for JSON
    encoding.'''
    result = {}
    for k, v in obj.iteritems():
        data = None
        # Inline known attribute types that can be represented in JSON
        if k.endswith('.int'):
            data = IntegerAttributeCodec().decode(v)
        elif k.endswith('.double'):
            data = DoubleAttributeCodec().decode(v)
        elif k.endswith('.patches'):
            distance, patches = PatchesAttributeCodec().decode(v)
            data = {
                'distance':
                distance,
                'patches': [{
                    'x0': tl[0],
                    'y0': tl[1],
                    'x1': br[0],
                    'y1': br[1]
                } for tl, br in patches],
            }
        else:
            # Treat remaining attributes as strings if: they don't have
            # a suffix representing a known binary type, they can be decoded
            # by the string codec (i.e., their last byte is 0), they are
            # valid UTF-8, and they are not the '' (object data) attribute.
            try:
                _base, suffix = k.rsplit('.', 1)
            except ValueError:
                suffix = None
            try:
                if k != '' and suffix not in ('jpeg', 'png', 'rgbimage',
                                              'binary'):
                    data = StringAttributeCodec().decode(v).decode('UTF-8')
            except ValueError:
                pass

        if data is not None:
            result[k] = {
                'data': data,
            }
        else:
            result[k] = {
                'raw_url':
                application.reverse_url('attribute-raw', search_key,
                                        object_key, k),
                'image_url':
                application.reverse_url('attribute-image', search_key,
                                        object_key, k),
            }
    result['_ResultURL'] = {
        'data': application.reverse_url('result', search_key, object_key),
    }
    _result_object_schema.validate(result)
    return result
Exemplo n.º 2
0
import io
from typing import Mapping, Dict, Union

from PIL import Image
from opendiamond.attributes import IntegerAttributeCodec

from delphi.attribute_provider import AttributeProvider

INT_CODEC = IntegerAttributeCodec()


class DiamondAttributeProvider(AttributeProvider):
    def __init__(self, attributes: Dict[str, bytes],
                 image_provider: Union[str, bytes]):
        self._attributes = attributes

        for attribute in ['_rows.int', '_cols.int', 'thumbnail.jpeg']:
            if attribute in self._attributes:
                del self._attributes[attribute]

        self._image_provider = image_provider

    def get(self) -> Mapping[str, bytes]:
        attributes = dict(self._attributes)

        image = Image.open(self._image_provider).convert('RGB')
        width, height = image.size

        attributes['_rows.int'] = INT_CODEC.encode(height)
        attributes['_cols.int'] = INT_CODEC.encode(width)
Exemplo n.º 3
0
 def set_int(self, key, value):
     '''Set the specified object attribute as an integer.  The key name
     should end with ".int".'''
     self.set_binary(key, IntegerAttributeCodec().encode(value))
Exemplo n.º 4
0
 def get_int(self, key):
     '''Get the specified object attribute, interpreting the raw data
     as a native-endian integer.  The key name should end with ".int".'''
     return IntegerAttributeCodec().decode(self.get_binary(key))