Spaces:
Running
Running
deploy from github actions
Browse files- app/routers/workers.py +25 -1
- tasks.py +45 -10
app/routers/workers.py
CHANGED
|
@@ -400,6 +400,29 @@ def agent_set_mode(token: str, is_public: bool, hostname: Optional[str] = None,
|
|
| 400 |
ws_manager.broadcast_sync({"type": "refresh", "tab": "workers"})
|
| 401 |
return {"is_public": worker.is_public}
|
| 402 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 403 |
@router.get("/agent/poll")
|
| 404 |
def agent_poll(
|
| 405 |
token: str,
|
|
@@ -486,7 +509,8 @@ def agent_poll(
|
|
| 486 |
if status == "offline":
|
| 487 |
worker.status = "offline"
|
| 488 |
elif status == "online":
|
| 489 |
-
if worker.status != "busy":
|
|
|
|
| 490 |
worker.status = "online"
|
| 491 |
worker.is_active = True
|
| 492 |
elif status == "busy":
|
|
|
|
| 400 |
ws_manager.broadcast_sync({"type": "refresh", "tab": "workers"})
|
| 401 |
return {"is_public": worker.is_public}
|
| 402 |
|
| 403 |
+
def _worker_tiene_trabajo(db: Session, worker: Worker) -> bool:
|
| 404 |
+
"""True si el worker tiene una canción en curso (o se están generando voces corales)."""
|
| 405 |
+
from datetime import timedelta
|
| 406 |
+
from app.models.process import Task
|
| 407 |
+
ahora = datetime.utcnow()
|
| 408 |
+
try:
|
| 409 |
+
cancion = db.query(Task.id).filter(
|
| 410 |
+
Task.processed_by_worker_id == worker.id,
|
| 411 |
+
Task.status == "processing",
|
| 412 |
+
Task.created_at > ahora - timedelta(hours=4),
|
| 413 |
+
).first()
|
| 414 |
+
if cancion:
|
| 415 |
+
return True
|
| 416 |
+
# Las voces corales no registran qué worker las genera: ante la duda se respeta el 'busy'
|
| 417 |
+
armonia = db.query(Task.id).filter(
|
| 418 |
+
Task.harmony_status == "generating",
|
| 419 |
+
Task.harmony_updated_at > ahora - timedelta(minutes=30),
|
| 420 |
+
).first()
|
| 421 |
+
return armonia is not None
|
| 422 |
+
except Exception:
|
| 423 |
+
return True
|
| 424 |
+
|
| 425 |
+
|
| 426 |
@router.get("/agent/poll")
|
| 427 |
def agent_poll(
|
| 428 |
token: str,
|
|
|
|
| 509 |
if status == "offline":
|
| 510 |
worker.status = "offline"
|
| 511 |
elif status == "online":
|
| 512 |
+
if worker.status != "busy" or not _worker_tiene_trabajo(db, worker):
|
| 513 |
+
# 'busy' sin canción en curso = quedó trabado (proceso cortado a mitad de camino)
|
| 514 |
worker.status = "online"
|
| 515 |
worker.is_active = True
|
| 516 |
elif status == "busy":
|
tasks.py
CHANGED
|
@@ -291,16 +291,17 @@ def find_worker_by_hostname(db, hostname: str):
|
|
| 291 |
return w
|
| 292 |
|
| 293 |
def update_worker_status(status: str, user_id: int = None):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 294 |
from app.database import SessionLocal
|
| 295 |
-
|
| 296 |
-
hostname = CURRENT_WORKER_HOSTNAME
|
| 297 |
db = SessionLocal()
|
| 298 |
try:
|
| 299 |
-
worker =
|
| 300 |
-
if user_id:
|
| 301 |
-
worker = db.query(Worker).filter(Worker.user_id == user_id).first()
|
| 302 |
-
if not worker:
|
| 303 |
-
worker = find_worker_by_hostname(db, hostname)
|
| 304 |
if worker:
|
| 305 |
if worker.status == "suspended":
|
| 306 |
return
|
|
@@ -812,6 +813,35 @@ def separar_voz_principal_y_coros(task, task_id: str, song_dir: str, hq_base: st
|
|
| 812 |
sf.write(os.path.join(song_dir, "coros.flac"), np.zeros((info.frames, info.channels), dtype="float32"),
|
| 813 |
info.samplerate, subtype=info.subtype)
|
| 814 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 815 |
def combinar_pistas(task_id: str, output_base: str, partes: list, destino: str):
|
| 816 |
"""
|
| 817 |
Suma varias pistas en una sola (p. ej. el instrumental de 2 pistas) y borra las originales.
|
|
@@ -2071,7 +2101,9 @@ def procesar_cancion_completa(self, file_path, task_id, stems, trim_start="", tr
|
|
| 2071 |
|
| 2072 |
logger.info(f"[{task_id}] Subiendo archivos...")
|
| 2073 |
_reportar_progreso(self, task_id, 95, 'Subiendo archivos...')
|
| 2074 |
-
|
|
|
|
|
|
|
| 2075 |
hf_urls = {}
|
| 2076 |
failed_stems = []
|
| 2077 |
from app.utils.hf_storage import upload_many_to_hf, HF_STORAGE_REPO
|
|
@@ -2209,7 +2241,7 @@ def procesar_cancion_completa(self, file_path, task_id, stems, trim_start="", tr
|
|
| 2209 |
task_record = db.query(TaskModel).filter(TaskModel.task_id == task_id).first()
|
| 2210 |
if task_record:
|
| 2211 |
task_record.telegram_file_ids = json.dumps(hf_urls)
|
| 2212 |
-
task_record.peaks =
|
| 2213 |
if acordes:
|
| 2214 |
task_record.chords = json.dumps(acordes)
|
| 2215 |
task_record.bpm = bpm_detectado
|
|
@@ -2843,6 +2875,8 @@ def sync_local_task_to_cloud(task_id, stems_to_upload, acordes, stems, user_id,
|
|
| 2843 |
continue
|
| 2844 |
existing.append((stem_name, stem_path, f"stems/{task_id}/{stem_name}.{ext}"))
|
| 2845 |
|
|
|
|
|
|
|
| 2846 |
# Todos los stems del respaldo en un solo commit
|
| 2847 |
try:
|
| 2848 |
uploaded = upload_many_to_hf([(path, key) for _, path, key in existing], commit_message=f"Respaldo de {task_id}")
|
|
@@ -2874,12 +2908,13 @@ def sync_local_task_to_cloud(task_id, stems_to_upload, acordes, stems, user_id,
|
|
| 2874 |
status="completed",
|
| 2875 |
telegram_file_ids=json.dumps(hf_urls),
|
| 2876 |
chords=json.dumps(acordes) if acordes else None,
|
|
|
|
| 2877 |
created_at=datetime.utcnow()
|
| 2878 |
)
|
| 2879 |
db.add(task_record)
|
| 2880 |
else:
|
| 2881 |
task_record.telegram_file_ids = json.dumps(hf_urls)
|
| 2882 |
-
task_record.peaks =
|
| 2883 |
if acordes:
|
| 2884 |
task_record.chords = json.dumps(acordes)
|
| 2885 |
task_record.status = "completed"
|
|
|
|
| 291 |
return w
|
| 292 |
|
| 293 |
def update_worker_status(status: str, user_id: int = None):
|
| 294 |
+
"""
|
| 295 |
+
Marca el estado del worker de ESTE equipo. `user_id` (dueño de la canción) ya no se usa
|
| 296 |
+
para buscarlo: con varios workers del mismo usuario marcaba ocupado a otro equipo, que
|
| 297 |
+
quedaba 'busy' para siempre y no se actualizaba.
|
| 298 |
+
"""
|
| 299 |
+
import socket
|
| 300 |
from app.database import SessionLocal
|
| 301 |
+
hostname = CURRENT_WORKER_HOSTNAME or socket.gethostname()
|
|
|
|
| 302 |
db = SessionLocal()
|
| 303 |
try:
|
| 304 |
+
worker = find_worker_by_hostname(db, hostname)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 305 |
if worker:
|
| 306 |
if worker.status == "suspended":
|
| 307 |
return
|
|
|
|
| 813 |
sf.write(os.path.join(song_dir, "coros.flac"), np.zeros((info.frames, info.channels), dtype="float32"),
|
| 814 |
info.samplerate, subtype=info.subtype)
|
| 815 |
|
| 816 |
+
_VOCES_CORALES_PEAKS = {"2da_voz", "2da_voz_baja", "3ra_voz", "3ra_voz_baja", "oct_alta", "oct_baja"}
|
| 817 |
+
|
| 818 |
+
|
| 819 |
+
def calcular_peaks_stems(task_id: str, stems_to_upload) -> str | None:
|
| 820 |
+
"""
|
| 821 |
+
Picos de onda de cada stem (para el Studio) calculados con los archivos locales, antes de
|
| 822 |
+
subirlos: así quedan guardados en tasks.peaks aunque los stems de la nube venzan.
|
| 823 |
+
Devuelve el JSON {"v", "n", "stems"} o None si no se pudo (la API los calcula a pedido).
|
| 824 |
+
"""
|
| 825 |
+
try:
|
| 826 |
+
from app.utils.peaks import PEAK_COUNT, PEAKS_VERSION, picos_de_stems
|
| 827 |
+
origenes = {
|
| 828 |
+
nombre: ruta for nombre, ruta, ext in stems_to_upload
|
| 829 |
+
if ext.lower() in ("m4a", "flac", "wav", "mp3")
|
| 830 |
+
and nombre not in _VOCES_CORALES_PEAKS and not nombre.endswith("_pitch")
|
| 831 |
+
and os.path.exists(ruta)
|
| 832 |
+
}
|
| 833 |
+
if not origenes:
|
| 834 |
+
return None
|
| 835 |
+
picos = picos_de_stems(origenes)
|
| 836 |
+
if not picos:
|
| 837 |
+
return None
|
| 838 |
+
logger.info(f"[{task_id}] Picos de onda calculados: {sorted(picos)}")
|
| 839 |
+
return json.dumps({"v": PEAKS_VERSION, "n": PEAK_COUNT, "stems": picos})
|
| 840 |
+
except Exception as e:
|
| 841 |
+
logger.warning(f"[{task_id}] No se pudieron calcular los picos de onda: {e}")
|
| 842 |
+
return None
|
| 843 |
+
|
| 844 |
+
|
| 845 |
def combinar_pistas(task_id: str, output_base: str, partes: list, destino: str):
|
| 846 |
"""
|
| 847 |
Suma varias pistas en una sola (p. ej. el instrumental de 2 pistas) y borra las originales.
|
|
|
|
| 2101 |
|
| 2102 |
logger.info(f"[{task_id}] Subiendo archivos...")
|
| 2103 |
_reportar_progreso(self, task_id, 95, 'Subiendo archivos...')
|
| 2104 |
+
|
| 2105 |
+
peaks_json = calcular_peaks_stems(task_id, stems_to_upload)
|
| 2106 |
+
|
| 2107 |
hf_urls = {}
|
| 2108 |
failed_stems = []
|
| 2109 |
from app.utils.hf_storage import upload_many_to_hf, HF_STORAGE_REPO
|
|
|
|
| 2241 |
task_record = db.query(TaskModel).filter(TaskModel.task_id == task_id).first()
|
| 2242 |
if task_record:
|
| 2243 |
task_record.telegram_file_ids = json.dumps(hf_urls)
|
| 2244 |
+
task_record.peaks = peaks_json # None: la API la calcula a pedido
|
| 2245 |
if acordes:
|
| 2246 |
task_record.chords = json.dumps(acordes)
|
| 2247 |
task_record.bpm = bpm_detectado
|
|
|
|
| 2875 |
continue
|
| 2876 |
existing.append((stem_name, stem_path, f"stems/{task_id}/{stem_name}.{ext}"))
|
| 2877 |
|
| 2878 |
+
peaks_json = calcular_peaks_stems(task_id, stems_to_upload)
|
| 2879 |
+
|
| 2880 |
# Todos los stems del respaldo en un solo commit
|
| 2881 |
try:
|
| 2882 |
uploaded = upload_many_to_hf([(path, key) for _, path, key in existing], commit_message=f"Respaldo de {task_id}")
|
|
|
|
| 2908 |
status="completed",
|
| 2909 |
telegram_file_ids=json.dumps(hf_urls),
|
| 2910 |
chords=json.dumps(acordes) if acordes else None,
|
| 2911 |
+
peaks=peaks_json,
|
| 2912 |
created_at=datetime.utcnow()
|
| 2913 |
)
|
| 2914 |
db.add(task_record)
|
| 2915 |
else:
|
| 2916 |
task_record.telegram_file_ids = json.dumps(hf_urls)
|
| 2917 |
+
task_record.peaks = peaks_json # None: la API la calcula a pedido
|
| 2918 |
if acordes:
|
| 2919 |
task_record.chords = json.dumps(acordes)
|
| 2920 |
task_record.status = "completed"
|