File size: 2,102 Bytes
6b556be b9cbaa2 6b556be | 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 | import cloudinary
import cloudinary.uploader
import cloudinary.api
import numpy as np
import io
from PIL import Image
from app.config import config
# Initialize Cloudinary if available
cloudinary_available = False
def initialize_cloudinary():
"""Initialize Cloudinary configuration"""
global cloudinary_available
try:
if config.ENABLE_CLOUDINARY and all([
config.CLOUDINARY_CLOUD_NAME,
config.CLOUDINARY_API_KEY,
config.CLOUDINARY_API_SECRET
]):
cloudinary.config(
cloud_name=config.CLOUDINARY_CLOUD_NAME,
api_key=config.CLOUDINARY_API_KEY,
api_secret=config.CLOUDINARY_API_SECRET
)
# Test configuration
cloudinary.api.ping()
cloudinary_available = True
print("Cloudinary configured successfully")
else:
print("Cloudinary not configured - using base64 images")
except Exception as e:
print(f"Cloudinary configuration failed: {e}")
cloudinary_available = False
async def upload_to_cloudinary(image_np: np.ndarray, folder: str, public_id: str) -> str:
"""Upload image to Cloudinary"""
if not cloudinary_available:
raise RuntimeError("Cloudinary not available")
try:
# Convert numpy array to bytes
if len(image_np.shape) == 2: # Grayscale
image_pil = Image.fromarray(image_np, mode='L')
else: # RGB
image_pil = Image.fromarray(image_np.astype(np.uint8))
buffer = io.BytesIO()
image_pil.save(buffer, format='PNG')
buffer.seek(0)
# Upload to Cloudinary
result = cloudinary.uploader.upload(
buffer.getvalue(),
folder=folder,
public_id=public_id,
resource_type="image"
)
return result['secure_url']
except Exception as e:
print(f"Cloudinary upload error: {e}")
raise
def is_cloudinary_available() -> bool:
"""Check if Cloudinary is available"""
return cloudinary_available |