File size: 5,099 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
"""
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()