Create qa.py
Browse files
qa.py
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from PIL import Image
|
3 |
+
from transformers import Blip2Processor, Blip2ForConditionalGeneration, BitsAndBytesConfig
|
4 |
+
|
5 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
6 |
+
quantization_config = BitsAndBytesConfig(load_in_8bit=True)
|
7 |
+
|
8 |
+
processor = Blip2Processor.from_pretrained("Salesforce/blip2-flan-t5-xl")
|
9 |
+
model = Blip2ForConditionalGeneration.from_pretrained(
|
10 |
+
"Salesforce/blip2-flan-t5-xl", device_map="auto"
|
11 |
+
)
|
12 |
+
|
13 |
+
def get_image_answer(image: Image.Image, question: str) -> str:
|
14 |
+
if image.mode != "RGB":
|
15 |
+
image = image.convert("RGB")
|
16 |
+
|
17 |
+
inputs = processor(images=image, text=question, return_tensors="pt")
|
18 |
+
inputs = {k: v.to(device, torch.float16 if device == "cuda" else torch.float32) for k, v in inputs.items()}
|
19 |
+
output_ids = model.generate(**inputs)
|
20 |
+
answer = processor.tokenizer.decode(output_ids[0], skip_special_tokens=True).strip()
|
21 |
+
return answer
|