File size: 5,956 Bytes
eae62a9 |
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 |
"""
Test script for the Depth Pro Distance Estimation FastAPI app.
"""
import requests
import numpy as np
from PIL import Image
import io
import tempfile
def create_test_image():
"""Create a simple test image"""
# Create a gradient image that simulates depth
width, height = 512, 384
image = np.zeros((height, width, 3), dtype=np.uint8)
# Create horizontal gradient (simulating depth perspective)
for y in range(height):
intensity = int(255 * (1 - y / height))
image[y, :, :] = [intensity, intensity//2, intensity//3]
# Add some edge features
image[50:60, :, :] = [255, 255, 255] # Top horizontal line
image[height-60:height-50, :, :] = [255, 255, 255] # Bottom horizontal line
return Image.fromarray(image)
def test_web_interface():
"""Test the web interface (HTML page)"""
try:
# Test if server returns HTML page
response = requests.get('http://localhost:7860/', timeout=10)
if response.status_code == 200:
content = response.text
if "Depth Pro Distance Estimation" in content and "upload" in content.lower():
print("Web Interface Test:")
print("Status Code:", response.status_code)
print("Content-Type:", response.headers.get('content-type', 'N/A'))
print("Page Title Found: β
")
print("Upload Form Found: β
")
print("β
Web interface test passed!")
return True
else:
print("β Web interface content validation failed")
return False
else:
print(f"β Web interface test failed with status code: {response.status_code}")
return False
except requests.ConnectionError:
print("β οΈ FastAPI server not running. Start the server with: python app.py")
return False
except Exception as e:
print(f"β Web interface test failed: {e}")
return False
def test_fastapi_endpoint():
"""Test the FastAPI endpoint (requires running server)"""
try:
# Create test image
test_image = create_test_image()
# Convert to bytes
img_byte_arr = io.BytesIO()
test_image.save(img_byte_arr, format='JPEG')
img_byte_arr.seek(0)
# Test API endpoint (assuming server is running on localhost:7860)
files = {'file': ('test_image.jpg', img_byte_arr, 'image/jpeg')}
response = requests.post('http://localhost:7860/estimate-depth', files=files, timeout=30)
if response.status_code == 200:
result = response.json()
print("FastAPI Endpoint Test:")
print("Status Code:", response.status_code)
print("Response:", result)
print("β
FastAPI endpoint test passed!")
return True
else:
print(f"β FastAPI endpoint test failed with status code: {response.status_code}")
print("Response:", response.text)
return False
except requests.ConnectionError:
print("β οΈ FastAPI server not running. Start the server with: python app.py")
return False
except Exception as e:
print(f"β FastAPI endpoint test failed: {e}")
return False
def test_depth_estimator():
"""Test the DepthEstimator class directly"""
try:
from app import DepthEstimator, DummyDepthPipeline
# Initialize estimator with dummy pipeline for testing
dummy_pipeline = DummyDepthPipeline()
estimator = DepthEstimator(dummy_pipeline)
# Create test image file
test_image = create_test_image()
with tempfile.NamedTemporaryFile(suffix='.jpg', delete=False) as temp_file:
test_image.save(temp_file, format='JPEG')
temp_file_path = temp_file.name
# Test depth estimation
depth_map, new_size, focal_length = estimator.estimate_depth(temp_file_path)
print("Depth Estimator Test:")
print("Depth map shape:", depth_map.shape if depth_map is not None else "None")
print("New size:", new_size)
print("Focal length:", focal_length)
if depth_map is not None:
print("Depth stats:", {
"min": np.min(depth_map),
"max": np.max(depth_map),
"mean": np.mean(depth_map)
})
print("β
Depth estimator test passed!")
return True
else:
print("β Depth estimator returned None")
return False
except Exception as e:
print(f"β Depth estimator test failed: {e}")
return False
if __name__ == "__main__":
print("π§ͺ Testing Depth Pro Distance Estimation App\n")
# Run tests
tests = [
("Depth Estimator", test_depth_estimator),
("Web Interface", test_web_interface),
("FastAPI Endpoint", test_fastapi_endpoint),
]
results = []
for test_name, test_func in tests:
print(f"\n--- {test_name} Test ---")
try:
success = test_func()
results.append((test_name, success))
except Exception as e:
print(f"β {test_name} test crashed: {e}")
results.append((test_name, False))
# Summary
print("\n" + "="*50)
print("π Test Summary:")
print("="*50)
passed = 0
for test_name, success in results:
status = "β
PASSED" if success else "β FAILED"
print(f"{test_name}: {status}")
if success:
passed += 1
print(f"\nTests passed: {passed}/{len(results)}")
if passed == len(results):
print("π All tests passed! The app is ready to deploy.")
else:
print("β οΈ Some tests failed. Please check the errors above.")
|