File size: 1,522 Bytes
625a888 |
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 |
import json
import os
from typing import Any, Dict, List
import numpy as np
from fastai.learner import load_learner
from PIL import Image
def label(file_name):
return train_labels[file_name.replace(".jpg", "")]
class ImageClassificationPipeline:
def __init__(self, path=""):
# IMPLEMENT_THIS
# Preload all the elements you are going to need at inference.
# For instance your model, processors, tokenizer that might be needed.
# This function is only called once, so do all the heavy processing I/O here"""
self.model = load_learner(os.path.join(path, "model.pkl"))
with open(os.path.join(path, "config.json")) as config:
config = json.load(config)
self.labels = config["labels"]
def __call__(self, inputs: "Image.Image") -> List[Dict[str, Any]]:
print('call')
"""
Args:
inputs (:obj:`PIL.Image`):
The raw image representation as PIL.
No transformation made whatsoever from the input. Make all necessary transformations here.
Return:
A :obj:`list`:. The list contains items that are dicts should be liked {"label": "XXX", "score": 0.82}
It is preferred if the returned list is in decreasing `score` order
"""
# IMPLEMENT_THIS
# FastAI expects a np array, not a PIL Image.
_, _, preds = self.model.predict(np.array(inputs))
preds = preds.tolist()
return [{
"label": label,
"score": preds[idx]
} for idx, label in enumerate(self.labels)] |