Spaces:
Sleeping
Sleeping
File size: 5,743 Bytes
a475b1f | 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 | """
Search Examples - Different ways to search your product catalog.
This example demonstrates various search methods and filtering options
available in the Image Search SDK.
"""
import sys
from pathlib import Path
# Add SDK to path
sdk_path = Path(__file__).parent.parent
sys.path.insert(0, str(sdk_path))
from image_search_sdk import ImageSearchClient, SearchOptions
def main():
print("Search Examples - Image Search SDK")
print("=" * 70)
# Initialize SDK (assuming already set up)
client = ImageSearchClient(
data_dir="./search_data",
vector_store_type="chromadb",
vector_store_config={"mode": "persistent", "path": "./search_data/vectors"}
)
# Connect to database (replace with your actual database)
client.connect_database(
connection_string="sqlite:///products.db",
table_name="products",
id_column="id",
title_column="title",
image_url_column="image_url"
)
# Example 1: Basic Text Search
print("\n" + "=" * 70)
print("EXAMPLE 1: Basic Text Search")
print("=" * 70)
results = client.search_by_text("running shoes", options=SearchOptions(top_k=5))
print(f"\nSearching for 'running shoes' - Found {len(results)} results:")
for i, result in enumerate(results, 1):
print(f"{i}. {result.product.title}")
print(f" Similarity: {result.similarity_score:.3f}")
if result.product.price:
print(f" Price: ${result.product.price:.2f}")
# Example 2: Text Search with Filters
print("\n" + "=" * 70)
print("EXAMPLE 2: Text Search with Category Filter")
print("=" * 70)
results = client.search_by_text(
"laptop",
options=SearchOptions(
top_k=10,
category="Electronics" # Filter by category
)
)
print(f"\nSearching for 'laptop' in Electronics - Found {len(results)} results:")
for i, result in enumerate(results[:3], 1): # Show top 3
print(f"{i}. {result.product.title}")
print(f" Category: {result.product.category}")
# Example 3: Image Search (by file path)
print("\n" + "=" * 70)
print("EXAMPLE 3: Search by Image File")
print("=" * 70)
# Assuming you have a local image file
image_path = "./sample_images/product.jpg"
if Path(image_path).exists():
results = client.search_by_image(
image_path,
options=SearchOptions(top_k=5)
)
print(f"\nSearching by image '{image_path}' - Found {len(results)} results:")
for i, result in enumerate(results, 1):
print(f"{i}. {result.product.title} (score: {result.similarity_score:.3f})")
else:
print(f"\nImage file not found: {image_path}")
print("Place a sample image at this path to test image search.")
# Example 4: Hybrid Search (combining image and text)
print("\n" + "=" * 70)
print("EXAMPLE 4: Combined Image + Text Search")
print("=" * 70)
print("\nNote: For hybrid search, use search_by_image and then filter results by text")
print("or use multiple search queries and combine results.")
# Example 5: Price Range Filtering
print("\n" + "=" * 70)
print("EXAMPLE 5: Search with Custom Filtering")
print("=" * 70)
results = client.search_by_text(
"smartphone",
options=SearchOptions(
top_k=20,
category="Electronics"
)
)
# Post-filter by price
affordable_results = [r for r in results if r.product.price and r.product.price < 500]
print(f"\nAffordable smartphones (< $500): {len(affordable_results)} results")
for i, result in enumerate(affordable_results[:3], 1):
print(f"{i}. {result.product.title}")
print(f" Price: ${result.product.price:.2f}")
print(f" Score: {result.similarity_score:.3f}")
# Example 6: Brand Filtering
print("\n" + "=" * 70)
print("EXAMPLE 6: Search with Brand Filter")
print("=" * 70)
results = client.search_by_text(
"wireless mouse",
options=SearchOptions(
top_k=10,
brand="Logitech" # Specific brand
)
)
print(f"\nLogitech wireless mouse products: {len(results)} results")
# Example 7: Getting Similar Products
print("\n" + "=" * 70)
print("EXAMPLE 7: Find Similar Products")
print("=" * 70)
# First, find a product
initial_results = client.search_by_text("leather wallet", options=SearchOptions(top_k=1))
if initial_results:
product = initial_results[0].product
print(f"\nBase product: {product.title}")
# Now find similar products (by searching with the same image)
if product.image_url:
similar_results = client.search_by_text(
product.title,
options=SearchOptions(
top_k=6, # Get 6 results (including the original)
category=product.category # Same category
)
)
print(f"\nSimilar products:")
for i, result in enumerate(similar_results[1:], 1): # Skip first (same product)
print(f"{i}. {result.product.title}")
print(f" Similarity: {result.similarity_score:.3f}")
# Show statistics
print("\n" + "=" * 70)
print("SYSTEM STATISTICS")
print("=" * 70)
stats = client.get_stats()
print(f"Total indexed products: {stats.get('total_vectors', 0):,}")
print(f"Vector store: {stats.get('store_type', 'N/A')}")
# Cleanup
client.close()
print("\nDone!")
if __name__ == "__main__":
main()
|