-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcaption_generator.py
More file actions
48 lines (42 loc) · 1.5 KB
/
caption_generator.py
File metadata and controls
48 lines (42 loc) · 1.5 KB
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
48
from PIL import Image
import torch
from transformers import BlipProcessor, BlipForConditionalGeneration
processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base", use_fast=True)
model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
model.eval()
def generate_caption(image_path, style="default"):
try:
image = Image.open(image_path).convert('RGB')
inputs = processor(images=image, return_tensors="pt")
if style == "funny":
generation_args = {
"do_sample": True,
"top_p": 0.9,
"temperature": 1.2,
"max_new_tokens": 40
}
elif style == "poetic":
generation_args = {
"do_sample": True,
"top_k": 50,
"temperature": 1.0,
"max_new_tokens": 60
}
elif style == "detailed":
generation_args = {
"do_sample": True,
"temperature": 0.7,
"top_p": 0.85,
"max_new_tokens": 70
}
else:
generation_args = {
"do_sample": False,
"max_new_tokens": 40
}
with torch.no_grad():
output = model.generate(**inputs, **generation_args)
caption = processor.decode(output[0], skip_special_tokens=True)
return caption
except Exception as e:
return f"Captioning Error: {str(e)}"