-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
192 lines (171 loc) · 7.13 KB
/
Copy pathapp.py
File metadata and controls
192 lines (171 loc) · 7.13 KB
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
import streamlit as st
from PIL import Image
import sqlite3
import requests
from io import BytesIO
from helper import QdrantHelper
qdrant_helper = QdrantHelper()
# Connect to SQLite database
conn = sqlite3.connect("products.db")
c = conn.cursor()
# Create products table if it doesn't exist
c.execute('''CREATE TABLE IF NOT EXISTS products
(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, description TEXT, image_url TEXT, image_captions TEXT, price REAL)''')
c.execute("SELECT COUNT(*) FROM products")
count = c.fetchone()[0]
# Load products from the database
def load_products():
c.execute("SELECT * FROM products ORDER BY id DESC")
products = []
for row in c.fetchall():
product = {
"id": row[0],
"name": row[1],
"description": row[2],
"image_url": row[3],
"image_captions": row[4],
"price": row[5],
}
products.append(product)
return products
# Download image from URL
def download_image(image_url):
try:
response = requests.get(image_url)
response.raise_for_status()
image_data = BytesIO(response.content)
return Image.open(image_data)
except (requests.exceptions.RequestException):
return None
# Display product card
def display_product_card(product, score, is_main=True):
with st.container(border=1):
col1, col2 = st.columns([1, 2])
with col1:
image = download_image(product["image_url"])
if image:
st.image(image, use_column_width=True)
else:
st.warning("Failed to load image.")
with col2:
st.subheader(product["name"])
if product['price']:
st.write(f"Price: {product['price']}")
description = product["description"]
if len(description) > 100:
description = f"{description[:100]}..."
st.write(f"Description: {description}")
st.progress(score)
st.text(f"Score: {score:.2f}")
key_prefix = "main_product" if is_main else "similar_product"
view_details_button = st.button("View Details", key=f"{key_prefix}_{product['id']}")
if view_details_button:
display_product_details(product)
# Display product details modal/page
def display_product_details(product):
st.subheader(f"Product Details: {product['name']}")
image = download_image(product["image_url"])
if image:
st.image(image, use_column_width=True)
else:
st.warning("Failed to load image.")
if product['price']:
st.write(f"Price: {product['price']}")
st.write(f"Description: {product['description']}")
find_similar_products(product)
# Find similar products
def find_similar_products(product):
query_text = f"{product['name']} {product['description']} {product['image_captions']}".replace("-", "").strip()
query_image_url = product["image_url"]
if query_text:
results = qdrant_helper.find_similar_items(query_text=query_text, num_results=5)
elif query_image_url:
try:
response = requests.get(query_image_url)
response.raise_for_status()
query_image = Image.open(BytesIO(response.content))
results = qdrant_helper.find_similar_items(query_image=query_image, num_results=5)
except (requests.exceptions.RequestException):
results = []
else:
st.warning("No query text or image provided.")
return
st.subheader("Similar Products")
similar_products = []
for result in results:
payload = result.payload
for other_product in load_products():
if payload["text"] == f"{other_product['name']} {other_product['description']} {other_product['image_captions']}".replace("-", "").strip():
similar_products.append((other_product, result.score))
break
if similar_products:
for similar_product, score in similar_products:
if similar_product["id"] != product["id"]:
display_product_card(similar_product, score, is_main=False)
else:
st.write("No similar products found.")
def main():
st.set_page_config(
page_title="VectorSearchShop",
page_icon=":shopping_cart:",
layout="wide"
)
st.title("Vector Search Shop")
# Search Section
with st.container():
col1, col2 = st.columns([1, 1])
with col1:
search_term = st.text_input("Search Products")
with col2:
uploaded_image = st.file_uploader("Upload Image", type=["jpg", "jpeg", "png"])
search_button = st.button("Search")
products = load_products()
if len(products) == 0:
st.warning("No products found.")
if search_button:
if uploaded_image and search_term:
search_results = qdrant_helper.combined_search(query_text=search_term, query_image=uploaded_image, num_results=10)
elif uploaded_image:
search_results = qdrant_helper.combined_search(query_image=uploaded_image, num_results=10)
elif search_term:
search_results = qdrant_helper.combined_search(query_text=search_term, num_results=10)
else:
st.warning("Please enter a search term or upload an image.")
search_results = []
if search_button:
if uploaded_image and search_term:
search_results = qdrant_helper.combined_search(query_text=search_term, query_image=uploaded_image, num_results=10)
elif uploaded_image:
search_results = qdrant_helper.combined_search(query_image=uploaded_image, num_results=10)
elif search_term:
search_results = qdrant_helper.combined_search(query_text=search_term, num_results=10)
else:
st.warning("Please enter a search term or upload an image.")
search_results = []
if search_results:
with st.container():
st.write("Search Results:")
with st.container():
search_result_products = []
for item_id, score in search_results:
product = next((p for p in products if p['id'] == item_id), None)
if product:
search_result_products.append((product, score))
if search_result_products:
product_grid = st.columns(3)
for i, (product, score) in enumerate(search_result_products):
with product_grid[i % 3]:
display_product_card(product, score, is_main=True)
else:
st.warning("No products found.")
else:
st.write(f"Total Products Count: {count}")
with st.container():
st.write("All Products:")
with st.container():
product_grid = st.columns(3)
for i, product in enumerate(products):
with product_grid[i % 3]:
display_product_card(product, 1.0, is_main=True)
if __name__ == "__main__":
main()