Spaces:
Running
Running
deploy from github actions
Browse files- app/main.py +2 -0
- app/models/process.py +2 -0
- app/routers/songs.py +2 -1
- app/routers/worker_datos.py +59 -6
- app/routers/workers.py +6 -0
- app/utils/despacho.py +40 -2
- app/utils/puente.py +240 -0
- app/utils/subidas_worker.py +117 -0
- app/utils/worker_datos.py +72 -6
- app/utils/worker_ops.py +57 -4
- puente_trabajos.py +107 -0
- tasks.py +13 -22
app/main.py
CHANGED
|
@@ -26,6 +26,8 @@ _COLUMNAS_NUEVAS = [
|
|
| 26 |
"ALTER TABLE user_groups ADD COLUMN IF NOT EXISTS perm_editar_pistas BOOLEAN",
|
| 27 |
"ALTER TABLE tasks ADD COLUMN IF NOT EXISTS processing_stage TEXT",
|
| 28 |
"ALTER TABLE tasks ADD COLUMN IF NOT EXISTS peaks TEXT",
|
|
|
|
|
|
|
| 29 |
]
|
| 30 |
try:
|
| 31 |
from sqlalchemy import text as _sql_text
|
|
|
|
| 26 |
"ALTER TABLE user_groups ADD COLUMN IF NOT EXISTS perm_editar_pistas BOOLEAN",
|
| 27 |
"ALTER TABLE tasks ADD COLUMN IF NOT EXISTS processing_stage TEXT",
|
| 28 |
"ALTER TABLE tasks ADD COLUMN IF NOT EXISTS peaks TEXT",
|
| 29 |
+
"ALTER TABLE tasks ADD COLUMN IF NOT EXISTS trabajo_json TEXT",
|
| 30 |
+
"ALTER TABLE workers ADD COLUMN IF NOT EXISTS publico_aprobado BOOLEAN",
|
| 31 |
]
|
| 32 |
try:
|
| 33 |
from sqlalchemy import text as _sql_text
|
app/models/process.py
CHANGED
|
@@ -42,6 +42,7 @@ class Task(Base):
|
|
| 42 |
# (si deja de avanzar, la tarea se dio por perdida y se permite reintentar)
|
| 43 |
harmony_stage = Column(Text, nullable=True, default=None)
|
| 44 |
processing_stage = Column(Text, nullable=True, default=None) # Etapa actual del procesamiento: {"p": %, "m": mensaje}
|
|
|
|
| 45 |
harmony_updated_at = Column(DateTime, nullable=True, default=None)
|
| 46 |
consumed_credit_type = Column(String, default="base", nullable=True) # base | bonus
|
| 47 |
processed_by_worker_id = Column(Integer, ForeignKey("workers.id", ondelete="SET NULL"), nullable=True)
|
|
@@ -73,6 +74,7 @@ class Worker(Base):
|
|
| 73 |
is_public = Column(Boolean, default=False) # True = procesa tareas comunitarias con recompensa, False = privado para su dueño
|
| 74 |
url = Column(String, nullable=True) # URL de despertar / HuggingFace Space URL
|
| 75 |
version = Column(String, nullable=True) # Versión del worker residencial que reporta el agente
|
|
|
|
| 76 |
|
| 77 |
owner = relationship("User", foreign_keys=[user_id])
|
| 78 |
|
|
|
|
| 42 |
# (si deja de avanzar, la tarea se dio por perdida y se permite reintentar)
|
| 43 |
harmony_stage = Column(Text, nullable=True, default=None)
|
| 44 |
processing_stage = Column(Text, nullable=True, default=None) # Etapa actual del procesamiento: {"p": %, "m": mensaje}
|
| 45 |
+
trabajo_json = Column(Text, nullable=True, default=None) # Trabajo entregado a un worker residencial (app/utils/puente.py)
|
| 46 |
harmony_updated_at = Column(DateTime, nullable=True, default=None)
|
| 47 |
consumed_credit_type = Column(String, default="base", nullable=True) # base | bonus
|
| 48 |
processed_by_worker_id = Column(Integer, ForeignKey("workers.id", ondelete="SET NULL"), nullable=True)
|
|
|
|
| 74 |
is_public = Column(Boolean, default=False) # True = procesa tareas comunitarias con recompensa, False = privado para su dueño
|
| 75 |
url = Column(String, nullable=True) # URL de despertar / HuggingFace Space URL
|
| 76 |
version = Column(String, nullable=True) # Versión del worker residencial que reporta el agente
|
| 77 |
+
publico_aprobado = Column(Boolean, default=False, nullable=True) # Un admin lo aprobó para canciones de otros (NULL = equipo anterior a esta regla)
|
| 78 |
|
| 79 |
owner = relationship("User", foreign_keys=[user_id])
|
| 80 |
|
app/routers/songs.py
CHANGED
|
@@ -121,6 +121,7 @@ def get_public_routing_queue(db: Session, solo_libres: bool = True):
|
|
| 121 |
"""
|
| 122 |
from app.models.process import Worker
|
| 123 |
from app.utils.hf_wake import COLA_HF, es_worker_hf
|
|
|
|
| 124 |
from app.utils.worker_version import worker_desactualizado
|
| 125 |
from datetime import datetime
|
| 126 |
|
|
@@ -129,7 +130,7 @@ def get_public_routing_queue(db: Session, solo_libres: bool = True):
|
|
| 129 |
candidatos = db.query(Worker).filter(Worker.is_public == True, Worker.status.in_(estados)).all()
|
| 130 |
for worker in candidatos:
|
| 131 |
is_recent = worker.last_seen and (now - worker.last_seen).total_seconds() < 120
|
| 132 |
-
if is_recent and not es_worker_hf(worker) and not worker_desactualizado(worker):
|
| 133 |
return "celery", worker
|
| 134 |
return COLA_HF, None
|
| 135 |
|
|
|
|
| 121 |
"""
|
| 122 |
from app.models.process import Worker
|
| 123 |
from app.utils.hf_wake import COLA_HF, es_worker_hf
|
| 124 |
+
from app.utils.puente import puede_publico
|
| 125 |
from app.utils.worker_version import worker_desactualizado
|
| 126 |
from datetime import datetime
|
| 127 |
|
|
|
|
| 130 |
candidatos = db.query(Worker).filter(Worker.is_public == True, Worker.status.in_(estados)).all()
|
| 131 |
for worker in candidatos:
|
| 132 |
is_recent = worker.last_seen and (now - worker.last_seen).total_seconds() < 120
|
| 133 |
+
if is_recent and not es_worker_hf(worker) and not worker_desactualizado(worker) and puede_publico(worker):
|
| 134 |
return "celery", worker
|
| 135 |
return COLA_HF, None
|
| 136 |
|
app/routers/worker_datos.py
CHANGED
|
@@ -4,14 +4,16 @@ API para los workers residenciales: todo lo que antes escribían directo en la b
|
|
| 4 |
El equipo se identifica con su token de usuario (MELODIX_USER_TOKEN, puede ser una lista separada
|
| 5 |
por comas) y su nombre de equipo (hostname). No necesita ninguna credencial de producción.
|
| 6 |
"""
|
| 7 |
-
|
|
|
|
| 8 |
|
| 9 |
-
from fastapi import APIRouter, Depends, Header, HTTPException
|
| 10 |
from pydantic import BaseModel
|
| 11 |
from sqlalchemy.orm import Session
|
| 12 |
|
| 13 |
from app.database import get_db
|
| 14 |
from app.models.process import Worker
|
|
|
|
| 15 |
from app.utils import worker_ops as ops
|
| 16 |
|
| 17 |
router = APIRouter(prefix="/workers/datos", tags=["Worker datos"])
|
|
@@ -64,6 +66,11 @@ class UrlsIn(BaseModel):
|
|
| 64 |
urls: dict
|
| 65 |
|
| 66 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
@router.get("/info")
|
| 68 |
def info(workers: list = Depends(workers_del_equipo)):
|
| 69 |
return ops.info_worker(workers)
|
|
@@ -80,6 +87,52 @@ def latido(workers: list = Depends(workers_del_equipo), db: Session = Depends(ge
|
|
| 80 |
return ops.latido(db, workers)
|
| 81 |
|
| 82 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
@router.post("/tareas/{task_id}/reclamar")
|
| 84 |
def reclamar(task_id: str, workers: list = Depends(workers_del_equipo), db: Session = Depends(get_db)):
|
| 85 |
return {"ok": ops.reclamar(db, workers, task_id)}
|
|
@@ -121,22 +174,22 @@ def respaldo(task_id: str, data: dict, workers: list = Depends(workers_del_equip
|
|
| 121 |
|
| 122 |
@router.get("/tareas/{task_id}/armonia")
|
| 123 |
def datos_armonia(task_id: str, workers: list = Depends(workers_del_equipo), db: Session = Depends(get_db)):
|
| 124 |
-
return _ejecutar(ops.datos_armonia, db, task_id)
|
| 125 |
|
| 126 |
|
| 127 |
@router.post("/tareas/{task_id}/armonia/etapa")
|
| 128 |
def etapa_armonia(task_id: str, data: EtapaIn, workers: list = Depends(workers_del_equipo), db: Session = Depends(get_db)):
|
| 129 |
-
_ejecutar(ops.etapa_armonia, db, task_id, data.p, data.m)
|
| 130 |
return {"ok": True}
|
| 131 |
|
| 132 |
|
| 133 |
@router.post("/tareas/{task_id}/armonia/completar")
|
| 134 |
def completar_armonia(task_id: str, data: UrlsIn, workers: list = Depends(workers_del_equipo), db: Session = Depends(get_db)):
|
| 135 |
-
_ejecutar(ops.completar_armonia, db, task_id, data.urls)
|
| 136 |
return {"ok": True}
|
| 137 |
|
| 138 |
|
| 139 |
@router.post("/tareas/{task_id}/armonia/error")
|
| 140 |
def error_armonia(task_id: str, workers: list = Depends(workers_del_equipo), db: Session = Depends(get_db)):
|
| 141 |
-
_ejecutar(ops.error_armonia, db, task_id)
|
| 142 |
return {"ok": True}
|
|
|
|
| 4 |
El equipo se identifica con su token de usuario (MELODIX_USER_TOKEN, puede ser una lista separada
|
| 5 |
por comas) y su nombre de equipo (hostname). No necesita ninguna credencial de producción.
|
| 6 |
"""
|
| 7 |
+
import os
|
| 8 |
+
from typing import List, Optional
|
| 9 |
|
| 10 |
+
from fastapi import APIRouter, Depends, Header, HTTPException, Request
|
| 11 |
from pydantic import BaseModel
|
| 12 |
from sqlalchemy.orm import Session
|
| 13 |
|
| 14 |
from app.database import get_db
|
| 15 |
from app.models.process import Worker
|
| 16 |
+
from app.utils import puente, subidas_worker
|
| 17 |
from app.utils import worker_ops as ops
|
| 18 |
|
| 19 |
router = APIRouter(prefix="/workers/datos", tags=["Worker datos"])
|
|
|
|
| 66 |
urls: dict
|
| 67 |
|
| 68 |
|
| 69 |
+
class ConfirmarIn(BaseModel):
|
| 70 |
+
archivos: List[str]
|
| 71 |
+
mensaje: Optional[str] = "Subir archivos"
|
| 72 |
+
|
| 73 |
+
|
| 74 |
@router.get("/info")
|
| 75 |
def info(workers: list = Depends(workers_del_equipo)):
|
| 76 |
return ops.info_worker(workers)
|
|
|
|
| 87 |
return ops.latido(db, workers)
|
| 88 |
|
| 89 |
|
| 90 |
+
@router.post("/trabajo")
|
| 91 |
+
def pedir_trabajo(workers: list = Depends(workers_del_equipo), db: Session = Depends(get_db)):
|
| 92 |
+
"""El equipo está libre: su siguiente canción, sacada solo de las colas que le corresponden."""
|
| 93 |
+
return {"trabajo": puente.siguiente_trabajo(db, workers)}
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@router.put("/tareas/{task_id}/archivos/{nombre}")
|
| 97 |
+
async def recibir_archivo(task_id: str, nombre: str, request: Request,
|
| 98 |
+
workers: list = Depends(workers_del_equipo), db: Session = Depends(get_db)):
|
| 99 |
+
_ejecutar(ops.exigir_subida, db, workers, task_id)
|
| 100 |
+
db.close() # la subida puede tardar minutos: no retener una conexión de la base
|
| 101 |
+
try:
|
| 102 |
+
ruta = subidas_worker.ruta_destino(task_id, nombre)
|
| 103 |
+
except subidas_worker.SubidaInvalida as e:
|
| 104 |
+
raise HTTPException(status_code=400, detail=str(e))
|
| 105 |
+
parcial = ruta + ".parte"
|
| 106 |
+
total = 0
|
| 107 |
+
try:
|
| 108 |
+
with open(parcial, "wb") as f:
|
| 109 |
+
async for bloque in request.stream():
|
| 110 |
+
total += len(bloque)
|
| 111 |
+
if total > subidas_worker.TAMANO_MAXIMO:
|
| 112 |
+
raise HTTPException(status_code=413, detail="Archivo demasiado grande")
|
| 113 |
+
f.write(bloque)
|
| 114 |
+
os.replace(parcial, ruta)
|
| 115 |
+
finally:
|
| 116 |
+
if os.path.exists(parcial):
|
| 117 |
+
os.remove(parcial)
|
| 118 |
+
return {"ok": True, "bytes": total}
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
@router.post("/tareas/{task_id}/archivos/confirmar")
|
| 122 |
+
def confirmar_archivos(task_id: str, data: ConfirmarIn, workers: list = Depends(workers_del_equipo),
|
| 123 |
+
db: Session = Depends(get_db)):
|
| 124 |
+
_ejecutar(ops.exigir_subida, db, workers, task_id)
|
| 125 |
+
try:
|
| 126 |
+
return {"lote": subidas_worker.confirmar(task_id, data.archivos, data.mensaje or "Subir archivos")}
|
| 127 |
+
except subidas_worker.SubidaInvalida as e:
|
| 128 |
+
raise HTTPException(status_code=400, detail=str(e))
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
@router.get("/archivos/lote/{lote}")
|
| 132 |
+
def estado_lote(lote: str, workers: list = Depends(workers_del_equipo)):
|
| 133 |
+
return subidas_worker.estado(lote)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
@router.post("/tareas/{task_id}/reclamar")
|
| 137 |
def reclamar(task_id: str, workers: list = Depends(workers_del_equipo), db: Session = Depends(get_db)):
|
| 138 |
return {"ok": ops.reclamar(db, workers, task_id)}
|
|
|
|
| 174 |
|
| 175 |
@router.get("/tareas/{task_id}/armonia")
|
| 176 |
def datos_armonia(task_id: str, workers: list = Depends(workers_del_equipo), db: Session = Depends(get_db)):
|
| 177 |
+
return _ejecutar(ops.datos_armonia, db, workers, task_id)
|
| 178 |
|
| 179 |
|
| 180 |
@router.post("/tareas/{task_id}/armonia/etapa")
|
| 181 |
def etapa_armonia(task_id: str, data: EtapaIn, workers: list = Depends(workers_del_equipo), db: Session = Depends(get_db)):
|
| 182 |
+
_ejecutar(ops.etapa_armonia, db, workers, task_id, data.p, data.m)
|
| 183 |
return {"ok": True}
|
| 184 |
|
| 185 |
|
| 186 |
@router.post("/tareas/{task_id}/armonia/completar")
|
| 187 |
def completar_armonia(task_id: str, data: UrlsIn, workers: list = Depends(workers_del_equipo), db: Session = Depends(get_db)):
|
| 188 |
+
_ejecutar(ops.completar_armonia, db, workers, task_id, data.urls)
|
| 189 |
return {"ok": True}
|
| 190 |
|
| 191 |
|
| 192 |
@router.post("/tareas/{task_id}/armonia/error")
|
| 193 |
def error_armonia(task_id: str, workers: list = Depends(workers_del_equipo), db: Session = Depends(get_db)):
|
| 194 |
+
_ejecutar(ops.error_armonia, db, workers, task_id)
|
| 195 |
return {"ok": True}
|
app/routers/workers.py
CHANGED
|
@@ -32,6 +32,7 @@ class WorkerResponse(BaseModel):
|
|
| 32 |
is_active: Optional[bool] = False
|
| 33 |
# Sin este campo FastAPI lo descartaba de la respuesta y el panel mostraba "Sin dato"
|
| 34 |
version: Optional[str] = None
|
|
|
|
| 35 |
owner_username: Optional[str] = None
|
| 36 |
|
| 37 |
class Config:
|
|
@@ -42,6 +43,7 @@ class WorkerUpdate(BaseModel):
|
|
| 42 |
status: Optional[str] = None
|
| 43 |
is_public: Optional[bool] = None
|
| 44 |
user_id: Optional[int] = None
|
|
|
|
| 45 |
|
| 46 |
@router.post("/register", response_model=WorkerResponse)
|
| 47 |
def register_worker(data: WorkerRegister, db: Session = Depends(get_db)):
|
|
@@ -117,6 +119,8 @@ def get_workers(db: Session = Depends(get_db), current_admin: AdminUser = Depend
|
|
| 117 |
"is_public": getattr(w, "is_public", False),
|
| 118 |
"is_active": getattr(w, "is_active", False),
|
| 119 |
"version": getattr(w, "version", None),
|
|
|
|
|
|
|
| 120 |
"owner_username": w.owner.username if w.owner else None
|
| 121 |
}
|
| 122 |
for w in workers
|
|
@@ -181,6 +185,8 @@ def update_worker(worker_id: int, data: WorkerUpdate, db: Session = Depends(get_
|
|
| 181 |
worker.name = data.name
|
| 182 |
if data.user_id is not None:
|
| 183 |
worker.user_id = data.user_id if data.user_id > 0 else None
|
|
|
|
|
|
|
| 184 |
if data.is_public is not None:
|
| 185 |
worker.is_public = data.is_public
|
| 186 |
if worker.user_id:
|
|
|
|
| 32 |
is_active: Optional[bool] = False
|
| 33 |
# Sin este campo FastAPI lo descartaba de la respuesta y el panel mostraba "Sin dato"
|
| 34 |
version: Optional[str] = None
|
| 35 |
+
publico_aprobado: Optional[bool] = None
|
| 36 |
owner_username: Optional[str] = None
|
| 37 |
|
| 38 |
class Config:
|
|
|
|
| 43 |
status: Optional[str] = None
|
| 44 |
is_public: Optional[bool] = None
|
| 45 |
user_id: Optional[int] = None
|
| 46 |
+
publico_aprobado: Optional[bool] = None
|
| 47 |
|
| 48 |
@router.post("/register", response_model=WorkerResponse)
|
| 49 |
def register_worker(data: WorkerRegister, db: Session = Depends(get_db)):
|
|
|
|
| 119 |
"is_public": getattr(w, "is_public", False),
|
| 120 |
"is_active": getattr(w, "is_active", False),
|
| 121 |
"version": getattr(w, "version", None),
|
| 122 |
+
# NULL = equipo anterior a la regla de aprobación: cuenta como aprobado
|
| 123 |
+
"publico_aprobado": w.publico_aprobado is not False,
|
| 124 |
"owner_username": w.owner.username if w.owner else None
|
| 125 |
}
|
| 126 |
for w in workers
|
|
|
|
| 185 |
worker.name = data.name
|
| 186 |
if data.user_id is not None:
|
| 187 |
worker.user_id = data.user_id if data.user_id > 0 else None
|
| 188 |
+
if data.publico_aprobado is not None:
|
| 189 |
+
worker.publico_aprobado = data.publico_aprobado
|
| 190 |
if data.is_public is not None:
|
| 191 |
worker.is_public = data.is_public
|
| 192 |
if worker.user_id:
|
app/utils/despacho.py
CHANGED
|
@@ -24,16 +24,21 @@ from app.utils.worker_version import _tupla, worker_desactualizado
|
|
| 24 |
logger = logging.getLogger(__name__)
|
| 25 |
|
| 26 |
VERSION_COLA_PROPIA = "2.8.23"
|
|
|
|
|
|
|
| 27 |
|
| 28 |
# Un equipo cuenta como conectado si dio señales de vida hace menos de esto
|
| 29 |
SEGUNDOS_CONECTADO = 120
|
| 30 |
# Después de mandarle una canción a un equipo, no se le manda otra durante este tiempo aunque figure
|
| 31 |
# libre: tarda unos segundos en tomarla y marcarse ocupado
|
| 32 |
SEGUNDOS_GRACIA_ENVIO = 90
|
|
|
|
|
|
|
| 33 |
# Cada cuánto revisa el despachador
|
| 34 |
INTERVALO_DESPACHO = 10
|
| 35 |
|
| 36 |
_ultimo_envio = {}
|
|
|
|
| 37 |
_lock = threading.Lock()
|
| 38 |
|
| 39 |
|
|
@@ -50,6 +55,29 @@ def soporta_cola_propia(worker) -> bool:
|
|
| 50 |
return bool(worker is not None and worker.user_id and actual and actual >= _tupla(VERSION_COLA_PROPIA))
|
| 51 |
|
| 52 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
def marcar_envio(worker_id: int):
|
| 54 |
with _lock:
|
| 55 |
_ultimo_envio[worker_id] = time.time()
|
|
@@ -227,7 +255,7 @@ def despachar_esperas(conexion=None) -> dict:
|
|
| 227 |
escuchan = {}
|
| 228 |
for w in equipos:
|
| 229 |
estado = _declarar(canal, cola_worker(w.id))
|
| 230 |
-
escuchan[w.id] = estado.consumer_count > 0
|
| 231 |
conectado = _conectado(w, ahora) and w.status != "suspended"
|
| 232 |
if conectado:
|
| 233 |
conectados[w.user_id].append(w)
|
|
@@ -294,7 +322,7 @@ def estado_colas(db, conexion=None) -> dict:
|
|
| 294 |
for w in equipos:
|
| 295 |
estado = _declarar(canal, cola_worker(w.id))
|
| 296 |
resultado["equipos"].append({"id": w.id, "hostname": w.hostname, "en_fila": estado.message_count,
|
| 297 |
-
"escuchando": estado.consumer_count > 0})
|
| 298 |
for user_id in sorted({w.user_id for w in equipos}):
|
| 299 |
canciones = _pendientes(canal, cola_espera(user_id))
|
| 300 |
if canciones:
|
|
@@ -324,6 +352,16 @@ def iniciar_despachador():
|
|
| 324 |
despachar_esperas()
|
| 325 |
except Exception as e:
|
| 326 |
logger.warning(f"[Despacho] Error en el despachador: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 327 |
try:
|
| 328 |
# Canción pública enviada a un voluntario que no la tomó a tiempo: la procesa Hugging Face
|
| 329 |
from app.utils.hf_wake import reenviar_tareas_publicas_sin_tomar
|
|
|
|
| 24 |
logger = logging.getLogger(__name__)
|
| 25 |
|
| 26 |
VERSION_COLA_PROPIA = "2.8.23"
|
| 27 |
+
# Desde esta versión el equipo no se conecta al broker: pide sus canciones a la API (app/utils/puente.py)
|
| 28 |
+
VERSION_PUENTE = "2.8.29"
|
| 29 |
|
| 30 |
# Un equipo cuenta como conectado si dio señales de vida hace menos de esto
|
| 31 |
SEGUNDOS_CONECTADO = 120
|
| 32 |
# Después de mandarle una canción a un equipo, no se le manda otra durante este tiempo aunque figure
|
| 33 |
# libre: tarda unos segundos en tomarla y marcarse ocupado
|
| 34 |
SEGUNDOS_GRACIA_ENVIO = 90
|
| 35 |
+
# Un equipo que pide por la API sigue "escuchando" si pidió trabajo hace menos de esto
|
| 36 |
+
SEGUNDOS_PEDIDO = 60
|
| 37 |
# Cada cuánto revisa el despachador
|
| 38 |
INTERVALO_DESPACHO = 10
|
| 39 |
|
| 40 |
_ultimo_envio = {}
|
| 41 |
+
_ultimo_pedido = {}
|
| 42 |
_lock = threading.Lock()
|
| 43 |
|
| 44 |
|
|
|
|
| 55 |
return bool(worker is not None and worker.user_id and actual and actual >= _tupla(VERSION_COLA_PROPIA))
|
| 56 |
|
| 57 |
|
| 58 |
+
def soporta_puente(worker) -> bool:
|
| 59 |
+
actual = _tupla(getattr(worker, "version", None) or "")
|
| 60 |
+
return bool(worker is not None and actual and actual >= _tupla(VERSION_PUENTE))
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def marcar_pedido(worker_ids: list):
|
| 64 |
+
with _lock:
|
| 65 |
+
ahora = time.time()
|
| 66 |
+
for worker_id in worker_ids:
|
| 67 |
+
_ultimo_pedido[worker_id] = ahora
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def pide_por_api(worker) -> bool:
|
| 71 |
+
"""Equipo con el motor nuevo funcionando: pidió trabajo hace poco o está procesando."""
|
| 72 |
+
if not soporta_puente(worker):
|
| 73 |
+
return False
|
| 74 |
+
if worker.status == "busy":
|
| 75 |
+
return True
|
| 76 |
+
with _lock:
|
| 77 |
+
t = _ultimo_pedido.get(worker.id)
|
| 78 |
+
return t is not None and time.time() - t < SEGUNDOS_PEDIDO
|
| 79 |
+
|
| 80 |
+
|
| 81 |
def marcar_envio(worker_id: int):
|
| 82 |
with _lock:
|
| 83 |
_ultimo_envio[worker_id] = time.time()
|
|
|
|
| 255 |
escuchan = {}
|
| 256 |
for w in equipos:
|
| 257 |
estado = _declarar(canal, cola_worker(w.id))
|
| 258 |
+
escuchan[w.id] = estado.consumer_count > 0 or pide_por_api(w)
|
| 259 |
conectado = _conectado(w, ahora) and w.status != "suspended"
|
| 260 |
if conectado:
|
| 261 |
conectados[w.user_id].append(w)
|
|
|
|
| 322 |
for w in equipos:
|
| 323 |
estado = _declarar(canal, cola_worker(w.id))
|
| 324 |
resultado["equipos"].append({"id": w.id, "hostname": w.hostname, "en_fila": estado.message_count,
|
| 325 |
+
"escuchando": estado.consumer_count > 0 or pide_por_api(w)})
|
| 326 |
for user_id in sorted({w.user_id for w in equipos}):
|
| 327 |
canciones = _pendientes(canal, cola_espera(user_id))
|
| 328 |
if canciones:
|
|
|
|
| 352 |
despachar_esperas()
|
| 353 |
except Exception as e:
|
| 354 |
logger.warning(f"[Despacho] Error en el despachador: {e}")
|
| 355 |
+
try:
|
| 356 |
+
from app.database import SessionLocal
|
| 357 |
+
from app.utils.puente import recuperar_perdidos
|
| 358 |
+
_db = SessionLocal()
|
| 359 |
+
try:
|
| 360 |
+
recuperar_perdidos(_db)
|
| 361 |
+
finally:
|
| 362 |
+
_db.close()
|
| 363 |
+
except Exception as e:
|
| 364 |
+
logger.warning(f"[Despacho] Error recuperando canciones de equipos caídos: {e}")
|
| 365 |
try:
|
| 366 |
# Canción pública enviada a un voluntario que no la tomó a tiempo: la procesa Hugging Face
|
| 367 |
from app.utils.hf_wake import reenviar_tareas_publicas_sin_tomar
|
app/utils/puente.py
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Reparto de canciones a los workers residenciales SIN darles la llave del broker.
|
| 3 |
+
|
| 4 |
+
Las colas siguen en RabbitMQ, pero solo la API las toca: el equipo pide su siguiente trabajo con su
|
| 5 |
+
token (POST /workers/datos/trabajo) y la API lo saca de las colas que le corresponden. Así, un equipo
|
| 6 |
+
solo puede recibir lo suyo y se le puede bloquear sin afectar a los demás.
|
| 7 |
+
|
| 8 |
+
RabbitMQ deja de guardar la canción al entregarla, por eso la API anota en tasks.trabajo_json lo
|
| 9 |
+
necesario para volver a encolarla si el equipo se apaga o se cierra a mitad de camino.
|
| 10 |
+
"""
|
| 11 |
+
import json
|
| 12 |
+
import logging
|
| 13 |
+
from datetime import datetime, timedelta
|
| 14 |
+
|
| 15 |
+
from app.models.process import Task
|
| 16 |
+
from app.utils import despacho
|
| 17 |
+
from app.utils.worker_version import worker_desactualizado
|
| 18 |
+
|
| 19 |
+
logger = logging.getLogger(__name__)
|
| 20 |
+
|
| 21 |
+
COLA_PUBLICA = "celery"
|
| 22 |
+
COLA_HF = "queue_hf"
|
| 23 |
+
|
| 24 |
+
TAREA_SEPARAR = "procesar_cancion_completa"
|
| 25 |
+
TAREA_ARMONIAS = "generar_armonias_task"
|
| 26 |
+
TAREA_LIMPIEZA = "eliminar_archivos_locales_task"
|
| 27 |
+
TAREAS_PERMITIDAS = (TAREA_SEPARAR, TAREA_ARMONIAS, TAREA_LIMPIEZA)
|
| 28 |
+
|
| 29 |
+
# Veces que se entrega una misma canción antes de darla por fallida
|
| 30 |
+
MAX_ENTREGAS = 3
|
| 31 |
+
# Canción entregada que el equipo nunca reclamó (se perdió la respuesta o se apagó justo)
|
| 32 |
+
MINUTOS_SIN_RECLAMAR = 10
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def puede_publico(worker) -> bool:
|
| 36 |
+
"""
|
| 37 |
+
Solo procesa canciones de otros usuarios si está en modo público y un administrador lo aprobó.
|
| 38 |
+
NULL = equipo que ya existía antes de esta regla (aprobado); los nuevos nacen en False.
|
| 39 |
+
"""
|
| 40 |
+
return bool(worker.is_public) and worker.publico_aprobado is not False
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def colas_del_equipo(workers: list) -> list:
|
| 44 |
+
"""[(cola, worker)] en orden de prioridad: primero lo propio, al final lo público."""
|
| 45 |
+
propias = [w for w in sorted(workers, key=lambda w: w.id) if w.user_id]
|
| 46 |
+
colas = [(despacho.cola_worker(w.id), w) for w in propias]
|
| 47 |
+
vistos = set()
|
| 48 |
+
for w in propias:
|
| 49 |
+
if w.user_id not in vistos:
|
| 50 |
+
vistos.add(w.user_id)
|
| 51 |
+
colas.append((f"queue_usr_{w.user_id}", w))
|
| 52 |
+
publico = next((w for w in propias if puede_publico(w)), None)
|
| 53 |
+
if publico is not None:
|
| 54 |
+
colas.append((COLA_PUBLICA, publico))
|
| 55 |
+
return colas
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _decodificar(mensaje):
|
| 59 |
+
"""(nombre, id, args, kwargs) de un mensaje de Celery (protocolo 2, JSON)."""
|
| 60 |
+
cabeceras = getattr(mensaje, "headers", None) or mensaje.properties.get("application_headers") or {}
|
| 61 |
+
cuerpo = mensaje.body.decode("utf-8") if isinstance(mensaje.body, (bytes, bytearray)) else mensaje.body
|
| 62 |
+
args, kwargs, _ = json.loads(cuerpo)
|
| 63 |
+
return cabeceras.get("task"), cabeceras.get("id"), args, kwargs
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _entregas_previas(task) -> int:
|
| 67 |
+
try:
|
| 68 |
+
return int(json.loads(task.trabajo_json).get("r", 0)) if task.trabajo_json else 0
|
| 69 |
+
except (ValueError, AttributeError, TypeError):
|
| 70 |
+
return 0
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _anotar(db, task, nombre, task_id, args, kwargs, cola, worker):
|
| 74 |
+
task.trabajo_json = json.dumps({
|
| 75 |
+
"n": nombre, "id": task_id, "a": args, "k": kwargs, "c": cola, "w": worker.id,
|
| 76 |
+
"t": datetime.utcnow().isoformat(timespec="seconds"), "r": _entregas_previas(task) + 1,
|
| 77 |
+
})
|
| 78 |
+
db.commit()
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _entregable(db, canal, mensaje, cola, worker):
|
| 82 |
+
"""Trabajo listo para entregar, o None si este mensaje no le toca a un equipo residencial."""
|
| 83 |
+
try:
|
| 84 |
+
nombre, task_id, args, kwargs = _decodificar(mensaje)
|
| 85 |
+
except (ValueError, TypeError, AttributeError) as e:
|
| 86 |
+
logger.warning(f"[Puente] Mensaje ilegible en '{cola}', se descarta: {e}")
|
| 87 |
+
canal.basic_ack(mensaje.delivery_tag)
|
| 88 |
+
return None
|
| 89 |
+
|
| 90 |
+
if nombre not in TAREAS_PERMITIDAS:
|
| 91 |
+
# Mantenimiento con acceso total: solo en Hugging Face
|
| 92 |
+
despacho._declarar(canal, COLA_HF)
|
| 93 |
+
canal.basic_publish(mensaje, exchange="", routing_key=COLA_HF)
|
| 94 |
+
canal.basic_ack(mensaje.delivery_tag)
|
| 95 |
+
return None
|
| 96 |
+
|
| 97 |
+
if nombre in (TAREA_SEPARAR, TAREA_ARMONIAS):
|
| 98 |
+
id_cancion = task_id if nombre == TAREA_SEPARAR else (args[0] if args else None)
|
| 99 |
+
task = db.query(Task).filter(Task.task_id == id_cancion).first()
|
| 100 |
+
if task is None:
|
| 101 |
+
canal.basic_ack(mensaje.delivery_tag) # el usuario la borró
|
| 102 |
+
return None
|
| 103 |
+
# Primero se anota y después se saca de RabbitMQ: si algo falla en medio queda duplicada
|
| 104 |
+
# (reclamar la descarta), nunca perdida
|
| 105 |
+
_anotar(db, task, nombre, task_id, args, kwargs, cola, worker)
|
| 106 |
+
canal.basic_ack(mensaje.delivery_tag)
|
| 107 |
+
return {"nombre": nombre, "id": task_id, "args": args, "kwargs": kwargs}
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def _trabajo_interrumpido(db, workers: list):
|
| 111 |
+
"""
|
| 112 |
+
El equipo pide trabajo solo cuando está libre: si figura procesando una canción, su proceso se
|
| 113 |
+
cerró a mitad de camino. Se le vuelve a entregar.
|
| 114 |
+
"""
|
| 115 |
+
from app.utils import worker_ops as ops
|
| 116 |
+
ids = [w.id for w in workers]
|
| 117 |
+
tareas = db.query(Task).filter(Task.processed_by_worker_id.in_(ids), Task.status == "processing",
|
| 118 |
+
Task.trabajo_json.isnot(None)).all()
|
| 119 |
+
for task in tareas:
|
| 120 |
+
try:
|
| 121 |
+
t = json.loads(task.trabajo_json)
|
| 122 |
+
except ValueError:
|
| 123 |
+
continue
|
| 124 |
+
if t.get("n") != TAREA_SEPARAR:
|
| 125 |
+
continue
|
| 126 |
+
if int(t.get("r", 0)) >= MAX_ENTREGAS:
|
| 127 |
+
logger.warning(f"[{task.task_id}] Se interrumpió {MAX_ENTREGAS} veces: se da por fallida.")
|
| 128 |
+
ops.fallar(db, workers, task.task_id, "El equipo se interrumpió varias veces", confiable=True)
|
| 129 |
+
continue
|
| 130 |
+
t["r"] = int(t.get("r", 0)) + 1
|
| 131 |
+
t["t"] = datetime.utcnow().isoformat(timespec="seconds")
|
| 132 |
+
task.trabajo_json = json.dumps(t)
|
| 133 |
+
db.commit()
|
| 134 |
+
logger.info(f"[{task.task_id}] El equipo la había dejado a medias: se le entrega de nuevo.")
|
| 135 |
+
return {"nombre": t["n"], "id": t["id"], "args": t["a"], "kwargs": t["k"]}
|
| 136 |
+
return None
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def siguiente_trabajo(db, workers: list, conexion=None):
|
| 140 |
+
"""El equipo está libre y pide trabajo. Devuelve {nombre, id, args, kwargs} o None."""
|
| 141 |
+
from app.utils import worker_ops as ops
|
| 142 |
+
|
| 143 |
+
info = ops.latido(db, workers)
|
| 144 |
+
activos = [w for w in workers if not worker_desactualizado(w)]
|
| 145 |
+
if info.get("suspendido") or not activos:
|
| 146 |
+
return None
|
| 147 |
+
despacho.marcar_pedido([w.id for w in activos])
|
| 148 |
+
|
| 149 |
+
pendiente = _trabajo_interrumpido(db, activos)
|
| 150 |
+
if pendiente is not None:
|
| 151 |
+
return pendiente
|
| 152 |
+
|
| 153 |
+
if conexion is None:
|
| 154 |
+
from tasks import celery_app
|
| 155 |
+
with celery_app.pool.acquire(block=True, timeout=10) as c:
|
| 156 |
+
return _sacar_de_colas(db, c.default_channel, activos)
|
| 157 |
+
return _sacar_de_colas(db, conexion.default_channel, activos)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def _sacar_de_colas(db, canal, workers: list):
|
| 161 |
+
for cola, worker in colas_del_equipo(workers):
|
| 162 |
+
despacho._declarar(canal, cola)
|
| 163 |
+
while True:
|
| 164 |
+
mensaje = canal.basic_get(queue=cola, no_ack=False)
|
| 165 |
+
if mensaje is None:
|
| 166 |
+
break
|
| 167 |
+
trabajo = _entregable(db, canal, mensaje, cola, worker)
|
| 168 |
+
if trabajo is not None:
|
| 169 |
+
despacho.quitar_espera(db, trabajo["id"])
|
| 170 |
+
return trabajo
|
| 171 |
+
return None
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def worker_de_trabajo(task):
|
| 175 |
+
"""Id del equipo al que se entregó el trabajo anotado en la canción, o None."""
|
| 176 |
+
try:
|
| 177 |
+
return json.loads(task.trabajo_json).get("w") if task.trabajo_json else None
|
| 178 |
+
except (ValueError, AttributeError):
|
| 179 |
+
return None
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
# ---------------------------------------------------------------------------
|
| 183 |
+
# Recuperación: canciones entregadas a equipos que dejaron de dar señales
|
| 184 |
+
# ---------------------------------------------------------------------------
|
| 185 |
+
|
| 186 |
+
def _destino_recuperada(db, task, trabajo: dict) -> str:
|
| 187 |
+
"""La cola pública pasa a Hugging Face; lo privado espera a otro equipo del dueño."""
|
| 188 |
+
if trabajo.get("c") == COLA_PUBLICA:
|
| 189 |
+
return COLA_HF
|
| 190 |
+
return despacho.cola_espera(task.user_id)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def recuperar_perdidos(db, publicar=None) -> int:
|
| 194 |
+
"""Una pasada: vuelve a encolar lo que quedó en equipos caídos. Devuelve cuántas canciones movió."""
|
| 195 |
+
from app.models.process import Worker
|
| 196 |
+
from app.utils import worker_ops as ops
|
| 197 |
+
|
| 198 |
+
if publicar is None:
|
| 199 |
+
from tasks import celery_app
|
| 200 |
+
|
| 201 |
+
def publicar(nombre, task_id, args, kwargs, cola):
|
| 202 |
+
celery_app.send_task(nombre, args=args, kwargs=kwargs, task_id=task_id, queue=cola)
|
| 203 |
+
|
| 204 |
+
ahora = datetime.utcnow()
|
| 205 |
+
movidas = 0
|
| 206 |
+
tareas = db.query(Task).filter(Task.trabajo_json.isnot(None),
|
| 207 |
+
Task.status.in_(("pending", "PENDING", "processing"))).all()
|
| 208 |
+
for task in tareas:
|
| 209 |
+
try:
|
| 210 |
+
t = json.loads(task.trabajo_json)
|
| 211 |
+
entregada = datetime.fromisoformat(t["t"])
|
| 212 |
+
except (ValueError, KeyError, TypeError):
|
| 213 |
+
continue
|
| 214 |
+
if t.get("n") != TAREA_SEPARAR or t.get("reenviado"):
|
| 215 |
+
continue
|
| 216 |
+
|
| 217 |
+
if task.processed_by_worker_id is not None:
|
| 218 |
+
w = db.query(Worker).filter(Worker.id == task.processed_by_worker_id).first()
|
| 219 |
+
caido = ops._tomador_caido(db, task.processed_by_worker_id) or (w is not None and w.status == "suspended")
|
| 220 |
+
else:
|
| 221 |
+
caido = ahora - entregada > timedelta(minutes=MINUTOS_SIN_RECLAMAR)
|
| 222 |
+
if not caido:
|
| 223 |
+
continue
|
| 224 |
+
|
| 225 |
+
if int(t.get("r", 0)) >= MAX_ENTREGAS:
|
| 226 |
+
ops.fallar(db, [], task.task_id, "Ningún equipo pudo terminarla", confiable=True)
|
| 227 |
+
continue
|
| 228 |
+
|
| 229 |
+
destino = _destino_recuperada(db, task, t)
|
| 230 |
+
publicar(t["n"], t["id"], t["a"], t["k"], destino)
|
| 231 |
+
t["reenviado"] = True
|
| 232 |
+
task.trabajo_json = json.dumps(t)
|
| 233 |
+
task.processed_by_worker_id = None
|
| 234 |
+
task.status = "pending"
|
| 235 |
+
db.commit()
|
| 236 |
+
if destino != COLA_HF:
|
| 237 |
+
despacho.marcar_espera(db, task.task_id, propia=True)
|
| 238 |
+
movidas += 1
|
| 239 |
+
logger.info(f"[{task.task_id}] El equipo no dio señales: la canción vuelve a '{destino}'.")
|
| 240 |
+
return movidas
|
app/utils/subidas_worker.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Subida de pistas de los workers residenciales: el equipo no tiene token de Hugging Face.
|
| 3 |
+
|
| 4 |
+
El equipo manda cada archivo a la API, que lo guarda en una carpeta temporal y, al confirmar, lo sube
|
| 5 |
+
al dataset con su propio token. Solo se aceptan archivos de canciones que ese equipo está procesando.
|
| 6 |
+
El commit a Hugging Face puede tardar minutos, así que corre en un hilo y el equipo consulta el resultado.
|
| 7 |
+
"""
|
| 8 |
+
import logging
|
| 9 |
+
import os
|
| 10 |
+
import re
|
| 11 |
+
import shutil
|
| 12 |
+
import tempfile
|
| 13 |
+
import threading
|
| 14 |
+
import time
|
| 15 |
+
import uuid
|
| 16 |
+
|
| 17 |
+
logger = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
+
CARPETA = os.path.join(tempfile.gettempdir(), "melodix_subidas")
|
| 20 |
+
NOMBRE_VALIDO = re.compile(r"^[A-Za-z0-9_\-]{1,60}\.(m4a|flac|json)$")
|
| 21 |
+
TAMANO_MAXIMO = 300 * 1024 * 1024
|
| 22 |
+
MAX_ARCHIVOS = 40
|
| 23 |
+
HORAS_CONSERVAR = 6
|
| 24 |
+
SEGUNDOS_RESULTADO = 3600
|
| 25 |
+
|
| 26 |
+
_lotes = {}
|
| 27 |
+
_lock = threading.Lock()
|
| 28 |
+
# Un commit a la vez: el dataset rechaza commits simultáneos y tiene límite por hora
|
| 29 |
+
_lock_commit = threading.Lock()
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class SubidaInvalida(Exception):
|
| 33 |
+
pass
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def carpeta_de(task_id: str) -> str:
|
| 37 |
+
return os.path.join(CARPETA, task_id)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def validar_nombre(nombre: str):
|
| 41 |
+
if not isinstance(nombre, str) or not NOMBRE_VALIDO.match(nombre):
|
| 42 |
+
raise SubidaInvalida(f"Nombre de archivo no permitido: {nombre}")
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def ruta_destino(task_id: str, nombre: str) -> str:
|
| 46 |
+
validar_nombre(nombre)
|
| 47 |
+
carpeta = carpeta_de(task_id)
|
| 48 |
+
os.makedirs(carpeta, exist_ok=True)
|
| 49 |
+
if len(os.listdir(carpeta)) >= MAX_ARCHIVOS and not os.path.exists(os.path.join(carpeta, nombre)):
|
| 50 |
+
raise SubidaInvalida("Demasiados archivos para esta canción")
|
| 51 |
+
return os.path.join(carpeta, nombre)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def _purgar_viejos():
|
| 55 |
+
limite = time.time() - HORAS_CONSERVAR * 3600
|
| 56 |
+
try:
|
| 57 |
+
for nombre in os.listdir(CARPETA):
|
| 58 |
+
ruta = os.path.join(CARPETA, nombre)
|
| 59 |
+
if os.path.getmtime(ruta) < limite:
|
| 60 |
+
shutil.rmtree(ruta, ignore_errors=True)
|
| 61 |
+
except OSError:
|
| 62 |
+
pass
|
| 63 |
+
with _lock:
|
| 64 |
+
for lote in [k for k, v in _lotes.items() if time.time() - v["t"] > SEGUNDOS_RESULTADO]:
|
| 65 |
+
del _lotes[lote]
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _subir(lote: str, task_id: str, archivos: list, mensaje: str):
|
| 69 |
+
from app.utils.hf_storage import upload_many_to_hf
|
| 70 |
+
try:
|
| 71 |
+
with _lock_commit:
|
| 72 |
+
urls = upload_many_to_hf(archivos, commit_message=mensaje)
|
| 73 |
+
resultado = {"estado": "listo", "urls": urls, "t": time.time()}
|
| 74 |
+
except Exception as e:
|
| 75 |
+
logger.error(f"[{task_id}] No se pudieron subir las pistas al dataset: {e}")
|
| 76 |
+
resultado = {"estado": "error", "urls": {}, "t": time.time()}
|
| 77 |
+
for ruta, _ in archivos:
|
| 78 |
+
try:
|
| 79 |
+
os.remove(ruta)
|
| 80 |
+
except OSError:
|
| 81 |
+
pass
|
| 82 |
+
try:
|
| 83 |
+
os.rmdir(carpeta_de(task_id)) # solo si quedó vacía
|
| 84 |
+
except OSError:
|
| 85 |
+
pass
|
| 86 |
+
with _lock:
|
| 87 |
+
_lotes[lote] = resultado
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def confirmar(task_id: str, nombres: list, mensaje: str) -> str:
|
| 91 |
+
"""Empieza a subir al dataset los archivos ya recibidos. Devuelve el id del lote."""
|
| 92 |
+
_purgar_viejos()
|
| 93 |
+
archivos = []
|
| 94 |
+
for nombre in nombres:
|
| 95 |
+
validar_nombre(nombre)
|
| 96 |
+
ruta = os.path.join(carpeta_de(task_id), nombre)
|
| 97 |
+
if not os.path.exists(ruta):
|
| 98 |
+
raise SubidaInvalida(f"Falta el archivo {nombre}")
|
| 99 |
+
archivos.append((ruta, f"stems/{task_id}/{nombre}"))
|
| 100 |
+
if not archivos:
|
| 101 |
+
raise SubidaInvalida("No hay archivos para subir")
|
| 102 |
+
|
| 103 |
+
lote = uuid.uuid4().hex
|
| 104 |
+
with _lock:
|
| 105 |
+
_lotes[lote] = {"estado": "subiendo", "urls": {}, "t": time.time()}
|
| 106 |
+
threading.Thread(target=_subir, args=(lote, task_id, archivos, f"{mensaje[:80]} ({task_id})"),
|
| 107 |
+
daemon=True, name=f"subida-{task_id}").start()
|
| 108 |
+
return lote
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def estado(lote: str) -> dict:
|
| 112 |
+
"""{'estado': 'subiendo'|'listo'|'error'|'desconocido', 'urls': {...}}"""
|
| 113 |
+
with _lock:
|
| 114 |
+
datos = _lotes.get(lote)
|
| 115 |
+
if datos is None:
|
| 116 |
+
return {"estado": "desconocido", "urls": {}} # la API se reinició: el equipo vuelve a subir
|
| 117 |
+
return {"estado": datos["estado"], "urls": datos["urls"]}
|
app/utils/worker_datos.py
CHANGED
|
@@ -113,6 +113,70 @@ def latido() -> dict:
|
|
| 113 |
return _api("POST", "/latido", intentos=1)
|
| 114 |
|
| 115 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
def reclamar(task_id: str) -> bool:
|
| 117 |
if MODO_DIRECTO:
|
| 118 |
with _Sesion() as s:
|
|
@@ -171,14 +235,14 @@ def datos_armonia(task_id: str) -> dict:
|
|
| 171 |
"""{'existe', 'urls', 'chords', 'folder'}"""
|
| 172 |
if MODO_DIRECTO:
|
| 173 |
with _Sesion() as s:
|
| 174 |
-
return _ops().datos_armonia(s.db, task_id)
|
| 175 |
return _api("GET", f"/tareas/{task_id}/armonia")
|
| 176 |
|
| 177 |
|
| 178 |
def etapa_armonia(task_id: str, progreso: int, mensaje: str):
|
| 179 |
if MODO_DIRECTO:
|
| 180 |
with _Sesion() as s:
|
| 181 |
-
_ops().etapa_armonia(s.db, task_id, progreso, mensaje)
|
| 182 |
return
|
| 183 |
_api("POST", f"/tareas/{task_id}/armonia/etapa", {"p": progreso, "m": mensaje}, intentos=1, timeout=10)
|
| 184 |
|
|
@@ -186,7 +250,7 @@ def etapa_armonia(task_id: str, progreso: int, mensaje: str):
|
|
| 186 |
def completar_armonia(task_id: str, urls: dict):
|
| 187 |
if MODO_DIRECTO:
|
| 188 |
with _Sesion() as s:
|
| 189 |
-
_ops().completar_armonia(s.db, task_id, urls)
|
| 190 |
return
|
| 191 |
_api("POST", f"/tareas/{task_id}/armonia/completar", {"urls": urls}, intentos=6, timeout=30)
|
| 192 |
|
|
@@ -194,7 +258,7 @@ def completar_armonia(task_id: str, urls: dict):
|
|
| 194 |
def error_armonia(task_id: str):
|
| 195 |
if MODO_DIRECTO:
|
| 196 |
with _Sesion() as s:
|
| 197 |
-
_ops().error_armonia(s.db, task_id)
|
| 198 |
return
|
| 199 |
_api("POST", f"/tareas/{task_id}/armonia/error")
|
| 200 |
|
|
@@ -204,6 +268,8 @@ def error_armonia(task_id: str):
|
|
| 204 |
# ---------------------------------------------------------------------------
|
| 205 |
|
| 206 |
CLAVES_PROHIBIDAS = ("DATABASE_URL", "SECRET_KEY", "SUPABASE_JWT_SECRET")
|
|
|
|
|
|
|
| 207 |
|
| 208 |
|
| 209 |
def es_worker_instalado(dir_api: str) -> bool:
|
|
@@ -211,7 +277,7 @@ def es_worker_instalado(dir_api: str) -> bool:
|
|
| 211 |
return os.path.exists(os.path.join(os.path.dirname(os.path.abspath(dir_api)), "version.txt"))
|
| 212 |
|
| 213 |
|
| 214 |
-
def limpiar_credenciales_env(ruta_env: str) -> list:
|
| 215 |
"""
|
| 216 |
Los instaladores viejos dejaban credenciales de producción en el .env del worker. En modo API
|
| 217 |
no se usan: se borran del archivo. Devuelve las claves borradas.
|
|
@@ -224,7 +290,7 @@ def limpiar_credenciales_env(ruta_env: str) -> list:
|
|
| 224 |
quedan, borradas = [], []
|
| 225 |
for linea in lineas:
|
| 226 |
clave = linea.split("=", 1)[0].strip()
|
| 227 |
-
if clave in CLAVES_PROHIBIDAS:
|
| 228 |
borradas.append(clave)
|
| 229 |
else:
|
| 230 |
quedan.append(linea)
|
|
|
|
| 113 |
return _api("POST", "/latido", intentos=1)
|
| 114 |
|
| 115 |
|
| 116 |
+
def pedir_trabajo():
|
| 117 |
+
"""Siguiente canción de este equipo ({nombre, id, args, kwargs}) o None. Solo modo API."""
|
| 118 |
+
return _api("POST", "/trabajo", intentos=1, timeout=30).get("trabajo")
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def _enviar_archivo(task_id: str, nombre: str, ruta: str) -> bool:
|
| 122 |
+
import requests
|
| 123 |
+
url = f"{API_URL}/workers/datos/tareas/{task_id}/archivos/{nombre}"
|
| 124 |
+
cabeceras = {**_cabeceras(), "Content-Type": "application/octet-stream"}
|
| 125 |
+
for i in range(4):
|
| 126 |
+
try:
|
| 127 |
+
with open(ruta, "rb") as f:
|
| 128 |
+
r = requests.put(url, data=f, headers=cabeceras, timeout=(30, 1800))
|
| 129 |
+
if r.status_code < 300:
|
| 130 |
+
return True
|
| 131 |
+
if r.status_code == 429:
|
| 132 |
+
time.sleep(30 * (i + 1))
|
| 133 |
+
continue
|
| 134 |
+
if r.status_code < 500:
|
| 135 |
+
logger.error(f"[{task_id}] La API rechazó {nombre}: {r.status_code} {r.text[:200]}")
|
| 136 |
+
return False
|
| 137 |
+
logger.warning(f"[{task_id}] Error {r.status_code} subiendo {nombre}, intento {i + 1}")
|
| 138 |
+
except Exception as e:
|
| 139 |
+
logger.warning(f"[{task_id}] Fallo subiendo {nombre}, intento {i + 1}: {str(e)[:160]}")
|
| 140 |
+
time.sleep(min(2 ** i * 5, 60))
|
| 141 |
+
return False
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def subir_a_hf(files, commit_message: str = "Subir archivos") -> dict:
|
| 145 |
+
"""
|
| 146 |
+
Sube archivos al dataset. files: [(ruta_local, 'stems/<task_id>/<nombre>')]; devuelve
|
| 147 |
+
{object_name: url} de los subidos. Hugging Face usa su token; los residenciales pasan por la API.
|
| 148 |
+
"""
|
| 149 |
+
if MODO_DIRECTO:
|
| 150 |
+
from app.utils.hf_storage import upload_many_to_hf
|
| 151 |
+
return upload_many_to_hf(files, commit_message=commit_message)
|
| 152 |
+
|
| 153 |
+
files = [(ruta, nombre) for ruta, nombre in files if os.path.exists(ruta)]
|
| 154 |
+
if not files:
|
| 155 |
+
return {}
|
| 156 |
+
task_id = files[0][1].split("/")[1]
|
| 157 |
+
for _ in range(2):
|
| 158 |
+
nombres = [clave.rsplit("/", 1)[1] for ruta, clave in files
|
| 159 |
+
if _enviar_archivo(task_id, clave.rsplit("/", 1)[1], ruta)]
|
| 160 |
+
if not nombres:
|
| 161 |
+
return {}
|
| 162 |
+
lote = _api("POST", f"/tareas/{task_id}/archivos/confirmar",
|
| 163 |
+
{"archivos": nombres, "mensaje": commit_message}, intentos=4, timeout=60)["lote"]
|
| 164 |
+
limite = time.time() + 1800
|
| 165 |
+
estado = {"estado": "subiendo"}
|
| 166 |
+
while estado["estado"] == "subiendo" and time.time() < limite:
|
| 167 |
+
time.sleep(5)
|
| 168 |
+
try:
|
| 169 |
+
estado = _api("GET", f"/archivos/lote/{lote}", intentos=3, timeout=20)
|
| 170 |
+
except ErrorDatosWorker as e:
|
| 171 |
+
logger.warning(f"[{task_id}] No se pudo consultar la subida: {str(e)[:160]}")
|
| 172 |
+
if estado["estado"] == "listo":
|
| 173 |
+
return estado.get("urls") or {}
|
| 174 |
+
if estado["estado"] != "desconocido":
|
| 175 |
+
return {}
|
| 176 |
+
logger.warning(f"[{task_id}] La API se reinició durante la subida: se envían de nuevo.")
|
| 177 |
+
return {}
|
| 178 |
+
|
| 179 |
+
|
| 180 |
def reclamar(task_id: str) -> bool:
|
| 181 |
if MODO_DIRECTO:
|
| 182 |
with _Sesion() as s:
|
|
|
|
| 235 |
"""{'existe', 'urls', 'chords', 'folder'}"""
|
| 236 |
if MODO_DIRECTO:
|
| 237 |
with _Sesion() as s:
|
| 238 |
+
return _ops().datos_armonia(s.db, s.workers, task_id, confiable=True)
|
| 239 |
return _api("GET", f"/tareas/{task_id}/armonia")
|
| 240 |
|
| 241 |
|
| 242 |
def etapa_armonia(task_id: str, progreso: int, mensaje: str):
|
| 243 |
if MODO_DIRECTO:
|
| 244 |
with _Sesion() as s:
|
| 245 |
+
_ops().etapa_armonia(s.db, s.workers, task_id, progreso, mensaje, confiable=True)
|
| 246 |
return
|
| 247 |
_api("POST", f"/tareas/{task_id}/armonia/etapa", {"p": progreso, "m": mensaje}, intentos=1, timeout=10)
|
| 248 |
|
|
|
|
| 250 |
def completar_armonia(task_id: str, urls: dict):
|
| 251 |
if MODO_DIRECTO:
|
| 252 |
with _Sesion() as s:
|
| 253 |
+
_ops().completar_armonia(s.db, s.workers, task_id, urls, confiable=True)
|
| 254 |
return
|
| 255 |
_api("POST", f"/tareas/{task_id}/armonia/completar", {"urls": urls}, intentos=6, timeout=30)
|
| 256 |
|
|
|
|
| 258 |
def error_armonia(task_id: str):
|
| 259 |
if MODO_DIRECTO:
|
| 260 |
with _Sesion() as s:
|
| 261 |
+
_ops().error_armonia(s.db, s.workers, task_id, confiable=True)
|
| 262 |
return
|
| 263 |
_api("POST", f"/tareas/{task_id}/armonia/error")
|
| 264 |
|
|
|
|
| 268 |
# ---------------------------------------------------------------------------
|
| 269 |
|
| 270 |
CLAVES_PROHIBIDAS = ("DATABASE_URL", "SECRET_KEY", "SUPABASE_JWT_SECRET")
|
| 271 |
+
# Con el motor que pide trabajo a la API tampoco hacen falta estas
|
| 272 |
+
CLAVES_SIN_BROKER = ("BROKER_URL", "REDIS_URL", "CLOUDAMQP_URL", "HF_TOKEN")
|
| 273 |
|
| 274 |
|
| 275 |
def es_worker_instalado(dir_api: str) -> bool:
|
|
|
|
| 277 |
return os.path.exists(os.path.join(os.path.dirname(os.path.abspath(dir_api)), "version.txt"))
|
| 278 |
|
| 279 |
|
| 280 |
+
def limpiar_credenciales_env(ruta_env: str, extra: tuple = ()) -> list:
|
| 281 |
"""
|
| 282 |
Los instaladores viejos dejaban credenciales de producción en el .env del worker. En modo API
|
| 283 |
no se usan: se borran del archivo. Devuelve las claves borradas.
|
|
|
|
| 290 |
quedan, borradas = [], []
|
| 291 |
for linea in lineas:
|
| 292 |
clave = linea.split("=", 1)[0].strip()
|
| 293 |
+
if clave in CLAVES_PROHIBIDAS or clave in extra:
|
| 294 |
borradas.append(clave)
|
| 295 |
else:
|
| 296 |
quedan.append(linea)
|
app/utils/worker_ops.py
CHANGED
|
@@ -208,6 +208,32 @@ def _recompensar(db, worker, task):
|
|
| 208 |
logger.warning(f"[{task.task_id}] Error al dar la recompensa del worker: {e}")
|
| 209 |
|
| 210 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 211 |
def _avisar(user_id, mensaje: dict):
|
| 212 |
try:
|
| 213 |
from app.websocket_manager import send_sync_message
|
|
@@ -244,9 +270,12 @@ def completar(db, workers: list, task_id: str, datos: dict, confiable: bool = Fa
|
|
| 244 |
task.status = "completed"
|
| 245 |
if worker is not None:
|
| 246 |
task.processed_by_worker_id = worker.id
|
|
|
|
| 247 |
_vencimiento(db, task)
|
| 248 |
_recompensar(db, worker, task)
|
| 249 |
db.commit()
|
|
|
|
|
|
|
| 250 |
|
| 251 |
_avisar(task.user_id, {"type": "song_processing_completed", "task_id": task_id,
|
| 252 |
"song_name": task.song_name, "status": "completed"})
|
|
@@ -262,6 +291,9 @@ def fallar(db, workers: list, task_id: str, error: str, confiable: bool = False)
|
|
| 262 |
if task.status == "failed":
|
| 263 |
return
|
| 264 |
task.status = "failed"
|
|
|
|
|
|
|
|
|
|
| 265 |
logger.warning(f"[{task_id}] Falló en el worker: {(error or '')[:250]}")
|
| 266 |
if task.user_id:
|
| 267 |
try:
|
|
@@ -316,11 +348,27 @@ def _exigir_armonia_en_curso(task):
|
|
| 316 |
raise OperacionNoPermitida("No hay voces corales pedidas para esta tarea")
|
| 317 |
|
| 318 |
|
| 319 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 320 |
task = _tarea(db, task_id)
|
| 321 |
if task is None:
|
| 322 |
return {"existe": False}
|
| 323 |
_exigir_armonia_en_curso(task)
|
|
|
|
| 324 |
from app.routers.songs import _resolve_task_folder
|
| 325 |
return {
|
| 326 |
"existe": True,
|
|
@@ -330,33 +378,38 @@ def datos_armonia(db, task_id: str) -> dict:
|
|
| 330 |
}
|
| 331 |
|
| 332 |
|
| 333 |
-
def etapa_armonia(db, task_id: str, progreso: int, mensaje: str):
|
| 334 |
task = _tarea(db, task_id)
|
| 335 |
if task is None:
|
| 336 |
return
|
| 337 |
_exigir_armonia_en_curso(task)
|
|
|
|
| 338 |
task.harmony_status = "generating"
|
| 339 |
task.harmony_stage = json.dumps({"p": int(progreso), "m": str(mensaje)[:200]})
|
| 340 |
task.harmony_updated_at = datetime.utcnow()
|
| 341 |
db.commit()
|
| 342 |
|
| 343 |
|
| 344 |
-
def completar_armonia(db, task_id: str, urls: dict):
|
| 345 |
task = _tarea(db, task_id)
|
| 346 |
if task is None:
|
| 347 |
return
|
| 348 |
_exigir_armonia_en_curso(task)
|
|
|
|
| 349 |
actuales = json.loads(task.telegram_file_ids) if task.telegram_file_ids else {}
|
| 350 |
actuales.update(_validar_urls(task_id, urls))
|
| 351 |
task.telegram_file_ids = json.dumps(actuales)
|
| 352 |
task.has_harmony = True
|
| 353 |
task.harmony_status = "completed"
|
|
|
|
| 354 |
db.commit()
|
| 355 |
|
| 356 |
|
| 357 |
-
def error_armonia(db, task_id: str):
|
| 358 |
task = _tarea(db, task_id)
|
| 359 |
if task is None or task.harmony_status == "completed":
|
| 360 |
return
|
|
|
|
| 361 |
task.harmony_status = "error"
|
|
|
|
| 362 |
db.commit()
|
|
|
|
| 208 |
logger.warning(f"[{task.task_id}] Error al dar la recompensa del worker: {e}")
|
| 209 |
|
| 210 |
|
| 211 |
+
def _borrar_original(task):
|
| 212 |
+
"""El audio original temporal se borra al terminar: el equipo ya no tiene permiso para hacerlo."""
|
| 213 |
+
import re
|
| 214 |
+
m = re.search(r"/resolve/main/(originals/.+)$", task.cloud_url or "")
|
| 215 |
+
if not m:
|
| 216 |
+
return
|
| 217 |
+
try:
|
| 218 |
+
from app.utils.hf_storage import delete_from_hf
|
| 219 |
+
delete_from_hf(m.group(1))
|
| 220 |
+
except Exception as e:
|
| 221 |
+
logger.warning(f"[{task.task_id}] No se pudo borrar el audio original: {e}")
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def exigir_subida(db, workers: list, task_id: str):
|
| 225 |
+
"""Un equipo solo sube pistas de canciones que procesa o que son de su dueño."""
|
| 226 |
+
from app.utils.puente import worker_de_trabajo
|
| 227 |
+
task = _tarea(db, task_id)
|
| 228 |
+
if task is None:
|
| 229 |
+
raise OperacionNoPermitida("La tarea no existe")
|
| 230 |
+
ids = {w.id for w in workers}
|
| 231 |
+
duenos = {w.user_id for w in workers if w.user_id}
|
| 232 |
+
if task.processed_by_worker_id in ids or worker_de_trabajo(task) in ids or task.user_id in duenos:
|
| 233 |
+
return
|
| 234 |
+
raise OperacionNoPermitida("La tarea no la procesa este worker")
|
| 235 |
+
|
| 236 |
+
|
| 237 |
def _avisar(user_id, mensaje: dict):
|
| 238 |
try:
|
| 239 |
from app.websocket_manager import send_sync_message
|
|
|
|
| 270 |
task.status = "completed"
|
| 271 |
if worker is not None:
|
| 272 |
task.processed_by_worker_id = worker.id
|
| 273 |
+
task.trabajo_json = None
|
| 274 |
_vencimiento(db, task)
|
| 275 |
_recompensar(db, worker, task)
|
| 276 |
db.commit()
|
| 277 |
+
if not confiable:
|
| 278 |
+
_borrar_original(task)
|
| 279 |
|
| 280 |
_avisar(task.user_id, {"type": "song_processing_completed", "task_id": task_id,
|
| 281 |
"song_name": task.song_name, "status": "completed"})
|
|
|
|
| 291 |
if task.status == "failed":
|
| 292 |
return
|
| 293 |
task.status = "failed"
|
| 294 |
+
task.trabajo_json = None
|
| 295 |
+
if not confiable:
|
| 296 |
+
_borrar_original(task)
|
| 297 |
logger.warning(f"[{task_id}] Falló en el worker: {(error or '')[:250]}")
|
| 298 |
if task.user_id:
|
| 299 |
try:
|
|
|
|
| 348 |
raise OperacionNoPermitida("No hay voces corales pedidas para esta tarea")
|
| 349 |
|
| 350 |
|
| 351 |
+
def _exigir_armonia_propia(workers: list, task, confiable: bool):
|
| 352 |
+
"""Las voces corales las termina el equipo al que se entregaron."""
|
| 353 |
+
if confiable:
|
| 354 |
+
return
|
| 355 |
+
from app.utils.despacho import soporta_puente
|
| 356 |
+
from app.utils.puente import worker_de_trabajo
|
| 357 |
+
asignado = worker_de_trabajo(task)
|
| 358 |
+
if asignado in {w.id for w in workers}:
|
| 359 |
+
return
|
| 360 |
+
# Equipos con el motor anterior (reciben por el broker, sin anotación) hasta que se actualicen
|
| 361 |
+
if asignado is None and workers and not all(soporta_puente(w) for w in workers):
|
| 362 |
+
return
|
| 363 |
+
raise OperacionNoPermitida("Estas voces corales no las procesa este worker")
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
def datos_armonia(db, workers: list, task_id: str, confiable: bool = False) -> dict:
|
| 367 |
task = _tarea(db, task_id)
|
| 368 |
if task is None:
|
| 369 |
return {"existe": False}
|
| 370 |
_exigir_armonia_en_curso(task)
|
| 371 |
+
_exigir_armonia_propia(workers, task, confiable)
|
| 372 |
from app.routers.songs import _resolve_task_folder
|
| 373 |
return {
|
| 374 |
"existe": True,
|
|
|
|
| 378 |
}
|
| 379 |
|
| 380 |
|
| 381 |
+
def etapa_armonia(db, workers: list, task_id: str, progreso: int, mensaje: str, confiable: bool = False):
|
| 382 |
task = _tarea(db, task_id)
|
| 383 |
if task is None:
|
| 384 |
return
|
| 385 |
_exigir_armonia_en_curso(task)
|
| 386 |
+
_exigir_armonia_propia(workers, task, confiable)
|
| 387 |
task.harmony_status = "generating"
|
| 388 |
task.harmony_stage = json.dumps({"p": int(progreso), "m": str(mensaje)[:200]})
|
| 389 |
task.harmony_updated_at = datetime.utcnow()
|
| 390 |
db.commit()
|
| 391 |
|
| 392 |
|
| 393 |
+
def completar_armonia(db, workers: list, task_id: str, urls: dict, confiable: bool = False):
|
| 394 |
task = _tarea(db, task_id)
|
| 395 |
if task is None:
|
| 396 |
return
|
| 397 |
_exigir_armonia_en_curso(task)
|
| 398 |
+
_exigir_armonia_propia(workers, task, confiable)
|
| 399 |
actuales = json.loads(task.telegram_file_ids) if task.telegram_file_ids else {}
|
| 400 |
actuales.update(_validar_urls(task_id, urls))
|
| 401 |
task.telegram_file_ids = json.dumps(actuales)
|
| 402 |
task.has_harmony = True
|
| 403 |
task.harmony_status = "completed"
|
| 404 |
+
task.trabajo_json = None
|
| 405 |
db.commit()
|
| 406 |
|
| 407 |
|
| 408 |
+
def error_armonia(db, workers: list, task_id: str, confiable: bool = False):
|
| 409 |
task = _tarea(db, task_id)
|
| 410 |
if task is None or task.harmony_status == "completed":
|
| 411 |
return
|
| 412 |
+
_exigir_armonia_propia(workers, task, confiable)
|
| 413 |
task.harmony_status = "error"
|
| 414 |
+
task.trabajo_json = None
|
| 415 |
db.commit()
|
puente_trabajos.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Motor del worker residencial: pide canciones a la API y las procesa.
|
| 3 |
+
|
| 4 |
+
Reemplaza a `celery worker` en los equipos de usuarios: el equipo no se conecta al broker ni tiene
|
| 5 |
+
token de Hugging Face, solo su token de usuario. El agente (MelodixWorkerAgent) arranca este proceso.
|
| 6 |
+
Las tareas siguen siendo las de tasks.py; aquí se ejecutan directamente, una a la vez.
|
| 7 |
+
"""
|
| 8 |
+
import argparse
|
| 9 |
+
import logging
|
| 10 |
+
import os
|
| 11 |
+
import threading
|
| 12 |
+
import time
|
| 13 |
+
|
| 14 |
+
# Antes de importar tasks: Celery no debe intentar conectarse a ningún broker
|
| 15 |
+
os.environ["WORKER_SIN_BROKER"] = "true"
|
| 16 |
+
|
| 17 |
+
INTERVALO_LIBRE = 15
|
| 18 |
+
ESPERA_MAXIMA = 180
|
| 19 |
+
INTERVALO_LATIDO = 30
|
| 20 |
+
# Se borran las llaves viejas cuando la versión nueva lleva este tiempo corriendo: antes, el
|
| 21 |
+
# actualizador todavía podría volver a la versión anterior, que las necesita
|
| 22 |
+
SEGUNDOS_ANTES_DE_LIMPIAR = 300
|
| 23 |
+
|
| 24 |
+
logger = logging.getLogger("puente_trabajos")
|
| 25 |
+
_ocupado = threading.Event()
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _latidos(worker_datos):
|
| 29 |
+
"""Mientras procesa no pide trabajo: el latido avisa que sigue vivo."""
|
| 30 |
+
while True:
|
| 31 |
+
time.sleep(INTERVALO_LATIDO)
|
| 32 |
+
if _ocupado.is_set():
|
| 33 |
+
try:
|
| 34 |
+
worker_datos.latido()
|
| 35 |
+
except Exception as e:
|
| 36 |
+
logger.warning(f"No se pudo enviar el latido: {str(e)[:160]}")
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _limpiar_llaves_viejas(worker_datos):
|
| 40 |
+
time.sleep(SEGUNDOS_ANTES_DE_LIMPIAR)
|
| 41 |
+
base = os.path.dirname(os.path.abspath(__file__))
|
| 42 |
+
try:
|
| 43 |
+
borradas = worker_datos.limpiar_credenciales_env(os.path.join(base, ".env"),
|
| 44 |
+
worker_datos.CLAVES_SIN_BROKER)
|
| 45 |
+
if borradas:
|
| 46 |
+
logger.info(f"Llaves viejas borradas del .env: {', '.join(borradas)}")
|
| 47 |
+
viejo = os.path.join(base, "credenciales_hf.env")
|
| 48 |
+
if os.path.exists(viejo) and worker_datos.es_worker_instalado(base):
|
| 49 |
+
os.remove(viejo)
|
| 50 |
+
logger.info("Archivo credenciales_hf.env borrado.")
|
| 51 |
+
except Exception as e:
|
| 52 |
+
logger.warning(f"No se pudieron limpiar las llaves viejas: {e}")
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _ejecutar(tasks, trabajo: dict):
|
| 56 |
+
nombre, task_id = trabajo["nombre"], trabajo["id"]
|
| 57 |
+
tarea = tasks.celery_app.tasks.get(nombre)
|
| 58 |
+
if tarea is None:
|
| 59 |
+
logger.error(f"[{task_id}] Tarea desconocida: {nombre}")
|
| 60 |
+
return
|
| 61 |
+
logger.info(f"[{task_id}] Inicia {nombre}")
|
| 62 |
+
_ocupado.set()
|
| 63 |
+
try:
|
| 64 |
+
resultado = tarea.apply(args=trabajo.get("args") or [], kwargs=trabajo.get("kwargs") or {}, task_id=task_id)
|
| 65 |
+
logger.info(f"[{task_id}] Terminó con estado {resultado.state}")
|
| 66 |
+
except Exception as e:
|
| 67 |
+
logger.error(f"[{task_id}] Error ejecutando la tarea: {e}", exc_info=True)
|
| 68 |
+
finally:
|
| 69 |
+
_ocupado.clear()
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def bucle(tasks, worker_datos):
|
| 73 |
+
fallos = 0
|
| 74 |
+
while True:
|
| 75 |
+
try:
|
| 76 |
+
trabajo = worker_datos.pedir_trabajo()
|
| 77 |
+
fallos = 0
|
| 78 |
+
except Exception as e:
|
| 79 |
+
fallos += 1
|
| 80 |
+
if fallos <= 2 or fallos % 10 == 0:
|
| 81 |
+
logger.warning(f"No se pudo pedir trabajo: {str(e)[:200]}")
|
| 82 |
+
time.sleep(min(ESPERA_MAXIMA, INTERVALO_LIBRE * (2 ** min(fallos, 4))))
|
| 83 |
+
continue
|
| 84 |
+
if trabajo:
|
| 85 |
+
_ejecutar(tasks, trabajo)
|
| 86 |
+
else:
|
| 87 |
+
time.sleep(INTERVALO_LIBRE)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def main():
|
| 91 |
+
parser = argparse.ArgumentParser()
|
| 92 |
+
parser.add_argument("--logfile", default=None)
|
| 93 |
+
args = parser.parse_args()
|
| 94 |
+
logging.basicConfig(level=logging.INFO, filename=args.logfile, encoding="utf-8",
|
| 95 |
+
format="[%(asctime)s: %(levelname)s] %(message)s")
|
| 96 |
+
|
| 97 |
+
import tasks
|
| 98 |
+
from app.utils import worker_datos
|
| 99 |
+
|
| 100 |
+
threading.Thread(target=_latidos, args=(worker_datos,), daemon=True, name="latidos").start()
|
| 101 |
+
threading.Thread(target=_limpiar_llaves_viejas, args=(worker_datos,), daemon=True, name="limpieza").start()
|
| 102 |
+
logger.info("Motor del worker listo: pidiendo canciones a la API.")
|
| 103 |
+
bucle(tasks, worker_datos)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
if __name__ == "__main__":
|
| 107 |
+
main()
|
tasks.py
CHANGED
|
@@ -1,21 +1,5 @@
|
|
| 1 |
import os
|
| 2 |
|
| 3 |
-
# Credenciales de Hugging Face que viajan en cada actualización del worker (las escribe
|
| 4 |
-
# publicar_worker.ps1). Mandan sobre el .env de la instalación, así un cambio de token
|
| 5 |
-
# llega a todos los workers con solo publicar una actualización.
|
| 6 |
-
_CRED_HF = os.path.join(os.path.dirname(os.path.abspath(__file__)), "credenciales_hf.env")
|
| 7 |
-
if os.path.exists(_CRED_HF):
|
| 8 |
-
try:
|
| 9 |
-
with open(_CRED_HF, encoding="utf-8") as _f:
|
| 10 |
-
for _linea in _f:
|
| 11 |
-
_linea = _linea.strip()
|
| 12 |
-
if _linea and not _linea.startswith("#") and "=" in _linea:
|
| 13 |
-
_k, _v = _linea.split("=", 1)
|
| 14 |
-
if _v.strip():
|
| 15 |
-
os.environ[_k.strip()] = _v.strip()
|
| 16 |
-
except Exception:
|
| 17 |
-
pass
|
| 18 |
-
|
| 19 |
# Compatibilidad de Python 3.10+ y NumPy 1.24+ para librosa y otras librerías viejas
|
| 20 |
import collections
|
| 21 |
import collections.abc
|
|
@@ -130,7 +114,10 @@ import ssl
|
|
| 130 |
DATABASE_URL = os.getenv("DATABASE_URL")
|
| 131 |
USE_DB_BROKER = os.getenv("USE_DB_BROKER", "false").lower() == "true"
|
| 132 |
|
| 133 |
-
if
|
|
|
|
|
|
|
|
|
|
| 134 |
# Usar la base de datos PostgreSQL (Neon) como broker y result backend de Celery
|
| 135 |
normalized_url = DATABASE_URL
|
| 136 |
if normalized_url.startswith("postgres://"):
|
|
@@ -1241,12 +1228,14 @@ def procesar_cancion_completa(self, file_path, task_id, stems, trim_start="", tr
|
|
| 1241 |
f.write(chunk)
|
| 1242 |
logger.info(f"[{task_id}] Archivo descargado con éxito.")
|
| 1243 |
|
| 1244 |
-
# Eliminar archivo original temporal de Hugging Face tras descarga
|
|
|
|
| 1245 |
try:
|
| 1246 |
from app.utils.hf_storage import delete_from_hf
|
|
|
|
| 1247 |
import re as _re
|
| 1248 |
_m = _re.search(r'/resolve/main/(originals/.+)$', cloud_url)
|
| 1249 |
-
if _m:
|
| 1250 |
delete_from_hf(_m.group(1))
|
| 1251 |
logger.info(f"[{task_id}] Archivo original temporal de Hugging Face eliminado: {_m.group(1)}")
|
| 1252 |
except Exception as _hfe:
|
|
@@ -2025,7 +2014,8 @@ def procesar_cancion_completa(self, file_path, task_id, stems, trim_start="", tr
|
|
| 2025 |
|
| 2026 |
hf_urls = {}
|
| 2027 |
failed_stems = []
|
| 2028 |
-
from app.utils.hf_storage import
|
|
|
|
| 2029 |
|
| 2030 |
if not check_task_still_exists(task_id):
|
| 2031 |
raise TaskCancelledException("Tarea cancelada por el usuario.")
|
|
@@ -2332,7 +2322,8 @@ def generar_armonias_task(self, task_id: str):
|
|
| 2332 |
logger.info(f"[{task_id}] La tarea ya no existe: no se generan voces corales.")
|
| 2333 |
return False
|
| 2334 |
registrar_etapa_armonia(task_id, 5, "Preparando la voz principal...")
|
| 2335 |
-
from app.utils.hf_storage import
|
|
|
|
| 2336 |
import json
|
| 2337 |
import os
|
| 2338 |
import shutil
|
|
@@ -2614,7 +2605,7 @@ def aplicar_recarga_mensual_creditos_task():
|
|
| 2614 |
def sync_local_task_to_cloud(task_id, stems_to_upload, acordes, stems, user_id, song_name, artist):
|
| 2615 |
logger.info(f"[{task_id}] Iniciando sincronización de respaldo a la nube en background (desde backup)...")
|
| 2616 |
try:
|
| 2617 |
-
from app.utils.
|
| 2618 |
|
| 2619 |
hf_urls = {}
|
| 2620 |
failed_stems = []
|
|
|
|
| 1 |
import os
|
| 2 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
# Compatibilidad de Python 3.10+ y NumPy 1.24+ para librosa y otras librerías viejas
|
| 4 |
import collections
|
| 5 |
import collections.abc
|
|
|
|
| 114 |
DATABASE_URL = os.getenv("DATABASE_URL")
|
| 115 |
USE_DB_BROKER = os.getenv("USE_DB_BROKER", "false").lower() == "true"
|
| 116 |
|
| 117 |
+
if os.getenv("WORKER_SIN_BROKER", "").lower() == "true":
|
| 118 |
+
# Worker residencial (puente_trabajos.py): las tareas se ejecutan en este proceso, sin broker
|
| 119 |
+
celery_app = Celery('tasks', broker='memory://', backend='cache+memory://')
|
| 120 |
+
elif USE_DB_BROKER and DATABASE_URL:
|
| 121 |
# Usar la base de datos PostgreSQL (Neon) como broker y result backend de Celery
|
| 122 |
normalized_url = DATABASE_URL
|
| 123 |
if normalized_url.startswith("postgres://"):
|
|
|
|
| 1228 |
f.write(chunk)
|
| 1229 |
logger.info(f"[{task_id}] Archivo descargado con éxito.")
|
| 1230 |
|
| 1231 |
+
# Eliminar archivo original temporal de Hugging Face tras descarga. En los equipos
|
| 1232 |
+
# residenciales lo borra la API al terminar (y sirve para reintentar si se apagan).
|
| 1233 |
try:
|
| 1234 |
from app.utils.hf_storage import delete_from_hf
|
| 1235 |
+
from app.utils import worker_datos as _wd
|
| 1236 |
import re as _re
|
| 1237 |
_m = _re.search(r'/resolve/main/(originals/.+)$', cloud_url)
|
| 1238 |
+
if _m and _wd.MODO_DIRECTO:
|
| 1239 |
delete_from_hf(_m.group(1))
|
| 1240 |
logger.info(f"[{task_id}] Archivo original temporal de Hugging Face eliminado: {_m.group(1)}")
|
| 1241 |
except Exception as _hfe:
|
|
|
|
| 2014 |
|
| 2015 |
hf_urls = {}
|
| 2016 |
failed_stems = []
|
| 2017 |
+
from app.utils.hf_storage import HF_STORAGE_REPO
|
| 2018 |
+
from app.utils.worker_datos import subir_a_hf as upload_many_to_hf
|
| 2019 |
|
| 2020 |
if not check_task_still_exists(task_id):
|
| 2021 |
raise TaskCancelledException("Tarea cancelada por el usuario.")
|
|
|
|
| 2322 |
logger.info(f"[{task_id}] La tarea ya no existe: no se generan voces corales.")
|
| 2323 |
return False
|
| 2324 |
registrar_etapa_armonia(task_id, 5, "Preparando la voz principal...")
|
| 2325 |
+
from app.utils.hf_storage import get_hf_download_url
|
| 2326 |
+
from app.utils.worker_datos import subir_a_hf as upload_many_to_hf
|
| 2327 |
import json
|
| 2328 |
import os
|
| 2329 |
import shutil
|
|
|
|
| 2605 |
def sync_local_task_to_cloud(task_id, stems_to_upload, acordes, stems, user_id, song_name, artist):
|
| 2606 |
logger.info(f"[{task_id}] Iniciando sincronización de respaldo a la nube en background (desde backup)...")
|
| 2607 |
try:
|
| 2608 |
+
from app.utils.worker_datos import subir_a_hf as upload_many_to_hf
|
| 2609 |
|
| 2610 |
hf_urls = {}
|
| 2611 |
failed_stems = []
|