Spaces:
Sleeping
Sleeping
Download app.py from christyoc1987/Imageembedding: direct link, hf CLI and curl.
- Browser
- Download file 2.83 kB
-
https://huggingface.co/spaces/christyoc1987/Imageembedding/resolve/main/app.py
- Command line
-
hf download hf://spaces/christyoc1987/Imageembedding/app.py
-
curl -L -o app.py https://huggingface.co/spaces/christyoc1987/Imageembedding/resolve/main/app.py
2.83 kB
| 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() |