Update pipeline.py
Browse files- pipeline.py +9 -4
pipeline.py
CHANGED
|
@@ -3,7 +3,9 @@ import tensorflow as tf
|
|
| 3 |
from tensorflow.keras.preprocessing.sequence import pad_sequences
|
| 4 |
from tensorflow.keras.preprocessing.text import tokenizer_from_json
|
| 5 |
import json
|
|
|
|
| 6 |
|
|
|
|
| 7 |
class Pipeline:
|
| 8 |
def __init__(self):
|
| 9 |
# Load tokenizer
|
|
@@ -15,9 +17,9 @@ class Pipeline:
|
|
| 15 |
# Load model (SavedModel format)
|
| 16 |
self.model = tf.keras.models.load_model(".")
|
| 17 |
|
| 18 |
-
#
|
| 19 |
self.label_map = None
|
| 20 |
-
if
|
| 21 |
with open("label_map.json", "r", encoding="utf-8") as f:
|
| 22 |
self.label_map = json.load(f)
|
| 23 |
|
|
@@ -30,6 +32,9 @@ class Pipeline:
|
|
| 30 |
padded = pad_sequences(seq, maxlen=self.max_len, padding='post', truncating='post')
|
| 31 |
pred_probs = self.model.predict(padded)
|
| 32 |
pred_label = int(np.argmax(pred_probs, axis=1)[0])
|
|
|
|
| 33 |
if self.label_map:
|
| 34 |
-
|
| 35 |
-
|
|
|
|
|
|
|
|
|
| 3 |
from tensorflow.keras.preprocessing.sequence import pad_sequences
|
| 4 |
from tensorflow.keras.preprocessing.text import tokenizer_from_json
|
| 5 |
import json
|
| 6 |
+
import os
|
| 7 |
|
| 8 |
+
# Hugging Face expects a class named Pipeline with __call__(self, inputs)
|
| 9 |
class Pipeline:
|
| 10 |
def __init__(self):
|
| 11 |
# Load tokenizer
|
|
|
|
| 17 |
# Load model (SavedModel format)
|
| 18 |
self.model = tf.keras.models.load_model(".")
|
| 19 |
|
| 20 |
+
# Load label map if available
|
| 21 |
self.label_map = None
|
| 22 |
+
if os.path.exists("label_map.json"):
|
| 23 |
with open("label_map.json", "r", encoding="utf-8") as f:
|
| 24 |
self.label_map = json.load(f)
|
| 25 |
|
|
|
|
| 32 |
padded = pad_sequences(seq, maxlen=self.max_len, padding='post', truncating='post')
|
| 33 |
pred_probs = self.model.predict(padded)
|
| 34 |
pred_label = int(np.argmax(pred_probs, axis=1)[0])
|
| 35 |
+
score = float(np.max(pred_probs))
|
| 36 |
if self.label_map:
|
| 37 |
+
label = self.label_map.get(str(pred_label), pred_label)
|
| 38 |
+
else:
|
| 39 |
+
label = pred_label
|
| 40 |
+
return {"label": label, "score": score}
|