File size: 5,605 Bytes
d2693ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Simple script to save annotated images from the Marine Species API.
No external dependencies required - uses only Python standard library.
"""

import requests
import base64
import json
import time
from pathlib import Path
import sys


def encode_image_to_base64(image_path: str) -> str:
    """Encode an image file to base64 string."""
    try:
        with open(image_path, "rb") as image_file:
            return base64.b64encode(image_file.read()).decode('utf-8')
    except Exception as e:
        print(f"Error encoding image {image_path}: {e}")
        return None


def save_base64_image(base64_string: str, output_path: str) -> bool:
    """Save a base64 encoded image to a file."""
    try:
        # Decode base64 to bytes
        image_bytes = base64.b64decode(base64_string)
        
        # Save directly to file
        with open(output_path, 'wb') as f:
            f.write(image_bytes)
        
        print(f"βœ… Saved annotated image: {output_path}")
        return True
        
    except Exception as e:
        print(f"❌ Failed to save image: {e}")
        return False


def process_image(api_url: str, image_path: str, output_dir: str):
    """Process an image and save the annotated result."""
    
    image_name = Path(image_path).stem
    print(f"\n🐟 Processing {Path(image_path).name}")
    print("-" * 50)
    
    # Encode input image
    print("πŸ“· Encoding image...")
    image_b64 = encode_image_to_base64(image_path)
    if not image_b64:
        return None
    
    # API request
    detection_request = {
        "image": image_b64,
        "confidence_threshold": 0.25,
        "iou_threshold": 0.45,
        "image_size": 640,
        "return_annotated_image": True
    }
    
    try:
        print("πŸ” Sending detection request...")
        start_time = time.time()
        
        response = requests.post(
            f"{api_url}/api/v1/detect",
            json=detection_request,
            timeout=60
        )
        
        request_time = time.time() - start_time
        print(f"⏱️  Request completed in {request_time:.2f}s")
        
        if response.status_code == 200:
            result = response.json()
            
            detections = result.get('detections', [])
            processing_time = result.get('processing_time', 0)
            annotated_image_b64 = result.get('annotated_image')
            
            print(f"βœ… SUCCESS!")
            print(f"   Processing Time: {processing_time:.3f}s")
            print(f"   Detections Found: {len(detections)}")
            
            # Show detections
            if detections:
                print(f"   🎯 Detected Species:")
                for i, detection in enumerate(detections[:5]):
                    species = detection.get('class_name', 'Unknown')
                    confidence = detection.get('confidence', 0)
                    print(f"      {i+1}. {species} ({confidence:.1%})")
            
            # Save annotated image
            if annotated_image_b64:
                output_path = Path(output_dir) / f"{image_name}_annotated.jpg"
                success = save_base64_image(annotated_image_b64, str(output_path))
                
                if success:
                    return str(output_path)
            else:
                print("   ❌ No annotated image returned")
                
        else:
            print(f"❌ Request failed: {response.status_code}")
            
    except Exception as e:
        print(f"❌ Request failed: {e}")
    
    return None


def main():
    """Main function."""
    api_url = "https://seamo-ai-fishapi.hf.space"
    
    print("🐟 Marine Species API - Save Annotated Images")
    print("=" * 60)
    
    # Create output directory
    output_dir = Path("annotated_results")
    output_dir.mkdir(exist_ok=True)
    print(f"πŸ“ Output directory: {output_dir.absolute()}")
    
    # Find test images
    image_dir = Path("docs/gradio/images")
    if not image_dir.exists():
        print(f"\n❌ Image directory not found: {image_dir}")
        return
    
    # Get image files
    image_files = []
    for ext in ['*.png', '*.jpg', '*.jpeg']:
        image_files.extend(image_dir.glob(ext))
    
    if not image_files:
        print(f"\n❌ No images found in {image_dir}")
        return
    
    print(f"πŸ“· Found {len(image_files)} test images")
    
    # Process each image
    saved_images = []
    for image_path in sorted(image_files):
        result_path = process_image(api_url, str(image_path), str(output_dir))
        if result_path:
            saved_images.append(result_path)
        time.sleep(1)
    
    # Summary
    print("\n" + "=" * 60)
    print(f"🎯 Results:")
    print(f"   πŸ“· Processed: {len(image_files)} images")
    print(f"   πŸ’Ύ Saved: {len(saved_images)} annotated images")
    
    if saved_images:
        print(f"\nπŸ–ΌοΈ  Annotated images saved:")
        for img_path in saved_images:
            print(f"   πŸ“„ {img_path}")
        
        print(f"\nπŸ’‘ To view the annotated images:")
        print(f"   πŸ–₯️  macOS: open {output_dir}")
        print(f"   🐧 Linux: xdg-open {output_dir}")
        print(f"   πŸͺŸ Windows: explorer {output_dir}")
        print(f"   πŸ“‚ Or browse to: {output_dir.absolute()}")
        
        print(f"\nπŸ” The images show:")
        print(f"   β€’ Bounding boxes around detected marine species")
        print(f"   β€’ Species names and confidence scores")
        print(f"   β€’ Color-coded detection results")


if __name__ == "__main__":
    main()