-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_api_client.py
More file actions
150 lines (122 loc) · 5.07 KB
/
test_api_client.py
File metadata and controls
150 lines (122 loc) · 5.07 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
#!/usr/bin/env python3
"""
🐟 Fish Detection API Test Client
Test script for the Fish Detection API
"""
import requests
import json
import os
import time
from pathlib import Path
# API Configuration
API_BASE_URL = "http://localhost:8000"
API_ENDPOINT = f"{API_BASE_URL}/detect-fish-speed"
HEALTH_ENDPOINT = f"{API_BASE_URL}/health"
def test_api_health():
"""Test if the API is running"""
try:
print("🔍 Testing API health...")
response = requests.get(HEALTH_ENDPOINT)
if response.status_code == 200:
print("✅ API is healthy!")
print(f" Response: {response.json()}")
return True
else:
print(f"❌ API health check failed: {response.status_code}")
return False
except requests.exceptions.ConnectionError:
print("❌ Cannot connect to API. Make sure the server is running.")
return False
except Exception as e:
print(f"❌ Health check error: {e}")
return False
def find_video_files():
"""Find video files in the current directory"""
video_extensions = ['.mp4', '.avi', '.mov', '.mkv', '.wmv']
video_files = []
for ext in video_extensions:
video_files.extend(Path('.').glob(f'*{ext}'))
video_files.extend(Path('.').glob(f'*{ext.upper()}'))
return video_files
def test_fish_detection(video_path, sensitivity='medium', max_frames=500):
"""Test fish detection with a video file"""
print(f"\n🎬 Testing fish detection with: {video_path}")
print(f" Sensitivity: {sensitivity}")
print(f" Max frames: {max_frames}")
# Prepare the file
files = {
'file': (video_path.name, open(video_path, 'rb'), 'video/mp4')
}
# Prepare the data
data = {
'sensitivity': sensitivity,
'max_frames': max_frames
}
try:
print("📤 Uploading video and starting detection...")
start_time = time.time()
response = requests.post(
API_ENDPOINT,
files=files,
data=data,
timeout=300 # 5 minute timeout
)
processing_time = time.time() - start_time
if response.status_code == 200:
result = response.json()
print(f"✅ Detection completed in {processing_time:.2f} seconds!")
print("\n📊 Results:")
print(f" 🐟 Average Speed: {result['detection_results']['average_speed_pixels_per_second']:.2f} pixels/second")
print(f" 🏃 Maximum Speed: {result['detection_results']['maximum_speed_pixels_per_second']:.2f} pixels/second")
print(f" 🐌 Minimum Speed: {result['detection_results']['minimum_speed_pixels_per_second']:.2f} pixels/second")
print(f" 🎯 Unique Fish Detected: {result['detection_results']['unique_fish_detected']}")
print(f" 📈 Total Detections: {result['detection_results']['total_fish_detections']}")
print(f" 🎬 Processed Frames: {result['video_info']['processed_frames']}")
print(f" ⏱️ Processing Time: {result['video_info']['processing_time_seconds']:.2f} seconds")
return result
else:
print(f"❌ Detection failed: {response.status_code}")
print(f" Error: {response.text}")
return None
except requests.exceptions.Timeout:
print("❌ Request timed out. The video might be too long or complex.")
return None
except Exception as e:
print(f"❌ Error during detection: {e}")
return None
finally:
files['file'][1].close()
def main():
"""Main test function"""
print("🐟 Fish Detection API Test Client")
print("=" * 40)
# Test API health
if not test_api_health():
print("\n❌ API is not available. Please start the server first:")
print(" ./start_api.sh")
return
# Find video files
video_files = find_video_files()
if not video_files:
print("\n❌ No video files found in the current directory.")
print(" Please add a video file (.mp4, .avi, .mov, .mkv, .wmv)")
return
print(f"\n📁 Found {len(video_files)} video file(s):")
for i, video_file in enumerate(video_files, 1):
print(f" {i}. {video_file.name}")
# Test with the first video file
test_video = video_files[0]
print(f"\n🎯 Testing with: {test_video.name}")
# Test different sensitivity levels
sensitivities = ['low', 'medium', 'high']
for sensitivity in sensitivities:
print(f"\n{'='*20} Testing {sensitivity.upper()} sensitivity {'='*20}")
result = test_fish_detection(test_video, sensitivity=sensitivity, max_frames=300)
if result:
print(f"✅ {sensitivity.capitalize()} sensitivity test completed successfully!")
else:
print(f"❌ {sensitivity.capitalize()} sensitivity test failed!")
time.sleep(2) # Wait between tests
print("\n🎉 All tests completed!")
if __name__ == "__main__":
main()