add img code
Browse files
app.py
CHANGED
|
@@ -1,20 +1,18 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
from pinecone import Pinecone
|
| 3 |
-
|
| 4 |
import os
|
| 5 |
from PIL import Image
|
| 6 |
import requests
|
| 7 |
from transformers import AutoProcessor, CLIPModel
|
| 8 |
import numpy as np
|
|
|
|
| 9 |
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
# Initialize Pinecone
|
| 13 |
-
pc = Pinecone(api_key="pcsk_6r4DPn_4P9LckhZak3PhebvSebnEBKQZuzYFeJL2X93LtLxZVBxyJ93inBAktefa8usvJC")
|
| 14 |
index_name = "unsplash-index"
|
| 15 |
unsplash_index = pc.Index(index_name)
|
| 16 |
|
| 17 |
-
# Load CLIP
|
| 18 |
@st.cache_resource
|
| 19 |
def load_clip_model():
|
| 20 |
model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
|
|
@@ -23,14 +21,23 @@ def load_clip_model():
|
|
| 23 |
|
| 24 |
model, processor = load_clip_model()
|
| 25 |
|
| 26 |
-
# Function to
|
| 27 |
def get_text_embedding(text):
|
| 28 |
inputs = processor(text=[text], return_tensors="pt", padding=True, truncation=True)
|
| 29 |
-
|
|
|
|
| 30 |
embedding = text_features.detach().cpu().numpy().flatten().tolist()
|
| 31 |
return embedding
|
| 32 |
|
| 33 |
-
# Function to
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
def search_similar_images(embedding, top_k=10):
|
| 35 |
results = unsplash_index.query(
|
| 36 |
vector=embedding,
|
|
@@ -38,44 +45,64 @@ def search_similar_images(embedding, top_k=10):
|
|
| 38 |
include_metadata=True,
|
| 39 |
namespace="image-search-dataset"
|
| 40 |
)
|
| 41 |
-
return results
|
| 42 |
|
| 43 |
-
# Streamlit UI
|
| 44 |
-
st.title("π
|
| 45 |
-
st.write("
|
| 46 |
|
| 47 |
-
#
|
| 48 |
-
|
|
|
|
| 49 |
|
| 50 |
-
|
| 51 |
-
if st.button("Search"):
|
| 52 |
if search_query:
|
| 53 |
-
# Generate embedding from text
|
| 54 |
with st.spinner("Generating embedding..."):
|
| 55 |
embedding = get_text_embedding(search_query)
|
| 56 |
-
|
| 57 |
-
# Search for similar images
|
| 58 |
with st.spinner("Searching for similar images..."):
|
| 59 |
-
matches = search_similar_images(embedding, top_k=
|
| 60 |
|
| 61 |
-
|
| 62 |
-
st.subheader("Top Similar Images")
|
| 63 |
for match in matches:
|
| 64 |
-
score = match
|
| 65 |
-
photo_id = match
|
| 66 |
-
url = match
|
|
|
|
| 67 |
st.write(f"**Photo ID**: {photo_id} | **Similarity Score**: {score:.4f}")
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
img = Image.open(response.raw)
|
| 73 |
-
st.image(img, caption=f"Photo ID: {photo_id}", use_container_width=True)
|
| 74 |
-
except Exception as e:
|
| 75 |
-
st.error(f"Could not load image from {url}: {e}")
|
| 76 |
else:
|
| 77 |
-
st.warning("Please enter a search query!")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
# Instructions
|
| 80 |
st.write("---")
|
| 81 |
-
st.write("Note: This app searches an Unsplash dataset indexed in Pinecone using CLIP embeddings
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
from pinecone import Pinecone
|
|
|
|
| 3 |
import os
|
| 4 |
from PIL import Image
|
| 5 |
import requests
|
| 6 |
from transformers import AutoProcessor, CLIPModel
|
| 7 |
import numpy as np
|
| 8 |
+
import torch
|
| 9 |
|
| 10 |
+
# β
Initialize Pinecone
|
| 11 |
+
pc = Pinecone(api_key="your-pinecone-api-key") # Replace with your API key
|
|
|
|
|
|
|
| 12 |
index_name = "unsplash-index"
|
| 13 |
unsplash_index = pc.Index(index_name)
|
| 14 |
|
| 15 |
+
# β
Load CLIP Model & Processor
|
| 16 |
@st.cache_resource
|
| 17 |
def load_clip_model():
|
| 18 |
model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
|
|
|
|
| 21 |
|
| 22 |
model, processor = load_clip_model()
|
| 23 |
|
| 24 |
+
# β
Function to Generate Embedding from Text
|
| 25 |
def get_text_embedding(text):
|
| 26 |
inputs = processor(text=[text], return_tensors="pt", padding=True, truncation=True)
|
| 27 |
+
with torch.no_grad():
|
| 28 |
+
text_features = model.get_text_features(**inputs)
|
| 29 |
embedding = text_features.detach().cpu().numpy().flatten().tolist()
|
| 30 |
return embedding
|
| 31 |
|
| 32 |
+
# β
Function to Generate Embedding from Image
|
| 33 |
+
def get_image_embedding(image):
|
| 34 |
+
inputs = processor(images=image, return_tensors="pt")
|
| 35 |
+
with torch.no_grad():
|
| 36 |
+
image_features = model.get_image_features(**inputs)
|
| 37 |
+
embedding = image_features.detach().cpu().numpy().flatten().tolist()
|
| 38 |
+
return embedding
|
| 39 |
+
|
| 40 |
+
# β
Function to Query Pinecone and Fetch Similar Images
|
| 41 |
def search_similar_images(embedding, top_k=10):
|
| 42 |
results = unsplash_index.query(
|
| 43 |
vector=embedding,
|
|
|
|
| 45 |
include_metadata=True,
|
| 46 |
namespace="image-search-dataset"
|
| 47 |
)
|
| 48 |
+
return results.get("matches", [])
|
| 49 |
|
| 50 |
+
# β
Streamlit UI
|
| 51 |
+
st.title("π Image & Text Search with CLIP & Pinecone")
|
| 52 |
+
st.write("Search for images using text or upload an image to find similar ones!")
|
| 53 |
|
| 54 |
+
# π **Option 1: Text-to-Image Search**
|
| 55 |
+
st.subheader("π Search by Text")
|
| 56 |
+
search_query = st.text_input("Enter a description (e.g., 'a cute cat', 'a red car')")
|
| 57 |
|
| 58 |
+
if st.button("π Search by Text"):
|
|
|
|
| 59 |
if search_query:
|
|
|
|
| 60 |
with st.spinner("Generating embedding..."):
|
| 61 |
embedding = get_text_embedding(search_query)
|
|
|
|
|
|
|
| 62 |
with st.spinner("Searching for similar images..."):
|
| 63 |
+
matches = search_similar_images(embedding, top_k=5)
|
| 64 |
|
| 65 |
+
st.subheader("π Top Similar Images")
|
|
|
|
| 66 |
for match in matches:
|
| 67 |
+
score = match.get("score", 0)
|
| 68 |
+
photo_id = match.get("id", "Unknown ID")
|
| 69 |
+
url = match.get("metadata", {}).get("url", None)
|
| 70 |
+
|
| 71 |
st.write(f"**Photo ID**: {photo_id} | **Similarity Score**: {score:.4f}")
|
| 72 |
+
if url:
|
| 73 |
+
st.image(url, caption=f"Photo ID: {photo_id}", use_column_width=True)
|
| 74 |
+
else:
|
| 75 |
+
st.warning(f"Image URL not found for Photo ID: {photo_id}")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
else:
|
| 77 |
+
st.warning("β οΈ Please enter a search query!")
|
| 78 |
+
|
| 79 |
+
# π **Option 2: Image-to-Image Search**
|
| 80 |
+
st.subheader("πΌοΈ Search by Image")
|
| 81 |
+
uploaded_file = st.file_uploader("Upload an image...", type=["jpg", "png", "jpeg"])
|
| 82 |
+
|
| 83 |
+
if uploaded_file:
|
| 84 |
+
image = Image.open(uploaded_file).convert("RGB")
|
| 85 |
+
st.image(image, caption="Uploaded Image", use_column_width=True)
|
| 86 |
+
|
| 87 |
+
if st.button("π Search by Image"):
|
| 88 |
+
with st.spinner("Generating embedding..."):
|
| 89 |
+
embedding = get_image_embedding(image)
|
| 90 |
+
|
| 91 |
+
with st.spinner("Searching for similar images..."):
|
| 92 |
+
matches = search_similar_images(embedding, top_k=5)
|
| 93 |
+
|
| 94 |
+
st.subheader("π Top Similar Images")
|
| 95 |
+
for match in matches:
|
| 96 |
+
score = match.get("score", 0)
|
| 97 |
+
photo_id = match.get("id", "Unknown ID")
|
| 98 |
+
url = match.get("metadata", {}).get("url", None)
|
| 99 |
+
|
| 100 |
+
st.write(f"**Photo ID**: {photo_id} | **Similarity Score**: {score:.4f}")
|
| 101 |
+
if url:
|
| 102 |
+
st.image(url, caption=f"Photo ID: {photo_id}", use_column_width=True)
|
| 103 |
+
else:
|
| 104 |
+
st.warning(f"Image URL not found for Photo ID: {photo_id}")
|
| 105 |
|
| 106 |
# Instructions
|
| 107 |
st.write("---")
|
| 108 |
+
st.write("Note: This app searches an Unsplash dataset indexed in Pinecone using CLIP embeddings for both text and images.")
|