taesiri commited on
Commit
d6fa528
·
verified ·
1 Parent(s): 7fc3bdc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +108 -94
app.py CHANGED
@@ -1,119 +1,133 @@
 
1
  import torch
2
  import torch.nn.functional as F
3
  import gradio as gr
4
- from transformers import CLIPProcessor, CLIPModel, AutoProcessor, AutoModel
5
- import spaces
 
 
 
 
 
 
 
 
 
 
6
 
7
- # Dictionary of available models with their image sizes
8
  MODELS = {
9
- "CLIP ViT-B/32": ("openai/clip-vit-base-patch32", 224, "clip"),
10
- "CLIP ViT-B/16": ("openai/clip-vit-base-patch16", 224, "clip"),
11
- "CLIP ViT-L/14": ("openai/clip-vit-large-patch14", 224, "clip"),
12
- "CLIP ViT-L/14@336px": ("openai/clip-vit-large-patch14-336", 336, "clip"),
13
- "SigLIP Large/16-256": ("google/siglip-large-patch16-256", 256, "siglip"),
14
- "SigLIP Base/16-384": ("google/siglip-base-patch16-384", 384, "siglip"),
15
- "SigLIP Large/16-384": ("google/siglip-large-patch16-384", 384, "siglip"),
16
  }
17
 
18
- # Initialize models and processors
19
- models = {}
20
- processors = {}
 
21
 
22
- for model_name, (model_path, _, model_type) in MODELS.items():
23
- if model_type == "clip":
24
- models[model_name] = CLIPModel.from_pretrained(model_path).to("cuda")
25
- processors[model_name] = CLIPProcessor.from_pretrained(model_path)
26
- elif model_type == "siglip":
27
- models[model_name] = AutoModel.from_pretrained(model_path).to("cuda")
28
- processors[model_name] = AutoProcessor.from_pretrained(model_path)
29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
 
 
 
 
 
 
 
 
31
  @spaces.GPU
32
- def calculate_score(image, text, model_name):
33
- labels = text.split(";")
34
- labels = [l.strip() for l in labels]
35
- labels = list(filter(None, labels))
36
- if len(labels) == 0:
37
- return dict()
38
-
39
- model = models[model_name]
40
- processor = processors[model_name]
41
- model_type = MODELS[model_name][2]
42
-
43
- # Preprocess the image and text
44
- inputs = processor(text=labels, images=[image], return_tensors="pt", padding="max_length")
45
- inputs = {k: v.to("cuda") for k, v in inputs.items()}
46
-
47
- # Calculate embeddings
48
  with torch.no_grad():
49
- outputs = model(**inputs)
50
- if model_type == "clip":
51
- image_embeds = outputs.image_embeds
52
- text_embeds = outputs.text_embeds
53
- elif model_type == "siglip":
54
- image_embeds = outputs.image_embeds
55
- text_embeds = outputs.text_embeds
56
-
57
- # Normalize embeddings
58
- image_embeds = F.normalize(image_embeds, p=2, dim=1)
59
- text_embeds = F.normalize(text_embeds, p=2, dim=1)
60
-
61
- # Calculate similarity
62
- if model_type == "clip":
63
- # For CLIP, use cosine similarity
64
- similarities = torch.mm(text_embeds, image_embeds.t()).squeeze(1)
65
- similarities = torch.clamp(similarities, min=0, max=1)
66
- elif model_type == "siglip":
67
- # For SigLIP, use sigmoid on dot product
68
- logits = torch.mm(text_embeds, image_embeds.t()).squeeze(1)
69
- similarities = torch.sigmoid(logits)
70
-
71
- # Convert to numpy array
72
- similarities = similarities.cpu().numpy()
73
-
74
- results_dict = {label: float(score) for label, score in zip(labels, similarities)}
75
- return results_dict
76
-
77
-
78
- with gr.Blocks() as demo:
79
- gr.Markdown("# Multi-Model CLIP and SigLIP Score")
80
- gr.Markdown(
81
- "Calculate the score (cosine similarity) between the given image and text descriptions using different CLIP and SigLIP model variants"
82
- )
83
 
84
  with gr.Row():
85
- image_input = gr.Image(type="pil")
86
- output_label = gr.Label()
87
 
88
  with gr.Row():
89
- text_input = gr.Textbox(label="Descriptions (separated by semicolons)")
90
- model_dropdown = gr.Dropdown(
91
- choices=list(MODELS.keys()), label="Model", value="CLIP ViT-B/16"
 
 
 
 
 
92
  )
93
 
94
- def process_inputs(image, text, model_name):
95
- if image is None or text.strip() == "":
96
- return None
97
- return calculate_score(image, text, model_name)
98
-
99
- inputs = [image_input, text_input, model_dropdown]
100
- outputs = output_label
101
 
102
- image_input.change(fn=process_inputs, inputs=inputs, outputs=outputs)
103
- text_input.submit(fn=process_inputs, inputs=inputs, outputs=outputs)
104
- model_dropdown.change(fn=process_inputs, inputs=inputs, outputs=outputs)
105
 
106
  gr.Examples(
107
  examples=[
108
- [
109
- "cat.jpg",
110
- "a cat stuck in a door; a cat in the air; a cat sitting; a cat standing; a cat is entering the matrix; a cat is entering the void",
111
- "CLIP ViT-B/16",
112
- ]
113
  ],
114
- fn=process_inputs,
115
- inputs=inputs,
116
- outputs=outputs,
117
  )
118
 
119
- demo.launch()
 
1
+ import os
2
  import torch
3
  import torch.nn.functional as F
4
  import gradio as gr
