Python源码示例:protobuf.protobuf_to_dict()

示例1
def update_protobuf_in_db(table_name, msg, id):
    try:
        # If protobuf has an id field and it's uint64, make it a string
        id_field = msg.DESCRIPTOR.fields_by_name['id']
        if id_field.type == id_field.TYPE_UINT64:
            id = str(id)
    except AttributeError:
        pass
    cur = g.db.cursor()
    msg_dict = protobuf_to_dict(msg, type_callable_map=type_callable_map)
    columns = ', '.join(list(msg_dict.keys()))
    placeholders = ':'+', :'.join(list(msg_dict.keys()))
    setters = ', '.join('{}=:{}'.format(key, key) for key in msg_dict)
    query = 'UPDATE %s SET %s WHERE id=%s' % (table_name, setters, id)
    cur.execute(query, msg_dict)
    g.db.commit() 
示例2
def predictions(self, image):
        """Get prediction for input image.

        Parameters
        ----------
        image : `numpy.ndarray`
            The input image in [h, n, c] ndarry format.

        Returns
        -------
        list
            List of prediction resutls.
            Each element is a dictionary containing:
            {'adult', 'medical', 'racy', 'spoof', 'violence'}.

        """
        from google.cloud import vision
        from protobuf_to_dict import protobuf_to_dict
        image_bytes = ndarray_to_bytes(image)
        image = vision.types.Image(content=image_bytes)
        response = self.model.safe_search_detection(image=image)
        predictions = protobuf_to_dict(response)['safe_search_annotation']
        return predictions 
示例3
def __call__(self, stream, content_type):
        """
        Args:
            stream:
            content_type:
        """
        try:
            data = stream.read()
        finally:
            stream.close()

        for possible_response in _possible_responses():
            try:
                return protobuf_to_dict(json_format.Parse(data, possible_response()))
            except (UnicodeDecodeError, DecodeError, json_format.ParseError):
                # given that the payload does not have the response type, there no way to infer
                # the response without keeping state, so I'm iterating all the options.
                pass
        return json.loads(data.decode()) 
示例4
def insert_protobuf_into_db(table_name, msg):
    cur = g.db.cursor()
    msg_dict = protobuf_to_dict(msg, type_callable_map=type_callable_map)
    columns = ', '.join(list(msg_dict.keys()))
    placeholders = ':'+', :'.join(list(msg_dict.keys()))
    query = 'INSERT INTO %s (%s) VALUES (%s)' % (table_name, columns, placeholders)
    cur.execute(query, msg_dict)
    g.db.commit()


# XXX: can't be used to 'nullify' a column value 
示例5
def predictions(self, image):
        """Get detection result for input image.

        Parameters
        ----------
        image : `numpy.ndarray`
            The input image in [h, n, c] ndarry format.

        Returns
        -------
        list
            List of batch prediction resutls.
            Each element is a dictionary containing:
            {'name', 'score', 'mid', 'bounding_poly'}.

        """
        from google.cloud import vision
        from google.protobuf.json_format import MessageToJson
        from protobuf_to_dict import protobuf_to_dict
        image_bytes = ndarray_to_bytes(image)
        image = vision.types.Image(content=image_bytes)
        response = self.model.object_localization(
            image=image).localized_object_annotations
        predictions = []
        for object in response:
            predictions.append(protobuf_to_dict(object))

        return predictions 
示例6
def predictions(self, image):
        """Get detection result for input image.

        Parameters
        ----------
        image : `numpy.ndarray`
            The input image in [h, n, c] ndarry format.

        Returns
        -------
        list
            List of batch prediction resutls.
            Each element is a dictionary containing:
            {'name', 'score', 'mid', 'bounding_poly'}.

        """
        from google.cloud import vision
        from google.protobuf.json_format import MessageToJson
        from protobuf_to_dict import protobuf_to_dict
        image_bytes = ndarray_to_bytes(image)
        image = vision.types.Image(content=image_bytes)
        response = self.model.object_localization(
            image=image).localized_object_annotations
        predictions = []
        for object in response:
            predictions.append(protobuf_to_dict(object))

        return predictions 
