Spaces:
Running
Running
Download app/utils/image_storage.py from Isaac105/melodix-api: direct link, hf CLI and curl.
- Browser
- Download file 2.73 kB
-
https://huggingface.co/spaces/Isaac105/melodix-api/resolve/main/app/utils/image_storage.py
- Command line
-
hf download hf://spaces/Isaac105/melodix-api/app/utils/image_storage.py
-
curl -L -o image_storage.py https://huggingface.co/spaces/Isaac105/melodix-api/resolve/main/app/utils/image_storage.py
2.73 kB
| """ | |
| Imágenes globales de Melodix (avatares, portadas, fotos de grupos, imágenes del panel) | |
| guardadas en un dataset propio de Hugging Face, separado de los stems para que sus | |
| commits no compitan con el límite de commits por hora del dataset de stems. | |
| Las imágenes de cada iglesia NO pasan por aquí: siguen en la cuenta de ImgBB de la iglesia. | |
| """ | |
| import os | |
| import base64 | |
| import logging | |
| import uuid | |
| from huggingface_hub import HfApi | |
| from app.utils.imgbb import compress_base64_image | |
| logger = logging.getLogger(__name__) | |
| HF_IMAGES_REPO = os.getenv("HF_IMAGES_REPO", "Isaac105/melodix-images") | |
| MAX_IMAGE_BASE64_CHARS = 43 * 1024 * 1024 # ~32 MB de imagen | |
| def _detect_extension(data: bytes): | |
| """Identifica el formato por su firma; solo se aceptan imágenes.""" | |
| if data.startswith(b'\x89PNG'): | |
| return 'png' | |
| if data.startswith(b'\xff\xd8\xff'): | |
| return 'jpg' | |
| if data.startswith(b'GIF8'): | |
| return 'gif' | |
| if data[:4] == b'RIFF' and data[8:12] == b'WEBP': | |
| return 'webp' | |
| return None | |
| def get_image_url(path_in_repo: str) -> str: | |
| return f"https://huggingface.co/datasets/{HF_IMAGES_REPO}/resolve/main/{path_in_repo}" | |
| def upload_global_image(base64_str: str, folder: str, compress: bool = False) -> str: | |
| """ | |
| Sube una imagen en base64 (con o sin prefijo data:) y devuelve su URL pública. | |
| Si ya es una URL, se retorna tal cual. Con compress=True se reduce a 800px en JPEG. | |
| Lanza ValueError si no es una imagen válida o si la subida falla. | |
| """ | |
| if base64_str.startswith("http://") or base64_str.startswith("https://"): | |
| return base64_str | |
| clean_base64 = base64_str.split(",", 1)[1] if "," in base64_str else base64_str | |
| if compress: | |
| clean_base64 = compress_base64_image(clean_base64) | |
| try: | |
| data = base64.b64decode(clean_base64) | |
| except Exception: | |
| raise ValueError("La imagen no tiene un formato válido.") | |
| ext = _detect_extension(data) | |
| if not ext: | |
| raise ValueError("El archivo no es una imagen PNG, JPG, GIF o WEBP.") | |
| token = os.getenv("HF_TOKEN") | |
| if not token: | |
| raise ValueError("HF_TOKEN no está configurado: no se pueden guardar imágenes.") | |
| path_in_repo = f"{folder}/{uuid.uuid4().hex}.{ext}" | |
| try: | |
| HfApi(token=token).upload_file( | |
| path_or_fileobj=data, | |
| path_in_repo=path_in_repo, | |
| repo_id=HF_IMAGES_REPO, | |
| repo_type="dataset", | |
| commit_message=f"Subir {path_in_repo}" | |
| ) | |
| except Exception as e: | |
| logger.error(f"Error subiendo imagen {path_in_repo} a Hugging Face: {e}") | |
| raise ValueError("No se pudo guardar la imagen. Intenta de nuevo.") | |
| return get_image_url(path_in_repo) | |