Spaces:
Sleeping
Sleeping
File size: 9,073 Bytes
d12790d | 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 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 | """
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()
|