pipeline_client.py 4.0 KB
Newer Older
B
barrierye 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# pylint: disable=doc-string-missing
import grpc
B
barrierye 已提交
16
import sys
B
barrierye 已提交
17
import numpy as np
B
barrierye 已提交
18 19
from numpy import *
import logging
B
barrierye 已提交
20
import functools
T
TeslaZhao 已提交
21
import json
22
import socket
T
TeslaZhao 已提交
23
from .channel import ChannelDataErrcode
B
barrierye 已提交
24 25 26
from .proto import pipeline_service_pb2
from .proto import pipeline_service_pb2_grpc

27
_LOGGER = logging.getLogger(__name__)
B
barrierye 已提交
28

B
barrierye 已提交
29 30

class PipelineClient(object):
31 32 33 34
    """
    PipelineClient provides the basic capabilities of the pipeline SDK
    """

B
barrierye 已提交
35 36
    def __init__(self):
        self._channel = None
B
barrierye 已提交
37 38
        self._profile_key = "pipeline.profile"
        self._profile_value = "1"
B
barrierye 已提交
39

B
barrierye 已提交
40 41 42 43 44 45
    def connect(self, endpoints):
        options = [('grpc.max_receive_message_length', 512 * 1024 * 1024),
                   ('grpc.max_send_message_length', 512 * 1024 * 1024),
                   ('grpc.lb_policy_name', 'round_robin')]
        g_endpoint = 'ipv4:{}'.format(','.join(endpoints))
        self._channel = grpc.insecure_channel(g_endpoint, options=options)
B
barrierye 已提交
46 47 48
        self._stub = pipeline_service_pb2_grpc.PipelineServiceStub(
            self._channel)

B
barrierye 已提交
49
    def _pack_request_package(self, feed_dict, profile):
B
barrierye 已提交
50
        req = pipeline_service_pb2.Request()
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67

        logid = feed_dict.get("logid")
        if logid is None:
            req.logid = 0
        else:
            req.logid = long(logid)
            feed_dict.pop("logid")

        clientip = feed_dict.get("clientip")
        if clientip is None:
            hostname = socket.gethostname()
            ip = socket.gethostbyname(hostname)
            req.clientip = ip
        else:
            req.clientip = clientip
            feed_dict.pop("clientip")

B
barriery 已提交
68
        np.set_printoptions(threshold=sys.maxsize)
B
barrierye 已提交
69
        for key, value in feed_dict.items():
70
            req.key.append(key)
B
barrierye 已提交
71
            if isinstance(value, np.ndarray):
72
                req.value.append(value.__repr__())
B
barriery 已提交
73
            elif isinstance(value, (str, unicode)):
74
                req.value.append(value)
B
barrierye 已提交
75
            elif isinstance(value, list):
76
                req.value.append(np.array(value).__repr__())
B
barrierye 已提交
77 78 79
            else:
                raise TypeError("only str and np.ndarray type is supported: {}".
                                format(type(value)))
B
barrierye 已提交
80
        if profile:
81 82
            req.key.append(self._profile_key)
            req.value.append(self._profile_value)
B
barrierye 已提交
83 84
        return req

B
barrierye 已提交
85
    def _unpack_response_package(self, resp, fetch):
T
TeslaZhao 已提交
86
        return resp
B
barrierye 已提交
87

B
barrierye 已提交
88
    def predict(self, feed_dict, fetch=None, asyn=False, profile=False):
B
barrierye 已提交
89 90 91
        if not isinstance(feed_dict, dict):
            raise TypeError(
                "feed must be dict type with format: {name: value}.")
W
wangjiawei04 已提交
92
        if fetch is not None and not isinstance(fetch, list):
B
barrierye 已提交
93
            raise TypeError("fetch must be list type with format: [name].")
B
barrierye 已提交
94
        req = self._pack_request_package(feed_dict, profile)
B
barrierye 已提交
95 96
        if not asyn:
            resp = self._stub.inference(req)
W
wangjiawei04 已提交
97
            return self._unpack_response_package(resp, fetch)
B
barrierye 已提交
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
        else:
            call_future = self._stub.inference.future(req)
            return PipelinePredictFuture(
                call_future,
                functools.partial(
                    self._unpack_response_package, fetch=fetch))


class PipelinePredictFuture(object):
    def __init__(self, call_future, callback_func):
        self.call_future_ = call_future
        self.callback_func_ = callback_func

    def result(self):
        resp = self.call_future_.result()
        return self.callback_func_(resp)