/
service.py
218 lines (169 loc) · 7.03 KB
/
service.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
from __future__ import annotations
import time
import typing as t
from typing import TYPE_CHECKING
from pydantic import BaseModel
from context_server_interceptor import AsyncContextInterceptor
import bentoml
from bentoml.io import File
from bentoml.io import JSON
from bentoml.io import Text
from bentoml.io import Image
from bentoml.io import Multipart
from bentoml.io import NumpyNdarray
from bentoml.io import PandasSeries
from bentoml.io import PandasDataFrame
from bentoml.testing.grpc import TestServiceServicer
from bentoml._internal.utils import LazyLoader
from bentoml._internal.utils.metrics import exponential_buckets
if TYPE_CHECKING:
import numpy as np
import pandas as pd
import PIL.Image
from numpy.typing import NDArray
from bentoml.grpc.v1alpha1 import service_test_pb2 as pb_test
from bentoml.grpc.v1alpha1 import service_test_pb2_grpc as services_test
from bentoml._internal.types import FileLike
from bentoml._internal.types import JSONSerializable
from bentoml.picklable_model import get_runnable
from bentoml._internal.runner.runner import RunnerMethod
RunnableImpl = get_runnable(bentoml.picklable_model.get("py_model.case-1.grpc.e2e"))
class PythonModelRunner(bentoml.Runner):
predict_file: RunnerMethod[RunnableImpl, [list[FileLike[bytes]]], list[bytes]]
echo_json: RunnerMethod[
RunnableImpl, [list[JSONSerializable]], list[JSONSerializable]
]
echo_ndarray: RunnerMethod[RunnableImpl, [NDArray[t.Any]], NDArray[t.Any]]
double_ndarray: RunnerMethod[RunnableImpl, [NDArray[t.Any]], NDArray[t.Any]]
multiply_float_ndarray: RunnerMethod[
RunnableImpl,
[NDArray[np.float32], NDArray[np.float32]],
NDArray[np.float32],
]
double_dataframe_column: RunnerMethod[
RunnableImpl, [pd.DataFrame], pd.DataFrame
]
echo_dataframe: RunnerMethod[RunnableImpl, [pd.DataFrame], pd.DataFrame]
else:
from bentoml.grpc.utils import import_generated_stubs
pb_test, services_test = import_generated_stubs(file="service_test.proto")
np = LazyLoader("np", globals(), "numpy")
pd = LazyLoader("pd", globals(), "pandas")
PIL = LazyLoader("PIL", globals(), "PIL")
PIL.Image = LazyLoader("PIL.Image", globals(), "PIL.Image")
py_model = t.cast(
"PythonModelRunner",
bentoml.picklable_model.get("py_model.case-1.grpc.e2e").to_runner(),
)
svc = bentoml.Service(name="general_grpc_service.case-1.e2e", runners=[py_model])
svc.mount_grpc_servicer(
TestServiceServicer,
add_servicer_fn=services_test.add_TestServiceServicer_to_server,
service_names=[v.full_name for v in pb_test.DESCRIPTOR.services_by_name.values()],
)
svc.add_grpc_interceptor(AsyncContextInterceptor, usage="NLP", accuracy_score=0.8247)
class IrisFeatures(BaseModel):
sepal_len: float
sepal_width: float
petal_len: float
petal_width: float
class IrisClassificationRequest(BaseModel):
request_id: str
iris_features: IrisFeatures
@svc.api(input=Text(), output=Text())
async def bonjour(inp: str) -> str:
return f"Hello, {inp}!"
@svc.api(input=JSON(), output=JSON())
async def echo_json(json_obj: JSONSerializable) -> JSONSerializable:
batched = await py_model.echo_json.async_run([json_obj])
return batched[0]
@svc.api(
input=JSON(pydantic_model=IrisClassificationRequest),
output=JSON(),
)
def echo_json_validate(input_data: IrisClassificationRequest) -> dict[str, float]:
print("request_id: ", input_data.request_id)
return input_data.iris_features.dict()
@svc.api(input=NumpyNdarray(), output=NumpyNdarray())
async def double_ndarray(arr: NDArray[t.Any]) -> NDArray[t.Any]:
return await py_model.double_ndarray.async_run(arr)
@svc.api(input=NumpyNdarray.from_sample(np.random.rand(2, 2)), output=NumpyNdarray())
async def echo_ndarray_from_sample(arr: NDArray[t.Any]) -> NDArray[t.Any]:
assert arr.shape == (2, 2)
return await py_model.echo_ndarray.async_run(arr)
@svc.api(input=NumpyNdarray(shape=(2, 2), enforce_shape=True), output=NumpyNdarray())
async def echo_ndarray_enforce_shape(arr: NDArray[t.Any]) -> NDArray[t.Any]:
assert arr.shape == (2, 2)
return await py_model.echo_ndarray.async_run(arr)
@svc.api(
input=NumpyNdarray(dtype=np.float32, enforce_dtype=True), output=NumpyNdarray()
)
async def echo_ndarray_enforce_dtype(arr: NDArray[t.Any]) -> NDArray[t.Any]:
assert arr.dtype == np.float32
return await py_model.echo_ndarray.async_run(arr)
@svc.api(input=PandasDataFrame(orient="columns"), output=PandasDataFrame())
async def echo_dataframe(df: pd.DataFrame) -> pd.DataFrame:
assert isinstance(df, pd.DataFrame)
return df
@svc.api(
input=PandasDataFrame.from_sample(
pd.DataFrame({"age": [3, 29], "height": [94, 170], "weight": [31, 115]}),
orient="columns",
),
output=PandasDataFrame(),
)
async def echo_dataframe_from_sample(df: pd.DataFrame) -> pd.DataFrame:
assert isinstance(df, pd.DataFrame)
return df
@svc.api(input=PandasSeries.from_sample(pd.Series([1, 2, 3])), output=PandasSeries())
async def echo_series_from_sample(series: pd.Series) -> pd.Series:
assert isinstance(series, pd.Series)
return series
@svc.api(
input=PandasDataFrame(dtype={"col1": "int64"}, orient="columns"),
output=PandasDataFrame(),
)
async def double_dataframe(df: pd.DataFrame) -> pd.DataFrame:
assert df["col1"].dtype == "int64"
output = await py_model.double_dataframe_column.async_run(df)
dfo = pd.DataFrame()
dfo["col1"] = output
return dfo
@svc.api(input=File(), output=File())
async def predict_file(f: FileLike[bytes]) -> bytes:
batch_ret = await py_model.predict_file.async_run([f])
return batch_ret[0]
@svc.api(input=Image(mime_type="image/bmp"), output=Image(mime_type="image/bmp"))
async def echo_image(f: PIL.Image.Image) -> NDArray[t.Any]:
assert isinstance(f, PIL.Image.Image)
return np.array(f)
histogram = bentoml.metrics.Histogram(
name="inference_latency",
documentation="Inference latency in seconds",
labelnames=["model_name", "model_version"],
buckets=exponential_buckets(0.001, 1.5, 10.0),
)
@svc.api(
input=Multipart(
original=Image(mime_type="image/bmp"), compared=Image(mime_type="image/bmp")
),
output=Multipart(meta=Text(), result=Image(mime_type="image/bmp")),
)
async def predict_multi_images(original: Image, compared: Image):
start = time.perf_counter()
output_array = await py_model.multiply_float_ndarray.async_run(
np.array(original), np.array(compared)
)
histogram.labels(model_name=py_model.name, model_version="v1").observe(
time.perf_counter() - start
)
img = PIL.Image.fromarray(output_array)
return {"meta": "success", "result": img}
@svc.api(input=bentoml.io.Text(), output=bentoml.io.Text())
def ensure_metrics_are_registered(data: str) -> str: # pylint: disable=unused-argument
histograms = [
m.name
for m in bentoml.metrics.text_string_to_metric_families()
if m.type == "histogram"
]
assert "inference_latency" in histograms