LA1512 commited on
Commit
576cae6
1 Parent(s): 3dd9480

Update handler.py

Browse files
Files changed (1) hide show
  1. 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.model = BartForConditionalGeneration.from_pretrained(path)
7
- self.tokenizer = AutoTokenizer(path)
 
 
 
 
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
- text_tokenized = self.tokenizer(
22
- [data], padding="max_length", truncation=True, max_length=1024,return_tensors='pt')
23
-
24
- prediction_token = self.model.generate(text_tokenized["input_ids"], max_length = 256, num_beams = 6)
25
-
26
- prediction_summary = self.tokenizer.decode(prediction_token[0][2:-1:1])
 
 
 
 
27
 
28
- return prediction_summary
 
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}]