Isaac105 commited on
Commit
0b6210a
·
1 Parent(s): d7d8713

deploy from github actions

Browse files
app/routers/songs.py CHANGED
@@ -397,9 +397,28 @@ async def queue_cloud_song(
397
 
398
 
399
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
400
  @router.post("/upload")
401
  async def subir_cancion(
402
  request: Request,
 
403
  file: UploadFile = File(...),
404
  stems: int = Form(...),
405
  title: str = Form(None),
@@ -536,6 +555,17 @@ async def subir_cancion(
536
  else:
537
  song_name_val = filename_no_ext
538
 
 
 
 
 
 
 
 
 
 
 
 
539
  from app.models.user import Device
540
  dev_rec = db.query(Device).filter(Device.user_id == user_id).first()
541
  dev_id_val = dev_rec.device_id if dev_rec else "web_client"
@@ -551,6 +581,8 @@ async def subir_cancion(
551
  nuevo_proceso.song_name = song_name_val
552
  nuevo_proceso.artist = artist_val
553
  nuevo_proceso.stems = stems
 
 
554
  else:
555
  nuevo_proceso = Task(
556
  task_id=task_id,
@@ -561,7 +593,8 @@ async def subir_cancion(
561
  stems=stems,
562
  status="pending",
563
  cloud_url=cloud_url,
564
- consumed_credit_type=consumed_type
 
565
  )
566
  db.add(nuevo_proceso)
567
 
@@ -570,6 +603,10 @@ async def subir_cancion(
570
 
571
  logger.info(f"[{task_id}] Tarea creada en BD")
572
 
 
 
 
 
573
  # ==========================================
574
  # ENCOLAR TAREA DE PROCESAMIENTO
575
  # ==========================================
 
397
 
398
 
399
 
400
+ def _guardar_caratula_del_archivo(task_id: str, cover_data_url: str):
401
+ """Sube la carátula incrustada en el audio y la asigna a la pista."""
402
+ from app.database import SessionLocal
403
+ from app.utils.image_storage import upload_global_image
404
+ _db = SessionLocal()
405
+ try:
406
+ url = upload_global_image(cover_data_url, folder="covers", compress=True)
407
+ task = _db.query(Task).filter(Task.task_id == task_id).first()
408
+ if task:
409
+ task.cover_url = url
410
+ _db.commit()
411
+ logger.info(f"[{task_id}] Carátula tomada del archivo: {url}")
412
+ except Exception as e:
413
+ logger.warning(f"[{task_id}] No se pudo guardar la carátula del archivo: {e}")
414
+ finally:
415
+ _db.close()
416
+
417
+
418
  @router.post("/upload")
419
  async def subir_cancion(
420
  request: Request,
421
+ background_tasks: BackgroundTasks,
422
  file: UploadFile = File(...),
423
  stems: int = Form(...),
424
  title: str = Form(None),
 
555
  else:
556
  song_name_val = filename_no_ext
557
 
558
+ # Las etiquetas del archivo mandan sobre lo que venga del formulario (decisión del usuario)
559
+ from app.utils.audio_tags import leer_etiquetas
560
+ etiquetas = leer_etiquetas(upload_path)
561
+ if etiquetas["title"]:
562
+ song_name_val = etiquetas["title"]
563
+ if etiquetas["artist"]:
564
+ artist_val = etiquetas["artist"]
565
+ if any(etiquetas.values()):
566
+ logger.info(f"[{task_id}] Etiquetas del archivo: título={etiquetas['title']!r} artista={etiquetas['artist']!r} "
567
+ f"álbum={etiquetas['album']!r} carátula={'sí' if etiquetas['cover_data_url'] else 'no'}")
568
+
569
  from app.models.user import Device
570
  dev_rec = db.query(Device).filter(Device.user_id == user_id).first()
571
  dev_id_val = dev_rec.device_id if dev_rec else "web_client"
 
581
  nuevo_proceso.song_name = song_name_val
582
  nuevo_proceso.artist = artist_val
583
  nuevo_proceso.stems = stems
584
+ if etiquetas["album"]:
585
+ nuevo_proceso.album = etiquetas["album"]
586
  else:
587
  nuevo_proceso = Task(
588
  task_id=task_id,
 
593
  stems=stems,
594
  status="pending",
595
  cloud_url=cloud_url,
596
+ consumed_credit_type=consumed_type,
597
+ album=etiquetas["album"]
598
  )
599
  db.add(nuevo_proceso)
600
 
 
603
 
604
  logger.info(f"[{task_id}] Tarea creada en BD")
605
 
606
+ # La carátula se sube en segundo plano para no demorar la respuesta
607
+ if etiquetas["cover_data_url"]:
608
+ background_tasks.add_task(_guardar_caratula_del_archivo, task_id, etiquetas["cover_data_url"])
609
+
610
  # ==========================================
611
  # ENCOLAR TAREA DE PROCESAMIENTO
612
  # ==========================================
app/utils/audio_tags.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Lectura de etiquetas (título, artista, álbum y carátula) de un archivo de audio subido.
3
+ Soporta ID3 (mp3/wav/aiff), MP4 (m4a/aac), FLAC y Vorbis/Opus (ogg).
4
+ Nunca lanza excepciones: si algo falla devuelve lo que haya podido leer.
5
+ """
6
+ import base64
7
+ import logging
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+ # Carátulas más grandes que esto se ignoran (después se comprimen a 800 px igual)
12
+ MAX_COVER_BYTES = 8 * 1024 * 1024
13
+
14
+
15
+ def _texto(valor):
16
+ if valor is None:
17
+ return None
18
+ if isinstance(valor, (list, tuple)):
19
+ valor = valor[0] if valor else None
20
+ if valor is None:
21
+ return None
22
+ texto = str(valor).replace("\x00", "").strip()
23
+ return texto or None
24
+
25
+
26
+ def _caratula(audio):
27
+ """Devuelve (bytes, mime) de la carátula incrustada, o (None, None)."""
28
+ tags = getattr(audio, "tags", None)
29
+
30
+ # FLAC
31
+ pictures = getattr(audio, "pictures", None)
32
+ if pictures:
33
+ frente = next((p for p in pictures if p.type == 3), pictures[0])
34
+ return frente.data, frente.mime or "image/jpeg"
35
+
36
+ if tags is None:
37
+ return None, None
38
+
39
+ # ID3 (APIC)
40
+ if hasattr(tags, "getall"):
41
+ frames = tags.getall("APIC")
42
+ if frames:
43
+ frente = next((f for f in frames if getattr(f, "type", None) == 3), frames[0])
44
+ return frente.data, frente.mime or "image/jpeg"
45
+
46
+ # MP4
47
+ try:
48
+ covr = tags.get("covr")
49
+ except Exception:
50
+ covr = None
51
+ if covr:
52
+ from mutagen.mp4 import MP4Cover
53
+ img = covr[0]
54
+ mime = "image/png" if getattr(img, "imageformat", None) == MP4Cover.FORMAT_PNG else "image/jpeg"
55
+ return bytes(img), mime
56
+
57
+ # Vorbis / Opus
58
+ try:
59
+ bloques = tags.get("metadata_block_picture")
60
+ except Exception:
61
+ bloques = None
62
+ if bloques:
63
+ from mutagen.flac import Picture
64
+ pic = Picture(base64.b64decode(bloques[0]))
65
+ return pic.data, pic.mime or "image/jpeg"
66
+
67
+ return None, None
68
+
69
+
70
+ def leer_etiquetas(ruta: str) -> dict:
71
+ """{'title', 'artist', 'album', 'cover_data_url'}; cada valor puede ser None."""
72
+ resultado = {"title": None, "artist": None, "album": None, "cover_data_url": None}
73
+ try:
74
+ import mutagen
75
+ except ImportError:
76
+ logger.warning("mutagen no está instalado: no se leen etiquetas del audio")
77
+ return resultado
78
+
79
+ try:
80
+ facil = mutagen.File(ruta, easy=True)
81
+ if facil is not None and facil.tags is not None:
82
+ resultado["title"] = _texto(facil.tags.get("title"))
83
+ resultado["artist"] = _texto(facil.tags.get("artist")) or _texto(facil.tags.get("albumartist"))
84
+ resultado["album"] = _texto(facil.tags.get("album"))
85
+ except Exception as e:
86
+ logger.info(f"No se pudieron leer etiquetas de texto de {ruta}: {e}")
87
+
88
+ try:
89
+ completo = mutagen.File(ruta)
90
+ if completo is not None:
91
+ data, mime = _caratula(completo)
92
+ if data and len(data) <= MAX_COVER_BYTES:
93
+ if not mime.startswith("image/"):
94
+ mime = "image/jpeg"
95
+ resultado["cover_data_url"] = f"data:{mime};base64," + base64.b64encode(data).decode("ascii")
96
+ except Exception as e:
97
+ logger.info(f"No se pudo leer la carátula de {ruta}: {e}")
98
+
99
+ return resultado
requirements.txt CHANGED
@@ -66,3 +66,4 @@ huggingface-hub>=0.19.0
66
  stripe>=7.0.0
67
  paypalrestsdk>=1.13.1 # PayPal Checkout API
68
 
 
 
66
  stripe>=7.0.0
67
  paypalrestsdk>=1.13.1 # PayPal Checkout API
68
 
69
+ mutagen==1.47.0