pyclient.py 2.5 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
16 17
from .proto import general_python_service_pb2
from .proto import general_python_service_pb2_grpc
B
barrierye 已提交
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
import numpy as np


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

    def connect(self, endpoint):
        self._channel = grpc.insecure_channel(endpoint)
        self._stub = general_python_service_pb2_grpc.GeneralPythonServiceStub(
            self._channel)

    def _pack_data_for_infer(self, feed_data):
        req = general_python_service_pb2.Request()
        for name, data in feed_data.items():
33 34 35 36
            if isinstance(data, list):
                data = np.array(data)
            elif not isinstance(data, np.ndarray):
                raise TypeError("only list and numpy array type is supported.")
B
barrierye 已提交
37
            req.feed_var_names.append(name)
38 39 40
            req.feed_insts.append(data.tobytes())
            req.shape.append(np.array(data.shape, dtype="int32").tobytes())
            req.type.append(str(data.dtype))
B
barrierye 已提交
41 42
        return req

43
    def predict(self, feed, fetch):
B
barrierye 已提交
44 45 46
        if not isinstance(feed, dict):
            raise TypeError(
                "feed must be dict type with format: {name: value}.")
47
        if not isinstance(fetch, list):
B
barrierye 已提交
48
            raise TypeError(
49
                "fetch_with_type must be list type with format: [name].")
B
barrierye 已提交
50 51
        req = self._pack_data_for_infer(feed)
        resp = self._stub.inference(req)
B
barrierye 已提交
52
        if resp.ecode != 0:
B
barrierye 已提交
53 54
            return {"ecode": resp.ecode, "error_info": resp.error_info}
        fetch_map = {"ecode": resp.ecode}
B
barrierye 已提交
55
        for idx, name in enumerate(resp.fetch_var_names):
56
            if name not in fetch:
B
barrierye 已提交
57 58
                continue
            fetch_map[name] = np.frombuffer(
59 60 61
                resp.fetch_insts[idx], dtype=resp.type[idx])
            fetch_map[name].shape = np.frombuffer(
                resp.shape[idx], dtype="int32")
B
barrierye 已提交
62
        return fetch_map