File size: 1,300 Bytes
c7f5de3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

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