File size: 1,980 Bytes
2df7b85
abb18af
 
 
 
365c9f9
abb18af
 
dcf0626
 
 
abb18af
 
 
cbe03c3
dcf0626
 
 
 
 
 
 
 
 
2df7b85
abb18af
 
dcf0626
abb18af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcf0626
abb18af
 
 
dcf0626
abb18af
 
 
dcf0626
 
 
abb18af
 
dcf0626
 
 
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
import gradio as gr
import torch
import open_clip
from PIL import Image
from torchvision import transforms

# Load OpenCLIP model
device = "cuda" if torch.cuda.is_available() else "cpu"
model, _, preprocess = open_clip.create_model_and_transforms(
    'ViT-B-32', pretrained='laion2b_s34b_b79k'
)
tokenizer = open_clip.get_tokenizer('ViT-B-32')
model.to(device)
model.eval()

# Main scoring function
def score_image_vs_keywords(image_path, keywords_csv):
    if not image_path or not keywords_csv.strip():
        return {"error": "Missing image or keywords"}

    try:
        image = Image.open(image_path).convert("RGB")
    except Exception as e:
        return {"error": f"Image loading failed: {e}"}

    keywords = [k.strip() for k in keywords_csv.split(',') if k.strip()]
    if not keywords:
        return {"error": "No valid keywords provided"}

    image_tensor = preprocess(image).unsqueeze(0).to(device)
    text_tokens = tokenizer(keywords).to(device)

    with torch.no_grad():
        image_features = model.encode_image(image_tensor)
        text_features = model.encode_text(text_tokens)

        # Normalize
        image_features /= image_features.norm(dim=-1, keepdim=True)
        text_features /= text_features.norm(dim=-1, keepdim=True)

        # Cosine similarity
        similarity = image_features @ text_features.T
        scores = similarity.squeeze(0).tolist()

    return {kw: round(score, 3) for kw, score in zip(keywords, scores)}

# Gradio interface
io = gr.Interface(
    fn=score_image_vs_keywords,
    inputs=[
        gr.Image(type="filepath", label="Upload Image"),  # filepath is crucial for HF queue
        gr.Textbox(label="Keywords (comma-separated)")
    ],
    outputs="json",
    title="OpenCLIP Visual Keyword Scorer",
    description="Upload an image and a list of keywords. Get cosine similarity scores via OpenCLIP.",
    allow_flagging="never"
)

# Launch app for Hugging Face Spaces
if __name__ == "__main__":
    io.launch()