示例7
def convert_request_to(target):
    """
    convert different kinds of request to needed input.

    there are 4 needed inputs:
    - GraphNode
    - GraphRelation
    - RawString
    - ExtractorInput
    """
    def _convert_request_to(func):
        @wraps(func)
        def wrapper(self, request, context):
            dctreq = protobuf_to_dict(request)
            if "props" in dctreq:
                req_props = dctreq["props"]
                dctreq["props"] = json.loads(req_props)
            if "start" in dctreq:
                start_props = dctreq["start"]["props"]
                dctreq["start"]["props"] = json.loads(start_props)
            if "end" in dctreq:
                end_props = dctreq["end"]["props"]
                dctreq["end"]["props"] = json.loads(end_props)
            request = from_dict(target, dctreq)
            result = func(self, request, context)
            return result
        return wrapper
    return _convert_request_to 
示例8
def test_meter_mod_loxi_to_grpc_converter(self):
        from ofagent.loxi.of13 import meter_band

        assertion_check_keys = dict()
        meter_bands = list()

        command_list = [const.OFPMC_ADD, const.OFPMC_MODIFY, const.OFPMC_DELETE]
        flag_list = [const.OFPMF_KBPS, const.OFPMF_PKTPS, const.OFPMF_BURST, const.OFPMF_STATS]
        meter_band_constructs = [meter_band.dscp_remark, meter_band.drop, meter_band.experimenter]

        assertion_check_keys['meter_band_entry_cnt'] = randint(0, 20)
        assertion_check_keys['xid_instance'] = randint(0, 0xFFFFFFFF)
        assertion_check_keys['command_instance'] = command_list[randint(0, len(command_list) - 1)]
        assertion_check_keys['flag_instance'] = flag_list[randint(0, len(flag_list) - 1)]

        for i in range(0, assertion_check_keys['meter_band_entry_cnt']):
            meter_band = meter_band_constructs[randint(0, len(meter_band_constructs)-1)]()
            assertion_check_keys['meter_band_type_' + str(i)] = meter_band.type
            meter_bands.append(meter_band)

        of_meter_mod_req = meter_mod(xid=assertion_check_keys['xid_instance'],
                                     command=assertion_check_keys['command_instance'],
                                     flags=assertion_check_keys['flag_instance'],
                                     meters=meter_bands)

        req = to_grpc(of_meter_mod_req)
        request = protobuf_to_dict(req)

        if request.has_key('flags'):
            self.assertEqual(request['flags'], assertion_check_keys['flag_instance'])

        if request.has_key('command'):
            self.assertEqual(request['command'], assertion_check_keys['command_instance'])

        if request.has_key('bands'):
            self.assertEqual(assertion_check_keys['meter_band_entry_cnt'], len(request['bands']))

            name_suffix = 0
            for i in request['bands']:
                self.assertEqual(i['type'], assertion_check_keys['meter_band_type_' + str(name_suffix)])
                name_suffix = name_suffix+1 
示例9
def pb2dict(pb):
    """
    Convert protobuf to a dict of values good for instantiating
    loxi objects (or any other objects). We specialize the protobuf_to_dict
    library call with our modified decoders.
    :param pb: protobuf as loaded into Python
    :return: dict of values
    """
    return protobuf_to_dict(pb, type_callable_map) 
