context-Classifier2 / test_api.py
parthraninga's picture
Upload 9 files
2afd81c verified
import requests
import json
import time
# Configuration
BASE_URL = "http://localhost:7860"
def test_api():
"""Test all API endpoints"""
print("πŸ§ͺ Testing Content Classifier API")
print("=" * 50)
# Test 1: Root endpoint
print("\nπŸ“ Testing root endpoint...")
try:
response = requests.get(f"{BASE_URL}/")
print(f"βœ… Status: {response.status_code}")
print(f"πŸ“„ Response: {json.dumps(response.json(), indent=2)}")
except Exception as e:
print(f"❌ Error: {e}")
# Test 2: Health check
print("\nπŸ₯ Testing health endpoint...")
try:
response = requests.get(f"{BASE_URL}/health")
print(f"βœ… Status: {response.status_code}")
print(f"πŸ“„ Response: {json.dumps(response.json(), indent=2)}")
except Exception as e:
print(f"❌ Error: {e}")
# Test 3: Model info
print("\nπŸ€– Testing model info endpoint...")
try:
response = requests.get(f"{BASE_URL}/model-info")
print(f"βœ… Status: {response.status_code}")
if response.status_code == 200:
print(f"πŸ“„ Response: {json.dumps(response.json(), indent=2)}")
else:
print(f"πŸ“„ Response: {response.text}")
except Exception as e:
print(f"❌ Error: {e}")
# Test 4: Prediction endpoint
print("\nπŸ” Testing prediction endpoint...")
test_cases = [
{
"text": "Hello, how are you today? I hope you're doing well!",
"expected": "positive sentiment"
},
{
"text": "I will destroy everything and cause harm!",
"expected": "threat detection"
},
{
"text": "This product is amazing, I love it so much!",
"expected": "positive sentiment"
},
{
"text": "I hate this, it's terrible and awful!",
"expected": "negative sentiment"
},
{
"text": "Neutral statement about weather conditions today.",
"expected": "neutral/low confidence"
}
]
for i, case in enumerate(test_cases, 1):
print(f"\nπŸ“ Test Case {i}: {case['expected']}")
print(f"πŸ’¬ Text: '{case['text'][:50]}{'...' if len(case['text']) > 50 else ''}'")
try:
payload = {
"text": case["text"],
"max_length": 512
}
response = requests.post(f"{BASE_URL}/predict", json=payload)
if response.status_code == 200:
result = response.json()
print(f"βœ… Status: {response.status_code}")
print(f"🎯 Is Threat: {result['is_threat']}")
print(f"πŸ“Š Confidence: {result['final_confidence']:.3f}")
print(f"⚠️ Threat Prediction: {result['threat_prediction']:.3f}")
print(f"😊 Sentiment: {result['sentiment_analysis']['label']} ({result['sentiment_analysis']['score']:.3f})")
print(f"πŸ”§ Models Used: {result['models_used']}")
else:
print(f"❌ Status: {response.status_code}")
print(f"πŸ“„ Response: {response.text}")
except Exception as e:
print(f"❌ Error: {e}")
print("\n" + "=" * 50)
print("🏁 API Testing Complete!")
def test_edge_cases():
"""Test edge cases and error conditions"""
print("\n🚨 Testing Edge Cases")
print("=" * 30)
edge_cases = [
{"text": "", "description": "Empty string"},
{"text": " ", "description": "Whitespace only"},
{"text": "A" * 1000, "description": "Very long text"},
{"text": "πŸ”₯πŸ’―πŸš€", "description": "Emoji only"},
{"text": "12345 67890", "description": "Numbers only"}
]
for case in edge_cases:
print(f"\nπŸ“ Testing: {case['description']}")
try:
payload = {"text": case["text"]}
response = requests.post(f"{BASE_URL}/predict", json=payload)
if response.status_code == 200:
result = response.json()
print(f"βœ… Success: Threat={result['is_threat']}, Confidence={result['final_confidence']:.3f}")
else:
print(f"⚠️ Status {response.status_code}: {response.json().get('detail', 'Unknown error')}")
except Exception as e:
print(f"❌ Error: {e}")
if __name__ == "__main__":
print("πŸ” Content Classifier API Test Suite")
print(f"🌐 Base URL: {BASE_URL}")
# Wait a moment for server to be ready
print("\n⏱️ Waiting for server to be ready...")
time.sleep(2)
# Run tests
test_api()
test_edge_cases()
print(f"\nπŸ“š Visit {BASE_URL}/docs for interactive API documentation")