Update handler.py
Browse files- handler.py +22 -34
handler.py
CHANGED
@@ -1,45 +1,33 @@
|
|
1 |
-
#Handler.py file needed
|
2 |
-
|
3 |
from PIL import Image
|
4 |
import torch
|
5 |
-
from transformers import
|
6 |
|
7 |
class ModelHandler:
|
8 |
def __init__(self):
|
9 |
-
|
10 |
-
self.
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
|
|
|
|
16 |
|
17 |
def preprocess(self, inputs):
|
18 |
-
#
|
19 |
-
image = Image.open(inputs[
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
text_context = inputs.get("text_context", "")
|
24 |
-
if text_context:
|
25 |
-
context_inputs = self.processor(text=text_context, return_tensors="pt").input_ids
|
26 |
-
else:
|
27 |
-
context_inputs = None
|
28 |
-
|
29 |
-
return pixel_values, context_inputs
|
30 |
|
31 |
-
def inference(self,
|
32 |
-
# Run inference on the
|
33 |
-
|
34 |
-
|
35 |
-
outputs = self.model.generate(pixel_values, input_ids=context_inputs)
|
36 |
-
else:
|
37 |
-
outputs = self.model.generate(pixel_values)
|
38 |
-
return outputs
|
39 |
|
40 |
-
def postprocess(self,
|
41 |
-
#
|
42 |
-
|
43 |
-
return {"digitized_text": decoded_text[0]}
|
44 |
|
45 |
service = ModelHandler()
|
|
|
|
|
|
|
1 |
from PIL import Image
|
2 |
import torch
|
3 |
+
from transformers import AutoModel, AutoTokenizer
|
4 |
|
5 |
class ModelHandler:
|
6 |
def __init__(self):
|
7 |
+
# Load the model and tokenizer with appropriate weights
|
8 |
+
self.model = AutoModel.from_pretrained(
|
9 |
+
'openbmb/MiniCPM-V-2_6',
|
10 |
+
trust_remote_code=True,
|
11 |
+
attn_implementation='sdpa',
|
12 |
+
torch_dtype=torch.bfloat16
|
13 |
+
).eval().cuda()
|
14 |
+
|
15 |
+
self.tokenizer = AutoTokenizer.from_pretrained('openbmb/MiniCPM-V-2_6', trust_remote_code=True)
|
16 |
|
17 |
def preprocess(self, inputs):
|
18 |
+
# Preprocess image input
|
19 |
+
image = Image.open(inputs['image'].file).convert('RGB')
|
20 |
+
question = inputs.get("question", "What is in the image?")
|
21 |
+
msgs = [{'role': 'user', 'content': [image, question]}]
|
22 |
+
return msgs
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
|
24 |
+
def inference(self, msgs):
|
25 |
+
# Run inference on the model
|
26 |
+
result = self.model.chat(image=None, msgs=msgs, tokenizer=self.tokenizer)
|
27 |
+
return result
|
|
|
|
|
|
|
|
|
28 |
|
29 |
+
def postprocess(self, result):
|
30 |
+
# Postprocess the output from the model
|
31 |
+
return {"generated_text": result}
|
|
|
32 |
|
33 |
service = ModelHandler()
|