Spaces:
Running
Running
Download app/utils/worker_datos.py from Isaac105/melodix-api: direct link, hf CLI and curl.
- Browser
- Download file 11.7 kB
-
https://huggingface.co/spaces/Isaac105/melodix-api/resolve/main/app/utils/worker_datos.py
- Command line
-
hf download hf://spaces/Isaac105/melodix-api/app/utils/worker_datos.py
-
curl -L -o worker_datos.py https://huggingface.co/spaces/Isaac105/melodix-api/resolve/main/app/utils/worker_datos.py
11.7 kB
| """ | |
| Acceso a datos del worker (lo usa tasks.py). | |
| - Modo "api" (workers residenciales): llama a la API con el token del usuario (MELODIX_USER_TOKEN) | |
| y el nombre del equipo. El equipo no tiene credenciales de la base de datos. | |
| - Modo "db" (Hugging Face, define SPACE_ID): llama directo a app/utils/worker_ops.py. | |
| WORKER_DATOS=db|api fuerza el modo (por ejemplo, para desarrollo). | |
| """ | |
| import logging | |
| import os | |
| import socket | |
| import time | |
| logger = logging.getLogger(__name__) | |
| MODO = os.getenv("WORKER_DATOS") or ("db" if os.getenv("SPACE_ID") else "api") | |
| MODO_DIRECTO = MODO == "db" | |
| API_URL = (os.getenv("MELODIX_API_URL") or "https://isaac105-melodix-api.hf.space").rstrip("/") | |
| # Lo fija tasks.py cuando Celery conoce el nombre del nodo (celery@<equipo>) | |
| _hostname = socket.gethostname() | |
| def fijar_hostname(hostname: str): | |
| global _hostname | |
| if hostname: | |
| _hostname = hostname | |
| class ErrorDatosWorker(Exception): | |
| """La API rechazó la operación o no respondió.""" | |
| # --------------------------------------------------------------------------- | |
| # Transporte | |
| # --------------------------------------------------------------------------- | |
| def _cabeceras(): | |
| tokens = os.getenv("MELODIX_USER_TOKEN", "") | |
| return {"X-Worker-Tokens": tokens, "X-Worker-Host": _hostname} | |
| def _api(metodo: str, ruta: str, json=None, intentos: int = 3, timeout: int = 20): | |
| import requests | |
| ultimo = None | |
| for i in range(intentos): | |
| try: | |
| r = requests.request(metodo, f"{API_URL}/workers/datos{ruta}", json=json, | |
| headers=_cabeceras(), timeout=timeout) | |
| if r.status_code < 300: | |
| return r.json() | |
| if r.status_code == 429: | |
| # HF limitó las peticiones de esta IP: se levanta solo en unos minutos, hay que esperar | |
| ultimo = ErrorDatosWorker("429: la API limitó las peticiones (Too Many Requests)") | |
| if i < intentos - 1: | |
| time.sleep(30 * (i + 1)) | |
| continue | |
| if r.status_code < 500: | |
| # Error del pedido (token, permiso, datos): reintentar no lo arregla | |
| raise ErrorDatosWorker(f"{r.status_code}: {r.text[:200]}") | |
| ultimo = ErrorDatosWorker(f"{r.status_code}: {r.text[:200]}") | |
| except ErrorDatosWorker: | |
| raise | |
| except Exception as e: | |
| ultimo = e | |
| if i < intentos - 1: | |
| time.sleep(min(2 ** i * 2, 30)) | |
| raise ErrorDatosWorker(f"La API no respondió ({ruta}): {ultimo}") | |
| class _Sesion: | |
| """Sesión de BD + filas del equipo para el modo directo.""" | |
| def __enter__(self): | |
| from app.database import SessionLocal | |
| from app.models.process import Worker | |
| self.db = SessionLocal() | |
| w = self.db.query(Worker).filter(Worker.hostname == _hostname).first() | |
| self.workers = [w] if w else [] | |
| return self | |
| def __exit__(self, *exc): | |
| self.db.close() | |
| def _ops(): | |
| from app.utils import worker_ops | |
| return worker_ops | |
| # --------------------------------------------------------------------------- | |
| # Operaciones | |
| # --------------------------------------------------------------------------- | |
| def info_worker() -> dict: | |
| """{'user_ids': [...], 'suspendido': bool}""" | |
| if MODO_DIRECTO: | |
| with _Sesion() as s: | |
| return _ops().info_worker(s.workers) | |
| return _api("GET", "/info") | |
| def actualizar_estado(status: str): | |
| if MODO_DIRECTO: | |
| with _Sesion() as s: | |
| _ops().actualizar_estado(s.db, s.workers, status) | |
| return | |
| _api("POST", "/estado", {"status": status}) | |
| def latido() -> dict: | |
| """Solo modo API (en HF el heartbeat también registra el worker; lo hace tasks.py).""" | |
| return _api("POST", "/latido", intentos=1) | |
| def pedir_trabajo(): | |
| """Siguiente canción de este equipo ({nombre, id, args, kwargs}) o None. Solo modo API.""" | |
| return _api("POST", "/trabajo", intentos=1, timeout=30).get("trabajo") | |
| def _enviar_archivo(task_id: str, nombre: str, ruta: str) -> bool: | |
| import requests | |
| url = f"{API_URL}/workers/datos/tareas/{task_id}/archivos/{nombre}" | |
| cabeceras = {**_cabeceras(), "Content-Type": "application/octet-stream"} | |
| for i in range(4): | |
| try: | |
| with open(ruta, "rb") as f: | |
| r = requests.put(url, data=f, headers=cabeceras, timeout=(30, 1800)) | |
| if r.status_code < 300: | |
| return True | |
| if r.status_code == 429: | |
| time.sleep(30 * (i + 1)) | |
| continue | |
| if r.status_code < 500: | |
| logger.error(f"[{task_id}] La API rechazó {nombre}: {r.status_code} {r.text[:200]}") | |
| return False | |
| logger.warning(f"[{task_id}] Error {r.status_code} subiendo {nombre}, intento {i + 1}") | |
| except Exception as e: | |
| logger.warning(f"[{task_id}] Fallo subiendo {nombre}, intento {i + 1}: {str(e)[:160]}") | |
| time.sleep(min(2 ** i * 5, 60)) | |
| return False | |
| def subir_a_hf(files, commit_message: str = "Subir archivos") -> dict: | |
| """ | |
| Sube archivos al dataset. files: [(ruta_local, 'stems/<task_id>/<nombre>')]; devuelve | |
| {object_name: url} de los subidos. Hugging Face usa su token; los residenciales pasan por la API. | |
| """ | |
| if MODO_DIRECTO: | |
| from app.utils.hf_storage import upload_many_to_hf | |
| return upload_many_to_hf(files, commit_message=commit_message) | |
| files = [(ruta, nombre) for ruta, nombre in files if os.path.exists(ruta)] | |
| if not files: | |
| return {} | |
| task_id = files[0][1].split("/")[1] | |
| for _ in range(2): | |
| nombres = [clave.rsplit("/", 1)[1] for ruta, clave in files | |
| if _enviar_archivo(task_id, clave.rsplit("/", 1)[1], ruta)] | |
| if not nombres: | |
| return {} | |
| lote = _api("POST", f"/tareas/{task_id}/archivos/confirmar", | |
| {"archivos": nombres, "mensaje": commit_message}, intentos=4, timeout=60)["lote"] | |
| limite = time.time() + 1800 | |
| estado = {"estado": "subiendo"} | |
| while estado["estado"] == "subiendo" and time.time() < limite: | |
| time.sleep(5) | |
| try: | |
| estado = _api("GET", f"/archivos/lote/{lote}", intentos=3, timeout=20) | |
| except ErrorDatosWorker as e: | |
| logger.warning(f"[{task_id}] No se pudo consultar la subida: {str(e)[:160]}") | |
| if estado["estado"] == "listo": | |
| return estado.get("urls") or {} | |
| if estado["estado"] != "desconocido": | |
| return {} | |
| logger.warning(f"[{task_id}] La API se reinició durante la subida: se envían de nuevo.") | |
| return {} | |
| def reclamar(task_id: str) -> bool: | |
| if MODO_DIRECTO: | |
| with _Sesion() as s: | |
| return _ops().reclamar(s.db, s.workers, task_id, confiable=True) | |
| return bool(_api("POST", f"/tareas/{task_id}/reclamar")["ok"]) | |
| def tarea_existe(task_id: str) -> bool: | |
| if MODO_DIRECTO: | |
| with _Sesion() as s: | |
| return _ops().tarea_existe(s.db, task_id) | |
| return bool(_api("GET", f"/tareas/{task_id}/existe")["existe"]) | |
| def guardar_etapa(task_id: str, progreso: int, mensaje: str): | |
| if MODO_DIRECTO: | |
| with _Sesion() as s: | |
| _ops().guardar_etapa(s.db, s.workers, task_id, progreso, mensaje, confiable=True) | |
| return | |
| _api("POST", f"/tareas/{task_id}/etapa", {"p": progreso, "m": mensaje}, intentos=1, timeout=10) | |
| def marcar_armonia_inline(task_id: str): | |
| if MODO_DIRECTO: | |
| with _Sesion() as s: | |
| _ops().marcar_armonia_inline(s.db, s.workers, task_id, confiable=True) | |
| return | |
| _api("POST", f"/tareas/{task_id}/armonia-inline") | |
| def reconocer(task_id: str, datos: dict) -> dict: | |
| if MODO_DIRECTO: | |
| with _Sesion() as s: | |
| return _ops().reconocer(s.db, s.workers, task_id, datos, confiable=True) | |
| return _api("POST", f"/tareas/{task_id}/reconocer", datos, intentos=2, timeout=30) | |
| def completar(task_id: str, datos: dict) -> bool: | |
| """El resultado ya está en HF: insistir bastante para no dejar la pista en 'procesando'.""" | |
| if MODO_DIRECTO: | |
| with _Sesion() as s: | |
| return _ops().completar(s.db, s.workers, task_id, datos, confiable=True) | |
| return bool(_api("POST", f"/tareas/{task_id}/completar", datos, intentos=6, timeout=30)["ok"]) | |
| def fallar(task_id: str, error: str): | |
| if MODO_DIRECTO: | |
| with _Sesion() as s: | |
| _ops().fallar(s.db, s.workers, task_id, error, confiable=True) | |
| return | |
| _api("POST", f"/tareas/{task_id}/fallar", {"error": (error or "")[:250]}, intentos=6, timeout=30) | |
| def respaldo_local(task_id: str, datos: dict): | |
| if MODO_DIRECTO: | |
| with _Sesion() as s: | |
| _ops().respaldo_local(s.db, s.workers, task_id, datos, confiable=True) | |
| return | |
| _api("POST", f"/tareas/{task_id}/respaldo", datos, intentos=6, timeout=30) | |
| def datos_armonia(task_id: str) -> dict: | |
| """{'existe', 'urls', 'chords', 'folder'}""" | |
| if MODO_DIRECTO: | |
| with _Sesion() as s: | |
| return _ops().datos_armonia(s.db, s.workers, task_id, confiable=True) | |
| return _api("GET", f"/tareas/{task_id}/armonia") | |
| def etapa_armonia(task_id: str, progreso: int, mensaje: str): | |
| if MODO_DIRECTO: | |
| with _Sesion() as s: | |
| _ops().etapa_armonia(s.db, s.workers, task_id, progreso, mensaje, confiable=True) | |
| return | |
| _api("POST", f"/tareas/{task_id}/armonia/etapa", {"p": progreso, "m": mensaje}, intentos=1, timeout=10) | |
| def completar_armonia(task_id: str, urls: dict, hashes=None): | |
| if MODO_DIRECTO: | |
| with _Sesion() as s: | |
| _ops().completar_armonia(s.db, s.workers, task_id, urls, hashes, confiable=True) | |
| return | |
| _api("POST", f"/tareas/{task_id}/armonia/completar", {"urls": urls, "hashes": hashes}, intentos=6, timeout=30) | |
| def error_armonia(task_id: str): | |
| if MODO_DIRECTO: | |
| with _Sesion() as s: | |
| _ops().error_armonia(s.db, s.workers, task_id, confiable=True) | |
| return | |
| _api("POST", f"/tareas/{task_id}/armonia/error") | |
| # --------------------------------------------------------------------------- | |
| # Limpieza de credenciales viejas | |
| # --------------------------------------------------------------------------- | |
| CLAVES_PROHIBIDAS = ("DATABASE_URL", "SECRET_KEY", "SUPABASE_JWT_SECRET") | |
| # Con el motor que pide trabajo a la API tampoco hacen falta estas | |
| CLAVES_SIN_BROKER = ("BROKER_URL", "REDIS_URL", "CLOUDAMQP_URL", "HF_TOKEN") | |
| def es_worker_instalado(dir_api: str) -> bool: | |
| """El instalador deja version.txt junto a la carpeta MelodixAPI (C:\\MelodixWorker). El repo no lo tiene.""" | |
| return os.path.exists(os.path.join(os.path.dirname(os.path.abspath(dir_api)), "version.txt")) | |
| def limpiar_credenciales_env(ruta_env: str, extra: tuple = ()) -> list: | |
| """ | |
| Los instaladores viejos dejaban credenciales de producción en el .env del worker. En modo API | |
| no se usan: se borran del archivo. Devuelve las claves borradas. | |
| Solo en un worker instalado: nunca toca el .env de desarrollo del repositorio. | |
| """ | |
| if MODO_DIRECTO or not os.path.exists(ruta_env) or not es_worker_instalado(os.path.dirname(ruta_env)): | |
| return [] | |
| with open(ruta_env, encoding="utf-8-sig") as f: | |
| lineas = f.readlines() | |
| quedan, borradas = [], [] | |
| for linea in lineas: | |
| clave = linea.split("=", 1)[0].strip() | |
| if clave in CLAVES_PROHIBIDAS or clave in extra: | |
| borradas.append(clave) | |
| else: | |
| quedan.append(linea) | |
| if borradas: | |
| with open(ruta_env, "w", encoding="utf-8") as f: | |
| f.writelines(quedan) | |
| return borradas | |