kiddobellamy commited on
Commit
42c2dda
·
verified ·
1 Parent(s): 7bb259c

Upload handler.py

Browse files
Files changed (1) hide show
  1. handler.py +39 -0
handler.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from transformers import AutoModelForVision2Seq, AutoTokenizer
3
+
4
+ class ModelHandler:
5
+ def __init__(self):
6
+ self.model = None
7
+ self.tokenizer = None
8
+
9
+ def initialize(self, context):
10
+ """ Load the model and tokenizer """
11
+ model_dir = context.system_properties.get("model_dir")
12
+ self.tokenizer = AutoTokenizer.from_pretrained(model_dir)
13
+ self.model = AutoModelForVision2Seq.from_pretrained(model_dir)
14
+ self.model.eval()
15
+
16
+ def preprocess(self, data):
17
+ """ Preprocess the input data before passing it to the model """
18
+ inputs = self.tokenizer(data, return_tensors="pt")
19
+ return inputs
20
+
21
+ def inference(self, inputs):
22
+ """ Run the forward pass of the model """
23
+ with torch.no_grad():
24
+ outputs = self.model(**inputs)
25
+ return outputs
26
+
27
+ def postprocess(self, outputs):
28
+ """ Post-process the output data from the model """
29
+ return outputs
30
+
31
+ # This is required for the Hugging Face inference endpoints
32
+ _handler = ModelHandler()
33
+
34
+ def handle(data, context):
35
+ if not _handler.model:
36
+ _handler.initialize(context)
37
+ inputs = _handler.preprocess(data)
38
+ outputs = _handler.inference(inputs)
39
+ return _handler.postprocess(outputs)