Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,45 +1,45 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
from transformers import CLIPProcessor, CLIPModel
|
| 3 |
from PIL import Image
|
| 4 |
import torch
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
clip_processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
|
| 9 |
-
|
| 10 |
-
# Load GPT-2 (or any captioning LLM)
|
| 11 |
-
lm_tokenizer = AutoTokenizer.from_pretrained("gpt2")
|
| 12 |
-
lm_model = AutoModelForCausalLM.from_pretrained("gpt2")
|
| 13 |
|
| 14 |
def generate_caption(image):
|
| 15 |
if image is None:
|
| 16 |
return "No image uploaded."
|
| 17 |
|
| 18 |
-
#
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
iface = gr.Interface(
|
| 38 |
fn=generate_caption,
|
| 39 |
inputs=gr.Image(type="pil"),
|
| 40 |
outputs=gr.Textbox(label="Generated Caption"),
|
| 41 |
-
title="Image Captioning with CLIP
|
| 42 |
-
description="
|
| 43 |
)
|
| 44 |
|
| 45 |
iface.launch()
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
from transformers import CLIPProcessor, CLIPModel
|
| 3 |
from PIL import Image
|
| 4 |
import torch
|
| 5 |
|
| 6 |
+
model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
|
| 7 |
+
processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
def generate_caption(image):
|
| 10 |
if image is None:
|
| 11 |
return "No image uploaded."
|
| 12 |
|
| 13 |
+
# Candidate text prompts
|
| 14 |
+
texts = [
|
| 15 |
+
"a photo of a cat",
|
| 16 |
+
"a photo of a dog",
|
| 17 |
+
"a photo of a man",
|
| 18 |
+
"a photo of a woman",
|
| 19 |
+
"a photo of a laptop",
|
| 20 |
+
"a photo of a smartphone",
|
| 21 |
+
"a photo of a city",
|
| 22 |
+
"a photo of a landscape",
|
| 23 |
+
"a photo of food",
|
| 24 |
+
"a photo of a car"
|
| 25 |
+
]
|
| 26 |
+
|
| 27 |
+
inputs = processor(text=texts, images=image, return_tensors="pt", padding=True)
|
| 28 |
+
outputs = model(**inputs)
|
| 29 |
+
|
| 30 |
+
logits_per_image = outputs.logits_per_image # image-text similarity scores
|
| 31 |
+
probs = logits_per_image.softmax(dim=1) # convert to probabilities
|
| 32 |
+
|
| 33 |
+
best_match = torch.argmax(probs).item()
|
| 34 |
+
caption = texts[best_match]
|
| 35 |
+
return f"Best match: {caption} (Confidence: {probs[0][best_match].item():.2f})"
|
| 36 |
|
| 37 |
iface = gr.Interface(
|
| 38 |
fn=generate_caption,
|
| 39 |
inputs=gr.Image(type="pil"),
|
| 40 |
outputs=gr.Textbox(label="Generated Caption"),
|
| 41 |
+
title="Image Captioning with CLIP",
|
| 42 |
+
description="Upload an image and get a dynamically generated caption using CLIP."
|
| 43 |
)
|
| 44 |
|
| 45 |
iface.launch()
|