Spaces:
Running
Running
File size: 2,733 Bytes
1bd7c46 | 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 67 68 69 70 71 72 73 | """
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)
|