logeswari commited on
Commit
67acbba
·
1 Parent(s): 90e30cf
Files changed (2) hide show
  1. app.py +119 -0
  2. requirements.txt +7 -0
app.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import requests
3
+ from PIL import Image, UnidentifiedImageError
4
+ import io
5
+ import numpy as np
6
+ from transformers import AutoProcessor, CLIPModel
7
+ import logging
8
+ from pinecone import Pinecone
9
+ import streamlit as st
10
+
11
+ # Function to check authentication
12
+ def check_authentication():
13
+ st.sidebar.title("🔑 Login")
14
+ username = st.sidebar.text_input("Username", key="username_input")
15
+ password = st.sidebar.text_input("Password", type="password", key="password_input")
16
+ login_button = st.sidebar.button("Login")
17
+
18
+ if login_button:
19
+ try:
20
+ stored_users = dict(st.secrets["credentials"]) # Convert to dictionary
21
+ if username in stored_users and stored_users[username] == password:
22
+ st.session_state["authenticated"] = True
23
+ st.session_state["username"] = username
24
+ st.rerun() # ✅ Updated method
25
+ else:
26
+ st.sidebar.error("❌ Invalid username or password")
27
+ except Exception as e:
28
+ st.sidebar.error("⚠️ Authentication system error")
29
+ st.sidebar.text(str(e))
30
+
31
+ # Check authentication status
32
+ if "authenticated" not in st.session_state:
33
+ st.session_state["authenticated"] = False
34
+
35
+ if not st.session_state["authenticated"]:
36
+ check_authentication()
37
+ st.stop()
38
+
39
+ # Main app content (only accessible after authentication)
40
+ st.write("Welcome! You are successfully authenticated.")
41
+
42
+
43
+ # Setup logging
44
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
45
+ logger = logging.getLogger(__name__)
46
+
47
+ # Load CLIP model and processor
48
+ model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
49
+ processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
50
+
51
+ # Initialize Pinecone
52
+ pc = Pinecone(api_key="pcsk_6QAd2e_Js1mL941ky9vvGhkGpsGmR7H8aDjKWp2vzpMiRDSvFEFGf5VT6meRJeAft1pNaE")
53
+ index_name = "images-index"
54
+
55
+ # Ensure Pinecone index exists
56
+ index_list = pc.list_indexes().names()
57
+ if index_name not in index_list:
58
+ st.error(f"Index '{index_name}' not found. Make sure it is created.")
59
+ st.stop()
60
+
61
+ # Initialize Pinecone index
62
+ unsplash_index = pc.Index(index_name)
63
+
64
+ def embed_text(text):
65
+ inputs = processor(text=text, return_tensors="pt")
66
+ text_features = model.get_text_features(**inputs)
67
+ return text_features.detach().cpu().numpy().flatten().tolist()
68
+
69
+ def embed_image(image):
70
+ inputs = processor(images=image, return_tensors="pt")
71
+ image_features = model.get_image_features(**inputs)
72
+ return image_features.detach().cpu().numpy().flatten().tolist()
73
+
74
+ # Streamlit UI
75
+ st.title("📌Image & Text Embedding Search using CLIP and Pinecone")
76
+
77
+ option = st.radio("Choose input type:", ("Text", "Image🏞️"))
78
+
79
+ if option == "Text":
80
+ query_text = st.text_input("Enter a search term:")
81
+ if st.button("Embed & Search"):
82
+ if query_text:
83
+ query_embedding = embed_text(query_text)
84
+ search_results = unsplash_index.query(
85
+ vector=query_embedding,
86
+ top_k=10,
87
+ include_metadata=True,
88
+ namespace="image-search-dataset"
89
+ )
90
+ if search_results and "matches" in search_results:
91
+ st.subheader("Search Results:")
92
+ for match in search_results["matches"]:
93
+ url = match["metadata"].get("url", "No URL")
94
+ st.image(url, caption=f"Score: {match['score']:.4f}", use_container_width=True)
95
+ else:
96
+ st.warning("No matching images found.")
97
+ else:
98
+ st.error("Please enter a search term.")
99
+
100
+ elif option == "Image":
101
+ uploaded_file = st.file_uploader("Upload an image:", type=["jpg", "jpeg", "png"])
102
+ if uploaded_file is not None:
103
+ image = Image.open(uploaded_file)
104
+ st.image(image, caption="Uploaded Image", use_container_width=True)
105
+ if st.button("Embed & Search"):
106
+ query_embedding = embed_image(image)
107
+ search_results = unsplash_index.query(
108
+ vector=query_embedding,
109
+ top_k=10,
110
+ include_metadata=True,
111
+ namespace="image-search-dataset"
112
+ )
113
+ if search_results and "matches" in search_results:
114
+ st.subheader("Search Results:")
115
+ for match in search_results["matches"]:
116
+ url = match["metadata"].get("url", "No URL")
117
+ st.image(url, caption=f"Score: {match['score']:.4f}", use_container_width=True)
118
+ else:
119
+ st.warning("No similar images found.")
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ streamlit
2
+ requests
3
+ pillow
4
+ numpy
5
+ transformers
6
+ torch
7
+ pinecone