forked from dbhavnakhatri/BreastCancerDetect_finalcodee
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_api.py
More file actions
174 lines (132 loc) ยท 4.95 KB
/
test_api.py
File metadata and controls
174 lines (132 loc) ยท 4.95 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
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
#!/usr/bin/env python3
"""
Test script for Breast Cancer Detection API
Tests both local and deployed versions
"""
import requests
import sys
from pathlib import Path
# Configuration
LOCAL_URL = "http://localhost:7860"
DEPLOYED_URL = "https://bhavanakhatri-breastcancerdetection.hf.space"
def test_health(base_url):
"""Test health endpoint"""
print(f"\n๐ฅ Testing health endpoint: {base_url}/health")
try:
response = requests.get(f"{base_url}/health", timeout=10)
response.raise_for_status()
data = response.json()
print(f"โ
Status: {data['status']}")
print(f"โ
Model Status: {data['model_status']}")
if data['model_status'] != 'loaded':
print(f"โ ๏ธ Warning: {data.get('model_error', 'Unknown error')}")
return False
return True
except Exception as e:
print(f"โ Health check failed: {e}")
return False
def test_prediction(base_url, image_path):
"""Test prediction endpoint"""
print(f"\n๐ฎ Testing prediction: {base_url}/predict")
if not Path(image_path).exists():
print(f"โ ๏ธ Image file not found: {image_path}")
print(" Skipping prediction test...")
return False
try:
with open(image_path, 'rb') as f:
files = {'file': f}
response = requests.post(
f"{base_url}/predict",
files=files,
timeout=30
)
response.raise_for_status()
data = response.json()
print(f"โ
Prediction: {data['prediction']}")
print(f"โ
Confidence: {data['confidence']:.2%}")
print(f"โ
Risk Level: {data['risk_assessment']['level']}")
print(f" Benign: {data['probabilities']['benign']:.2f}%")
print(f" Malignant: {data['probabilities']['malignant']:.2f}%")
return True
except Exception as e:
print(f"โ Prediction failed: {e}")
return False
def test_batch_prediction(base_url, image_paths):
"""Test batch prediction endpoint"""
print(f"\n๐ฆ Testing batch prediction: {base_url}/batch-predict")
# Filter existing files
existing_files = [p for p in image_paths if Path(p).exists()]
if not existing_files:
print("โ ๏ธ No image files found. Skipping batch test...")
return False
try:
files = [('files', open(p, 'rb')) for p in existing_files]
response = requests.post(
f"{base_url}/batch-predict",
files=files,
timeout=60
)
# Close file handles
for _, f in files:
f.close()
response.raise_for_status()
data = response.json()
print(f"โ
Total images: {data['total_images']}")
print(f"โ
Successful: {data['successful']}")
print(f"โ
Summary:")
print(f" Benign: {data['summary']['benign']}")
print(f" Malignant: {data['summary']['malignant']}")
return True
except Exception as e:
print(f"โ Batch prediction failed: {e}")
return False
def main():
"""Main test function"""
print("=" * 60)
print("๐งช Breast Cancer Detection API - Test Suite")
print("=" * 60)
# Determine which API to test
if len(sys.argv) > 1:
if sys.argv[1] == "local":
base_url = LOCAL_URL
print("\n๐ Testing LOCAL API")
elif sys.argv[1] == "deployed":
base_url = DEPLOYED_URL
print("\n๐ Testing DEPLOYED API")
else:
base_url = sys.argv[1]
print(f"\n๐ Testing CUSTOM URL: {base_url}")
else:
# Default to local
base_url = LOCAL_URL
print("\n๐ Testing LOCAL API (use 'deployed' for production)")
print(f"URL: {base_url}")
print("=" * 60)
# Test health
health_ok = test_health(base_url)
if not health_ok:
print("\nโ Health check failed. Stopping tests.")
sys.exit(1)
# Test single prediction
test_image = "test_image.jpg"
if Path(test_image).exists():
test_prediction(base_url, test_image)
else:
print(f"\nโ ๏ธ Test image not found: {test_image}")
print(" Create a test image to test prediction endpoint")
# Test batch prediction
test_images = ["test1.jpg", "test2.jpg", "test3.jpg"]
existing_images = [img for img in test_images if Path(img).exists()]
if existing_images:
test_batch_prediction(base_url, existing_images)
else:
print("\nโ ๏ธ No test images found for batch prediction test")
print("\n" + "=" * 60)
print("โ
Testing complete!")
print("=" * 60)
print("\n๐ View API documentation:")
print(f" {base_url}/")
print("\n๐ ReDoc documentation:")
print(f" {base_url}/redoc")
if __name__ == "__main__":
main()