enmeshfade's picture
Update app.py
dcf0626 verified
Raw History Blame Contribute Delete
1.98 kB
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()