Update handler.py
Browse files- handler.py +38 -17
handler.py
CHANGED
@@ -1,24 +1,45 @@
|
|
1 |
from typing import Dict, List, Any
|
2 |
-
from transformers import pipeline, BitsAndBytesConfig
|
3 |
from PIL import Image
|
4 |
import requests
|
5 |
import torch
|
|
|
6 |
|
7 |
class EndpointHandler():
|
8 |
def __init__(self, path=""):
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
from typing import Dict, List, Any
|
|
|
2 |
from PIL import Image
|
3 |
import requests
|
4 |
import torch
|
5 |
+
from transformers import AutoProcessor, LlavaForConditionalGeneration
|
6 |
|
7 |
class EndpointHandler():
|
8 |
def __init__(self, path=""):
|
9 |
+
model_id = ""
|
10 |
+
model = LlavaForConditionalGeneration.from_pretrained(
|
11 |
+
model_id,
|
12 |
+
torch_dtype=torch.float16,
|
13 |
+
low_cpu_mem_usage=True,
|
14 |
+
).to(0)
|
15 |
+
processor = AutoProcessor.from_pretrained(model_id)
|
16 |
+
|
17 |
+
def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
|
18 |
+
parameters = data.pop("inputs",data)
|
19 |
+
inputs = data.pop("inputs", data)
|
20 |
+
if parameters is not None:
|
21 |
+
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
22 |
+
image = Image.open(requests.get(url, stream=True).raw)
|
23 |
+
prompt = "USER: <image>\nWhat are these?\nASSISTANT:"
|
24 |
+
output = model.generate(**inputs, max_new_tokens=200, do_sample=False)
|
25 |
+
return output
|
26 |
+
|
27 |
+
|
28 |
+
prompt = "USER: <image>\nWhat are these?\nASSISTANT:"
|
29 |
+
image_file = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
30 |
+
|
31 |
+
model = LlavaForConditionalGeneration.from_pretrained(
|
32 |
+
model_id,
|
33 |
+
torch_dtype=torch.float16,
|
34 |
+
low_cpu_mem_usage=True,
|
35 |
+
).to(0)
|
36 |
+
|
37 |
+
processor = AutoProcessor.from_pretrained(model_id)
|
38 |
+
|
39 |
+
|
40 |
+
raw_image = Image.open(requests.get(image_file, stream=True).raw)
|
41 |
+
inputs = processor(prompt, raw_image, return_tensors='pt').to(0, torch.float16)
|
42 |
+
|
43 |
+
output = model.generate(**inputs, max_new_tokens=200, do_sample=False)
|
44 |
+
print(processor.decode(output[0][2:], skip_special_tokens=True))
|
45 |
+
|