| import base64
|
| import numpy as np
|
| from PIL import Image
|
| import io
|
| from math import radians, cos, sin, asin, sqrt
|
|
|
| def base64_to_image(base64_string):
|
| """Convert base64 string to PIL Image"""
|
| try:
|
|
|
| if ',' in base64_string:
|
| base64_string = base64_string.split(',')[1]
|
|
|
|
|
| image_data = base64.b64decode(base64_string)
|
| image = Image.open(io.BytesIO(image_data))
|
|
|
|
|
| if image.mode != 'RGB':
|
| image = image.convert('RGB')
|
|
|
| return image
|
| except Exception as e:
|
| raise ValueError(f"Failed to decode base64 image: {str(e)}")
|
|
|
|
|
| def image_to_numpy(image):
|
| """Convert PIL Image to numpy array"""
|
| return np.array(image)
|
|
|
|
|
| def haversine_distance(lat1, lon1, lat2, lon2):
|
| """
|
| Calculate the great circle distance between two points
|
| on the earth (specified in decimal degrees)
|
| Returns distance in meters
|
| """
|
|
|
| lat1, lon1, lat2, lon2 = map(radians, [lat1, lon1, lat2, lon2])
|
|
|
|
|
| dlat = lat2 - lat1
|
| dlon = lon2 - lon1
|
| a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
|
| c = 2 * asin(sqrt(a))
|
|
|
|
|
| r = 6371000
|
|
|
| return c * r
|
|
|
|
|
| def format_error_response(message, code=400):
|
| """Format error response"""
|
| return {
|
| 'success': False,
|
| 'error': message
|
| }, code
|
|
|
|
|
| def format_success_response(data=None, message=None):
|
| """Format success response"""
|
| response = {'success': True}
|
| if message:
|
| response['message'] = message
|
| if data:
|
| response['data'] = data
|
| return response, 200
|
|
|
|
|
| def validate_coordinates(latitude, longitude):
|
| """Validate GPS coordinates"""
|
| try:
|
| lat = float(latitude)
|
| lon = float(longitude)
|
|
|
| if not (-90 <= lat <= 90):
|
| return False, "Latitude must be between -90 and 90"
|
| if not (-180 <= lon <= 180):
|
| return False, "Longitude must be between -180 and 180"
|
|
|
| return True, None
|
| except (ValueError, TypeError):
|
| return False, "Invalid coordinate format"
|
|
|