espejelomar commited on
Commit
85f51f8
1 Parent(s): 30414ea

Add pipeline

Browse files
Files changed (1) hide show
  1. pipeline.py +36 -0
pipeline.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, List
2
+
3
+ import numpy as np
4
+ from huggingface_hub import from_pretrained_fastai
5
+ from PIL import Image
6
+
7
+
8
+ class ImageClassificationPipeline(Pipeline):
9
+ def __init__(self, model_id: str):
10
+ self.model = from_pretrained_fastai(model_id)
11
+
12
+ # Obtain labels
13
+ self.id2label = self.model.dls.vocab
14
+
15
+ # Return at most the top 5 predicted classes
16
+ self.top_k = 5
17
+
18
+ def __call__(self, inputs: "Image.Image") -> List[Dict[str, Any]]:
19
+ """
20
+ Args:
21
+ inputs (:obj:`PIL.Image`):
22
+ The raw image representation as PIL.
23
+ No transformation made whatsoever from the input. Make all necessary transformations here.
24
+ Return:
25
+ A :obj:`list`:. The list contains items that are dicts should be liked {"label": "XXX", "score": 0.82}
26
+ It is preferred if the returned list is in decreasing `score` order
27
+ """
28
+ # FastAI expects a np array, not a PIL Image.
29
+ _, _, preds = self.model.predict(np.array(inputs))
30
+ preds = preds.tolist()
31
+
32
+ labels = [
33
+ {"label": str(self.id2label[i]), "score": float(preds[i])}
34
+ for i in range(len(preds))
35
+ ]
36
+ return sorted(labels, key=lambda tup: tup["score"], reverse=True)[: self.top_k]