Update handler.py
Browse files- handler.py +18 -10
handler.py
CHANGED
@@ -3,11 +3,15 @@ from transformers import pipeline, AutoTokenizer, BartForConditionalGeneration
|
|
3 |
|
4 |
class EndpointHandler():
|
5 |
def __init__(self, path=""):
|
6 |
-
self.
|
7 |
-
|
|
|
|
|
|
|
|
|
8 |
|
9 |
|
10 |
-
def __call__(self, data: str) -> str:
|
11 |
"""
|
12 |
data args:
|
13 |
inputs (:obj: `str`)
|
@@ -18,11 +22,15 @@ class EndpointHandler():
|
|
18 |
# get inputs
|
19 |
|
20 |
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
|
|
|
|
|
|
|
|
27 |
|
28 |
-
return
|
|
|
3 |
|
4 |
class EndpointHandler():
|
5 |
def __init__(self, path=""):
|
6 |
+
self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
7 |
+
try:
|
8 |
+
self.model = BartForConditionalGeneration.from_pretrained(path).to(self.device)
|
9 |
+
self.tokenizer = AutoTokenizer.from_pretrained(path)
|
10 |
+
except Exception as e:
|
11 |
+
print(f"Error loading model or tokenizer from path {path}: {e}")
|
12 |
|
13 |
|
14 |
+
def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
|
15 |
"""
|
16 |
data args:
|
17 |
inputs (:obj: `str`)
|
|
|
22 |
# get inputs
|
23 |
|
24 |
|
25 |
+
inputs = data.get("inputs", "")
|
26 |
+
if not inputs:
|
27 |
+
return [{"error": "No inputs provided"}]
|
28 |
+
|
29 |
+
tokenized_input = self.tokenizer(inputs, return_tensors="pt", truncation=True, max_length=1024, padding="max_length")
|
30 |
+
tokenized_input = tokenized_input.to(self.device) # Move input tensors to the same device as model
|
31 |
+
|
32 |
+
summary_ids = self.model.generate(**tokenized_input, max_length=256, do_sample=True, top_p=0.8)
|
33 |
+
|
34 |
+
summary_text = self.tokenizer.decode(summary_ids[0], skip_special_tokens=True)
|
35 |
|
36 |
+
return [{"summary": summary_text}]
|