File size: 2,832 Bytes
4d345dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import gradio as gr
from PIL import Image
import torch
import clip
import numpy as np

# Load CLIP Model
device = "cuda" if torch.cuda.is_available() else "cpu"
model, preprocess = clip.load("ViT-B/32", device=device)

# Store embeddings and images
stored_images = []
stored_embeddings = []

# Function to preprocess and embed images
def embed_images(files):
    """Embeds images using CLIP model and stores them.

    Args:
        files (list): List of uploaded image files.

    Returns:
        str: Status message indicating the number of images embedded.
    """
    global stored_images, stored_embeddings
    stored_images = []
    stored_embeddings = []

    for file in files:
        # Open the file using PIL.Image
        img = Image.open(file.name)  
        image = preprocess(img).unsqueeze(0).to(device)
        with torch.no_grad():
            embedding = model.encode_image(image)
        stored_images.append(img)
        stored_embeddings.append(embedding.cpu().numpy())

    return f"{len(files)} images embedded successfully!"

# Function to query with a question
def query_image(question):
    """Queries the stored images based on a text question.

    Args:
        question (str): The text question to query with.

    Returns:
        tuple: A tuple containing the status message and the most relevant image (or None if no images are available).
    """
    if not stored_embeddings:
        return "No images available. Please upload first.", None

    # Embed the text
    text = clip.tokenize([question]).to(device)
    with torch.no_grad():
        text_embedding = model.encode_text(text).cpu().numpy()

    # Calculate cosine similarities
    similarities = [np.dot(text_embedding, emb.T) / 
                    (np.linalg.norm(text_embedding) * np.linalg.norm(emb))
                    for emb in stored_embeddings]

    best_idx = int(np.argmax(similarities))
    return f"Best match for: '{question}'", stored_images[best_idx]

# Gradio Interface
# Updated to use gr.Files to allow multiple file uploads
image_input = gr.Files(label="Upload up to 5 images")  
status_output = gr.Textbox(label="Status")
question_input = gr.Textbox(label="Ask a question to find a relevant image")
result_output = gr.Image(type="pil", label="Most relevant image")

image_embed_button = gr.Button("Create Embeddings")
query_button = gr.Button("Find Relevant Image")

with gr.Blocks() as demo:
    with gr.Row():
        image_input.render()
        image_embed_button.render()
    status_output.render()

    with gr.Row():
        question_input.render()
        query_button.render()
    result_output.render()

    image_embed_button.click(embed_images, inputs=image_input, outputs=status_output)
    query_button.click(query_image, inputs=question_input, outputs=[status_output, result_output])

demo.launch()