pf-depth / example_usage.py
jay208's picture
1.0.0
eae62a9
"""
Example usage of the Depth Pro Distance Estimation API.
This script demonstrates how to use both the Gradio interface and FastAPI endpoints.
"""
import requests
import numpy as np
from PIL import Image
import io
import json
def create_sample_image():
"""Create a sample image for testing"""
width, height = 640, 480
# Create a perspective-like image
image = np.zeros((height, width, 3), dtype=np.uint8)
# Background gradient (sky to ground)
for y in range(height):
sky_intensity = max(0, 255 - int(255 * y / height))
ground_intensity = min(255, int(128 * y / height))
image[y, :, 0] = sky_intensity # Red channel
image[y, :, 1] = sky_intensity # Green channel
image[y, :, 2] = sky_intensity + ground_intensity # Blue channel
# Add some structural elements
# Horizontal lines to simulate path edges
image[height//3:height//3+10, :, :] = [255, 255, 255] # Top edge
image[2*height//3:2*height//3+10, :, :] = [200, 200, 200] # Middle
image[height-50:height-40, :, :] = [150, 150, 150] # Bottom edge
# Vertical elements
image[:, width//4:width//4+5, :] = [100, 100, 100] # Left
image[:, 3*width//4:3*width//4+5, :] = [100, 100, 100] # Right
return Image.fromarray(image)
def test_api_endpoint(base_url="http://localhost:7860"):
"""Test the FastAPI endpoint"""
print("πŸ§ͺ Testing FastAPI Endpoint")
print("=" * 40)
try:
# Create sample image
sample_image = create_sample_image()
# Convert to bytes
img_byte_arr = io.BytesIO()
sample_image.save(img_byte_arr, format='JPEG', quality=95)
img_byte_arr.seek(0)
# Make API request
files = {'file': ('sample_image.jpg', img_byte_arr, 'image/jpeg')}
print(f"Sending request to {base_url}/estimate-depth...")
response = requests.post(f'{base_url}/estimate-depth', files=files, timeout=60)
if response.status_code == 200:
result = response.json()
print("βœ… API Request Successful!")
print("\nResults:")
print(f" πŸ“ Distance: {result.get('distance_meters', 'N/A')} meters")
print(f" 🎯 Focal Length: {result.get('focal_length_px', 'N/A')} pixels")
print(f" πŸ“Š Depth Map Shape: {result.get('depth_map_shape', 'N/A')}")
print(f" πŸ” Top Pixel: {result.get('topmost_pixel', 'N/A')}")
print(f" πŸ”½ Bottom Pixel: {result.get('bottommost_pixel', 'N/A')}")
depth_stats = result.get('depth_stats', {})
if depth_stats:
print(f" πŸ“ˆ Depth Range: {depth_stats.get('min_depth', 0):.2f}m - {depth_stats.get('max_depth', 0):.2f}m")
print(f" πŸ“Š Mean Depth: {depth_stats.get('mean_depth', 0):.2f}m")
return True
else:
print(f"❌ API Request Failed!")
print(f"Status Code: {response.status_code}")
print(f"Response: {response.text}")
return False
except requests.exceptions.ConnectionError:
print("❌ Connection Error!")
print("Make sure the server is running with: python app.py")
return False
except Exception as e:
print(f"❌ Unexpected Error: {e}")
return False
def save_sample_image():
"""Save a sample image for manual testing"""
sample_image = create_sample_image()
filename = "sample_test_image.jpg"
sample_image.save(filename, quality=95)
print(f"πŸ’Ύ Sample image saved as '{filename}'")
print("You can upload this image to test the Gradio interface manually.")
return filename
def main():
"""Main function to run examples"""
print("πŸš€ Depth Pro Distance Estimation - Example Usage")
print("=" * 55)
print()
# Save sample image
sample_file = save_sample_image()
print()
# Test API if server is running
print("Testing API endpoint...")
api_success = test_api_endpoint()
print()
if not api_success:
print("πŸ’‘ To test the API:")
print("1. Run: python app.py")
print("2. Wait for 'Running on http://0.0.0.0:7860'")
print("3. Run this script again")
print()
print("πŸ’‘ To test the web interface:")
print("1. Run: python app.py")
print("2. Open http://localhost:7860 in your browser")
print(f"3. Upload the generated image: {sample_file}")
print()
print("🌐 For Hugging Face Spaces deployment:")
print("1. Create a new Space on https://huggingface.co/spaces")
print("2. Choose 'Docker' as the SDK")
print("3. Upload all files from this directory")
print("4. The Space will automatically build and deploy")
print()
print("πŸ“ Example curl command:")
print("curl -X POST http://localhost:7860/estimate-depth \\")
print(f" -F 'file=@{sample_file}' \\")
print(" -H 'Content-Type: multipart/form-data'")
if __name__ == "__main__":
main()