pipeline_client.py 2.9 KB
Newer Older
B
barrierye 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# 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
import numpy as np
B
barrierye 已提交
17 18
from numpy import *
import logging
B
barrierye 已提交
19
import functools
B
barrierye 已提交
20 21 22
from .proto import pipeline_service_pb2
from .proto import pipeline_service_pb2_grpc

B
barrierye 已提交
23 24
_LOGGER = logging.getLogger(__name__)

B
barrierye 已提交
25 26 27 28 29 30 31 32 33 34

class PipelineClient(object):
    def __init__(self):
        self._channel = None

    def connect(self, endpoint):
        self._channel = grpc.insecure_channel(endpoint)
        self._stub = pipeline_service_pb2_grpc.PipelineServiceStub(
            self._channel)

B
barrierye 已提交
35
    def _pack_request_package(self, feed_dict):
B
barrierye 已提交
36 37 38 39 40 41 42 43
        req = pipeline_service_pb2.Request()
        for key, value in feed_dict.items():
            if not isinstance(value, str):
                raise TypeError("only str type is supported.")
            req.key.append(key)
            req.value.append(value)
        return req

B
barrierye 已提交
44
    def _unpack_response_package(self, resp, fetch):
B
barrierye 已提交
45 46 47 48 49 50
        if resp.ecode != 0:
            return {"ecode": resp.ecode, "error_info": resp.error_info}
        fetch_map = {"ecode": resp.ecode}
        for idx, key in enumerate(resp.key):
            if key not in fetch:
                continue
B
barrierye 已提交
51 52 53 54 55 56
            data = resp.value[idx]
            try:
                data = eval(resp.value[idx])
            except Exception as e:
                pass
            fetch_map[key] = data
B
barrierye 已提交
57
        return fetch_map
B
barrierye 已提交
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84

    def predict(self, feed_dict, fetch, asyn=False):
        if not isinstance(feed_dict, dict):
            raise TypeError(
                "feed must be dict type with format: {name: value}.")
        if not isinstance(fetch, list):
            raise TypeError("fetch must be list type with format: [name].")
        req = self._pack_request_package(feed_dict)
        if not asyn:
            resp = self._stub.inference(req)
            return self._unpack_response_package(resp)
        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)