""" 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()