File size: 5,021 Bytes
2afd81c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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")