Add inference endpoint
Browse files- README.md +1 -0
- example_input.json +3 -0
- handler.py +53 -0
README.md
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
Please use the image nvcr.io/nvidia/pytorch:21.11-py3 when you want to launch it
|
example_input.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"inputs": "https://media.lesechos.com/api/v1/images/view/5dadc9de8fe56f4ddf251469/1280x720/0602095339508-web-tete.jpg"
|
| 3 |
+
}
|
handler.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Dict, List, Any
|
| 2 |
+
from torchvision.models import resnet18, ResNet18_Weights
|
| 3 |
+
from torchvision.io import read_image
|
| 4 |
+
from PIL import Image
|
| 5 |
+
import io
|
| 6 |
+
import requests
|
| 7 |
+
import torchvision.transforms.functional as transform
|
| 8 |
+
|
| 9 |
+
from torch2trt import torch2trt
|
| 10 |
+
from torchvision.models.alexnet import alexnet
|
| 11 |
+
import torch
|
| 12 |
+
|
| 13 |
+
# create some regular pytorch model...
|
| 14 |
+
model = alexnet(pretrained=True).eval().cuda()
|
| 15 |
+
|
| 16 |
+
# create example data
|
| 17 |
+
x = torch.ones((1, 3, 224, 224)).cuda()
|
| 18 |
+
|
| 19 |
+
# convert to TensorRT feeding sample data as input
|
| 20 |
+
model_trt = torch2trt(model, [x])
|
| 21 |
+
|
| 22 |
+
class EndpointHandler():
|
| 23 |
+
def __init__(self, path=""):
|
| 24 |
+
weights = ResNet18_Weights.DEFAULT
|
| 25 |
+
# create some regular pytorch model...
|
| 26 |
+
model = resnet18(weights=weights).eval().cuda()
|
| 27 |
+
|
| 28 |
+
# create example data
|
| 29 |
+
x = torch.ones((1, 3, 224, 224)).cuda()
|
| 30 |
+
|
| 31 |
+
# convert to TensorRT feeding sample data as input
|
| 32 |
+
self.pipeline = torch2trt(model, [x])
|
| 33 |
+
self.preprocess = weights.transforms()
|
| 34 |
+
|
| 35 |
+
def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
|
| 36 |
+
"""
|
| 37 |
+
data args:
|
| 38 |
+
inputs (:obj: `str`)
|
| 39 |
+
Return:
|
| 40 |
+
A :obj:`list` | `dict`: will be serialized and returned
|
| 41 |
+
"""
|
| 42 |
+
# get inputs
|
| 43 |
+
inputs = data.pop("inputs",data)
|
| 44 |
+
if inputs.startswith("http") or inputs.startswith("www"):
|
| 45 |
+
response = requests.get(inputs).content
|
| 46 |
+
img = transform.to_tensor(Image.open(io.BytesIO(response)))
|
| 47 |
+
else:
|
| 48 |
+
img = read_image(inputs)
|
| 49 |
+
|
| 50 |
+
batch = self.preprocess(img).unsqueeze(0)
|
| 51 |
+
prediction = self.pipeline(batch).squeeze(0).softmax(0)
|
| 52 |
+
|
| 53 |
+
return prediction.tolist()
|