Spaces:
Runtime error
Runtime error
File size: 1,283 Bytes
0d08077 |
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 35 36 37 38 39 40 41 42 43 44 45 46 47 |
from transformers import AutoProcessor, AutoModelForCausalLM
class GitBaseCocoModel:
def __init__(self, device, checkpoint="microsoft/git-base-coco"):
"""
A wrapper class for the Git-Base-COCO model. It is a pretrained model for image captioning.
-----
Parameters:
device: torch.device
The device to run the model on.
checkpoint: str
The checkpoint to load the model from.
-----
Returns:
None
"""
self.checkpoint = checkpoint
self.device = device
self.processor = AutoProcessor.from_pretrained(self.checkpoint)
self.model = AutoModelForCausalLM.from_pretrained(self.checkpoint).to(self.device)
def generate(self, image, max_len=50, num_captions=1):
"""
Generates captions for the given image.
-----
Parameters:
image: PIL.Image
The image to generate captions for.
max_len: int
The maximum length of the caption.
num_captions: int
The number of captions to generate.
"""
pixel_values = self.processor(
images=image, return_tensors="pt"
).pixel_values.to(self.device)
generated_ids = self.model.generate(
pixel_values=pixel_values,
max_length=max_len,
num_beams=num_captions,
num_return_sequences=num_captions,
)
return self.processor.batch_decode(generated_ids, skip_special_tokens=True)
|