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b4
 
 
 
 
 
fe8c0ed
5eaf0b4
 
 
 
0345daa
5eaf0b4
 
 
 
 
0345daa
75f92fd
fe8c0ed
5eaf0b4
 
 
0345daa
5eaf0b4
 
 
0345daa
5eaf0b4
0345daa
5eaf0b4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
"""
Operaciones de base de datos que necesita un worker mientras procesa una canción.

Las usan dos caminos:
- Los workers residenciales (equipos de usuarios y voluntarios) NO tienen credenciales de la base:
  llaman a la API (app/routers/worker_datos.py) y la API ejecuta estas funciones.
- Los workers de Hugging Face (nuestros) las llaman directo (app/utils/worker_datos.py, modo "db").

Lo sensible (créditos, vencimiento de los stems, avisos a la app) se decide acá, del lado del
servidor, con el worker identificado por su token: el worker solo informa resultados.

`workers` es la lista de filas del equipo que llama. En modo directo (Hugging Face) puede llegar
`confiable=True`: no se verifica que la tarea sea suya.
"""
import json
import logging
from datetime import datetime, timedelta

from app.models.process import Task, Worker

logger = logging.getLogger(__name__)


class OperacionNoPermitida(Exception):
    """El worker intentó tocar una tarea que no es suya."""


# ---------------------------------------------------------------------------
# Worker
# ---------------------------------------------------------------------------

def info_worker(workers: list) -> dict:
    """
    Usuarios vinculados a este equipo, si está suspendido y sus colas propias (una por fila de
    `workers`: ver app/utils/despacho.py). El worker escucha esas colas desde 2.8.23.
    """
    from app.utils.despacho import cola_worker
    return {
        "user_ids": sorted({w.user_id for w in workers if w.user_id}),
        "suspendido": any(w.status == "suspended" for w in workers),
        "colas": [cola_worker(w.id) for w in sorted(workers, key=lambda w: w.id) if w.user_id],
    }


def actualizar_estado(db, workers: list, status: str):
    if status not in ("online", "busy", "offline"):
        raise ValueError("Estado inválido")
    for w in workers:
        if w.status == "suspended":
            continue
        w.status = status
        w.last_seen = datetime.utcnow()
    db.commit()


def latido(db, workers: list) -> dict:
    """Heartbeat de Celery: offline -> online; busy y suspendido se conservan."""
    for w in workers:
        if w.status == "offline":
            w.status = "online"
        w.last_seen = datetime.utcnow()
    db.commit()
    return info_worker(workers)


# ---------------------------------------------------------------------------
# Tareas de separación
# ---------------------------------------------------------------------------

def _tarea(db, task_id: str):
    return db.query(Task).filter(Task.task_id == task_id).first()


def _worker_para(workers: list, task):
    """Fila del equipo que corresponde a la tarea: la del dueño de la canción si la hay."""
    for w in workers:
        if task is not None and w.user_id == task.user_id:
            return w
    return workers[0] if workers else None


def _exigir_propia(workers: list, task, confiable: bool = False):
    """La tarea tiene que haber sido reclamada por este equipo."""
    if confiable:
        return
    ids = {w.id for w in workers}
    if task is None or task.processed_by_worker_id not in ids:
        raise OperacionNoPermitida("La tarea no la procesa este worker")


MINUTOS_SIN_SENALES_TOMADOR = 10


def _tomador_caido(db, worker_id: int) -> bool:
    """El equipo que tomó una canción no da señales de vida hace rato (se apagó o se cortó)."""
    w = db.query(Worker).filter(Worker.id == worker_id).first()
    if w is None or w.last_seen is None:
        return True
    return w.status == "offline" or datetime.utcnow() - w.last_seen > timedelta(minutes=MINUTOS_SIN_SENALES_TOMADOR)


def reclamar(db, workers: list, task_id: str, confiable: bool = False) -> bool:
    """
    Marca la tarea como tomada por este equipo. False si ya la tomó otro (la API la reenvió a HF
    porque ningún residencial la tomaba a tiempo). Si la tarea no existe devuelve True: lo
    maneja tarea_existe (el usuario la borró).
    """
    task = _tarea(db, task_id)
    if task is None:
        return True
    if not workers:
        # Worker de confianza sin registro (HF recién arrancado): se procesa igual, como antes
        return confiable
    ids = {w.id for w in workers}
    if task.processed_by_worker_id is not None and task.processed_by_worker_id not in ids:
        if not _tomador_caido(db, task.processed_by_worker_id) or task.status == "completed":
            return False
        # El equipo que la había tomado se apagó a mitad de camino: la canción volvió a la cola y
        # la toma este equipo (si no, quedaba en "procesando" para siempre)
        logger.warning(f"[{task_id}] El worker {task.processed_by_worker_id} que la procesaba no da señales: "
                       f"la toma otro equipo.")
        task.processed_by_worker_id = None
    if task.processed_by_worker_id is None:
        task.processed_by_worker_id = _worker_para(workers, task).id
    task.status = "processing"
    db.commit()
    return True


