Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
!pip install git+https://github.com/openai/CLIP.git
|
| 2 |
+
!pip install gradio
|
| 3 |
+
!pip install numpy
|
| 4 |
+
import gradio as gr
|
| 5 |
+
from PIL import Image
|
| 6 |
+
import torch
|
| 7 |
+
import clip
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
# Load CLIP Model
|
| 11 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 12 |
+
model, preprocess = clip.load("ViT-B/32", device=device)
|
| 13 |
+
|
| 14 |
+
# Store embeddings and images
|
| 15 |
+
stored_images = []
|
| 16 |
+
stored_embeddings = []
|
| 17 |
+
|
| 18 |
+
# Function to preprocess and embed images
|
| 19 |
+
def embed_images(files):
|
| 20 |
+
"""Embeds images using CLIP model and stores them.
|
| 21 |
+
|
| 22 |
+
Args:
|
| 23 |
+
files (list): List of uploaded image files.
|
| 24 |
+
|
| 25 |
+
Returns:
|
| 26 |
+
str: Status message indicating the number of images embedded.
|
| 27 |
+
"""
|
| 28 |
+
global stored_images, stored_embeddings
|
| 29 |
+
stored_images = []
|
| 30 |
+
stored_embeddings = []
|
| 31 |
+
|
| 32 |
+
for file in files:
|
| 33 |
+
# Open the file using PIL.Image
|
| 34 |
+
img = Image.open(file.name)
|
| 35 |
+
image = preprocess(img).unsqueeze(0).to(device)
|
| 36 |
+
with torch.no_grad():
|
| 37 |
+
embedding = model.encode_image(image)
|
| 38 |
+
stored_images.append(img)
|
| 39 |
+
stored_embeddings.append(embedding.cpu().numpy())
|
| 40 |
+
|
| 41 |
+
return f"{len(files)} images embedded successfully!"
|
| 42 |
+
|
| 43 |
+
# Function to query with a question
|
| 44 |
+
def query_image(question):
|
| 45 |
+
"""Queries the stored images based on a text question.
|
| 46 |
+
|
| 47 |
+
Args:
|
| 48 |
+
question (str): The text question to query with.
|
| 49 |
+
|
| 50 |
+
Returns:
|
| 51 |
+
tuple: A tuple containing the status message and the most relevant image (or None if no images are available).
|
| 52 |
+
"""
|
| 53 |
+
if not stored_embeddings:
|
| 54 |
+
return "No images available. Please upload first.", None
|
| 55 |
+
|
| 56 |
+
# Embed the text
|
| 57 |
+
text = clip.tokenize([question]).to(device)
|
| 58 |
+
with torch.no_grad():
|
| 59 |
+
text_embedding = model.encode_text(text).cpu().numpy()
|
| 60 |
+
|
| 61 |
+
# Calculate cosine similarities
|
| 62 |
+
similarities = [np.dot(text_embedding, emb.T) /
|
| 63 |
+
(np.linalg.norm(text_embedding) * np.linalg.norm(emb))
|
| 64 |
+
for emb in stored_embeddings]
|
| 65 |
+
|
| 66 |
+
best_idx = int(np.argmax(similarities))
|
| 67 |
+
return f"Best match for: '{question}'", stored_images[best_idx]
|
| 68 |
+
|
| 69 |
+
# Gradio Interface
|
| 70 |
+
# Updated to use gr.Files to allow multiple file uploads
|
| 71 |
+
image_input = gr.Files(label="Upload up to 5 images")
|
| 72 |
+
status_output = gr.Textbox(label="Status")
|
| 73 |
+
question_input = gr.Textbox(label="Ask a question to find a relevant image")
|
| 74 |
+
result_output = gr.Image(type="pil", label="Most relevant image")
|
| 75 |
+
|
| 76 |
+
image_embed_button = gr.Button("Create Embeddings")
|
| 77 |
+
query_button = gr.Button("Find Relevant Image")
|
| 78 |
+
|
| 79 |
+
with gr.Blocks() as demo:
|
| 80 |
+
with gr.Row():
|
| 81 |
+
image_input.render()
|
| 82 |
+
image_embed_button.render()
|
| 83 |
+
status_output.render()
|
| 84 |
+
|
| 85 |
+
with gr.Row():
|
| 86 |
+
question_input.render()
|
| 87 |
+
query_button.render()
|
| 88 |
+
result_output.render()
|
| 89 |
+
|
| 90 |
+
image_embed_button.click(embed_images, inputs=image_input, outputs=status_output)
|
| 91 |
+
query_button.click(query_image, inputs=question_input, outputs=[status_output, result_output])
|
| 92 |
+
|
| 93 |
+
demo.launch()
|