Spaces:
Sleeping
Sleeping
| """ | |
| Test script for Product Classification API | |
| Run this to test your API endpoints | |
| """ | |
| import requests | |
| import json | |
| from typing import Dict, List | |
| # API base URL | |
| BASE_URL = "http://localhost:8000" | |
| def test_health(): | |
| """Test health check endpoint""" | |
| print("\n" + "=" * 80) | |
| print("TEST 1: Health Check") | |
| print("=" * 80) | |
| response = requests.get(f"{BASE_URL}/health") | |
| if response.status_code == 200: | |
| data = response.json() | |
| print("β API is healthy!") | |
| print(f" Status: {data['status']}") | |
| print(f" Categories loaded: {data['categories_loaded']:,}") | |
| print(f" Embedding dimension: {data['embedding_dimension']}") | |
| else: | |
| print(f"β Health check failed: {response.status_code}") | |
| return response.status_code == 200 | |
| def test_single_classification(): | |
| """Test single product classification""" | |
| print("\n" + "=" * 80) | |
| print("TEST 2: Single Product Classification") | |
| print("=" * 80) | |
| # Test product | |
| product = { | |
| "id": "test_001", | |
| "title": "Sony WH-1000XM5 Wireless Headphones", | |
| "product_type": "Headphones", | |
| "vendor": "Sony", | |
| "tags": ["audio", "electronics", "wireless", "bluetooth"], | |
| "description": "Premium noise-canceling over-ear headphones", | |
| } | |
| print(f"\nπ± Test Product: {product['title']}") | |
| response = requests.post(f"{BASE_URL}/classify", json=product) | |
| if response.status_code == 200: | |
| result = response.json() | |
| print(f"\nβ Classification successful!") | |
| print(f" Action: {result['action']}") | |
| print(f" Top Category: {result['top_category']}") | |
| print(f" Confidence: {result['top_confidence']}%") | |
| print(f" Processing Time: {result['processing_time_ms']}ms") | |
| print(f"\nπ Top 3 Alternative Categories:") | |
| for alt in result["alternatives"][:3]: | |
| print(f" {alt['rank']}. {alt['category_path']}") | |
| print(f" Confidence: {alt['confidence_percentage']}%") | |
| return True | |
| else: | |
| print(f"β Classification failed: {response.status_code}") | |
| print(f" Error: {response.text}") | |
| return False | |
| def test_batch_classification(): | |
| """Test batch product classification""" | |
| print("\n" + "=" * 80) | |
| print("TEST 3: Batch Classification") | |
| print("=" * 80) | |
| # Multiple test products | |
| products = [ | |
| { | |
| "id": "prod_001", | |
| "title": "Samsung Galaxy S24 Ultra", | |
| "product_type": "Smartphone", | |
| "vendor": "Samsung", | |
| "tags": ["electronics", "phone", "mobile", "android"], | |
| }, | |
| { | |
| "id": "prod_002", | |
| "title": "KitchenAid Stand Mixer", | |
| "product_type": "Kitchen Appliance", | |
| "vendor": "KitchenAid", | |
| "tags": ["appliance", "kitchen", "cooking"], | |
| }, | |
| { | |
| "id": "prod_003", | |
| "title": "Nike Air Zoom Running Shoes", | |
| "product_type": "Athletic Footwear", | |
| "vendor": "Nike", | |
| "tags": ["shoes", "sports", "running", "athletic"], | |
| }, | |
| ] | |
| batch_request = {"products": products, "top_k": 3} | |
| print(f"\nπ¦ Testing batch of {len(products)} products...") | |
| response = requests.post(f"{BASE_URL}/classify-batch", json=batch_request) | |
| if response.status_code == 200: | |
| result = response.json() | |
| print(f"\nβ Batch classification successful!") | |
| print(f" Total products: {result['total_products']}") | |
| print(f" Processing time: {result['processing_time_ms']:.2f}ms") | |
| print( | |
| f" Time per product: {result['processing_time_ms']/result['total_products']:.2f}ms" | |
| ) | |
| print(f"\nπ Action Distribution:") | |
| for action, count in result["action_counts"].items(): | |
| percentage = (count / result["total_products"]) * 100 | |
| print(f" {action}: {count} ({percentage:.1f}%)") | |
| print(f"\nπ― Individual Results:") | |
| for res in result["results"]: | |
| print(f"\n β’ {res.get('product_id', 'N/A')}") | |
| print(f" Action: {res['action']}") | |
| print(f" Confidence: {res.get('top_confidence', 0)}%") | |
| if res.get("top_category"): | |
| print(f" Category: {res['top_category'][:60]}...") | |
| return True | |
| else: | |
| print(f"β Batch classification failed: {response.status_code}") | |
| print(f" Error: {response.text}") | |
| return False | |
| def test_various_products(): | |
| """Test with various product types""" | |
| print("\n" + "=" * 80) | |
| print("TEST 4: Various Product Types") | |
| print("=" * 80) | |
| test_cases = [ | |
| { | |
| "name": "Electronics", | |
| "product": { | |
| "title": "MacBook Pro 16 inch M3", | |
| "product_type": "Laptop Computer", | |
| "vendor": "Apple", | |
| "tags": ["computer", "laptop", "electronics"], | |
| }, | |
| }, | |
| { | |
| "name": "Books", | |
| "product": { | |
| "title": "The Great Gatsby by F. Scott Fitzgerald", | |
| "product_type": "Book", | |
| "vendor": "Scribner", | |
| "tags": ["books", "fiction", "literature", "classic"], | |
| }, | |
| }, | |
| { | |
| "name": "Home Appliances", | |
| "product": { | |
| "title": "Dyson V15 Detect Vacuum Cleaner", | |
| "product_type": "Vacuum Cleaner", | |
| "vendor": "Dyson", | |
| "tags": ["appliance", "cleaning", "home", "cordless"], | |
| }, | |
| }, | |
| { | |
| "name": "Toys", | |
| "product": { | |
| "title": "LEGO Star Wars Millennium Falcon", | |
| "product_type": "Building Toy", | |
| "vendor": "LEGO", | |
| "tags": ["toys", "kids", "lego", "star wars", "building"], | |
| }, | |
| }, | |
| ] | |
| results_summary = [] | |
| for test_case in test_cases: | |
| print(f"\nπ§ͺ Testing: {test_case['name']}") | |
| print(f" Product: {test_case['product']['title']}") | |
| response = requests.post(f"{BASE_URL}/classify", json=test_case["product"]) | |
| if response.status_code == 200: | |
| result = response.json() | |
| confidence = result["top_confidence"] | |
| action = result["action"] | |
| emoji = ( | |
| "β " | |
| if action == "AUTO_APPROVE" | |
| else "β οΈ" if action == "QUICK_REVIEW" else "β" | |
| ) | |
| print(f" {emoji} {action}: {confidence}%") | |
| results_summary.append( | |
| { | |
| "category": test_case["name"], | |
| "confidence": confidence, | |
| "action": action, | |
| } | |
| ) | |
| else: | |
| print(f" β Failed: {response.status_code}") | |
| results_summary.append( | |
| {"category": test_case["name"], "confidence": 0, "action": "ERROR"} | |
| ) | |
| # Print summary | |
| print(f"\nπ SUMMARY:") | |
| print("-" * 80) | |
| avg_confidence = sum(r["confidence"] for r in results_summary) / len( | |
| results_summary | |
| ) | |
| auto_approve_count = sum( | |
| 1 for r in results_summary if r["action"] == "AUTO_APPROVE" | |
| ) | |
| print(f"Average Confidence: {avg_confidence:.2f}%") | |
| print( | |
| f"Auto-Approve Rate: {auto_approve_count}/{len(results_summary)} ({auto_approve_count/len(results_summary)*100:.1f}%)" | |
| ) | |
| return True | |
| def run_all_tests(): | |
| """Run all tests""" | |
| print("\n" + "=" * 80) | |
| print("π§ͺ RUNNING ALL API TESTS") | |
| print("=" * 80) | |
| print("\nMake sure API is running: uvicorn src.api:app --reload") | |
| tests = [ | |
| ("Health Check", test_health), | |
| ("Single Classification", test_single_classification), | |
| ("Batch Classification", test_batch_classification), | |
| ("Various Products", test_various_products), | |
| ] | |
| results = [] | |
| for test_name, test_func in tests: | |
| try: | |
| result = test_func() | |
| results.append((test_name, result)) | |
| except requests.exceptions.ConnectionError: | |
| print(f"\nβ Connection Error: Is the API running?") | |
| print(" Start it with: uvicorn src.api:app --reload") | |
| return | |
| except Exception as e: | |
| print(f"\nβ Error in {test_name}: {e}") | |
| results.append((test_name, False)) | |
| # Final summary | |
| print("\n" + "=" * 80) | |
| print("π TEST RESULTS SUMMARY") | |
| print("=" * 80) | |
| for test_name, result in results: | |
| status = "β PASS" if result else "β FAIL" | |
| print(f"{status} - {test_name}") | |
| passed = sum(1 for _, r in results if r) | |
| total = len(results) | |
| print(f"\nπ― Overall: {passed}/{total} tests passed ({passed/total*100:.1f}%)") | |
| if passed == total: | |
| print("\nπ ALL TESTS PASSED! Your API is working perfectly!") | |
| else: | |
| print(f"\nβ οΈ Some tests failed. Check the errors above.") | |
| if __name__ == "__main__": | |
| run_all_tests() | |