hughtayloe commited on
Commit
5701230
1 Parent(s): 237b9d2

Update handler.py

Browse files
Files changed (1) hide show
  1. 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
- quantization_config = BitsAndBytesConfig(
10
- load_in_4bit=True,
11
- bnb_4bit_compute_dtype=torch.float16
12
- )
13
- self.pipeline = pipeline("image-to-text", model=path, model_kwargs={"quantization_config": quantization_config})
14
-
15
- def __call__(self, data: Dict[Any, Any]):
16
- totalarr = []
17
- inputs = data.pop("inputs", '')
18
- prompt_base = data.pop("prompt", "")
19
- for x in inputs:
20
- image = Image.open(requests.get(x, stream=True).raw)
21
- prompt = f"USER: <image>\n{prompt_base}.Answer in one word\nASSISTANT:"
22
- outputs = self.pipeline(image, prompt=prompt, generate_kwargs={"max_new_tokens": 200})
23
- totalarr.append(outputs)
24
- return totalarr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+