Spaces:
Running
Running
deploy from github actions
Browse files- app/database.py +5 -3
- app/main.py +24 -2
- app/routers/admin.py +5 -2
- app/routers/auth.py +23 -8
- app/routers/midi.py +1 -1
- app/routers/payments.py +5 -5
- app/routers/songs.py +22 -20
- tasks.py +1 -1
app/database.py
CHANGED
|
@@ -28,9 +28,11 @@ if DATABASE_URL:
|
|
| 28 |
}
|
| 29 |
engine = create_engine(
|
| 30 |
DATABASE_URL,
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
|
|
|
|
|
|
| 34 |
# Reabrir conexiones cada 30 s obligaba a reconectar (SSL) muy seguido; 5 min basta,
|
| 35 |
# pool_pre_ping descarta las que el pooler haya cerrado.
|
| 36 |
pool_recycle=300,
|
|
|
|
| 28 |
}
|
| 29 |
engine = create_engine(
|
| 30 |
DATABASE_URL,
|
| 31 |
+
# 40 = hilos de FastAPI (anyio): cada petición normal ocupa uno y, como mucho, una conexión.
|
| 32 |
+
# Con 20 las peticiones 21-40 esperaban y fallaban en ráfagas (p. ej. tras una subida).
|
| 33 |
+
pool_size=15,
|
| 34 |
+
max_overflow=25,
|
| 35 |
+
pool_timeout=20,
|
| 36 |
# Reabrir conexiones cada 30 s obligaba a reconectar (SSL) muy seguido; 5 min basta,
|
| 37 |
# pool_pre_ping descarta las que el pooler haya cerrado.
|
| 38 |
pool_recycle=300,
|
app/main.py
CHANGED
|
@@ -149,7 +149,9 @@ async def startup_event():
|
|
| 149 |
|
| 150 |
@app.websocket("/ws/admin")
|
| 151 |
async def websocket_admin_endpoint(websocket: WebSocket, token: Optional[str] = Query(None)):
|
| 152 |
-
|
|
|
|
|
|
|
| 153 |
await websocket.close(code=status.WS_1008_POLICY_VIOLATION)
|
| 154 |
return
|
| 155 |
await ws_manager.connect(websocket)
|
|
@@ -186,7 +188,27 @@ app.add_middleware(
|
|
| 186 |
allow_methods=["*"],
|
| 187 |
allow_headers=["*"],
|
| 188 |
)
|
| 189 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
|
| 191 |
# Servir archivos estáticos (audios)
|
| 192 |
# Ajustar rutas relativas si es necesario
|
|
|
|
| 149 |
|
| 150 |
@app.websocket("/ws/admin")
|
| 151 |
async def websocket_admin_endpoint(websocket: WebSocket, token: Optional[str] = Query(None)):
|
| 152 |
+
from starlette.concurrency import run_in_threadpool
|
| 153 |
+
# Consulta la base: en un hilo aparte para no frenar el event loop
|
| 154 |
+
if not await run_in_threadpool(_ws_admin_allowed, token):
|
| 155 |
await websocket.close(code=status.WS_1008_POLICY_VIOLATION)
|
| 156 |
return
|
| 157 |
await ws_manager.connect(websocket)
|
|
|
|
| 188 |
allow_methods=["*"],
|
| 189 |
allow_headers=["*"],
|
| 190 |
)
|
| 191 |
+
# Audio y zip ya vienen comprimidos: pasarlos por gzip (que corre en el event loop) frenaba
|
| 192 |
+
# todas las peticiones mientras alguien descargaba stems. Solo se comprime lo demás (JSON),
|
| 193 |
+
# con nivel 6: casi la misma reducción que el 9 con bastante menos CPU.
|
| 194 |
+
_RUTAS_BINARIAS = ("/audios", "/songs/proxy-stem", "/workers/datos/archivos")
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
class GZipSelectivo:
|
| 198 |
+
def __init__(self, app, minimum_size: int = 500, compresslevel: int = 6):
|
| 199 |
+
self.app = app
|
| 200 |
+
self.gzip = GZipMiddleware(app, minimum_size=minimum_size, compresslevel=compresslevel)
|
| 201 |
+
|
| 202 |
+
async def __call__(self, scope, receive, send):
|
| 203 |
+
if scope["type"] == "http":
|
| 204 |
+
ruta = scope.get("path", "")
|
| 205 |
+
if ruta.startswith(_RUTAS_BINARIAS) or ruta.endswith("/export"):
|
| 206 |
+
await self.app(scope, receive, send)
|
| 207 |
+
return
|
| 208 |
+
await self.gzip(scope, receive, send)
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
app.add_middleware(GZipSelectivo, minimum_size=500)
|
| 212 |
|
| 213 |
# Servir archivos estáticos (audios)
|
| 214 |
# Ajustar rutas relativas si es necesario
|
app/routers/admin.py
CHANGED
|
@@ -107,7 +107,10 @@ def get_current_admin(
|
|
| 107 |
db.rollback()
|
| 108 |
admin = db.query(AdminUser).filter(AdminUser.username == username).first()
|
| 109 |
except Exception:
|
| 110 |
-
|
|
|
|
|
|
|
|
|
|
| 111 |
|
| 112 |
if admin is None:
|
| 113 |
raise credentials_exception
|
|
@@ -115,7 +118,7 @@ def get_current_admin(
|
|
| 115 |
|
| 116 |
|
| 117 |
@router.post("/token", response_model=AdminTokenResponse)
|
| 118 |
-
|
| 119 |
form_data: OAuth2PasswordRequestForm = Depends(),
|
| 120 |
db: Session = Depends(get_db)
|
| 121 |
):
|
|
|
|
| 107 |
db.rollback()
|
| 108 |
admin = db.query(AdminUser).filter(AdminUser.username == username).first()
|
| 109 |
except Exception:
|
| 110 |
+
# Base caída o saturada: 503 (reintentar). Con 401 el panel cerraba la sesión.
|
| 111 |
+
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
| 112 |
+
detail="Servicio ocupado, intenta de nuevo en unos segundos.",
|
| 113 |
+
headers={"Retry-After": "5"})
|
| 114 |
|
| 115 |
if admin is None:
|
| 116 |
raise credentials_exception
|
|
|
|
| 118 |
|
| 119 |
|
| 120 |
@router.post("/token", response_model=AdminTokenResponse)
|
| 121 |
+
def login_admin(
|
| 122 |
form_data: OAuth2PasswordRequestForm = Depends(),
|
| 123 |
db: Session = Depends(get_db)
|
| 124 |
):
|
app/routers/auth.py
CHANGED
|
@@ -77,6 +77,14 @@ def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
|
|
| 77 |
|
| 78 |
SUPABASE_JWT_SECRET = os.getenv("SUPABASE_JWT_SECRET", SECRET_KEY)
|
| 79 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
# Función normal (no async): consulta la base de forma bloqueante, así FastAPI la corre en un
|
| 81 |
# hilo aparte y no frena las demás peticiones mientras espera a la base.
|
| 82 |
def get_current_user(
|
|
@@ -150,8 +158,11 @@ def get_current_user(
|
|
| 150 |
try:
|
| 151 |
db.rollback()
|
| 152 |
user = db.query(User).filter(User.email == email).first()
|
| 153 |
-
except Exception:
|
| 154 |
-
|
|
|
|
|
|
|
|
|
|
| 155 |
|
| 156 |
if user is None:
|
| 157 |
logger.warning(f"Usuario no encontrado: {email}")
|
|
@@ -166,7 +177,11 @@ def get_current_user(
|
|
| 166 |
|
| 167 |
# Validar el dispositivo si el token contiene device_id
|
| 168 |
if device_id:
|
| 169 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
if not device_exists:
|
| 171 |
logger.warning(f"Sesión invalidada: Dispositivo {device_id} ya no está registrado para el usuario {user.username}")
|
| 172 |
raise HTTPException(
|
|
@@ -299,7 +314,7 @@ def _liberar_dispositivos_inactivos(db: Session, user) -> int:
|
|
| 299 |
|
| 300 |
|
| 301 |
@router.post("/token", response_model=Token)
|
| 302 |
-
|
| 303 |
form_data: OAuth2PasswordRequestForm = Depends(),
|
| 304 |
device_id: Optional[str] = Form(None),
|
| 305 |
device_name: Optional[str] = Form(None),
|
|
@@ -438,7 +453,7 @@ async def login_for_access_token(
|
|
| 438 |
|
| 439 |
|
| 440 |
@router.get("/users/me", response_model=UserOut)
|
| 441 |
-
|
| 442 |
db: Session = Depends(get_db),
|
| 443 |
current_user: User = Depends(get_current_user)
|
| 444 |
):
|
|
@@ -456,7 +471,7 @@ async def read_users_me(
|
|
| 456 |
|
| 457 |
|
| 458 |
@router.post("/logout")
|
| 459 |
-
|
| 460 |
device_id: str = Form(...),
|
| 461 |
db: Session = Depends(get_db),
|
| 462 |
current_user: User = Depends(get_current_user)
|
|
@@ -480,7 +495,7 @@ async def logout(
|
|
| 480 |
|
| 481 |
|
| 482 |
@router.get("/users/devices")
|
| 483 |
-
|
| 484 |
db: Session = Depends(get_db),
|
| 485 |
current_user: User = Depends(get_current_user)
|
| 486 |
):
|
|
@@ -504,7 +519,7 @@ async def list_devices(
|
|
| 504 |
}
|
| 505 |
|
| 506 |
@router.post("/register-device")
|
| 507 |
-
|
| 508 |
device_data: DeviceRegister,
|
| 509 |
db: Session = Depends(get_db),
|
| 510 |
current_user: User = Depends(get_current_user)
|
|
|
|
| 77 |
|
| 78 |
SUPABASE_JWT_SECRET = os.getenv("SUPABASE_JWT_SECRET", SECRET_KEY)
|
| 79 |
|
| 80 |
+
|
| 81 |
+
def _base_no_disponible() -> HTTPException:
|
| 82 |
+
return HTTPException(
|
| 83 |
+
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
| 84 |
+
detail="Servicio ocupado, intenta de nuevo en unos segundos.",
|
| 85 |
+
headers={"Retry-After": "5"},
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
# Función normal (no async): consulta la base de forma bloqueante, así FastAPI la corre en un
|
| 89 |
# hilo aparte y no frena las demás peticiones mientras espera a la base.
|
| 90 |
def get_current_user(
|
|
|
|
| 158 |
try:
|
| 159 |
db.rollback()
|
| 160 |
user = db.query(User).filter(User.email == email).first()
|
| 161 |
+
except Exception as e2:
|
| 162 |
+
# Un fallo de la base no es un token malo: con 401 las apps cerraban la sesión de todos
|
| 163 |
+
# cada vez que la base se saturaba. 503 = "reintenta", la sesión se conserva.
|
| 164 |
+
logger.error(f"[Auth] Base no disponible al validar el token: {e2}")
|
| 165 |
+
raise _base_no_disponible()
|
| 166 |
|
| 167 |
if user is None:
|
| 168 |
logger.warning(f"Usuario no encontrado: {email}")
|
|
|
|
| 177 |
|
| 178 |
# Validar el dispositivo si el token contiene device_id
|
| 179 |
if device_id:
|
| 180 |
+
try:
|
| 181 |
+
device_exists = db.query(Device).filter(Device.user_id == user.id, Device.device_id == device_id).first()
|
| 182 |
+
except Exception as e_dev:
|
| 183 |
+
logger.error(f"[Auth] Base no disponible al validar el dispositivo: {e_dev}")
|
| 184 |
+
raise _base_no_disponible()
|
| 185 |
if not device_exists:
|
| 186 |
logger.warning(f"Sesión invalidada: Dispositivo {device_id} ya no está registrado para el usuario {user.username}")
|
| 187 |
raise HTTPException(
|
|
|
|
| 314 |
|
| 315 |
|
| 316 |
@router.post("/token", response_model=Token)
|
| 317 |
+
def login_for_access_token(
|
| 318 |
form_data: OAuth2PasswordRequestForm = Depends(),
|
| 319 |
device_id: Optional[str] = Form(None),
|
| 320 |
device_name: Optional[str] = Form(None),
|
|
|
|
| 453 |
|
| 454 |
|
| 455 |
@router.get("/users/me", response_model=UserOut)
|
| 456 |
+
def read_users_me(
|
| 457 |
db: Session = Depends(get_db),
|
| 458 |
current_user: User = Depends(get_current_user)
|
| 459 |
):
|
|
|
|
| 471 |
|
| 472 |
|
| 473 |
@router.post("/logout")
|
| 474 |
+
def logout(
|
| 475 |
device_id: str = Form(...),
|
| 476 |
db: Session = Depends(get_db),
|
| 477 |
current_user: User = Depends(get_current_user)
|
|
|
|
| 495 |
|
| 496 |
|
| 497 |
@router.get("/users/devices")
|
| 498 |
+
def list_devices(
|
| 499 |
db: Session = Depends(get_db),
|
| 500 |
current_user: User = Depends(get_current_user)
|
| 501 |
):
|
|
|
|
| 519 |
}
|
| 520 |
|
| 521 |
@router.post("/register-device")
|
| 522 |
+
def register_device(
|
| 523 |
device_data: DeviceRegister,
|
| 524 |
db: Session = Depends(get_db),
|
| 525 |
current_user: User = Depends(get_current_user)
|
app/routers/midi.py
CHANGED
|
@@ -16,7 +16,7 @@ MIDI_UPLOAD_DIR = os.path.join(BASE_DIR, "uploads", "midi")
|
|
| 16 |
os.makedirs(MIDI_UPLOAD_DIR, exist_ok=True)
|
| 17 |
|
| 18 |
@router.post("/upload", status_code=status.HTTP_201_CREATED)
|
| 19 |
-
|
| 20 |
file: UploadFile = File(...),
|
| 21 |
title: Optional[str] = Form(None),
|
| 22 |
artist: Optional[str] = Form("Artista desconocido"),
|
|
|
|
| 16 |
os.makedirs(MIDI_UPLOAD_DIR, exist_ok=True)
|
| 17 |
|
| 18 |
@router.post("/upload", status_code=status.HTTP_201_CREATED)
|
| 19 |
+
def upload_midi_file(
|
| 20 |
file: UploadFile = File(...),
|
| 21 |
title: Optional[str] = Form(None),
|
| 22 |
artist: Optional[str] = Form("Artista desconocido"),
|
app/routers/payments.py
CHANGED
|
@@ -236,7 +236,7 @@ def capture_paypal_order(
|
|
| 236 |
"message": "Este pago de PayPal ya fue acreditado anteriormente.",
|
| 237 |
"credits_awarded": existing.amount,
|
| 238 |
"already_processed": True,
|
| 239 |
-
"new_total_credits": owner_user.total_credits,
|
| 240 |
"user_id": owner_user.id,
|
| 241 |
"username": owner_user.username,
|
| 242 |
}
|
|
@@ -365,7 +365,7 @@ def capture_paypal_order(
|
|
| 365 |
"message": "Este pago de PayPal ya fue acreditado anteriormente.",
|
| 366 |
"credits_awarded": existing.amount if existing else credits_awarded,
|
| 367 |
"already_processed": True,
|
| 368 |
-
"new_total_credits": owner_user.total_credits if owner_user else target_user.total_credits,
|
| 369 |
"user_id": owner_user.id if owner_user else target_user.id,
|
| 370 |
"username": owner_user.username if owner_user else target_user.username,
|
| 371 |
}
|
|
@@ -385,7 +385,7 @@ def capture_paypal_order(
|
|
| 385 |
"success": True,
|
| 386 |
"credits_awarded": credits_awarded,
|
| 387 |
"amount_paid_usd": amount_paid_usd,
|
| 388 |
-
"new_total_credits": target_user.total_credits,
|
| 389 |
"order_id": order_id,
|
| 390 |
"user_id": target_user.id,
|
| 391 |
"username": target_user.username,
|
|
@@ -501,7 +501,7 @@ def verify_checkout_session(
|
|
| 501 |
"message": "Este pago ya fue acreditado anteriormente.",
|
| 502 |
"credits_awarded": existing.amount,
|
| 503 |
"already_processed": True,
|
| 504 |
-
"new_total_credits": user.total_credits,
|
| 505 |
"user_id": user.id,
|
| 506 |
"username": user.username,
|
| 507 |
}
|
|
@@ -537,7 +537,7 @@ def verify_checkout_session(
|
|
| 537 |
"success": True,
|
| 538 |
"credits_awarded": credits_awarded,
|
| 539 |
"amount_paid_usd": amount_paid_usd,
|
| 540 |
-
"new_total_credits": user.total_credits,
|
| 541 |
"session_id": stripe_session_id,
|
| 542 |
"user_id": user.id,
|
| 543 |
"username": user.username,
|
|
|
|
| 236 |
"message": "Este pago de PayPal ya fue acreditado anteriormente.",
|
| 237 |
"credits_awarded": existing.amount,
|
| 238 |
"already_processed": True,
|
| 239 |
+
"new_total_credits": owner_user.total_credits, "credits": owner_user.credits or 0, "bonus_credits": owner_user.bonus_credits or 0,
|
| 240 |
"user_id": owner_user.id,
|
| 241 |
"username": owner_user.username,
|
| 242 |
}
|
|
|
|
| 365 |
"message": "Este pago de PayPal ya fue acreditado anteriormente.",
|
| 366 |
"credits_awarded": existing.amount if existing else credits_awarded,
|
| 367 |
"already_processed": True,
|
| 368 |
+
"new_total_credits": owner_user.total_credits if owner_user else target_user.total_credits, "credits": (owner_user or target_user).credits or 0, "bonus_credits": (owner_user or target_user).bonus_credits or 0,
|
| 369 |
"user_id": owner_user.id if owner_user else target_user.id,
|
| 370 |
"username": owner_user.username if owner_user else target_user.username,
|
| 371 |
}
|
|
|
|
| 385 |
"success": True,
|
| 386 |
"credits_awarded": credits_awarded,
|
| 387 |
"amount_paid_usd": amount_paid_usd,
|
| 388 |
+
"new_total_credits": target_user.total_credits, "credits": target_user.credits or 0, "bonus_credits": target_user.bonus_credits or 0,
|
| 389 |
"order_id": order_id,
|
| 390 |
"user_id": target_user.id,
|
| 391 |
"username": target_user.username,
|
|
|
|
| 501 |
"message": "Este pago ya fue acreditado anteriormente.",
|
| 502 |
"credits_awarded": existing.amount,
|
| 503 |
"already_processed": True,
|
| 504 |
+
"new_total_credits": user.total_credits, "credits": user.credits or 0, "bonus_credits": user.bonus_credits or 0,
|
| 505 |
"user_id": user.id,
|
| 506 |
"username": user.username,
|
| 507 |
}
|
|
|
|
| 537 |
"success": True,
|
| 538 |
"credits_awarded": credits_awarded,
|
| 539 |
"amount_paid_usd": amount_paid_usd,
|
| 540 |
+
"new_total_credits": user.total_credits, "credits": user.credits or 0, "bonus_credits": user.bonus_credits or 0,
|
| 541 |
"session_id": stripe_session_id,
|
| 542 |
"user_id": user.id,
|
| 543 |
"username": user.username,
|
app/routers/songs.py
CHANGED
|
@@ -330,7 +330,7 @@ class CloudQueueRequest(BaseModel):
|
|
| 330 |
auto_harmonize: bool = False
|
| 331 |
|
| 332 |
@router.post("/queue-cloud")
|
| 333 |
-
|
| 334 |
request: CloudQueueRequest,
|
| 335 |
db: Session = Depends(get_db),
|
| 336 |
current_user: User = Depends(get_current_user)
|
|
@@ -416,7 +416,7 @@ async def queue_cloud_song(
|
|
| 416 |
"message": "Encolado desde la nube",
|
| 417 |
"task_id": task_id,
|
| 418 |
"celery_id": job.id,
|
| 419 |
-
"credits_left": credits_left
|
| 420 |
}
|
| 421 |
except Exception as e:
|
| 422 |
import traceback
|
|
@@ -455,7 +455,7 @@ def _guardar_caratula_del_archivo(task_id: str, cover_data_url: str):
|
|
| 455 |
|
| 456 |
|
| 457 |
@router.post("/upload")
|
| 458 |
-
|
| 459 |
request: Request,
|
| 460 |
background_tasks: BackgroundTasks,
|
| 461 |
file: UploadFile = File(...),
|
|
@@ -656,7 +656,7 @@ async def subir_cancion(
|
|
| 656 |
return {
|
| 657 |
"celery_id": job.id,
|
| 658 |
"task_id": task_id,
|
| 659 |
-
"credits_left": credits_left,
|
| 660 |
"message": "Canción encolada para procesamiento"
|
| 661 |
}
|
| 662 |
|
|
@@ -791,7 +791,7 @@ def subir_youtube(
|
|
| 791 |
return {
|
| 792 |
"celery_id": job.id,
|
| 793 |
"task_id": task_id,
|
| 794 |
-
"credits_left": credits_left,
|
| 795 |
"message": "Enlace de YouTube encolado en Worker Residencial"
|
| 796 |
}
|
| 797 |
except Exception as e:
|
|
@@ -811,7 +811,7 @@ def subir_youtube(
|
|
| 811 |
|
| 812 |
|
| 813 |
@router.get("/status/{celery_id}", response_model=ProcesoResultado)
|
| 814 |
-
|
| 815 |
celery_id: str,
|
| 816 |
db: Session = Depends(get_db)
|
| 817 |
):
|
|
@@ -1050,7 +1050,7 @@ async def consultar_estado(
|
|
| 1050 |
|
| 1051 |
|
| 1052 |
@router.get("/history")
|
| 1053 |
-
|
| 1054 |
db: Session = Depends(get_db),
|
| 1055 |
current_user: User = Depends(get_current_user),
|
| 1056 |
limit: int = 500,
|
|
@@ -1178,7 +1178,7 @@ class CleanupRequest(BaseModel):
|
|
| 1178 |
secret: str
|
| 1179 |
|
| 1180 |
@router.post("/cleanup-expired")
|
| 1181 |
-
|
| 1182 |
data: CleanupRequest,
|
| 1183 |
db: Session = Depends(get_db)
|
| 1184 |
):
|
|
@@ -1425,7 +1425,7 @@ def get_task_by_id(
|
|
| 1425 |
}
|
| 1426 |
|
| 1427 |
@router.get("/stems/{task_id}")
|
| 1428 |
-
|
| 1429 |
task_id: str,
|
| 1430 |
request: Request,
|
| 1431 |
db: Session = Depends(get_db),
|
|
@@ -1568,6 +1568,7 @@ def get_stem_peaks(
|
|
| 1568 |
}
|
| 1569 |
faltantes = {k: v for k, v in origenes.items() if k not in guardados}
|
| 1570 |
if faltantes:
|
|
|
|
| 1571 |
nuevos = picos_de_stems(faltantes)
|
| 1572 |
if nuevos:
|
| 1573 |
guardados = {**guardados, **nuevos}
|
|
@@ -1675,7 +1676,7 @@ async def proxy_stem(
|
|
| 1675 |
|
| 1676 |
|
| 1677 |
@router.post("/{task_id}/reset-cloud-stems")
|
| 1678 |
-
|
| 1679 |
task_id: str,
|
| 1680 |
db: Session = Depends(get_db),
|
| 1681 |
current_user: User = Depends(get_current_user)
|
|
@@ -1702,7 +1703,7 @@ async def reset_cloud_stems(
|
|
| 1702 |
|
| 1703 |
|
| 1704 |
@router.post("/confirm-download/{task_id}")
|
| 1705 |
-
|
| 1706 |
task_id: str,
|
| 1707 |
device_id: Optional[str] = Form(None),
|
| 1708 |
download_type: str = "stems",
|
|
@@ -1839,6 +1840,7 @@ def exportar_pista(
|
|
| 1839 |
cabeceras = {"Authorization": f"Bearer {token}"} if token else {}
|
| 1840 |
archivos = {}
|
| 1841 |
try:
|
|
|
|
| 1842 |
with httpx.Client(follow_redirects=True, timeout=120.0, headers=cabeceras) as cliente:
|
| 1843 |
for nombre in nombres:
|
| 1844 |
url = urls[nombre]
|
|
@@ -2018,7 +2020,7 @@ def importar_pista(
|
|
| 2018 |
|
| 2019 |
background_tasks.add_task(_terminar_importacion, task_id, current_user.id, carpeta, archivos, manifiesto)
|
| 2020 |
en_segundo_plano = True
|
| 2021 |
-
return {"task_id": task_id, "credits_left": credits_left, "message": "Importando pista"}
|
| 2022 |
except PaqueteInvalido as e:
|
| 2023 |
raise HTTPException(status_code=400, detail=str(e))
|
| 2024 |
except HTTPException:
|
|
@@ -2094,7 +2096,7 @@ def _limpiar_archivos_de_tarea(task_id: str, cloud_url: Optional[str], carpetas_
|
|
| 2094 |
logger.warning(f"[{task_id}] Error eliminando archivos de Supabase storage: {se}")
|
| 2095 |
|
| 2096 |
@router.delete("/cleanup/{task_id}")
|
| 2097 |
-
|
| 2098 |
task_id: str,
|
| 2099 |
background_tasks: BackgroundTasks,
|
| 2100 |
db: Session = Depends(get_db),
|
|
@@ -2168,7 +2170,7 @@ async def limpiar_tarea(
|
|
| 2168 |
# ==========================================
|
| 2169 |
|
| 2170 |
@router.get("/sync-requests/pending")
|
| 2171 |
-
|
| 2172 |
device_id: Optional[str] = None,
|
| 2173 |
db: Session = Depends(get_db),
|
| 2174 |
current_user: User = Depends(get_current_user)
|
|
@@ -2182,7 +2184,7 @@ async def list_pending_sync_requests(
|
|
| 2182 |
|
| 2183 |
|
| 2184 |
@router.post("/sync-requests/claim-upload/{task_id}")
|
| 2185 |
-
|
| 2186 |
task_id: str,
|
| 2187 |
device_id: str = Form(...),
|
| 2188 |
db: Session = Depends(get_db),
|
|
@@ -2213,7 +2215,7 @@ async def claim_upload_lock(
|
|
| 2213 |
|
| 2214 |
|
| 2215 |
@router.post("/sync-requests/upload/{task_id}/{stem_name}")
|
| 2216 |
-
|
| 2217 |
task_id: str,
|
| 2218 |
stem_name: str,
|
| 2219 |
file: UploadFile = File(...),
|
|
@@ -2282,7 +2284,7 @@ async def upload_sync_stem(
|
|
| 2282 |
|
| 2283 |
|
| 2284 |
@router.post("/sync-requests/complete-upload/{task_id}")
|
| 2285 |
-
|
| 2286 |
task_id: str,
|
| 2287 |
db: Session = Depends(get_db),
|
| 2288 |
current_user: User = Depends(get_current_user)
|
|
@@ -2362,7 +2364,7 @@ def _estado_generacion_armonia(task_record, db: Session):
|
|
| 2362 |
|
| 2363 |
|
| 2364 |
@router.get("/harmony-status/{task_id}")
|
| 2365 |
-
|
| 2366 |
task_id: str,
|
| 2367 |
db: Session = Depends(get_db),
|
| 2368 |
current_user: User = Depends(get_current_user)
|
|
@@ -2479,7 +2481,7 @@ async def harmony_status(
|
|
| 2479 |
}
|
| 2480 |
|
| 2481 |
@router.post("/harmonize/{task_id}")
|
| 2482 |
-
|
| 2483 |
task_id: str,
|
| 2484 |
force: bool = False,
|
| 2485 |
db: Session = Depends(get_db),
|
|
@@ -2727,7 +2729,7 @@ def run_local_processing(file_path, task_id, stems, trim_start, trim_end, user_i
|
|
| 2727 |
pass
|
| 2728 |
|
| 2729 |
@router.post("/upload-local")
|
| 2730 |
-
|
| 2731 |
background_tasks: BackgroundTasks,
|
| 2732 |
file: Optional[UploadFile] = File(None),
|
| 2733 |
youtube_url: Optional[str] = Form(None),
|
|
|
|
| 330 |
auto_harmonize: bool = False
|
| 331 |
|
| 332 |
@router.post("/queue-cloud")
|
| 333 |
+
def queue_cloud_song(
|
| 334 |
request: CloudQueueRequest,
|
| 335 |
db: Session = Depends(get_db),
|
| 336 |
current_user: User = Depends(get_current_user)
|
|
|
|
| 416 |
"message": "Encolado desde la nube",
|
| 417 |
"task_id": task_id,
|
| 418 |
"celery_id": job.id,
|
| 419 |
+
"credits_left": credits_left, "credits": current_user.credits or 0, "bonus_credits": current_user.bonus_credits or 0
|
| 420 |
}
|
| 421 |
except Exception as e:
|
| 422 |
import traceback
|
|
|
|
| 455 |
|
| 456 |
|
| 457 |
@router.post("/upload")
|
| 458 |
+
def subir_cancion(
|
| 459 |
request: Request,
|
| 460 |
background_tasks: BackgroundTasks,
|
| 461 |
file: UploadFile = File(...),
|
|
|
|
| 656 |
return {
|
| 657 |
"celery_id": job.id,
|
| 658 |
"task_id": task_id,
|
| 659 |
+
"credits_left": credits_left, "credits": current_user.credits or 0, "bonus_credits": current_user.bonus_credits or 0,
|
| 660 |
"message": "Canción encolada para procesamiento"
|
| 661 |
}
|
| 662 |
|
|
|
|
| 791 |
return {
|
| 792 |
"celery_id": job.id,
|
| 793 |
"task_id": task_id,
|
| 794 |
+
"credits_left": credits_left, "credits": current_user.credits or 0, "bonus_credits": current_user.bonus_credits or 0,
|
| 795 |
"message": "Enlace de YouTube encolado en Worker Residencial"
|
| 796 |
}
|
| 797 |
except Exception as e:
|
|
|
|
| 811 |
|
| 812 |
|
| 813 |
@router.get("/status/{celery_id}", response_model=ProcesoResultado)
|
| 814 |
+
def consultar_estado(
|
| 815 |
celery_id: str,
|
| 816 |
db: Session = Depends(get_db)
|
| 817 |
):
|
|
|
|
| 1050 |
|
| 1051 |
|
| 1052 |
@router.get("/history")
|
| 1053 |
+
def historial_canciones(
|
| 1054 |
db: Session = Depends(get_db),
|
| 1055 |
current_user: User = Depends(get_current_user),
|
| 1056 |
limit: int = 500,
|
|
|
|
| 1178 |
secret: str
|
| 1179 |
|
| 1180 |
@router.post("/cleanup-expired")
|
| 1181 |
+
def cleanup_expired_stems(
|
| 1182 |
data: CleanupRequest,
|
| 1183 |
db: Session = Depends(get_db)
|
| 1184 |
):
|
|
|
|
| 1425 |
}
|
| 1426 |
|
| 1427 |
@router.get("/stems/{task_id}")
|
| 1428 |
+
def get_stems(
|
| 1429 |
task_id: str,
|
| 1430 |
request: Request,
|
| 1431 |
db: Session = Depends(get_db),
|
|
|
|
| 1568 |
}
|
| 1569 |
faltantes = {k: v for k, v in origenes.items() if k not in guardados}
|
| 1570 |
if faltantes:
|
| 1571 |
+
db.commit() # Libera la conexión mientras ffmpeg analiza (puede tardar)
|
| 1572 |
nuevos = picos_de_stems(faltantes)
|
| 1573 |
if nuevos:
|
| 1574 |
guardados = {**guardados, **nuevos}
|
|
|
|
| 1676 |
|
| 1677 |
|
| 1678 |
@router.post("/{task_id}/reset-cloud-stems")
|
| 1679 |
+
def reset_cloud_stems(
|
| 1680 |
task_id: str,
|
| 1681 |
db: Session = Depends(get_db),
|
| 1682 |
current_user: User = Depends(get_current_user)
|
|
|
|
| 1703 |
|
| 1704 |
|
| 1705 |
@router.post("/confirm-download/{task_id}")
|
| 1706 |
+
def confirmar_descarga(
|
| 1707 |
task_id: str,
|
| 1708 |
device_id: Optional[str] = Form(None),
|
| 1709 |
download_type: str = "stems",
|
|
|
|
| 1840 |
cabeceras = {"Authorization": f"Bearer {token}"} if token else {}
|
| 1841 |
archivos = {}
|
| 1842 |
try:
|
| 1843 |
+
db.commit() # Libera la conexión mientras se descargan los stems
|
| 1844 |
with httpx.Client(follow_redirects=True, timeout=120.0, headers=cabeceras) as cliente:
|
| 1845 |
for nombre in nombres:
|
| 1846 |
url = urls[nombre]
|
|
|
|
| 2020 |
|
| 2021 |
background_tasks.add_task(_terminar_importacion, task_id, current_user.id, carpeta, archivos, manifiesto)
|
| 2022 |
en_segundo_plano = True
|
| 2023 |
+
return {"task_id": task_id, "credits_left": credits_left, "credits": current_user.credits or 0, "bonus_credits": current_user.bonus_credits or 0, "message": "Importando pista"}
|
| 2024 |
except PaqueteInvalido as e:
|
| 2025 |
raise HTTPException(status_code=400, detail=str(e))
|
| 2026 |
except HTTPException:
|
|
|
|
| 2096 |
logger.warning(f"[{task_id}] Error eliminando archivos de Supabase storage: {se}")
|
| 2097 |
|
| 2098 |
@router.delete("/cleanup/{task_id}")
|
| 2099 |
+
def limpiar_tarea(
|
| 2100 |
task_id: str,
|
| 2101 |
background_tasks: BackgroundTasks,
|
| 2102 |
db: Session = Depends(get_db),
|
|
|
|
| 2170 |
# ==========================================
|
| 2171 |
|
| 2172 |
@router.get("/sync-requests/pending")
|
| 2173 |
+
def list_pending_sync_requests(
|
| 2174 |
device_id: Optional[str] = None,
|
| 2175 |
db: Session = Depends(get_db),
|
| 2176 |
current_user: User = Depends(get_current_user)
|
|
|
|
| 2184 |
|
| 2185 |
|
| 2186 |
@router.post("/sync-requests/claim-upload/{task_id}")
|
| 2187 |
+
def claim_upload_lock(
|
| 2188 |
task_id: str,
|
| 2189 |
device_id: str = Form(...),
|
| 2190 |
db: Session = Depends(get_db),
|
|
|
|
| 2215 |
|
| 2216 |
|
| 2217 |
@router.post("/sync-requests/upload/{task_id}/{stem_name}")
|
| 2218 |
+
def upload_sync_stem(
|
| 2219 |
task_id: str,
|
| 2220 |
stem_name: str,
|
| 2221 |
file: UploadFile = File(...),
|
|
|
|
| 2284 |
|
| 2285 |
|
| 2286 |
@router.post("/sync-requests/complete-upload/{task_id}")
|
| 2287 |
+
def complete_sync_upload(
|
| 2288 |
task_id: str,
|
| 2289 |
db: Session = Depends(get_db),
|
| 2290 |
current_user: User = Depends(get_current_user)
|
|
|
|
| 2364 |
|
| 2365 |
|
| 2366 |
@router.get("/harmony-status/{task_id}")
|
| 2367 |
+
def harmony_status(
|
| 2368 |
task_id: str,
|
| 2369 |
db: Session = Depends(get_db),
|
| 2370 |
current_user: User = Depends(get_current_user)
|
|
|
|
| 2481 |
}
|
| 2482 |
|
| 2483 |
@router.post("/harmonize/{task_id}")
|
| 2484 |
+
def harmonize_song(
|
| 2485 |
task_id: str,
|
| 2486 |
force: bool = False,
|
| 2487 |
db: Session = Depends(get_db),
|
|
|
|
| 2729 |
pass
|
| 2730 |
|
| 2731 |
@router.post("/upload-local")
|
| 2732 |
+
def upload_song_local(
|
| 2733 |
background_tasks: BackgroundTasks,
|
| 2734 |
file: Optional[UploadFile] = File(None),
|
| 2735 |
youtube_url: Optional[str] = Form(None),
|
tasks.py
CHANGED
|
@@ -2547,7 +2547,7 @@ def generar_armonias_task(self, task_id: str):
|
|
| 2547 |
download_url = get_hf_download_url(object_key)
|
| 2548 |
|
| 2549 |
# Descargar archivo
|
| 2550 |
-
r = requests.get(download_url, stream=True)
|
| 2551 |
r.raise_for_status()
|
| 2552 |
with open(vocals_path, 'wb') as f:
|
| 2553 |
for chunk in r.iter_content(chunk_size=8192):
|
|
|
|
| 2547 |
download_url = get_hf_download_url(object_key)
|
| 2548 |
|
| 2549 |
# Descargar archivo
|
| 2550 |
+
r = requests.get(download_url, stream=True, timeout=(15, 120)) # sin timeout un corte colgaba al worker
|
| 2551 |
r.raise_for_status()
|
| 2552 |
with open(vocals_path, 'wb') as f:
|
| 2553 |
for chunk in r.iter_content(chunk_size=8192):
|