forked from geopavlakos/hamer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_hammer_api.py
More file actions
256 lines (207 loc) · 8.81 KB
/
test_hammer_api.py
File metadata and controls
256 lines (207 loc) · 8.81 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
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
#!/usr/bin/env python3
"""
Test script for HaMeR Hand Tracking API
This script tests both endpoints of the API with example data.
"""
import base64
import json
import os
import requests
import time
from pathlib import Path
def test_health_check(base_url: str = "http://localhost:8000"):
"""Test the health check endpoint"""
print("🏥 Testing health check endpoint...")
try:
response = requests.get(f"{base_url}/health", timeout=10)
if response.status_code == 200:
result = response.json()
print(f"✅ Health check passed: {result}")
return True
else:
print(f"❌ Health check failed: {response.status_code}")
return False
except requests.RequestException as e:
print(f"❌ Health check failed: {e}")
return False
def test_directory_endpoint(
base_url: str = "http://localhost:8000", image_dir: str = "example_data"
):
"""Test the directory prediction endpoint"""
print("📁 Testing directory endpoint...")
# Check if directory exists
if not Path(image_dir).exists():
print(f"❌ Directory not found: {image_dir}")
return False
request_data = {
"image_directory": image_dir,
"file_extensions": ["*.jpg", "*.png", "*.jpeg"],
"rescale_factor": 2.0,
"body_detector": "vitdet",
}
try:
print(f" Sending request to process images in: {image_dir}")
response = requests.post(
f"{base_url}/predict_from_directory",
json=request_data,
timeout=120, # Longer timeout for model processing
)
if response.status_code == 200:
result = response.json()
print(f"✅ Directory prediction successful!")
print(f" Total images: {result['total_images']}")
print(f" Successful: {result['successful_predictions']}")
print(f" Failed: {result['failed_predictions']}")
# Print details for first few results
for i, img_result in enumerate(result["results"][:3]):
print(f" Image {i + 1}: {img_result['image_name']}")
print(f" Hands detected: {len(img_result['hands'])}")
for j, hand in enumerate(img_result["hands"]):
hand_type = "Right" if hand["is_right_hand"] else "Left"
print(f" Hand {j + 1}: {hand_type} hand")
print(f" Vertices: {len(hand['vertices'])} points")
print(f" Joints: {len(hand['joints'])} points")
# Validate prediction structure
is_valid, message = validate_prediction_structure(hand)
if is_valid:
print(f" ✅ Structure validation: {message}")
else:
print(f" ❌ Structure validation failed: {message}")
return False
return True
else:
print(f"❌ Directory prediction failed: {response.status_code}")
print(f" Response: {response.text}")
return False
except requests.RequestException as e:
print(f"❌ Directory prediction failed: {e}")
return False
def test_image_list_endpoint(
base_url: str = "http://localhost:8000",
test_image_path: str = "example_data/test1.jpg",
):
"""Test the image list prediction endpoint"""
print("🖼️ Testing image list endpoint...")
# Check if test image exists
if not Path(test_image_path).exists():
print(f"❌ Test image not found: {test_image_path}")
return False
# Encode image to base64
try:
with open(test_image_path, "rb") as f:
image_data = f.read()
image_b64 = base64.b64encode(image_data).decode("utf-8")
except Exception as e:
print(f"❌ Failed to encode image: {e}")
return False
request_data = {
"images_base64": [image_b64],
"image_names": [Path(test_image_path).name],
"rescale_factor": 2.0,
"body_detector": "vitdet",
}
try:
print(f" Sending base64 encoded image: {Path(test_image_path).name}")
response = requests.post(
f"{base_url}/predict_from_images",
json=request_data,
timeout=120, # Longer timeout for model processing
)
if response.status_code == 200:
result = response.json()
print(f"✅ Image list prediction successful!")
print(f" Total images: {result['total_images']}")
print(f" Successful: {result['successful_predictions']}")
print(f" Failed: {result['failed_predictions']}")
# Print details for the result
if result["results"]:
img_result = result["results"][0]
print(f" Image: {img_result['image_name']}")
print(f" Hands detected: {len(img_result['hands'])}")
for j, hand in enumerate(img_result["hands"]):
hand_type = "Right" if hand["is_right_hand"] else "Left"
print(f" Hand {j + 1}: {hand_type} hand")
print(f" Vertices: {len(hand['vertices'])} points")
print(f" Joints: {len(hand['joints'])} points")
print(f" Confidence: {hand['confidence_score']}")
# Validate prediction structure
is_valid, message = validate_prediction_structure(hand)
if is_valid:
print(f" ✅ Structure validation: {message}")
else:
print(f" ❌ Structure validation failed: {message}")
return False
return True
else:
print(f"❌ Image list prediction failed: {response.status_code}")
print(f" Response: {response.text}")
return False
except requests.RequestException as e:
print(f"❌ Image list prediction failed: {e}")
return False
def validate_prediction_structure(hand_prediction: dict):
"""Validate the structure of a hand prediction"""
required_fields = ["vertices", "joints", "is_right_hand", "confidence_score"]
for field in required_fields:
if field not in hand_prediction:
return False, f"Missing field: {field}"
# Check vertices structure (should be 778x3)
vertices = hand_prediction["vertices"]
if not isinstance(vertices, list) or len(vertices) != 778:
return (
False,
f"Invalid vertices structure: expected 778 points, got {len(vertices)}",
)
if len(vertices) > 0 and len(vertices[0]) != 3:
return (
False,
f"Invalid vertex dimension: expected 3D points, got {len(vertices[0])}D",
)
# Check joints structure (should be 21x3)
joints = hand_prediction["joints"]
if not isinstance(joints, list) or len(joints) != 21:
return False, f"Invalid joints structure: expected 21 points, got {len(joints)}"
if len(joints) > 0 and len(joints[0]) != 3:
return (
False,
f"Invalid joint dimension: expected 3D points, got {len(joints[0])}D",
)
return True, "Valid structure"
def main():
"""Run all API tests"""
print("🚀 Starting HaMeR API Tests")
print("📝 Note: This tests the refactored API which now uses the modular inference engine")
print("=" * 50)
base_url = "http://localhost:8000"
# Wait for server to be ready
print("⏳ Waiting for server to be ready...")
max_retries = 30
for i in range(max_retries):
if test_health_check(base_url):
break
if i < max_retries - 1:
print(f" Retrying in 2 seconds... ({i + 1}/{max_retries})")
time.sleep(2)
else:
print("❌ Server not ready after 60 seconds")
print("💡 Start the server with: python hamer_api.py")
return
print("\n" + "=" * 50)
# Test directory endpoint
success_dir = test_directory_endpoint(base_url)
print("\n" + "=" * 50)
# Test image list endpoint
success_img = test_image_list_endpoint(base_url)
print("\n" + "=" * 50)
print("📊 Test Summary:")
print(f" Health Check: ✅")
print(f" Directory Endpoint: {'✅' if success_dir else '❌'}")
print(f" Image List Endpoint: {'✅' if success_img else '❌'}")
if success_dir and success_img:
print("\n🎉 All API tests passed!")
print("✅ The refactored API maintains full backward compatibility!")
print("\n💡 Try the new library interface with: python test_hamer_library.py")
else:
print("\n⚠️ Some tests failed. Check the output above for details.")
if __name__ == "__main__":
main()