5
+ import spaces # keep this!
6
+ from transformers import (
7
+ CLIPProcessor,
8
+ CLIPModel,
9
+ SiglipProcessor, # transformers ≥ 4.40
10
+ SiglipModel,
11
+ )
12
+
13
+ # ---------------------------------------------------------------------
14
+ # 1. CONFIG
15
+ # ---------------------------------------------------------------------
16
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
17
 
 
18
  MODELS = {
19
+ "CLIP ViT-B/32": ("openai/clip-vit-base-patch32", 224, "clip"),
20
+ "CLIP ViT-B/16": ("openai/clip-vit-base-patch16", 224, "clip"),
21
+ "CLIP ViT-L/14": ("openai/clip-vit-large-patch14", 224, "clip"),
22
+ "CLIP ViT-L/14@336": ("openai/clip-vit-large-patch14-336", 336, "clip"),
23
+ "SigLIP Large-256": ("google/siglip-large-patch16-256", 256, "siglip"),
24
+ "SigLIP Base-384": ("google/siglip-base-patch16-384", 384, "siglip"),
25
+ "SigLIP Large-384": ("google/siglip-large-patch16-384", 384, "siglip"),
26
  }
27
 
28
+ # ---------------------------------------------------------------------
29
+ # 2. LAZY MODEL LOADING
30
+ # ---------------------------------------------------------------------
31
+ _models, _processors = {}, {}
32
 
33
+ def _load_model(name: str):
34
+ path, _, kind = MODELS[name]
 
 
 
 
 
35
 
36
+ kwargs = dict(
37
+ low_cpu_mem_usage=False, # avoid meta-device bug
38
+ torch_dtype=torch.float16, # faster & smaller
39
+ )
40
+
41
+ if kind == "clip":
42
+ model = CLIPModel.from_pretrained(path, **kwargs).to(DEVICE)
43
+ processor = CLIPProcessor.from_pretrained(path)
44
+ else:
45
+ model = SiglipModel.from_pretrained(path, **kwargs).to(DEVICE)
46
+ processor = SiglipProcessor.from_pretrained(path)
47
+
48
+ model.eval()
49
+ return model, processor
50
 
51
+ def get_model(name: str):
52
+ if name not in _models:
53
+ _models[name], _processors[name] = _load_model(name)
54
+ return _models[name], _processors[name]
55
+
56
+ # ---------------------------------------------------------------------
57
+ # 3. SCORING FUNCTION (runs on GPU in Spaces)
58
+ # ---------------------------------------------------------------------
59
  @spaces.GPU
60
+ def calculate_score(image, text: str, model_name: str):
61
+ labels = [t.strip() for t in text.split(";") if t.strip()]
62
+ if not labels:
63
+ return {}
64
+
65
+ model, processor = get_model(model_name)
66
+ kind = MODELS[model_name][2]
67
+
68
+ inputs = processor(
69
+ text=labels,
70
+ images=image,
71
+ padding=True,
72
+ return_tensors="pt",
73
+ ).to(DEVICE)
74
+
 
75
  with torch.no_grad():
76
+ if kind == "clip":
77
+ out = model(**inputs)
78
+ img_emb = out.image_embeds
79
+ txt_emb = out.text_embeds
80
+ else:
81
+ img_emb = model.get_image_features(pixel_values=inputs["pixel_values"])
82
+ txt_emb = model.get_text_features(
83
+ input_ids=inputs["input_ids"],
84
+ attention_mask=inputs["attention_mask"],
85
+ )
86
+
87
+ img_emb = F.normalize(img_emb, p=2, dim=-1)
88
+ txt_emb = F.normalize(txt_emb, p=2, dim=-1)
89
+
90
+ scores = (txt_emb @ img_emb.T).squeeze(1) # cosine
91
+ if kind == "siglip":
92
+ scores = torch.sigmoid(scores) # paper’s choice
93
+
94
+ return {lbl: float(score.clamp(0, 1)) for lbl, score in zip(labels, scores.cpu())}
95
+
96
+ # ---------------------------------------------------------------------
97
+ # 4. GRADIO UI
98
+ # ---------------------------------------------------------------------
99
+ with gr.Blocks(title="CLIP / SigLIP Image-Text Similarity") as demo:
100
+ gr.Markdown("## Compare an image with multiple text prompts")
 
 
 
 
 
 
 
 
 
101
 
102
  with gr.Row():
103
+ image_in = gr.Image(type="pil", label="Image")
104
+ score_out = gr.Label(label="Similarity (0‒1)")
105
 
106
  with gr.Row():
107
+ text_in = gr.Textbox(
108
+ label="Text prompts (use ‘;’ to separate)",
109
+ placeholder="a cat; a flying cat; a dog",
110
+ )
111
+ model_in = gr.Dropdown(
112
+ choices=list(MODELS.keys()),
113
+ value="CLIP ViT-B/16",
114
+ label="Model",
115
  )
116
 
117
+ def infer(img, txt, mdl):
118
+ return calculate_score(img, txt, mdl) if img and txt.strip() else {}
 
 
 
 
 
119
 
120
+ for comp in (image_in, text_in, model_in):
121
+ comp.change(infer, [image_in, text_in, model_in], score_out)
 
122
 
123
  gr.Examples(
124
  examples=[
125
+ ["cat.jpg",
126
+ "a cat stuck in a door; a cat jumping; a dog",
127
+ "CLIP ViT-B/16"],
 
 
128
  ],
129
+ inputs=[image_in, text_in, model_in],
130
+ outputs=score_out,
 
131
  )
132
 
133
+ demo.launch()