hong_seungbum
add application file
c7f5de3
raw
history blame
1.3 kB
from PIL import Image
from transformers import Blip2Processor, Blip2ForConditionalGeneration
import torch
from models import load_transformers
class blip2:
device = "cuda" if torch.cuda.is_available() else "cpu"
def __init__(self, model_pretrain:str = "Salesforce/blip2-opt-2.7b"):
self.processor = Blip2Processor.from_pretrained(model_pretrain)
self.model = Blip2ForConditionalGeneration.from_pretrained(
model_pretrain, device_map={"": 0}, torch_dtype=torch.float16
)
def image_captioning(self, image: Image.Image) -> str:
inputs = self.processor(images=image, 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
def visual_question_answering(self, image: Image.Image, prompt: str) -> str:
inputs = self.processor(images=image, text=prompt, return_tensors="pt").to(device=self.device, dtype=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