Download app/cloudinary_utils.py from Mohamed424/stroke-segmentation-backend: direct link, hf CLI and curl.
- Browser
- Download file 2.1 kB
-
https://huggingface.co/spaces/Mohamed424/stroke-segmentation-backend/resolve/main/app/cloudinary_utils.py
- Command line
-
hf download hf://spaces/Mohamed424/stroke-segmentation-backend/app/cloudinary_utils.py
-
curl -L -o cloudinary_utils.py https://huggingface.co/spaces/Mohamed424/stroke-segmentation-backend/resolve/main/app/cloudinary_utils.py
2.1 kB
| 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 |