示例10
def predictions(self, image):
        """Get prediction for input image

        Parameters
        ----------
        image : `numpy.ndarray`
            The input image in [h, n, c] ndarry format.

        Returns
        -------
        list
            List of anitporn prediction resutls.
            Each element is a dictionary containing:
            {'class_name', 'probability'}

        """
        from perceptron.utils.protobuf.general_classify_client_pb2 import GeneralClassifyResponse
        from perceptron.utils.protobuf.general_classify_client_pb2 import GeneralClassifyRequest
        from perceptron.utils.protobuf.protobuf_to_dict import protobuf_to_dict
        from perceptron.utils.protobuf.protobuf_to_dict import dict_to_protobuf
        import ujson as json
        import base64
        import urllib.request as request

        image_data = ndarray_to_bytes(image)
        proto_data = GeneralClassifyRequest()
        proto_data.image = image_data
        for i in range(len(self._apiType)):
            classifytype = proto_data.classify_type.add()
            classifytype.type_name = self._apiType[i]
        classifytype.topnum = 5
        data = proto_data.SerializeToString()

        import base64, random
        logid = random.randint(1000000, 100000000)
        req_array = {
            'appid': '123456',
            'logid': logid,
            'format': 'json',
            'from': 'test-python',
            'cmdid': '123',
            'clientip': '0.0.0.0',
            'data': base64.b64encode(data),
        }
        req_data = json.dumps(req_array).encode('ascii')

        # send request
        req = request.Request(self.url, req_data)
        req.add_header('Content-Type', 'application/json')
        try:    
            res_data = request.urlopen(req)
            response = res_data.read()
        except Exception as e:
            print(e)
        response = response.decode("utf-8")
        result = json.loads(response)
        proto_result = GeneralClassifyResponse()
        proto_result.ParseFromString(base64.b64decode(result['result']))
        result_json = protobuf_to_dict(proto_result)
        result['result'] = result_json
        return result 
示例11
def convert_to_legacy_config_dict(artifact_config, root_dir, output_dir):
    artifact_config_dict = protobuf_to_dict(artifact_config)
    common = {}
    common['api_name'] = artifact_config.api_name
    common['api_version'] = artifact_config.api_version
    common['organization_name'] = artifact_config.organization_name
    common['service_yaml'] = artifact_config.service_yaml
    common['gapic_yaml'] = artifact_config.gapic_yaml
    common['proto_package'] = artifact_config.proto_package
    if 'grpc_service_config' in artifact_config_dict:
        common['grpc_service_config'] = artifact_config_dict['grpc_service_config']
    common['samples'] = artifact_config.samples
    src_proto_paths = artifact_config_dict.get('src_proto_paths', [])
    common['src_proto_path'], excluded_proto_path = _calculate_proto_paths(src_proto_paths)
    if excluded_proto_path:
        common['excluded_proto_path'] = excluded_proto_path
    common['import_proto_path'] = [root_dir]
    common['output_dir'] = output_dir
    common['proto_deps'] = []
    if 'proto_deps' in artifact_config_dict:
        common['proto_deps'] = artifact_config_dict['proto_deps']
    if 'test_proto_deps' in artifact_config_dict:
        common['test_proto_deps'] = artifact_config_dict['test_proto_deps']
    common['artifact_type'] = Artifact.Type.Name(artifact_config.type)
    common['language_out_override'] = artifact_config.language_out_override

    result = {}
    result['common'] = common

    if artifact_config.type == Artifact.GAPIC_CONFIG\
        or artifact_config.type == Artifact.DISCOGAPIC_CONFIG:
        # Early return if the artifact type is GAPIC_CONFIG or DISCOGAPIC_CONFIG
        return result

    language = Artifact.Language.Name(
        artifact_config.language).lower()
    language_config_dict = {}
    rel_gapic_code_dir = _calculate_rel_gapic_output_dir(
        language, artifact_config.api_name, artifact_config.api_version)
    language_config_dict['gapic_code_dir'] = os.path.join(
        output_dir, rel_gapic_code_dir)
    if artifact_config.release_level != Artifact.RELEASE_LEVEL_UNSPECIFIED:
        language_config_dict['release_level'] = (
            Artifact.ReleaseLevel.Name(
                artifact_config.release_level).lower())

    result[language] = language_config_dict
    return result