Spaces:
Running
Running
Download app/utils/worker_ops.py from Isaac105/melodix-api: direct link, hf CLI and curl.
- Browser
- Download file 18.6 kB
-
https://huggingface.co/spaces/Isaac105/melodix-api/resolve/main/app/utils/worker_ops.py
- Command line
-
hf download hf://spaces/Isaac105/melodix-api/app/utils/worker_ops.py
-
curl -L -o worker_ops.py https://huggingface.co/spaces/Isaac105/melodix-api/resolve/main/app/utils/worker_ops.py
18.6 kB
| """ | |
| Operaciones de base de datos que necesita un worker mientras procesa una canción. | |
| Las usan dos caminos: | |
| - Los workers residenciales (equipos de usuarios y voluntarios) NO tienen credenciales de la base: | |
| llaman a la API (app/routers/worker_datos.py) y la API ejecuta estas funciones. | |
| - Los workers de Hugging Face (nuestros) las llaman directo (app/utils/worker_datos.py, modo "db"). | |
| Lo sensible (créditos, vencimiento de los stems, avisos a la app) se decide acá, del lado del | |
| servidor, con el worker identificado por su token: el worker solo informa resultados. | |
| `workers` es la lista de filas del equipo que llama. En modo directo (Hugging Face) puede llegar | |
| `confiable=True`: no se verifica que la tarea sea suya. | |
| """ | |
| import json | |
| import logging | |
| from datetime import datetime, timedelta | |
| from app.models.process import Task, Worker | |
| logger = logging.getLogger(__name__) | |
| class OperacionNoPermitida(Exception): | |
| """El worker intentó tocar una tarea que no es suya.""" | |
| # --------------------------------------------------------------------------- | |
| # Worker | |
| # --------------------------------------------------------------------------- | |
| def info_worker(workers: list) -> dict: | |
| """ | |
| Usuarios vinculados a este equipo, si está suspendido y sus colas propias (una por fila de | |
| `workers`: ver app/utils/despacho.py). El worker escucha esas colas desde 2.8.23. | |
| """ | |
| from app.utils.despacho import cola_worker | |
| return { | |
| "user_ids": sorted({w.user_id for w in workers if w.user_id}), | |
| "suspendido": any(w.status == "suspended" for w in workers), | |
| "colas": [cola_worker(w.id) for w in sorted(workers, key=lambda w: w.id) if w.user_id], | |
| } | |
| def actualizar_estado(db, workers: list, status: str): | |
| if status not in ("online", "busy", "offline"): | |
| raise ValueError("Estado inválido") | |
| for w in workers: | |
| if w.status == "suspended": | |
| continue | |
| w.status = status | |
| w.last_seen = datetime.utcnow() | |
| db.commit() | |
| def latido(db, workers: list) -> dict: | |
| """Heartbeat de Celery: offline -> online; busy y suspendido se conservan.""" | |
| for w in workers: | |
| if w.status == "offline": | |
| w.status = "online" | |
| w.last_seen = datetime.utcnow() | |
| db.commit() | |
| return info_worker(workers) | |
| # --------------------------------------------------------------------------- | |
| # Tareas de separación | |
| # --------------------------------------------------------------------------- | |
| def _tarea(db, task_id: str): | |
| return db.query(Task).filter(Task.task_id == task_id).first() | |
| def _worker_para(workers: list, task): | |
| """Fila del equipo que corresponde a la tarea: la del dueño de la canción si la hay.""" | |
| for w in workers: | |
| if task is not None and w.user_id == task.user_id: | |
| return w | |
| return workers[0] if workers else None | |
| def _exigir_propia(workers: list, task, confiable: bool = False): | |
| """La tarea tiene que haber sido reclamada por este equipo.""" | |
| if confiable: | |
| return | |
| ids = {w.id for w in workers} | |
| if task is None or task.processed_by_worker_id not in ids: | |
| raise OperacionNoPermitida("La tarea no la procesa este worker") | |
| MINUTOS_SIN_SENALES_TOMADOR = 10 | |
| def _tomador_caido(db, worker_id: int) -> bool: | |
| """El equipo que tomó una canción no da señales de vida hace rato (se apagó o se cortó).""" | |
| w = db.query(Worker).filter(Worker.id == worker_id).first() | |
| if w is None or w.last_seen is None: | |
| return True | |
| return w.status == "offline" or datetime.utcnow() - w.last_seen > timedelta(minutes=MINUTOS_SIN_SENALES_TOMADOR) | |
| def reclamar(db, workers: list, task_id: str, confiable: bool = False) -> bool: | |
| """ | |
| Marca la tarea como tomada por este equipo. False si ya la tomó otro (la API la reenvió a HF | |
| porque ningún residencial la tomaba a tiempo). Si la tarea no existe devuelve True: lo | |
| maneja tarea_existe (el usuario la borró). | |
| """ | |
| task = _tarea(db, task_id) | |
| if task is None: | |
| return True | |
| if not workers: | |
| # Worker de confianza sin registro (HF recién arrancado): se procesa igual, como antes | |
| return confiable | |
| ids = {w.id for w in workers} | |
| if task.processed_by_worker_id is not None and task.processed_by_worker_id not in ids: | |
| if not _tomador_caido(db, task.processed_by_worker_id) or task.status == "completed": | |
| return False | |
| # El equipo que la había tomado se apagó a mitad de camino: la canción volvió a la cola y | |
| # la toma este equipo (si no, quedaba en "procesando" para siempre) | |
| logger.warning(f"[{task_id}] El worker {task.processed_by_worker_id} que la procesaba no da señales: " | |
| f"la toma otro equipo.") | |
| task.processed_by_worker_id = None | |
| if task.processed_by_worker_id is None: | |
| task.processed_by_worker_id = _worker_para(workers, task).id | |
| task.status = "processing" | |
| db.commit() | |
| return True | |
| def tarea_existe(db, task_id: str) -> bool: | |
| return _tarea(db, task_id) is not None | |
| def guardar_etapa(db, workers: list, task_id: str, progreso: int, mensaje: str, confiable: bool = False): | |
| task = _tarea(db, task_id) | |
| if task is None: | |
| return | |
| _exigir_propia(workers, task, confiable) | |
| # "t": hora (del servidor) del último avance; el agente la usa para saber si la canción está trabada | |
| task.processing_stage = json.dumps({"p": int(progreso), "m": str(mensaje)[:200], | |
| "t": datetime.utcnow().isoformat(timespec="seconds")}) | |
| db.commit() | |
| def minutos_sin_avance(db, worker): | |
| """ | |
| Minutos desde el último avance de la canción que procesa este equipo, o None si no se sabe | |
| (no hay canción en curso o el avance es de una versión que no guardaba la hora). | |
| """ | |
| task = (db.query(Task) | |
| .filter(Task.processed_by_worker_id == worker.id, Task.status == "processing") | |
| .order_by(Task.created_at.desc()).first()) | |
| if task is None or not task.processing_stage: | |
| return None | |
| try: | |
| t = json.loads(task.processing_stage).get("t") | |
| if not t: | |
| return None | |
| return max(0, int((datetime.utcnow() - datetime.fromisoformat(t)).total_seconds() // 60)) | |
| except (ValueError, AttributeError, TypeError): | |
| return None | |
| def marcar_armonia_inline(db, workers: list, task_id: str, confiable: bool = False): | |
| task = _tarea(db, task_id) | |
| if task is None: | |
| return | |
| _exigir_propia(workers, task, confiable) | |
| task.has_harmony = True | |
| task.harmony_status = "completed" | |
| db.commit() | |
| def _validar_urls(task_id: str, urls: dict) -> dict: | |
| """Solo se aceptan archivos de esta tarea dentro del dataset de stems.""" | |
| from app.utils.hf_storage import HF_STORAGE_REPO | |
| prefijo = f"https://huggingface.co/datasets/{HF_STORAGE_REPO}/resolve/main/stems/{task_id}/" | |
| limpias = {} | |
| for nombre, url in (urls or {}).items(): | |
| if not isinstance(nombre, str) or not isinstance(url, str) or not url.startswith(prefijo) or ".." in url: | |
| raise OperacionNoPermitida(f"URL de stem no permitida: {nombre}") | |
| limpias[nombre[:80]] = url | |
| return limpias | |
| def _vencimiento(db, task) -> None: | |
| """Premium o compartida con un grupo: permanente. Usuario normal: 30 días.""" | |
| from app.models.user import User | |
| user = db.query(User).filter(User.id == task.user_id).first() | |
| es_premium = bool(user and user.is_premium) | |
| es_de_grupo = bool(task.group_id or task.group_ids) | |
| task.cloud_expires_at = None if (es_premium or es_de_grupo) else datetime.utcnow() + timedelta(days=30) | |
| def _recompensar(db, worker, task): | |
| """Créditos por procesar: bono al dueño con su propio worker o al voluntario que ayudó.""" | |
| from app.utils.credits import reward_bonus_credit, reward_public_worker_owner | |
| if worker is None: | |
| return | |
| try: | |
| if worker.user_id and worker.user_id == task.user_id: | |
| if task.consumed_credit_type == "base": | |
| reward_bonus_credit(db, user_id=task.user_id, amount=1, | |
| concept="bono_worker_privado", reference_id=task.task_id) | |
| elif worker.is_public and worker.user_id and worker.user_id != task.user_id: | |
| reward_public_worker_owner(db, worker_hostname=worker.hostname, task_id=task.task_id, amount=1) | |
| except Exception as e: | |
| logger.warning(f"[{task.task_id}] Error al dar la recompensa del worker: {e}") | |
| def _borrar_original(task): | |
| """El audio original temporal se borra al terminar: el equipo ya no tiene permiso para hacerlo.""" | |
| import re | |
| m = re.search(r"/resolve/main/(originals/.+)$", task.cloud_url or "") | |
| if not m: | |
| return | |
| try: | |
| from app.utils.hf_storage import delete_from_hf | |
| delete_from_hf(m.group(1)) | |
| except Exception as e: | |
| logger.warning(f"[{task.task_id}] No se pudo borrar el audio original: {e}") | |
| def exigir_subida(db, workers: list, task_id: str): | |
| """Un equipo solo sube pistas de canciones que procesa o que son de su dueño.""" | |
| from app.utils.puente import worker_de_trabajo | |
| task = _tarea(db, task_id) | |
| if task is None: | |
| raise OperacionNoPermitida("La tarea no existe") | |
| ids = {w.id for w in workers} | |
| duenos = {w.user_id for w in workers if w.user_id} | |
| if task.processed_by_worker_id in ids or worker_de_trabajo(task) in ids or task.user_id in duenos: | |
| return | |
| raise OperacionNoPermitida("La tarea no la procesa este worker") | |
| def _avisar(user_id, mensaje: dict): | |
| try: | |
| from app.websocket_manager import send_sync_message | |
| send_sync_message(mensaje, user_id) | |
| except Exception: | |
| pass | |
| def completar(db, workers: list, task_id: str, datos: dict, confiable: bool = False) -> bool: | |
| """ | |
| Registra el resultado de la separación. `datos`: urls (stem -> url), peaks, chords, bpm, beats, | |
| downbeats, tuning_info, con_armonias. Devuelve False si la tarea ya no existe. | |
| """ | |
| task = _tarea(db, task_id) | |
| if task is None: | |
| return False | |
| _exigir_propia(workers, task, confiable) | |
| worker = _worker_para(workers, task) | |
| task.telegram_file_ids = json.dumps(_validar_urls(task_id, datos.get("urls"))) | |
| task.peaks = datos.get("peaks") | |
| if datos.get("chords"): | |
| task.chords = json.dumps(datos["chords"]) | |
| if datos.get("bpm") is not None: | |
| task.bpm = datos["bpm"] | |
| if datos.get("beats"): | |
| task.beats = json.dumps([round(float(b), 4) for b in datos["beats"]]) | |
| task.downbeats = json.dumps(datos["downbeats"]) if datos.get("downbeats") else None | |
| if datos.get("tuning_info"): | |
| task.tuning_info = json.dumps(datos["tuning_info"]) | |
| if datos.get("con_armonias"): | |
| task.has_harmony = True | |
| task.harmony_status = "completed" | |
| task.status = "completed" | |
| if worker is not None: | |
| task.processed_by_worker_id = worker.id | |
| task.trabajo_json = None | |
| from app.utils import audio_compartido | |
| faltan_corales = audio_compartido.registrar_resultado(db, task, datos) | |
| _vencimiento(db, task) | |
| if datos.get("fuente_id") is None: # Unir pistas ya hechas no es procesar: no genera recompensa | |
| _recompensar(db, worker, task) | |
| db.commit() | |
| if not confiable: | |
| _borrar_original(task) | |
| if faltan_corales: | |
| _encolar_corales(db, task) | |
| _avisar(task.user_id, {"type": "song_processing_completed", "task_id": task_id, | |
| "song_name": task.song_name, "status": "completed"}) | |
| return True | |
| def _encolar_corales(db, task): | |
| try: | |
| from app.routers.songs import encolar_armonias | |
| encolar_armonias(db, task, task.user_id) | |
| except Exception as e: | |
| logger.error(f"[{task.task_id}] No se pudieron encolar las voces corales: {e}") | |
| def reconocer(db, workers: list, task_id: str, datos: dict, confiable: bool = False) -> dict: | |
| """ | |
| ¿Este audio ya se procesó antes? Si es idéntico deja la pista lista sin separar. El crédito ya | |
| se cobró al subirla; al no procesar no hay recompensa para el equipo. | |
| """ | |
| from app.utils import audio_compartido | |
| task = _tarea(db, task_id) | |
| if task is None: | |
| return audio_compartido.PROCESAR | |
| _exigir_propia(workers, task, confiable) | |
| decision = audio_compartido.decidir(db, task, datos if isinstance(datos, dict) else {}) | |
| if decision["accion"] != "listo": | |
| return decision | |
| task.status = "completed" | |
| task.processing_stage = None | |
| task.trabajo_json = None | |
| _vencimiento(db, task) | |
| db.commit() | |
| if not confiable: | |
| _borrar_original(task) | |
| if decision["faltan_corales"]: | |
| _encolar_corales(db, task) | |
| _avisar(task.user_id, {"type": "song_processing_completed", "task_id": task_id, | |
| "song_name": task.song_name, "status": "completed"}) | |
| return decision | |
| def fallar(db, workers: list, task_id: str, error: str, confiable: bool = False): | |
| """Fallo definitivo: marca la tarea y reembolsa el crédito una sola vez.""" | |
| task = _tarea(db, task_id) | |
| if task is None: | |
| return | |
| _exigir_propia(workers, task, confiable) | |
| if task.status == "failed": | |
| return | |
| task.status = "failed" | |
| task.trabajo_json = None | |
| if not confiable: | |
| _borrar_original(task) | |
| logger.warning(f"[{task_id}] Falló en el worker: {(error or '')[:250]}") | |
| if task.user_id: | |
| try: | |
| from app.models.user import User | |
| from app.utils.credits import refund_credits | |
| user = db.query(User).filter(User.id == task.user_id).first() | |
| if user: | |
| refund_credits(db, user, 1, "reembolso_error_procesamiento", reference_id=task_id, | |
| credit_type=task.consumed_credit_type or "base") | |
| except Exception as e: | |
| logger.error(f"[{task_id}] Error reembolsando crédito al fallar: {e}") | |
| db.commit() | |
| if task.user_id: | |
| _avisar(task.user_id, {"type": "song_processing_failed", "task_id": task_id, | |
| "song_name": task.song_name, "status": "failed"}) | |
| def respaldo_local(db, workers: list, task_id: str, datos: dict, confiable: bool = False): | |
| """ | |
| Pista procesada en modo local (sin cola): se crea o actualiza su registro con los stems ya | |
| subidos. Solo para canciones del dueño del equipo. | |
| """ | |
| user_ids = {w.user_id for w in workers if w.user_id} | |
| task = _tarea(db, task_id) | |
| if task is not None and task.user_id not in user_ids and not confiable: | |
| raise OperacionNoPermitida("La tarea no es del dueño de este worker") | |
| urls = _validar_urls(task_id, datos.get("urls")) | |
| if task is None: | |
| user_id = datos.get("user_id") | |
| if user_id not in user_ids and not confiable: | |
| raise OperacionNoPermitida("La tarea no es del dueño de este worker") | |
| task = Task(task_id=task_id, user_id=user_id, device_id="local_worker", | |
| song_name=(datos.get("song_name") or "Pista Local")[:200], | |
| artist=(datos.get("artist") or "")[:200], stems=int(datos.get("stems") or 4), | |
| created_at=datetime.utcnow()) | |
| db.add(task) | |
| task.telegram_file_ids = json.dumps(urls) | |
| task.peaks = datos.get("peaks") | |
| if datos.get("chords"): | |
| task.chords = json.dumps(datos["chords"]) | |
| task.status = "completed" | |
| db.commit() | |
| # --------------------------------------------------------------------------- | |
| # Voces corales (generadas a pedido) | |
| # --------------------------------------------------------------------------- | |
| def _exigir_armonia_en_curso(task): | |
| # 'error' también vale: la API la marca así si tarda demasiado, y el worker igual puede terminarla | |
| if task is None or (task.harmony_status or "none") == "none": | |
| raise OperacionNoPermitida("No hay voces corales pedidas para esta tarea") | |
| def _exigir_armonia_propia(workers: list, task, confiable: bool): | |
| """Las voces corales las termina el equipo al que se entregaron.""" | |
| if confiable: | |
| return | |
| from app.utils.despacho import soporta_puente | |
| from app.utils.puente import worker_de_trabajo | |
| asignado = worker_de_trabajo(task) | |
| if asignado in {w.id for w in workers}: | |
| return | |
| # Equipos con el motor anterior (reciben por el broker, sin anotación) hasta que se actualicen | |
| if asignado is None and workers and not all(soporta_puente(w) for w in workers): | |
| return | |
| raise OperacionNoPermitida("Estas voces corales no las procesa este worker") | |
| def datos_armonia(db, workers: list, task_id: str, confiable: bool = False) -> dict: | |
| task = _tarea(db, task_id) | |
| if task is None: | |
| return {"existe": False} | |
| _exigir_armonia_en_curso(task) | |
| _exigir_armonia_propia(workers, task, confiable) | |
| from app.routers.songs import _resolve_task_folder | |
| return { | |
| "existe": True, | |
| "urls": json.loads(task.telegram_file_ids) if task.telegram_file_ids else {}, | |
| "chords": json.loads(task.chords) if task.chords else None, | |
| "folder": _resolve_task_folder(task_id, db), | |
| } | |
| def etapa_armonia(db, workers: list, task_id: str, progreso: int, mensaje: str, confiable: bool = False): | |
| task = _tarea(db, task_id) | |
| if task is None: | |
| return | |
| _exigir_armonia_en_curso(task) | |
| _exigir_armonia_propia(workers, task, confiable) | |
| task.harmony_status = "generating" | |
| task.harmony_stage = json.dumps({"p": int(progreso), "m": str(mensaje)[:200]}) | |
| task.harmony_updated_at = datetime.utcnow() | |
| db.commit() | |
| def completar_armonia(db, workers: list, task_id: str, urls: dict, hashes=None, confiable: bool = False): | |
| task = _tarea(db, task_id) | |
| if task is None: | |
| return | |
| _exigir_armonia_en_curso(task) | |
| _exigir_armonia_propia(workers, task, confiable) | |
| actuales = json.loads(task.telegram_file_ids) if task.telegram_file_ids else {} | |
| actuales.update(_validar_urls(task_id, urls)) | |
| task.telegram_file_ids = json.dumps(actuales) | |
| task.has_harmony = True | |
| task.harmony_status = "completed" | |
| task.trabajo_json = None | |
| from app.utils import audio_compartido | |
| audio_compartido.anotar_corales(db, task, actuales, hashes) | |
| db.commit() | |
| def error_armonia(db, workers: list, task_id: str, confiable: bool = False): | |
| task = _tarea(db, task_id) | |
| if task is None or task.harmony_status == "completed": | |
| return | |
| _exigir_armonia_propia(workers, task, confiable) | |
| task.harmony_status = "error" | |
| task.trabajo_json = None | |
| db.commit() | |