def tarea_existe(db, task_id: str) -> bool:
    return _tarea(db, task_id) is not None


def guardar_etapa(db, workers: list, task_id: str, progreso: int, mensaje: str, confiable: bool = False):
    task = _tarea(db, task_id)
    if task is None:
        return
    _exigir_propia(workers, task, confiable)
    # "t": hora (del servidor) del último avance; el agente la usa para saber si la canción está trabada
    task.processing_stage = json.dumps({"p": int(progreso), "m": str(mensaje)[:200],
                                        "t": datetime.utcnow().isoformat(timespec="seconds")})
    db.commit()


def minutos_sin_avance(db, worker):
    """
    Minutos desde el último avance de la canción que procesa este equipo, o None si no se sabe
    (no hay canción en curso o el avance es de una versión que no guardaba la hora).
    """
    task = (db.query(Task)
            .filter(Task.processed_by_worker_id == worker.id, Task.status == "processing")
            .order_by(Task.created_at.desc()).first())
    if task is None or not task.processing_stage:
        return None
    try:
        t = json.loads(task.processing_stage).get("t")
        if not t:
            return None
        return max(0, int((datetime.utcnow() - datetime.fromisoformat(t)).total_seconds() // 60))
    except (ValueError, AttributeError, TypeError):
        return None


def marcar_armonia_inline(db, workers: list, task_id: str, confiable: bool = False):
    task = _tarea(db, task_id)
    if task is None:
        return
    _exigir_propia(workers, task, confiable)
    task.has_harmony = True
    task.harmony_status = "completed"
    db.commit()


def _validar_urls(task_id: str, urls: dict) -> dict:
    """Solo se aceptan archivos de esta tarea dentro del dataset de stems."""
    from app.utils.hf_storage import HF_STORAGE_REPO
    prefijo = f"https://huggingface.co/datasets/{HF_STORAGE_REPO}/resolve/main/stems/{task_id}/"
    limpias = {}
    for nombre, url in (urls or {}).items():
        if not isinstance(nombre, str) or not isinstance(url, str) or not url.startswith(prefijo) or ".." in url:
            raise OperacionNoPermitida(f"URL de stem no permitida: {nombre}")
        limpias[nombre[:80]] = url
    return limpias


def _vencimiento(db, task) -> None:
    """Premium o compartida con un grupo: permanente. Usuario normal: 30 días."""
    from app.models.user import User
    user = db.query(User).filter(User.id == task.user_id).first()
    es_premium = bool(user and user.is_premium)
    es_de_grupo = bool(task.group_id or task.group_ids)
    task.cloud_expires_at = None if (es_premium or es_de_grupo) else datetime.utcnow() + timedelta(days=30)


def _recompensar(db, worker, task):
    """Créditos por procesar: bono al dueño con su propio worker o al voluntario que ayudó."""
    from app.utils.credits import reward_bonus_credit, reward_public_worker_owner
    if worker is None:
        return
    try:
        if worker.user_id and worker.user_id == task.user_id:
            if task.consumed_credit_type == "base":
                reward_bonus_credit(db, user_id=task.user_id, amount=1,
                                    concept="bono_worker_privado", reference_id=task.task_id)
        elif worker.is_public and worker.user_id and worker.user_id != task.user_id:
            reward_public_worker_owner(db, worker_hostname=worker.hostname, task_id=task.task_id, amount=1)
    except Exception as e:
        logger.warning(f"[{task.task_id}] Error al dar la recompensa del worker: {e}")


def _borrar_original(task):
    """El audio original temporal se borra al terminar: el equipo ya no tiene permiso para hacerlo."""
    import re
    m = re.search(r"/resolve/main/(originals/.+)$", task.cloud_url or "")
    if not m:
        return
    try:
        from app.utils.hf_storage import delete_from_hf
        delete_from_hf(m.group(1))
    except Exception as e:
        logger.warning(f"[{task.task_id}] No se pudo borrar el audio original: {e}")


def exigir_subida(db, workers: list, task_id: str):
    """Un equipo solo sube pistas de canciones que procesa o que son de su dueño."""
    from app.utils.puente import worker_de_trabajo
    task = _tarea(db, task_id)
    if task is None:
        raise OperacionNoPermitida("La tarea no existe")
    ids = {w.id for w in workers}
    duenos = {w.user_id for w in workers if w.user_id}
    if task.processed_by_worker_id in ids or worker_de_trabajo(task) in ids or task.user_id in duenos:
        return
    raise OperacionNoPermitida("La tarea no la procesa este worker")


def _avisar(user_id, mensaje: dict):
    try:
        from app.websocket_manager import send_sync_message
        send_sync_message(mensaje, user_id)
    except Exception:
        pass


def completar(db, workers: list, task_id: str, datos: dict, confiable: bool = False) -> bool:
    """
    Registra el resultado de la separación. `datos`: urls (stem -> url), peaks, chords, bpm, beats,
    downbeats, tuning_info, con_armonias. Devuelve False si la tarea ya no existe.
    """
    task = _tarea(db, task_id)
    if task is None:
        return False
    _exigir_propia(workers, task, confiable)
    worker = _worker_para(workers, task)

    task.telegram_file_ids = json.dumps(_validar_urls(task_id, datos.get("urls")))
    task.peaks = datos.get("peaks")
    if datos.get("chords"):
        task.chords = json.dumps(datos["chords"])
    if datos.get("bpm") is not None:
        task.bpm = datos["bpm"]
    if datos.get("beats"):
        task.beats = json.dumps([round(float(b), 4) for b in datos["beats"]])
    task.downbeats = json.dumps(datos["downbeats"]) if datos.get("downbeats") else None
    if datos.get("tuning_info"):
        task.tuning_info = json.dumps(datos["tuning_info"])
    if datos.get("con_armonias"):
        task.has_harmony = True
        task.harmony_status = "completed"
    task.status = "completed"
    if worker is not None:
        task.processed_by_worker_id = worker.id
    task.trabajo_json = None
    from app.utils import audio_compartido
    faltan_corales = audio_compartido.registrar_resultado(db, task, datos)
    _vencimiento(db, task)
    if datos.get("fuente_id") is None:  # Unir pistas ya hechas no es procesar: no genera recompensa
        _recompensar(db, worker, task)
    db.commit()
    if not confiable:
        _borrar_original(task)
    if faltan_corales:
        _encolar_corales(db, task)

    _avisar(task.user_id, {"type": "song_processing_completed", "task_id": task_id,
                           "song_name": task.song_name, "status": "completed"})
    return True


def _encolar_corales(db, task):
    try:
        from app.routers.songs import encolar_armonias
        encolar_armonias(db, task, task.user_id)
    except Exception as e:
        logger.error(f"[{task.task_id}] No se pudieron encolar las voces corales: {e}")


def reconocer(db, workers: list, task_id: str, datos: dict, confiable: bool = False) -> dict:
    """
    ¿Este audio ya se procesó antes? Si es idéntico deja la pista lista sin separar. El crédito ya
    se cobró al subirla; al no procesar no hay recompensa para el equipo.
    """
    from app.utils import audio_compartido
    task = _tarea(db, task_id)
    if task is None:
        return audio_compartido.PROCESAR
    _exigir_propia(workers, task, confiable)
    decision = audio_compartido.decidir(db, task, datos if isinstance(datos, dict) else {})
    if decision["accion"] != "listo":
        return decision

    task.status = "completed"
    task.processing_stage = None
    task.trabajo_json = None
    _vencimiento(db, task)
    db.commit()
    if not confiable:
        _borrar_original(task)
    if decision["faltan_corales"]:
        _encolar_corales(db, task)
    _avisar(task.user_id, {"type": "song_processing_completed", "task_id": task_id,
                           "song_name": task.song_name, "status": "completed"})
    return decision


def fallar(db, workers: list, task_id: str, error: str, confiable: bool = False):
    """Fallo definitivo: marca la tarea y reembolsa el crédito una sola vez."""
    task = _tarea(db, task_id)
    if task is None:
        return
    _exigir_propia(workers, task, confiable)
    if task.status == "failed":
        return
    task.status = "failed"
    task.trabajo_json = None
    if not confiable:
        _borrar_original(task)
    logger.warning(f"[{task_id}] Falló en el worker: {(error or '')[:250]}")
    if task.user_id:
        try:
            from app.models.user import User
            from app.utils.credits import refund_credits
            user = db.query(User).filter(User.id == task.user_id).first()
            if user:
                refund_credits(db, user, 1, "reembolso_error_procesamiento", reference_id=task_id,
                               credit_type=task.consumed_credit_type or "base")
        except Exception as e:
            logger.error(f"[{task_id}] Error reembolsando crédito al fallar: {e}")
    db.commit()
    if task.user_id:
        _avisar(task.user_id, {"type": "song_processing_failed", "task_id": task_id,
                               "song_name": task.song_name, "status": "failed"})


def respaldo_local(db, workers: list, task_id: str, datos: dict, confiable: bool = False):
    """
    Pista procesada en modo local (sin cola): se crea o actualiza su registro con los stems ya
    subidos. Solo para canciones del dueño del equipo.
    """
    user_ids = {w.user_id for w in workers if w.user_id}
    task = _tarea(db, task_id)
    if task is not None and task.user_id not in user_ids and not confiable:
        raise OperacionNoPermitida("La tarea no es del dueño de este worker")
    urls = _validar_urls(task_id, datos.get("urls"))
    if task is None:
        user_id = datos.get("user_id")
        if user_id not in user_ids and not confiable:
            raise OperacionNoPermitida("La tarea no es del dueño de este worker")
        task = Task(task_id=task_id, user_id=user_id, device_id="local_worker",
                    song_name=(datos.get("song_name") or "Pista Local")[:200],
                    artist=(datos.get("artist") or "")[:200], stems=int(datos.get("stems") or 4),
                    created_at=datetime.utcnow())
        db.add(task)
    task.telegram_file_ids = json.dumps(urls)
    task.peaks = datos.get("peaks")
    if datos.get("chords"):
        task.chords = json.dumps(datos["chords"])
    task.status = "completed"
    db.commit()


# ---------------------------------------------------------------------------
# Voces corales (generadas a pedido)
# ---------------------------------------------------------------------------

def _exigir_armonia_en_curso(task):
    # 'error' también vale: la API la marca así si tarda demasiado, y el worker igual puede terminarla
    if task is None or (task.harmony_status or "none") == "none":
        raise OperacionNoPermitida("No hay voces corales pedidas para esta tarea")


def _exigir_armonia_propia(workers: list, task, confiable: bool):
    """Las voces corales las termina el equipo al que se entregaron."""
    if confiable:
        return
    from app.utils.despacho import soporta_puente
    from app.utils.puente import worker_de_trabajo
    asignado = worker_de_trabajo(task)
    if asignado in {w.id for w in workers}:
        return
    # Equipos con el motor anterior (reciben por el broker, sin anotación) hasta que se actualicen
    if asignado is None and workers and not all(soporta_puente(w) for w in workers):
        return
    raise OperacionNoPermitida("Estas voces corales no las procesa este worker")


def datos_armonia(db, workers: list, task_id: str, confiable: bool = False) -> dict:
    task = _tarea(db, task_id)
    if task is None:
        return {"existe": False}
    _exigir_armonia_en_curso(task)
    _exigir_armonia_propia(workers, task, confiable)
    from app.routers.songs import _resolve_task_folder
    return {
        "existe": True,
        "urls": json.loads(task.telegram_file_ids) if task.telegram_file_ids else {},
        "chords": json.loads(task.chords) if task.chords else None,
        "folder": _resolve_task_folder(task_id, db),
    }


def etapa_armonia(db, workers: list, task_id: str, progreso: int, mensaje: str, confiable: bool = False):
    task = _tarea(db, task_id)
    if task is None:
        return
    _exigir_armonia_en_curso(task)
    _exigir_armonia_propia(workers, task, confiable)
    task.harmony_status = "generating"
    task.harmony_stage = json.dumps({"p": int(progreso), "m": str(mensaje)[:200]})
    task.harmony_updated_at = datetime.utcnow()
    db.commit()


def completar_armonia(db, workers: list, task_id: str, urls: dict, hashes=None, confiable: bool = False):
    task = _tarea(db, task_id)
    if task is None:
        return
    _exigir_armonia_en_curso(task)
    _exigir_armonia_propia(workers, task, confiable)
    actuales = json.loads(task.telegram_file_ids) if task.telegram_file_ids else {}
    actuales.update(_validar_urls(task_id, urls))
    task.telegram_file_ids = json.dumps(actuales)
    task.has_harmony = True
    task.harmony_status = "completed"
    task.trabajo_json = None
    from app.utils import audio_compartido
    audio_compartido.anotar_corales(db, task, actuales, hashes)
    db.commit()


def error_armonia(db, workers: list, task_id: str, confiable: bool = False):
    task = _tarea(db, task_id)
    if task is None or task.harmony_status == "completed":
        return
    _exigir_armonia_propia(workers, task, confiable)
    task.harmony_status = "error"
    task.trabajo_json = None
    db.commit()