|
|
|
from PIL import Image |
|
from transformers import AutoProcessor, BlipForQuestionAnswering |
|
import torch |
|
|
|
|
|
class blip: |
|
device = "cuda" if torch.cuda.is_available() else "cpu" |
|
|
|
|
|
def __init__(self, model_pretrain:str = "Salesforce/blip-vqa-base"): |
|
self.processor = AutoProcessor.from_pretrained(model_pretrain) |
|
self.model = BlipForQuestionAnswering.from_pretrained( |
|
model_pretrain, device_map={"": 0}, torch_dtype=torch.float16 |
|
) |
|
|
|
def image_captioning(self, image: Image.Image) -> str: |
|
|
|
text = "What are the features of this picture??" |
|
inputs = self.processor(images=image, text=text, return_tensors="pt").to(self.device, torch.float16) |
|
outputs = self.model.generate(**inputs) |
|
|
|
return self.processor.decode(outputs[0], skip_special_tokens=True) |
|
|
|
def visual_question_answering(self, image: Image.Image, prompt: str) -> str: |
|
inputs = self.processor(images=image, text=prompt, return_tensors="pt").to(self.device, torch.float16) |
|
|
|
generated_ids = self.model.generate(**inputs) |
|
generated_text = self.processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip() |
|
|
|
return generated_text |
|
|