-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathclip_score.py
More file actions
22 lines (15 loc) · 747 Bytes
/
Copy pathclip_score.py
File metadata and controls
22 lines (15 loc) · 747 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from transformers import CLIPProcessor, CLIPModel
import PIL
def get_clip_score(clip_model: CLIPModel, clip_processor: CLIPProcessor, text: str, image: PIL.Image):
inputs = clip_processor(text=text, images=image, return_tensors="pt", padding=True)
inputs = {k: v.to("cuda") for k, v in inputs.items()}
# Get CLIP embeddings
outputs = clip_model(**inputs)
image_embeds = outputs.image_embeds
text_embeds = outputs.text_embeds
# Normalize embeddings
image_embeds = image_embeds / image_embeds.norm(p=2, dim=-1, keepdim=True)
text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
# Compute cosine similarity
clip_score = (image_embeds @ text_embeds.T).item()
return clip_score