-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_api.py
More file actions
83 lines (74 loc) · 3.01 KB
/
test_api.py
File metadata and controls
83 lines (74 loc) · 3.01 KB
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
```python
"""
API Test Script
================
This script tests the API's functionality by performing health checks and batch predictions.
"""
import requests
import json
def test_api(base_url: str = "http://127.0.0.1:8000") -> None:
"""
Test the API's health and perform a batch prediction.
Args:
base_url (str, optional): The base URL of the API. Defaults to "http://127.0.0.1:8000".
Returns:
None
"""
# Test 1: Health check
print("Test 1: Checking API status (/health)...")
try:
# Send a GET request to the API's health endpoint
resp = requests.get(f"{base_url}/health", timeout=5)
print(f"Status: {resp.status_code}")
print(f"Response: {json.dumps(resp.json(), indent=2, ensure_ascii=False)}")
except requests.exceptions.ConnectionError:
# Handle connection errors
print("Error: API is not running!")
print("Start it first: python -m uvicorn src.api.main:app --reload")
return
except Exception as e:
# Handle any other exceptions
print(f"Error during health check: {e}")
return
# Test 2: Batch prediction
print("\nTest 2: Sentiment prediction (/predict_batch)...")
# Define a payload with sample comments
payload = {
"comments": [
{"id": "1", "text": "This video is amazing! I learned so much."},
{"id": "2", "text": "Terrible content, waste of time."},
{"id": "3", "text": "It was okay, nothing special."},
{"id": "4", "text": "I love this video, thank you so much!"},
{"id": "5", "text": "Not great content..."}
]
}
try:
# Send a POST request to the API's batch prediction endpoint
resp = requests.post(
f"{base_url}/predict_batch",
json=payload,
timeout=10
)
print(f"Status: {resp.status_code}")
if resp.status_code == 200:
# Parse the response JSON
result = resp.json()
print(f"\nStatistics:")
print(f" Total: {result['stats']['total']}")
print(f" Positive: {result['stats']['positive']} ({result['stats']['positive_pct']}%)")
print(f" Neutral: {result['stats']['neutral']} ({result['stats']['neutral_pct']}%)")
print(f" Negative: {result['stats']['negative']} ({result['stats']['negative_pct']}%)")
print(f"\nDetailed predictions:")
# Iterate over the predictions and print them
for pred in result['predictions']:
sentiment_label = "Positive" if pred['sentiment'] == 1 else ("Negative" if pred['sentiment'] == -1 else "Neutral")
print(f" [{pred['id']}] {sentiment_label} ({pred['confidence']*100:.1f}%): {pred['text'][:50]}...")
else:
# Handle non-200 status codes
print(f"Error: {resp.text}")
except Exception as e:
# Handle any other exceptions
print(f"Error during prediction: {e}")
if __name__ == "__main__":
test_api()
```