Spaces:
Running
Running
Download app/utils/subidas_worker.py from Isaac105/melodix-api: direct link, hf CLI and curl.
- Browser
- Download file 4.03 kB
-
https://huggingface.co/spaces/Isaac105/melodix-api/resolve/main/app/utils/subidas_worker.py
- Command line
-
hf download hf://spaces/Isaac105/melodix-api/app/utils/subidas_worker.py
-
curl -L -o subidas_worker.py https://huggingface.co/spaces/Isaac105/melodix-api/resolve/main/app/utils/subidas_worker.py
4.03 kB
| """ | |
| Subida de pistas de los workers residenciales: el equipo no tiene token de Hugging Face. | |
| El equipo manda cada archivo a la API, que lo guarda en una carpeta temporal y, al confirmar, lo sube | |
| al dataset con su propio token. Solo se aceptan archivos de canciones que ese equipo está procesando. | |
| El commit a Hugging Face puede tardar minutos, así que corre en un hilo y el equipo consulta el resultado. | |
| """ | |
| import logging | |
| import os | |
| import re | |
| import shutil | |
| import tempfile | |
| import threading | |
| import time | |
| import uuid | |
| logger = logging.getLogger(__name__) | |
| CARPETA = os.path.join(tempfile.gettempdir(), "melodix_subidas") | |
| NOMBRE_VALIDO = re.compile(r"^[A-Za-z0-9_\-]{1,60}\.(m4a|flac|json)$") | |
| TAMANO_MAXIMO = 300 * 1024 * 1024 | |
| MAX_ARCHIVOS = 40 | |
| HORAS_CONSERVAR = 6 | |
| SEGUNDOS_RESULTADO = 3600 | |
| _lotes = {} | |
| _lock = threading.Lock() | |
| # Un commit a la vez: el dataset rechaza commits simultáneos y tiene límite por hora | |
| _lock_commit = threading.Lock() | |
| class SubidaInvalida(Exception): | |
| pass | |
| def carpeta_de(task_id: str) -> str: | |
| return os.path.join(CARPETA, task_id) | |
| def validar_nombre(nombre: str): | |
| if not isinstance(nombre, str) or not NOMBRE_VALIDO.match(nombre): | |
| raise SubidaInvalida(f"Nombre de archivo no permitido: {nombre}") | |
| def ruta_destino(task_id: str, nombre: str) -> str: | |
| validar_nombre(nombre) | |
| carpeta = carpeta_de(task_id) | |
| os.makedirs(carpeta, exist_ok=True) | |
| if len(os.listdir(carpeta)) >= MAX_ARCHIVOS and not os.path.exists(os.path.join(carpeta, nombre)): | |
| raise SubidaInvalida("Demasiados archivos para esta canción") | |
| return os.path.join(carpeta, nombre) | |
| def _purgar_viejos(): | |
| limite = time.time() - HORAS_CONSERVAR * 3600 | |
| try: | |
| for nombre in os.listdir(CARPETA): | |
| ruta = os.path.join(CARPETA, nombre) | |
| if os.path.getmtime(ruta) < limite: | |
| shutil.rmtree(ruta, ignore_errors=True) | |
| except OSError: | |
| pass | |
| with _lock: | |
| for lote in [k for k, v in _lotes.items() if time.time() - v["t"] > SEGUNDOS_RESULTADO]: | |
| del _lotes[lote] | |
| def _subir(lote: str, task_id: str, archivos: list, mensaje: str): | |
| from app.utils.hf_storage import upload_many_to_hf | |
| try: | |
| with _lock_commit: | |
| urls = upload_many_to_hf(archivos, commit_message=mensaje) | |
| resultado = {"estado": "listo", "urls": urls, "t": time.time()} | |
| except Exception as e: | |
| logger.error(f"[{task_id}] No se pudieron subir las pistas al dataset: {e}") | |
| resultado = {"estado": "error", "urls": {}, "t": time.time()} | |
| for ruta, _ in archivos: | |
| try: | |
| os.remove(ruta) | |
| except OSError: | |
| pass | |
| try: | |
| os.rmdir(carpeta_de(task_id)) # solo si quedó vacía | |
| except OSError: | |
| pass | |
| with _lock: | |
| _lotes[lote] = resultado | |
| def confirmar(task_id: str, nombres: list, mensaje: str) -> str: | |
| """Empieza a subir al dataset los archivos ya recibidos. Devuelve el id del lote.""" | |
| _purgar_viejos() | |
| archivos = [] | |
| for nombre in nombres: | |
| validar_nombre(nombre) | |
| ruta = os.path.join(carpeta_de(task_id), nombre) | |
| if not os.path.exists(ruta): | |
| raise SubidaInvalida(f"Falta el archivo {nombre}") | |
| archivos.append((ruta, f"stems/{task_id}/{nombre}")) | |
| if not archivos: | |
| raise SubidaInvalida("No hay archivos para subir") | |
| lote = uuid.uuid4().hex | |
| with _lock: | |
| _lotes[lote] = {"estado": "subiendo", "urls": {}, "t": time.time()} | |
| threading.Thread(target=_subir, args=(lote, task_id, archivos, f"{mensaje[:80]} ({task_id})"), | |
| daemon=True, name=f"subida-{task_id}").start() | |
| return lote | |
| def estado(lote: str) -> dict: | |
| """{'estado': 'subiendo'|'listo'|'error'|'desconocido', 'urls': {...}}""" | |
| with _lock: | |
| datos = _lotes.get(lote) | |
| if datos is None: | |
| return {"estado": "desconocido", "urls": {}} # la API se reinició: el equipo vuelve a subir | |
| return {"estado": datos["estado"], "urls": datos["urls"]} | |