merve HF staff commited on
Commit
a7ce59e
·
1 Parent(s): 88764cd

Upload pipeline.py

Browse files
Files changed (1) hide show
  1. pipeline.py +78 -0
pipeline.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from typing import Any, Dict, List
3
+
4
+ import tensorflow as tf
5
+ from tensorflow import keras
6
+ from app.pipelines import Pipeline
7
+ from huggingface_hub import from_pretrained_keras, hf_hub_download
8
+ from PIL import Image
9
+ import base64
10
+
11
+
12
+ MODEL_FILENAME = "saved_model.pb"
13
+ CONFIG_FILENAME = "config.json"
14
+
15
+
16
+ class PreTrainedPipeline(Pipeline):
17
+ def __init__(self, model_id: str):
18
+
19
+
20
+ # Reload Keras SavedModel
21
+ self.model = from_pretrained_keras(model_id)
22
+
23
+ # Number of labels
24
+ self.num_labels = self.model.output_shape[1]
25
+
26
+ # Config is required to know the mapping to label.
27
+ config_file = hf_hub_download(model_id, filename=CONFIG_FILENAME)
28
+ with open(config_file) as config:
29
+ config = json.load(config)
30
+
31
+ self.id2label = config.get(
32
+ "id2label", {str(i): f"LABEL_{i}" for i in range(self.num_labels)}
33
+ )
34
+
35
+ def __call__(self, inputs: "Image.Image") -> List[Dict[str, Any]]:
36
+ """
37
+ Args:
38
+ inputs (:obj:`PIL.Image`):
39
+ The raw image representation as PIL.
40
+ No transformation made whatsoever from the input. Make all necessary transformations here.
41
+ Return:
42
+ A :obj:`list`:. The list contains items that are dicts should be liked {"label": "XXX" (str), mask: "base64 encoding of the mask" (str), "score": float}
43
+ It is preferred if the returned list is in decreasing `score` order
44
+ """
45
+ # Resize image to expected size
46
+
47
+ expected_input_size = self.model.input_shape
48
+ if expected_input_size[-1] == 1:
49
+ inputs = inputs.convert("L")
50
+
51
+ target_size = (expected_input_size[1], expected_input_size[2])
52
+ img = tf.image.resize(inputs, target_size)
53
+
54
+ img_array = tf.keras.preprocessing.image.img_to_array(img)
55
+ img_array = img_array[tf.newaxis, ...]
56
+
57
+ predictions = self.model.predict(img_array, axis=-1)
58
+
59
+ self.single_output_unit = (
60
+ self.model.output_shape[1] == 1
61
+ ) # if there are two classes
62
+
63
+ if self.single_output_unit:
64
+ score = predictions[0][0]
65
+ labels = [
66
+ {"label": str(self.id2label["1"]), "score": float(score)},
67
+ {"label": str(self.id2label["0"]), "score": float(1 - score)},
68
+ ]
69
+ else:
70
+ labels = [
71
+ {
72
+ "label": str(self.id2label[str(i)]),
73
+ "mask": base64.b64encode(predictions[0][i]),
74
+ "score": float(score),
75
+ }
76
+ for i, score in enumerate(predictions[0])
77
+ ]
78
+ return sorted(labels, key=lambda tup: tup["score"], reverse=True)[: self.top_k]