Spaces:
Running
Running
deploy from github actions
Browse files- app/routers/songs.py +6 -2
- app/routers/workers.py +21 -1
- app/utils/despacho.py +120 -6
- app/utils/worker_ops.py +22 -1
- tasks.py +15 -5
app/routers/songs.py
CHANGED
|
@@ -168,6 +168,8 @@ def encolar_procesamiento(db: Session, user_id: int, task_id: str, file_path: st
|
|
| 168 |
despacho.reservar(db, worker_elegido)
|
| 169 |
logger.info(f"[{task_id}] Worker '{worker_elegido.hostname}' marcado como busy (enrutamiento preventivo).")
|
| 170 |
db.commit()
|
|
|
|
|
|
|
| 171 |
|
| 172 |
if es_publica:
|
| 173 |
registrar_tarea_en_cola_publica(task_id, args, task_kwargs)
|
|
@@ -760,6 +762,8 @@ def subir_youtube(
|
|
| 760 |
if worker_elegido is not None:
|
| 761 |
despacho.reservar(db, worker_elegido)
|
| 762 |
logger.info(f"[{task_id}] Worker '{worker_elegido.hostname}' marcado como busy (enrutamiento preventivo YouTube).")
|
|
|
|
|
|
|
| 763 |
|
| 764 |
return {
|
| 765 |
"celery_id": job.id,
|
|
@@ -943,13 +947,13 @@ async def consultar_estado(
|
|
| 943 |
|
| 944 |
# Si Celery no tiene la etapa a mano, usar la última que el worker guardó en la BD
|
| 945 |
# (así la app no vuelve a "Procesando..." entre etapas)
|
| 946 |
-
if not mensaje and estado not in ("SUCCESS", "FAILURE") and task_record and getattr(task_record, "processing_stage", None) and (task_record.status or "").lower() in ("processing", "progress"):
|
| 947 |
try:
|
| 948 |
import json as _json
|
| 949 |
etapa = _json.loads(task_record.processing_stage)
|
| 950 |
mensaje = etapa.get("m") or ""
|
| 951 |
progreso = progreso or int(etapa.get("p") or 0)
|
| 952 |
-
if mensaje:
|
| 953 |
estado = "PROGRESS"
|
| 954 |
except Exception:
|
| 955 |
pass
|
|
|
|
| 168 |
despacho.reservar(db, worker_elegido)
|
| 169 |
logger.info(f"[{task_id}] Worker '{worker_elegido.hostname}' marcado como busy (enrutamiento preventivo).")
|
| 170 |
db.commit()
|
| 171 |
+
if queue_name.startswith("espera_usr_"):
|
| 172 |
+
despacho.marcar_espera(db, task_id, propia=True)
|
| 173 |
|
| 174 |
if es_publica:
|
| 175 |
registrar_tarea_en_cola_publica(task_id, args, task_kwargs)
|
|
|
|
| 762 |
if worker_elegido is not None:
|
| 763 |
despacho.reservar(db, worker_elegido)
|
| 764 |
logger.info(f"[{task_id}] Worker '{worker_elegido.hostname}' marcado como busy (enrutamiento preventivo YouTube).")
|
| 765 |
+
if queue_name and queue_name.startswith("espera_usr_"):
|
| 766 |
+
despacho.marcar_espera(db, task_id, propia=res_worker.user_id == user_id)
|
| 767 |
|
| 768 |
return {
|
| 769 |
"celery_id": job.id,
|
|
|
|
| 947 |
|
| 948 |
# Si Celery no tiene la etapa a mano, usar la última que el worker guardó en la BD
|
| 949 |
# (así la app no vuelve a "Procesando..." entre etapas)
|
| 950 |
+
if not mensaje and estado not in ("SUCCESS", "FAILURE") and task_record and getattr(task_record, "processing_stage", None) and (task_record.status or "").lower() in ("processing", "progress", "pending"):
|
| 951 |
try:
|
| 952 |
import json as _json
|
| 953 |
etapa = _json.loads(task_record.processing_stage)
|
| 954 |
mensaje = etapa.get("m") or ""
|
| 955 |
progreso = progreso or int(etapa.get("p") or 0)
|
| 956 |
+
if mensaje and not etapa.get("espera"): # En espera sigue pendiente: solo cambia el texto
|
| 957 |
estado = "PROGRESS"
|
| 958 |
except Exception:
|
| 959 |
pass
|
app/routers/workers.py
CHANGED
|
@@ -30,6 +30,8 @@ class WorkerResponse(BaseModel):
|
|
| 30 |
user_id: Optional[int] = None
|
| 31 |
is_public: Optional[bool] = False
|
| 32 |
is_active: Optional[bool] = False
|
|
|
|
|
|
|
| 33 |
owner_username: Optional[str] = None
|
| 34 |
|
| 35 |
class Config:
|
|
@@ -120,6 +122,17 @@ def get_workers(db: Session = Depends(get_db), current_admin: AdminUser = Depend
|
|
| 120 |
for w in workers
|
| 121 |
]
|
| 122 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
@router.put("/{worker_id}", response_model=WorkerResponse)
|
| 124 |
def update_worker(worker_id: int, data: WorkerUpdate, db: Session = Depends(get_db), current_admin: AdminUser = Depends(get_current_admin)):
|
| 125 |
if not current_admin.perm_workers:
|
|
@@ -547,13 +560,20 @@ def agent_poll(
|
|
| 547 |
"status": "online"
|
| 548 |
}
|
| 549 |
|
| 550 |
-
|
| 551 |
"command": current_command,
|
| 552 |
"is_active": worker.is_active,
|
| 553 |
"is_public": bool(getattr(worker, "is_public", False)),
|
| 554 |
"user_id": worker.user_id,
|
| 555 |
"status": worker.status
|
| 556 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 557 |
|
| 558 |
@router.get("/agent/poll-public")
|
| 559 |
def agent_poll_public(hostname: str, status: str, db: Session = Depends(get_db)):
|
|
|
|
| 30 |
user_id: Optional[int] = None
|
| 31 |
is_public: Optional[bool] = False
|
| 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:
|
|
|
|
| 122 |
for w in workers
|
| 123 |
]
|
| 124 |
|
| 125 |
+
@router.get("/colas")
|
| 126 |
+
def get_colas(db: Session = Depends(get_db), current_admin: AdminUser = Depends(get_current_admin)):
|
| 127 |
+
"""Canciones en espera por usuario y sin empezar en la cola de cada equipo (app/utils/despacho.py)."""
|
| 128 |
+
if not current_admin.perm_workers:
|
| 129 |
+
raise HTTPException(status_code=403, detail="No tiene permisos para gestionar workers")
|
| 130 |
+
from app.utils.despacho import estado_colas
|
| 131 |
+
try:
|
| 132 |
+
return estado_colas(db)
|
| 133 |
+
except Exception as e:
|
| 134 |
+
raise HTTPException(status_code=503, detail=f"No se pudo leer el broker: {e}")
|
| 135 |
+
|
| 136 |
@router.put("/{worker_id}", response_model=WorkerResponse)
|
| 137 |
def update_worker(worker_id: int, data: WorkerUpdate, db: Session = Depends(get_db), current_admin: AdminUser = Depends(get_current_admin)):
|
| 138 |
if not current_admin.perm_workers:
|
|
|
|
| 560 |
"status": "online"
|
| 561 |
}
|
| 562 |
|
| 563 |
+
respuesta = {
|
| 564 |
"command": current_command,
|
| 565 |
"is_active": worker.is_active,
|
| 566 |
"is_public": bool(getattr(worker, "is_public", False)),
|
| 567 |
"user_id": worker.user_id,
|
| 568 |
"status": worker.status
|
| 569 |
}
|
| 570 |
+
if worker.status == "busy":
|
| 571 |
+
# El agente (2.8.24+) solo fuerza una actualización si la canción está trabada
|
| 572 |
+
from app.utils.worker_ops import minutos_sin_avance
|
| 573 |
+
sin_avance = minutos_sin_avance(db, worker)
|
| 574 |
+
if sin_avance is not None:
|
| 575 |
+
respuesta["sin_avance_min"] = sin_avance
|
| 576 |
+
return respuesta
|
| 577 |
|
| 578 |
@router.get("/agent/poll-public")
|
| 579 |
def agent_poll_public(hostname: str, status: str, db: Session = Depends(get_db)):
|
app/utils/despacho.py
CHANGED
|
@@ -109,6 +109,47 @@ def reservar(db, worker):
|
|
| 109 |
db.commit()
|
| 110 |
|
| 111 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
# ---------------------------------------------------------------------------
|
| 113 |
# Despachador: mueve canciones de la espera a los equipos que quedan libres
|
| 114 |
# ---------------------------------------------------------------------------
|
|
@@ -122,15 +163,34 @@ def _pendientes(canal, cola: str) -> int:
|
|
| 122 |
return _declarar(canal, cola).message_count
|
| 123 |
|
| 124 |
|
| 125 |
-
|
| 126 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
_declarar(canal, destino)
|
| 128 |
mensaje = canal.basic_get(queue=origen, no_ack=False)
|
| 129 |
if mensaje is None:
|
| 130 |
-
return
|
| 131 |
canal.basic_publish(mensaje, exchange="", routing_key=destino)
|
| 132 |
canal.basic_ack(mensaje.delivery_tag)
|
| 133 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
|
| 135 |
|
| 136 |
def despachar_esperas(conexion=None) -> dict:
|
|
@@ -173,8 +233,12 @@ def despachar_esperas(conexion=None) -> dict:
|
|
| 173 |
conectados[w.user_id].append(w)
|
| 174 |
if estado.message_count == 0 or (conectado and escuchan[w.id]):
|
| 175 |
continue
|
| 176 |
-
while
|
|
|
|
|
|
|
|
|
|
| 177 |
resumen["devueltas"] += 1
|
|
|
|
| 178 |
logger.info(f"[Despacho] '{w.hostname}' no está recibiendo: sus canciones vuelven a la espera.")
|
| 179 |
|
| 180 |
# 2. Equipos libres: la siguiente canción que espera
|
|
@@ -186,9 +250,12 @@ def despachar_esperas(conexion=None) -> dict:
|
|
| 186 |
if (not esta_libre(w, ahora) or not escuchan[w.id]
|
| 187 |
or _pendientes(canal, cola_worker(w.id)) > 0):
|
| 188 |
continue
|
| 189 |
-
|
|
|
|
| 190 |
break
|
| 191 |
reservar(db, w)
|
|
|
|
|
|
|
| 192 |
resumen["enviadas"] += 1
|
| 193 |
logger.info(f"[Despacho] Canción en espera del usuario {user_id} enviada a '{w.hostname}'.")
|
| 194 |
finally:
|
|
@@ -199,6 +266,47 @@ def despachar_esperas(conexion=None) -> dict:
|
|
| 199 |
return resumen
|
| 200 |
|
| 201 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
_hilo_iniciado = False
|
| 203 |
|
| 204 |
|
|
@@ -216,6 +324,12 @@ def iniciar_despachador():
|
|
| 216 |
despachar_esperas()
|
| 217 |
except Exception as e:
|
| 218 |
logger.warning(f"[Despacho] Error en el despachador: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
time.sleep(INTERVALO_DESPACHO)
|
| 220 |
|
| 221 |
threading.Thread(target=_bucle, daemon=True, name="despachador").start()
|
|
|
|
| 109 |
db.commit()
|
| 110 |
|
| 111 |
|
| 112 |
+
# Lo que ve el usuario en la app mientras su canción espera (no dice qué equipo la procesa)
|
| 113 |
+
MENSAJE_ESPERA_PROPIA = "En espera: tus equipos están ocupados"
|
| 114 |
+
MENSAJE_ESPERA = "En espera de un equipo libre"
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def marcar_espera(db, task_id: str, propia: bool = True):
|
| 118 |
+
"""La canción quedó en la espera: la app lo muestra en vez de "Pendiente"."""
|
| 119 |
+
import json
|
| 120 |
+
from app.models.process import Task
|
| 121 |
+
task = db.query(Task).filter(Task.task_id == task_id).first()
|
| 122 |
+
if task is None or task.status not in ("pending", "PENDING"):
|
| 123 |
+
return
|
| 124 |
+
mensaje = MENSAJE_ESPERA_PROPIA if propia else MENSAJE_ESPERA
|
| 125 |
+
task.processing_stage = json.dumps({"p": 0, "m": mensaje, "espera": True})
|
| 126 |
+
db.commit()
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def quitar_espera(db, task_id: str):
|
| 130 |
+
"""La canción salió de la espera hacia un equipo: se borra el aviso (el equipo pone su avance)."""
|
| 131 |
+
import json
|
| 132 |
+
from app.models.process import Task
|
| 133 |
+
task = db.query(Task).filter(Task.task_id == task_id).first()
|
| 134 |
+
if task is None or not task.processing_stage:
|
| 135 |
+
return
|
| 136 |
+
try:
|
| 137 |
+
if json.loads(task.processing_stage).get("espera"):
|
| 138 |
+
task.processing_stage = None
|
| 139 |
+
db.commit()
|
| 140 |
+
except (ValueError, AttributeError):
|
| 141 |
+
pass
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def _task_id_de(mensaje):
|
| 145 |
+
"""Id de la tarea de Celery que lleva el mensaje (cabecera 'id' del protocolo 2)."""
|
| 146 |
+
try:
|
| 147 |
+
cabeceras = getattr(mensaje, "headers", None) or mensaje.properties.get("application_headers") or {}
|
| 148 |
+
return cabeceras.get("id")
|
| 149 |
+
except Exception:
|
| 150 |
+
return None
|
| 151 |
+
|
| 152 |
+
|
| 153 |
# ---------------------------------------------------------------------------
|
| 154 |
# Despachador: mueve canciones de la espera a los equipos que quedan libres
|
| 155 |
# ---------------------------------------------------------------------------
|
|
|
|
| 163 |
return _declarar(canal, cola).message_count
|
| 164 |
|
| 165 |
|
| 166 |
+
class _Movido(str):
|
| 167 |
+
"""Resultado de _mover_una cuando sí movió algo: el id de la tarea ('' si no se sabe), siempre verdadero."""
|
| 168 |
+
def __bool__(self):
|
| 169 |
+
return True
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def _mover_una(canal, origen: str, destino: str):
|
| 173 |
+
"""
|
| 174 |
+
Pasa un mensaje de una cola a otra sin modificarlo. Devuelve None si el origen está vacío y,
|
| 175 |
+
si movió uno, el id de su tarea (como _Movido, que siempre es verdadero).
|
| 176 |
+
"""
|
| 177 |
_declarar(canal, destino)
|
| 178 |
mensaje = canal.basic_get(queue=origen, no_ack=False)
|
| 179 |
if mensaje is None:
|
| 180 |
+
return None
|
| 181 |
canal.basic_publish(mensaje, exchange="", routing_key=destino)
|
| 182 |
canal.basic_ack(mensaje.delivery_tag)
|
| 183 |
+
return _Movido(_task_id_de(mensaje) or "")
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def _avisar_espera(db, task_id: str, dueno_equipos: int):
|
| 187 |
+
"""Canción devuelta a la espera: la app vuelve a mostrar "En espera"."""
|
| 188 |
+
if not task_id:
|
| 189 |
+
return
|
| 190 |
+
from app.models.process import Task
|
| 191 |
+
task = db.query(Task).filter(Task.task_id == task_id).first()
|
| 192 |
+
if task is not None:
|
| 193 |
+
marcar_espera(db, task_id, propia=task.user_id == dueno_equipos)
|
| 194 |
|
| 195 |
|
| 196 |
def despachar_esperas(conexion=None) -> dict:
|
|
|
|
| 233 |
conectados[w.user_id].append(w)
|
| 234 |
if estado.message_count == 0 or (conectado and escuchan[w.id]):
|
| 235 |
continue
|
| 236 |
+
while True:
|
| 237 |
+
movida = _mover_una(canal, cola_worker(w.id), cola_espera(w.user_id))
|
| 238 |
+
if not movida:
|
| 239 |
+
break
|
| 240 |
resumen["devueltas"] += 1
|
| 241 |
+
_avisar_espera(db, str(movida), w.user_id)
|
| 242 |
logger.info(f"[Despacho] '{w.hostname}' no está recibiendo: sus canciones vuelven a la espera.")
|
| 243 |
|
| 244 |
# 2. Equipos libres: la siguiente canción que espera
|
|
|
|
| 250 |
if (not esta_libre(w, ahora) or not escuchan[w.id]
|
| 251 |
or _pendientes(canal, cola_worker(w.id)) > 0):
|
| 252 |
continue
|
| 253 |
+
movida = _mover_una(canal, espera, cola_worker(w.id))
|
| 254 |
+
if not movida:
|
| 255 |
break
|
| 256 |
reservar(db, w)
|
| 257 |
+
if str(movida):
|
| 258 |
+
quitar_espera(db, str(movida))
|
| 259 |
resumen["enviadas"] += 1
|
| 260 |
logger.info(f"[Despacho] Canción en espera del usuario {user_id} enviada a '{w.hostname}'.")
|
| 261 |
finally:
|
|
|
|
| 266 |
return resumen
|
| 267 |
|
| 268 |
|
| 269 |
+
def estado_colas(db, conexion=None) -> dict:
|
| 270 |
+
"""
|
| 271 |
+
Para el panel de admin: canciones que esperan por usuario y canciones sin empezar en la cola de
|
| 272 |
+
cada equipo (la que está procesando no cuenta: ya no está "en la cola").
|
| 273 |
+
"""
|
| 274 |
+
from app.models.process import Worker
|
| 275 |
+
from app.models.user import User
|
| 276 |
+
|
| 277 |
+
ahora = datetime.utcnow()
|
| 278 |
+
equipos = [w for w in db.query(Worker).filter(
|
| 279 |
+
Worker.user_id.isnot(None),
|
| 280 |
+
Worker.last_seen > ahora - timedelta(days=7)).order_by(Worker.id).all()
|
| 281 |
+
if soporta_cola_propia(w)]
|
| 282 |
+
resultado = {"equipos": [], "esperas": []}
|
| 283 |
+
if not equipos:
|
| 284 |
+
return resultado
|
| 285 |
+
|
| 286 |
+
if conexion is None:
|
| 287 |
+
from tasks import celery_app
|
| 288 |
+
conexion = celery_app.connection_for_write()
|
| 289 |
+
cerrar = True
|
| 290 |
+
else:
|
| 291 |
+
cerrar = False
|
| 292 |
+
try:
|
| 293 |
+
canal = conexion.default_channel
|
| 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:
|
| 301 |
+
usuario = db.query(User).filter(User.id == user_id).first()
|
| 302 |
+
resultado["esperas"].append({"user_id": user_id, "canciones": canciones,
|
| 303 |
+
"username": usuario.username if usuario else None})
|
| 304 |
+
finally:
|
| 305 |
+
if cerrar:
|
| 306 |
+
conexion.release()
|
| 307 |
+
return resultado
|
| 308 |
+
|
| 309 |
+
|
| 310 |
_hilo_iniciado = False
|
| 311 |
|
| 312 |
|
|
|
|
| 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
|
| 330 |
+
reenviar_tareas_publicas_sin_tomar()
|
| 331 |
+
except Exception as e:
|
| 332 |
+
logger.warning(f"[Despacho] Error en el respaldo a Hugging Face: {e}")
|
| 333 |
time.sleep(INTERVALO_DESPACHO)
|
| 334 |
|
| 335 |
threading.Thread(target=_bucle, daemon=True, name="despachador").start()
|
app/utils/worker_ops.py
CHANGED
|
@@ -136,10 +136,31 @@ def guardar_etapa(db, workers: list, task_id: str, progreso: int, mensaje: str,
|
|
| 136 |
if task is None:
|
| 137 |
return
|
| 138 |
_exigir_propia(workers, task, confiable)
|
| 139 |
-
|
|
|
|
|
|
|
| 140 |
db.commit()
|
| 141 |
|
| 142 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
def marcar_armonia_inline(db, workers: list, task_id: str, confiable: bool = False):
|
| 144 |
task = _tarea(db, task_id)
|
| 145 |
if task is None:
|
|
|
|
| 136 |
if task is None:
|
| 137 |
return
|
| 138 |
_exigir_propia(workers, task, confiable)
|
| 139 |
+
# "t": hora (del servidor) del último avance; el agente la usa para saber si la canción está trabada
|
| 140 |
+
task.processing_stage = json.dumps({"p": int(progreso), "m": str(mensaje)[:200],
|
| 141 |
+
"t": datetime.utcnow().isoformat(timespec="seconds")})
|
| 142 |
db.commit()
|
| 143 |
|
| 144 |
|
| 145 |
+
def minutos_sin_avance(db, worker):
|
| 146 |
+
"""
|
| 147 |
+
Minutos desde el último avance de la canción que procesa este equipo, o None si no se sabe
|
| 148 |
+
(no hay canción en curso o el avance es de una versión que no guardaba la hora).
|
| 149 |
+
"""
|
| 150 |
+
task = (db.query(Task)
|
| 151 |
+
.filter(Task.processed_by_worker_id == worker.id, Task.status == "processing")
|
| 152 |
+
.order_by(Task.created_at.desc()).first())
|
| 153 |
+
if task is None or not task.processing_stage:
|
| 154 |
+
return None
|
| 155 |
+
try:
|
| 156 |
+
t = json.loads(task.processing_stage).get("t")
|
| 157 |
+
if not t:
|
| 158 |
+
return None
|
| 159 |
+
return max(0, int((datetime.utcnow() - datetime.fromisoformat(t)).total_seconds() // 60))
|
| 160 |
+
except (ValueError, AttributeError, TypeError):
|
| 161 |
+
return None
|
| 162 |
+
|
| 163 |
+
|
| 164 |
def marcar_armonia_inline(db, workers: list, task_id: str, confiable: bool = False):
|
| 165 |
task = _tarea(db, task_id)
|
| 166 |
if task is None:
|
tasks.py
CHANGED
|
@@ -652,6 +652,11 @@ def _reportar_progreso(task, task_id: str, progress: int, message: str):
|
|
| 652 |
logger.debug(f"[{task_id}] No se pudo guardar la etapa en la BD: {e}")
|
| 653 |
|
| 654 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 655 |
def _ejecutar_con_progreso(task, task_id: str, command: list, env: dict, desde: int, hasta: int, mensaje: str):
|
| 656 |
"""
|
| 657 |
Ejecuta un proceso de separación reportando su progreso (escalado entre `desde` y `hasta`)
|
|
@@ -671,6 +676,7 @@ def _ejecutar_con_progreso(task, task_id: str, command: list, env: dict, desde:
|
|
| 671 |
stderr_lines = []
|
| 672 |
last_db_check = _time.time()
|
| 673 |
last_reported = desde - 5
|
|
|
|
| 674 |
while True:
|
| 675 |
line = process.stderr.readline()
|
| 676 |
if not line and process.poll() is not None:
|
|
@@ -691,8 +697,9 @@ def _ejecutar_con_progreso(task, task_id: str, command: list, env: dict, desde:
|
|
| 691 |
match = re.search(r'(\d+)%', line)
|
| 692 |
if match:
|
| 693 |
progress = desde + int(min(int(match.group(1)), 100) * (hasta - desde) / 100)
|
| 694 |
-
if progress >= last_reported + 5:
|
| 695 |
-
last_reported = progress
|
|
|
|
| 696 |
_reportar_progreso(task, task_id, progress, mensaje)
|
| 697 |
|
| 698 |
if process.returncode != 0:
|
|
@@ -1254,7 +1261,7 @@ def procesar_cancion_completa(self, file_path, task_id, stems, trim_start="", tr
|
|
| 1254 |
if not reclamar_tarea(task_id):
|
| 1255 |
# Ignore no publica estado: un SUCCESS acá marcaría como terminada la tarea que procesa el otro worker
|
| 1256 |
from celery.exceptions import Ignore
|
| 1257 |
-
logger.info(f"[{task_id}]
|
| 1258 |
raise Ignore()
|
| 1259 |
|
| 1260 |
update_worker_status("busy", user_id=user_id)
|
|
@@ -1711,6 +1718,7 @@ def procesar_cancion_completa(self, file_path, task_id, stems, trim_start="", tr
|
|
| 1711 |
last_db_check = _time.time()
|
| 1712 |
stderr_lines = []
|
| 1713 |
last_reported_progress = -1
|
|
|
|
| 1714 |
|
| 1715 |
while True:
|
| 1716 |
line = process.stderr.readline()
|
|
@@ -1741,8 +1749,10 @@ def procesar_cancion_completa(self, file_path, task_id, stems, trim_start="", tr
|
|
| 1741 |
# Demucs es la mayor parte del trabajo, lo escalaremos al 90% del progreso total
|
| 1742 |
total_progress = int(percent * demucs_progress_scale)
|
| 1743 |
# Enviar actualización solo cada 5% para ahorrar cuota de broker (CloudAMQP)
|
| 1744 |
-
if total_progress >= last_reported_progress + 5 or total_progress >= 90
|
| 1745 |
-
|
|
|
|
|
|
|
| 1746 |
_reportar_progreso(self, task_id, total_progress, 'Separando pistas...')
|
| 1747 |
logger.debug(f"[{task_id}] Progreso Demucs: {percent}%")
|
| 1748 |
except Exception as e:
|
|
|
|
| 652 |
logger.debug(f"[{task_id}] No se pudo guardar la etapa en la BD: {e}")
|
| 653 |
|
| 654 |
|
| 655 |
+
# Aunque el porcentaje no cambie, se reporta cada tanto: la hora del último avance le dice al agente si la
|
| 656 |
+
# canción sigue viva (en PCs lentas, 5 puntos de avance pueden tardar más de media hora)
|
| 657 |
+
SEGUNDOS_LATIDO_AVANCE = 300
|
| 658 |
+
|
| 659 |
+
|
| 660 |
def _ejecutar_con_progreso(task, task_id: str, command: list, env: dict, desde: int, hasta: int, mensaje: str):
|
| 661 |
"""
|
| 662 |
Ejecuta un proceso de separación reportando su progreso (escalado entre `desde` y `hasta`)
|
|
|
|
| 676 |
stderr_lines = []
|
| 677 |
last_db_check = _time.time()
|
| 678 |
last_reported = desde - 5
|
| 679 |
+
ultimo_reporte = _time.time()
|
| 680 |
while True:
|
| 681 |
line = process.stderr.readline()
|
| 682 |
if not line and process.poll() is not None:
|
|
|
|
| 697 |
match = re.search(r'(\d+)%', line)
|
| 698 |
if match:
|
| 699 |
progress = desde + int(min(int(match.group(1)), 100) * (hasta - desde) / 100)
|
| 700 |
+
if progress >= last_reported + 5 or _time.time() - ultimo_reporte > SEGUNDOS_LATIDO_AVANCE:
|
| 701 |
+
last_reported = max(last_reported, progress)
|
| 702 |
+
ultimo_reporte = _time.time()
|
| 703 |
_reportar_progreso(task, task_id, progress, mensaje)
|
| 704 |
|
| 705 |
if process.returncode != 0:
|
|
|
|
| 1261 |
if not reclamar_tarea(task_id):
|
| 1262 |
# Ignore no publica estado: un SUCCESS acá marcaría como terminada la tarea que procesa el otro worker
|
| 1263 |
from celery.exceptions import Ignore
|
| 1264 |
+
logger.info(f"[{task_id}] Otra PC o Hugging Face ya tomó esta canción. Se descarta el duplicado.")
|
| 1265 |
raise Ignore()
|
| 1266 |
|
| 1267 |
update_worker_status("busy", user_id=user_id)
|
|
|
|
| 1718 |
last_db_check = _time.time()
|
| 1719 |
stderr_lines = []
|
| 1720 |
last_reported_progress = -1
|
| 1721 |
+
ultimo_reporte = _time.time()
|
| 1722 |
|
| 1723 |
while True:
|
| 1724 |
line = process.stderr.readline()
|
|
|
|
| 1749 |
# Demucs es la mayor parte del trabajo, lo escalaremos al 90% del progreso total
|
| 1750 |
total_progress = int(percent * demucs_progress_scale)
|
| 1751 |
# Enviar actualización solo cada 5% para ahorrar cuota de broker (CloudAMQP)
|
| 1752 |
+
if (total_progress >= last_reported_progress + 5 or total_progress >= 90
|
| 1753 |
+
or _time.time() - ultimo_reporte > SEGUNDOS_LATIDO_AVANCE):
|
| 1754 |
+
last_reported_progress = max(last_reported_progress, total_progress)
|
| 1755 |
+
ultimo_reporte = _time.time()
|
| 1756 |
_reportar_progreso(self, task_id, total_progress, 'Separando pistas...')
|
| 1757 |
logger.debug(f"[{task_id}] Progreso Demucs: {percent}%")
|
| 1758 |
except Exception as e:
|