#!/usr/bin/env python3 """ Script to test the Marine Species API and save annotated images for viewing. """ import requests import base64 import json import time from pathlib import Path import sys from PIL import Image import io 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) # Open with PIL and save image = Image.open(io.BytesIO(image_bytes)) image.save(output_path) print(f"āœ… Saved annotated image: {output_path}") return True except Exception as e: print(f"āŒ Failed to save image: {e}") return False def test_and_save_annotated_image(api_url: str, image_path: str, output_dir: str): """Test API with 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 False # Prepare 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 top detections if detections: print(f" šŸŽÆ Top Detections:") for i, detection in enumerate(detections[:3]): species = detection.get('class_name', 'Unknown') confidence = detection.get('confidence', 0) print(f" {i+1}. {species} (confidence: {confidence:.3f})") # 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: print(f" šŸ–¼ļø View annotated image: {output_path}") return str(output_path) else: print(" āŒ No annotated image returned") else: print(f"āŒ Request failed with status {response.status_code}") print(f" Response: {response.text}") except Exception as e: print(f"āŒ Request failed: {e}") return None def main(): """Main function.""" # API URL api_url = sys.argv[1] if len(sys.argv) > 1 else "https://seamo-ai-fishapi.hf.space" print("🐟 Marine Species API - Annotated Image Viewer") print("=" * 60) print(f"API URL: {api_url}") # 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 image files found in {image_dir}") return print(f"\nšŸ“ Found {len(image_files)} test images") # Process each image saved_images = [] for image_path in sorted(image_files): result_path = test_and_save_annotated_image(api_url, str(image_path), str(output_dir)) if result_path: saved_images.append(result_path) time.sleep(1) # Small delay between requests # Summary print("\n" + "=" * 60) print(f"šŸŽÆ Summary:") print(f" Processed: {len(image_files)} images") print(f" Saved: {len(saved_images)} annotated images") if saved_images: print(f"\nšŸ–¼ļø Annotated images saved to:") for img_path in saved_images: print(f" - {img_path}") print(f"\nšŸ’” To view the images:") print(f" - Open the files in any image viewer") print(f" - Or run: open {output_dir}") # macOS print(f" - Or run: xdg-open {output_dir}") # Linux print(f" - Or navigate to: {output_dir.absolute()}") if __name__ == "__main__": main()