-
Notifications
You must be signed in to change notification settings - Fork 757
/
service.py
178 lines (130 loc) · 4.76 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
from __future__ import annotations
import typing as t
from typing import TYPE_CHECKING
import numpy as np
import pandas as pd
import pydantic
from PIL.Image import Image as PILImage
from PIL.Image import fromarray
from starlette.requests import Request
import bentoml
from bentoml.io import File
from bentoml.io import JSON
from bentoml.io import Image
from bentoml.io import Multipart
from bentoml.io import NumpyNdarray
from bentoml.io import PandasDataFrame
if TYPE_CHECKING:
from numpy.typing import NDArray
from starlette.types import Send
from starlette.types import Scope
from starlette.types import ASGIApp
from starlette.types import Receive
from bentoml._internal.types import FileLike
from bentoml._internal.types import JSONSerializable
py_model = bentoml.picklable_model.get("py_model.case-1.http.e2e").to_runner()
svc = bentoml.Service(name="general_http_service.case-1.e2e", runners=[py_model])
@svc.api(input=JSON(), output=JSON())
async def echo_json(json_obj: JSONSerializable) -> JSONSerializable:
batch_ret = await py_model.echo_json.async_run([json_obj])
return batch_ret[0]
@svc.api(input=JSON(), output=JSON())
def echo_json_sync(json_obj: JSONSerializable) -> JSONSerializable:
batch_ret = py_model.echo_json.run([json_obj])
return batch_ret[0]
class ValidateSchema(pydantic.BaseModel):
name: str
endpoints: t.List[str]
@svc.api(
input=JSON(pydantic_model=ValidateSchema),
output=JSON(),
)
async def echo_json_enforce_structure(json_obj: JSONSerializable) -> JSONSerializable:
batch_ret = await py_model.echo_json.async_run([json_obj])
return batch_ret[0]
@svc.api(input=JSON(), output=JSON())
async def echo_obj(obj: JSONSerializable) -> JSONSerializable:
return await py_model.echo_obj.async_run(obj)
@svc.api(
input=NumpyNdarray(shape=(2, 2), enforce_shape=True),
output=NumpyNdarray(shape=(2, 2)),
)
async def predict_ndarray_enforce_shape(inp: NDArray[t.Any]) -> NDArray[t.Any]:
assert inp.shape == (2, 2)
return await py_model.predict_ndarray.async_run(inp)
@svc.api(
input=NumpyNdarray(dtype="uint8", enforce_dtype=True),
output=NumpyNdarray(dtype="str"),
)
async def predict_ndarray_enforce_dtype(inp: NDArray[t.Any]) -> NDArray[t.Any]:
assert inp.dtype == np.dtype("uint8")
return await py_model.predict_ndarray.async_run(inp)
@svc.api(
input=NumpyNdarray(),
output=NumpyNdarray(),
)
async def predict_ndarray_multi_output(
inp: "np.ndarray[t.Any, np.dtype[t.Any]]",
) -> "np.ndarray[t.Any, np.dtype[t.Any]]":
out1, out2 = await py_model.echo_multi_ndarray.async_run(inp, inp)
return out1 + out2
@svc.api(
input=PandasDataFrame(dtype={"col1": "int64"}, orient="records"),
output=PandasDataFrame(),
)
async def predict_dataframe(df: pd.DataFrame) -> pd.DataFrame:
assert df["col1"].dtype == "int64"
output = await py_model.predict_dataframe.async_run(df)
dfo = pd.DataFrame()
dfo["col1"] = output
assert isinstance(dfo, pd.DataFrame)
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(), output=Image(mime_type="image/bmp"))
async def echo_image(f: PILImage) -> NDArray[t.Any]:
assert isinstance(f, PILImage)
return np.array(f)
@svc.api(
input=Multipart(original=Image(), compared=Image()),
output=Multipart(img1=Image(), img2=Image()),
)
async def predict_multi_images(original: Image, compared: Image):
output_array = await py_model.predict_multi_ndarray.async_run(
np.array(original), np.array(compared)
)
img = fromarray(output_array)
return dict(img1=img, img2=img)
@svc.api(
input=Multipart(original=Image(), compared=Image()),
output=Multipart(img1=Image(), img2=Image()),
)
async def predict_different_args(compared: Image, original: Image):
output_array = await py_model.predict_multi_ndarray.async_run(
np.array(original), np.array(compared)
)
img = fromarray(output_array)
return dict(img1=img, img2=img)
# customise the service
class AllowPingMiddleware:
def __init__(
self,
app: ASGIApp,
) -> None:
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] == "http":
req = Request(scope, receive)
if req.url.path == "/ping":
scope["path"] = "/livez"
await self.app(scope, receive, send)
return
svc.add_asgi_middleware(AllowPingMiddleware) # type: ignore (hint not yet supported for hooks)
from fastapi import FastAPI
fastapi_app = FastAPI()
@fastapi_app.get("/hello")
def hello():
return {"Hello": "World"}
svc.mount_asgi_app(fastapi_app)