Spaces:
Sleeping
Sleeping
File size: 8,753 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 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 | """
Plug-and-Run Integration Example - Image Search SDK
This example demonstrates how customers can integrate image search
into their existing e-commerce systems with automatic embedding generation.
"""
from image_search_sdk import ImageSearchClient, Product, SearchOptions
def main():
print("π Plug-and-Run Image Search Integration Example")
print("=" * 60)
# 1. Initialize client with different storage backends
print("\n1. Initializing Image Search Client...")
# Option A: Local file storage (simple, no database setup)
client_local = ImageSearchClient(
api_key="is_your_api_key_here",
base_url="http://localhost:8000",
embedding_storage="local",
storage_config={
'storage_path': './my_embeddings'
}
)
# Option B: PostgreSQL with pgvector (production-ready)
client_pgvector = ImageSearchClient(
api_key="is_your_api_key_here",
base_url="http://localhost:8000",
embedding_storage="pgvector",
storage_config={
'connection_string': 'postgresql://user:password@localhost:5432/my_ecommerce_db',
'table_name': 'product_embeddings'
}
)
# Use local storage for this example
client = client_local
# 2. Connect to existing product database
print("\n2. Connecting to existing product database...")
client.connect_database(
connection_string="sqlite:///my_products.db",
table_name="products",
id_column="product_id",
title_column="product_name",
image_url_column="image_url",
category_column="category",
brand_column="brand",
price_column="price",
rating_column="rating",
enable_auto_embedding=True # Enable automatic embedding generation
)
# 3. Add products with automatic embedding generation
print("\n3. Adding products with automatic embedding generation...")
# Create sample products
products = [
Product(
id="prod_001",
title="Wireless Bluetooth Headphones",
image_url="https://example.com/headphones.jpg",
category="Electronics",
brand="TechBrand",
price=99.99,
rating=4.5,
description="High-quality wireless headphones with noise cancellation"
),
Product(
id="prod_002",
title="Smart Fitness Watch",
image_url="https://example.com/watch.jpg",
category="Electronics",
brand="FitTech",
price=199.99,
rating=4.2,
description="Advanced fitness tracking smartwatch"
),
Product(
id="prod_003",
title="Coffee Maker Pro",
image_url="https://example.com/coffee.jpg",
category="Appliances",
brand="BrewMaster",
price=149.99,
rating=4.7,
description="Professional-grade coffee maker"
)
]
# Add products - embeddings are generated automatically in the background
for product in products:
success = client.add_product_with_auto_embedding(product)
print(f"Added product {product.id}: {'β
' if success else 'β'}")
# 4. Wait for embeddings to be generated
print("\n4. Waiting for automatic embedding generation...")
import time
time.sleep(5) # Give time for background processing
# Check embedding generation stats
stats = client.get_embedding_stats()
print(f"Embedding Stats: {stats}")
# 5. Search using local embeddings (fast, no API calls)
print("\n5. Searching using local embeddings...")
# Generate a query embedding (in real usage, this would come from an image or text)
# For demo purposes, we'll use a dummy embedding
import numpy as np
dummy_query_embedding = np.random.rand(768).tolist()
# Search with filters
options = SearchOptions(
top_k=5,
min_price=50.0,
max_price=200.0,
category="Electronics"
)
results = client.search_local(dummy_query_embedding, options)
print(f"Found {len(results)} results:")
for result in results:
print(f" - {result.product.title} (Score: {result.similarity_score:.3f})")
# 6. Update a product (embeddings regenerated automatically)
print("\n6. Updating product (automatic embedding regeneration)...")
updated_product = Product(
id="prod_001",
title="Wireless Bluetooth Headphones Pro", # Updated title
image_url="https://example.com/headphones_pro.jpg", # Updated image
category="Electronics",
brand="TechBrand",
price=129.99, # Updated price
rating=4.8, # Updated rating
description="Premium wireless headphones with advanced noise cancellation"
)
success = client.update_product_with_auto_embedding(updated_product)
print(f"Updated product: {'β
' if success else 'β'}")
# 7. Delete a product (embeddings cleaned up automatically)
print("\n7. Deleting product (automatic embedding cleanup)...")
success = client.delete_product_with_auto_embedding("prod_003")
print(f"Deleted product: {'β
' if success else 'β'}")
# 8. Integration with existing e-commerce workflow
print("\n8. Integration with existing e-commerce workflow...")
# Example: Customer uploads a product image
def handle_customer_image_upload(image_path: str):
"""Example function showing how to integrate with existing workflow."""
print(f"Customer uploaded image: {image_path}")
# Search for similar products
results = client.search_by_image(image_path, SearchOptions(top_k=3))
print("Similar products found:")
for result in results:
print(f" - {result.product.title} (Similarity: {result.similarity_score:.3f})")
return results
# Example: Customer searches by text
def handle_customer_text_search(query: str):
"""Example function for text-based search."""
print(f"Customer searched: '{query}'")
results = client.search_by_text(query, SearchOptions(top_k=5))
print("Search results:")
for result in results:
print(f" - {result.product.title} (Score: {result.similarity_score:.3f})")
return results
# Simulate customer interactions
print("\nSimulating customer interactions...")
handle_customer_text_search("wireless headphones")
# 9. System monitoring
print("\n9. System monitoring...")
status = client.get_status()
print(f"System Status: {status.is_healthy}")
print(f"Total Products: {status.total_products}")
print(f"Indexed Products: {status.indexed_products}")
print(f"Search Latency: {status.search_latency_ms}ms")
# 10. Cleanup
print("\n10. Cleaning up...")
client.close()
print("β
Integration complete!")
def demonstrate_different_storage_options():
"""Demonstrate different storage backend options."""
print("\n" + "="*60)
print("π Storage Backend Options")
print("="*60)
# Local file storage - good for development and small catalogs
print("\n1. Local File Storage:")
print(" - Simple setup, no database required")
print(" - Good for development and small catalogs (<10K products)")
print(" - Files stored in local directory")
# PostgreSQL with pgvector - production ready
print("\n2. PostgreSQL with pgvector:")
print(" - Production-ready, scalable")
print(" - Good for large catalogs (100K+ products)")
print(" - ACID compliance, backup support")
print(" - Advanced querying capabilities")
# Example configurations
print("\n3. Configuration Examples:")
print("\n Local Storage:")
print(" ```python")
print(" client = ImageSearchClient(")
print(" api_key='your_key',")
print(" embedding_storage='local',")
print(" storage_config={'storage_path': './embeddings'}")
print(" )")
print(" ```")
print("\n PostgreSQL Storage:")
print(" ```python")
print(" client = ImageSearchClient(")
print(" api_key='your_key',")
print(" embedding_storage='pgvector',")
print(" storage_config={")
print(" 'connection_string': 'postgresql://user:pass@localhost/db',")
print(" 'table_name': 'product_embeddings'")
print(" }")
print(" )")
print(" ```")
if __name__ == "__main__":
main()
demonstrate_different_storage_options()
|