-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
running_blip2.py
78 lines (58 loc) · 1.97 KB
/
running_blip2.py
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# %%
!pip install transformers accelerate
# %%
import requests
from PIL import Image
from transformers import Blip2Processor, Blip2ForConditionalGeneration
import torch
import os
device = torch.device("cuda", 0)
device
# %%
processor = Blip2Processor.from_pretrained("Salesforce/blip2-opt-2.7b")
model = Blip2ForConditionalGeneration.from_pretrained("Salesforce/blip2-opt-2.7b", torch_dtype=torch.float16)
# %%
model.to(device)
# %%
import urllib.parse as parse
import os
# a function to determine whether a string is a URL or not
def is_url(string):
try:
result = parse.urlparse(string)
return all([result.scheme, result.netloc, result.path])
except:
return False
# a function to load an image
def load_image(image_path):
if is_url(image_path):
return Image.open(requests.get(image_path, stream=True).raw)
elif os.path.exists(image_path):
return Image.open(image_path)
# %%
raw_image = load_image("http://images.cocodataset.org/test-stuff2017/000000007226.jpg")
# %%
question = "a"
inputs = processor(raw_image, question, return_tensors="pt").to(device, dtype=torch.float16)
# %%
out = model.generate(**inputs)
print(processor.decode(out[0], skip_special_tokens=True))
# %%
question = "a vintage car driving down a street"
inputs = processor(raw_image, question, return_tensors="pt").to(device, dtype=torch.float16)
# %%
out = model.generate(**inputs)
print(processor.decode(out[0], skip_special_tokens=True))
# %%
question = "Question: What is the estimated year of these cars? Answer:"
inputs = processor(raw_image, question, return_tensors="pt").to(device, dtype=torch.float16)
# %%
out = model.generate(**inputs)
print(processor.decode(out[0], skip_special_tokens=True))
# %%
question = "Question: What is the color of the car? Answer:"
inputs = processor(raw_image, question, return_tensors="pt").to(device, dtype=torch.float16)
# %%
out = model.generate(**inputs)
print(processor.decode(out[0], skip_special_tokens=True))
# %%