-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2759 lines (2368 loc) · 110 KB
/
Copy pathapp.py
File metadata and controls
2759 lines (2368 loc) · 110 KB
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Aplicación web Flask para el gestor de descarga de música.
Interfaz web moderna con soporte completo para videos embebidos de YouTube.
"""
import os
import sys
import re
import json
import shutil
import threading
import time
import webbrowser
import logging
from pathlib import Path
from urllib.parse import quote
from dotenv import load_dotenv
# Configurar TensorFlow para reducir verbosidad de logs
# Solo mostrar errores críticos, una línea por ejecución
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # 0=all, 1=info, 2=warnings, 3=errors only
os.environ['TF_CPP_MIN_VLOG_LEVEL'] = '3' # Desactivar logs verbosos
# Importar Flask
try:
from flask import Flask, render_template, request, jsonify, send_file
from flask_cors import CORS
except ImportError:
print("❌ Flask no está instalado. Instala con: pip install flask flask-cors")
exit(1)
def _get_config_dir() -> Path:
"""Directorio donde se guarda el .env. Fijo: junto al .exe si está empaquetado, sino junto a app.py."""
if getattr(sys, 'frozen', False):
return Path(sys.executable).parent.resolve()
return Path(__file__).parent.resolve()
# Cargar variables de entorno antes de resolver la ruta de la BD (siempre desde la misma ubicación)
load_dotenv(_get_config_dir() / '.env')
# Resolver ruta de la base de datos (si falla la por defecto, preguntar al usuario)
from database import MusicDatabase, get_or_choose_db_path
_db_path = get_or_choose_db_path()
if _db_path is None:
print("❌ No se pudo abrir o crear la base de datos. Se canceló la elección de ubicación.")
sys.exit(1)
# Importar módulos del proyecto (download_youtube usa DB_PATH del entorno)
from download_youtube import (
download_audio, get_video_info, extract_metadata_from_title,
detect_genre_online, get_output_folder, check_file_exists,
register_song_in_db, add_id3_tags,
save_rejected_video, is_rejected_video, sanitize_filename,
check_audio_volume, apply_volume_offset,
get_liked_videos_from_url, process_imported_mp3,
redownload_full, get_genre_from_essentia,
generate_waveform_data,
SUPPORTED_COOKIE_BROWSERS, get_cookies_browser, get_cookies_file,
apply_cookies_to_opts, has_cookies_configured
)
from download_quick import download_quick
from query_db import show_statistics, search_songs
import uuid
# Importar clasificador TF para precarga en background
try:
from genre_classifier_tf import preload_model_async, is_model_ready
TF_CLASSIFIER_AVAILABLE = True
except ImportError:
TF_CLASSIFIER_AVAILABLE = False
# Inicializar base de datos (ruta ya resuelta en get_or_choose_db_path)
DB_PATH = os.getenv('DB_PATH', None)
db = MusicDatabase(DB_PATH)
MUSIC_FOLDER = os.getenv('MUSIC_FOLDER', os.path.expanduser('~/Music'))
# Tiempo máximo (segundos) que /api/playlist puede tardar antes de devolver un
# resultado parcial. Evita que la interfaz se quede colgada indefinidamente.
try:
PLAYLIST_TIMEOUT = int(os.getenv('PLAYLIST_TIMEOUT', '180'))
except (TypeError, ValueError):
PLAYLIST_TIMEOUT = 180
# Crear aplicación Flask
app = Flask(__name__)
CORS(app)
app.config['SECRET_KEY'] = os.urandom(24)
# Configurar logging para suprimir logs automáticos de polling de estado
class StatusPollingFilter(logging.Filter):
"""Filtro para suprimir logs de polling de estado de descargas."""
def filter(self, record):
# Suprimir logs de Werkzeug para rutas de polling de estado
# Werkzeug registra en el formato: "GET /api/download/status/xxx HTTP/1.1" 200
message = str(record.getMessage())
if '/api/download/status/' in message:
return False
# /api/logs se consulta cada segundo desde la consola web: no ensuciar
# (y además evitaría un bucle de ruido, porque su propio log se capturaría)
if '/api/logs' in message:
return False
return True
# Aplicar filtro al logger de Werkzeug
werkzeug_logger = logging.getLogger('werkzeug')
werkzeug_logger.addFilter(StatusPollingFilter())
# ============================================================================
# Captura de la salida del servidor para mostrarla en la consola de la web
# ----------------------------------------------------------------------------
# Todo lo que el backend imprime con print() se duplica en un buffer circular
# que el navegador consulta vía GET /api/logs. Así la consola flotante muestra
# el progreso real del servidor y se distingue "está trabajando" de "colgado".
# ============================================================================
from collections import deque
LOG_CHANNELS = ('download', 'database', 'playlist', 'import', 'testing', 'config', 'server')
_log_buffer = deque(maxlen=4000)
_log_lock = threading.Lock()
_log_seq = 0
_log_ctx = threading.local()
def set_log_channel(channel, request_id=None):
"""Asocia el hilo actual a una pestaña de la consola web (y a una petición)."""
_log_ctx.channel = channel if channel in LOG_CHANNELS else 'server'
_log_ctx.rid = request_id
# Línea de acceso de Werkzeug: '... "GET /api/x HTTP/1.1" 200 -'. Es ruido en la
# consola web (el navegador ya sabe qué ha pedido), así que no se guarda.
_ACCESS_LOG_RE = re.compile(r'"(GET|POST|PUT|DELETE|HEAD|OPTIONS|PATCH) .*HTTP/[\d.]+"\s+\d{3}')
def _push_log_line(text):
"""Añade una línea al buffer que consume la consola web."""
global _log_seq
text = text.rstrip('\r\n')
if not text.strip():
return
if _ACCESS_LOG_RE.search(text):
return
with _log_lock:
_log_seq += 1
_log_buffer.append({
'seq': _log_seq,
'ts': time.strftime('%H:%M:%S'),
'channel': getattr(_log_ctx, 'channel', 'server'),
'rid': getattr(_log_ctx, 'rid', None),
'text': text[:2000],
})
class _TeeStream:
"""Escribe en la salida real y, además, en el buffer de la consola web."""
def __init__(self, stream):
self._stream = stream
self._partial = {}
def write(self, data):
try:
if self._stream is not None:
self._stream.write(data)
except Exception:
pass
try:
# Acumular por hilo hasta tener líneas completas
tid = threading.get_ident()
buf = self._partial.get(tid, '') + str(data)
parts = buf.split('\n')
self._partial[tid] = parts.pop()
for line in parts:
_push_log_line(line)
except Exception:
pass
return len(data) if data else 0
def flush(self):
try:
if self._stream is not None:
self._stream.flush()
except Exception:
pass
def isatty(self):
try:
return bool(self._stream) and self._stream.isatty()
except Exception:
return False
def __getattr__(self, name):
return getattr(self.__dict__.get('_stream'), name)
if not isinstance(sys.stdout, _TeeStream):
sys.stdout = _TeeStream(sys.stdout)
if not isinstance(sys.stderr, _TeeStream):
sys.stderr = _TeeStream(sys.stderr)
# Cada endpoint escribe en la pestaña de la consola web que le corresponde
_LOG_CHANNEL_BY_PATH = (
('/api/playlist', 'playlist'),
('/api/youtube/search', 'download'),
('/api/download', 'download'),
('/api/import', 'import'),
('/api/songs', 'database'),
('/api/database', 'database'),
('/api/test', 'testing'),
('/api/config', 'config'),
('/api/cookies', 'config'),
)
@app.before_request
def _tag_log_channel():
path = request.path or ''
# log_id (opcional) lo manda el cliente para poder seguir SOLO esta petición
rid = request.args.get('log_id') or None
for prefix, channel in _LOG_CHANNEL_BY_PATH:
if path.startswith(prefix):
set_log_channel(channel, rid)
return
set_log_channel('server', rid)
@app.route('/api/logs', methods=['GET'])
def get_server_logs():
"""Devuelve las líneas de log del servidor posteriores a `since`.
Query params:
since: último `seq` recibido (omitirlo devuelve las últimas 150 líneas;
-1 no devuelve líneas, sólo el `last_seq` actual, útil para que
el cliente marque el punto de partida antes de una operación)
channel: lista separada por comas de canales a filtrar (ej: playlist,server)
rid: devolver sólo las líneas de la petición con ese `log_id` (tiene
prioridad sobre `channel`; así una carga cancelada no mezcla su
salida con la nueva)
"""
since = request.args.get('since', type=int)
channel = request.args.get('channel')
rid = request.args.get('rid')
with _log_lock:
items = list(_log_buffer)
last_seq = _log_seq
if since == -1:
items = []
elif since is None:
items = items[-150:]
else:
items = [item for item in items if item['seq'] > since]
if rid:
items = [item for item in items if item.get('rid') == rid]
elif channel:
wanted = {c.strip() for c in channel.split(',') if c.strip()}
items = [item for item in items if item['channel'] in wanted]
# last_seq es global (no filtrado) para que el cliente avance siempre
return jsonify({'success': True, 'logs': items, 'last_seq': last_seq})
# Manejador de errores global para asegurar respuestas JSON
@app.errorhandler(404)
def not_found(error):
"""Maneja errores 404 devolviendo JSON."""
return jsonify({'success': False, 'error': 'Ruta no encontrada'}), 404
@app.errorhandler(500)
def internal_error(error):
"""Maneja errores 500 devolviendo JSON."""
return jsonify({'success': False, 'error': 'Error interno del servidor'}), 500
@app.errorhandler(Exception)
def handle_exception(e):
"""Maneja cualquier excepción no capturada devolviendo JSON."""
import traceback
traceback.print_exc()
return jsonify({'success': False, 'error': str(e)}), 500
# Estado global para descargas y tareas
download_status = {}
download_logs = {}
import_status = {}
import_logs = {}
direct_download_tasks = {}
redownload_full_status = {}
def _normalize_file_path_from_db(file_path_raw: str):
"""
Convierte una ruta guardada en la BD a una ruta válida en el SO actual.
En Windows, rutas WSL/Linux como /mnt/c/Users/... se convierten a C:\\Users\\...
"""
if not file_path_raw or not file_path_raw.strip():
return None
path_str = file_path_raw.strip()
if sys.platform == 'win32':
# WSL: /mnt/c/... -> C:\...
if path_str.startswith('/mnt/') and len(path_str) > 5:
drive_letter = path_str[5] # 'c', 'd', etc.
rest = path_str[6:].replace('/', os.sep)
path_str = f'{drive_letter.upper()}:{os.sep}{rest}'
path_obj = Path(path_str)
try:
path_obj = path_obj.resolve()
except (OSError, RuntimeError):
pass
return path_obj
def _fetch_albumart_for_song(song: dict):
"""
Busca album art para una canción siguiendo esta prioridad:
1. APIC embebida en el MP3
2. Thumbnail directo de YouTube (si video_id es ID válido de YT)
3. iTunes Search API — portada cuadrada 600x600, mayor calidad
4. Búsqueda en YouTube via yt-dlp (si hay ID en el título, lo usa directamente;
si no, busca por artista+título)
Devuelve la URL del thumbnail o None si no se encuentra.
"""
import urllib.request
import urllib.parse
video_id = (song.get('video_id') or '').strip()
title = (song.get('title') or '').strip()
artist = (song.get('artist') or '').strip()
# Título limpio (sin el [video_id] del nombre de archivo)
clean_title = re.sub(r'\[[A-Za-z0-9_-]{11}\]', '', title).strip(' -–')
# 1. APIC embebida en el MP3
file_path_raw = (song.get('file_path') or '').strip()
if file_path_raw:
path_obj = _normalize_file_path_from_db(file_path_raw)
if path_obj and path_obj.exists() and path_obj.is_file():
try:
from mutagen.id3 import ID3
from mutagen.mp3 import MP3 as _MP3
_audio = _MP3(str(path_obj), ID3=ID3)
if any(k.startswith('APIC') for k in _audio.keys()):
return f'/api/database/song/{video_id}/cover'
except Exception:
pass
# 2. Thumbnail directo de YouTube para IDs válidos (11 caracteres alfanuméricos)
if re.match(r'^[A-Za-z0-9_-]{11}$', video_id):
return f'https://i.ytimg.com/vi/{video_id}/maxresdefault.jpg'
# 3. iTunes Search API — portadas cuadradas de alta calidad (600x600)
# Va antes del thumbnail de YouTube para importadas porque el video puede estar borrado
if artist or clean_title:
try:
# Evitar duplicar el artista si el título ya empieza por él ("Yves Larock - Rise Up…")
search_title = clean_title
if artist and search_title.lower().startswith(artist.lower()):
search_title = search_title[len(artist):].lstrip(' \t-–').strip()
term = f'{artist} {search_title}'.strip() if search_title else artist
search_url = (
f'https://itunes.apple.com/search?term={urllib.parse.quote(term)}'
f'&media=music&limit=5'
)
req = urllib.request.Request(search_url, headers={'User-Agent': 'Mozilla/5.0'})
with urllib.request.urlopen(req, timeout=10) as resp:
data = json.loads(resp.read().decode())
for r in (data.get('results') or []):
art = (r.get('artworkUrl100') or '').replace('100x100bb', '600x600bb')
if art:
return art
except Exception:
pass
# 4. ID de YouTube extraído del título — verificar que la imagen existe antes de devolverla
yt_id_in_title = re.search(r'\[([A-Za-z0-9_-]{11})\]', title)
if yt_id_in_title:
yt_id = yt_id_in_title.group(1)
for res in ('maxresdefault', 'hqdefault', 'mqdefault'):
yt_url = f'https://i.ytimg.com/vi/{yt_id}/{res}.jpg'
try:
req = urllib.request.Request(yt_url, headers={'User-Agent': 'Mozilla/5.0'})
req.get_method = lambda: 'HEAD'
with urllib.request.urlopen(req, timeout=5) as r:
if r.status == 200:
return yt_url
except Exception:
pass
# 5. Búsqueda en YouTube via yt-dlp (último recurso)
if artist or clean_title:
try:
import yt_dlp as _yt_dlp
search_query = f'{artist} - {clean_title}' if artist and clean_title else (artist or clean_title)
ydl_opts = {
'quiet': True,
'no_warnings': True,
'extract_flat': True,
'skip_download': True,
'socket_timeout': 10,
'ignoreerrors': True,
}
apply_cookies_to_opts(ydl_opts)
with _yt_dlp.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(f'ytsearch1:{search_query}', download=False)
entries = (info or {}).get('entries') or []
if entries and entries[0]:
vid = entries[0].get('id')
if vid and re.match(r'^[A-Za-z0-9_-]{11}$', vid):
return f'https://i.ytimg.com/vi/{vid}/hqdefault.jpg'
except Exception:
pass
return None
@app.route('/')
def index():
"""Página principal."""
return render_template('index.html')
@app.route('/api/playlist', methods=['GET'])
def get_playlist():
"""Obtiene la lista de canciones de la playlist."""
start_time = time.time()
playlist_url = request.args.get('url', 'https://music.youtube.com/playlist?list=LM')
limit = int(request.args.get('limit', 20))
hide_ignored = request.args.get('hide_ignored', 'true').lower() == 'true'
print(f"[{time.strftime('%H:%M:%S')}] 🎵 GET /api/playlist - Iniciando carga de playlist")
print(f" URL: {playlist_url}")
print(f" Límite: {limit}, Ocultar ignoradas: {hide_ignored}")
print(f" Cookies configuradas: {'sí' if has_cookies_configured() else 'NO (la playlist devolverá 0 canciones)'}")
print(f" Tiempo máximo de la petición: {PLAYLIST_TIMEOUT}s")
try:
videos_data = []
batch_size = limit * 5 # Tamaño de cada lote a obtener
start_index = 1 # Índice inicial (1-based)
max_batches = 10 # Máximo de lotes a intentar (para evitar bucles infinitos)
batch_count = 0
skipped_count = 0 # Contador de canciones omitidas
timed_out = False # Se agotó PLAYLIST_TIMEOUT antes de completar
print(f"[{time.strftime('%H:%M:%S')}] 🔄 Procesando playlist en lotes hasta encontrar {limit} videos válidos...")
# Si hide_ignored está activado, obtener videos en lotes hasta tener suficientes válidos
# Si no está activado, solo obtener un lote
while len(videos_data) < limit and batch_count < max_batches:
if time.time() - start_time > PLAYLIST_TIMEOUT:
timed_out = True
print(f"[{time.strftime('%H:%M:%S')}] ⏱️ Tiempo máximo agotado ({PLAYLIST_TIMEOUT}s): devolviendo lo encontrado hasta ahora")
break
batch_count += 1
current_batch_size = batch_size if hide_ignored else limit
print(f"[{time.strftime('%H:%M:%S')}] 🔍 Lote {batch_count}/{max_batches}: Obteniendo videos desde índice {start_index} (hasta {start_index + current_batch_size - 1})...")
batch_start = time.time()
liked_videos = get_liked_videos_from_url(playlist_url, limit=current_batch_size, start_index=start_index)
batch_elapsed = time.time() - batch_start
if not liked_videos:
print(f" ⚠️ No se obtuvieron más videos de la playlist (lote vacío tras {batch_elapsed:.1f}s)")
break
print(f" ✅ Obtenidos {len(liked_videos)} videos en este lote ({batch_elapsed:.1f}s)")
# Procesar los videos del lote actual
for idx, video in enumerate(liked_videos, 1):
# Si ya tenemos suficientes videos y hide_ignored está activado, parar
if hide_ignored and len(videos_data) >= limit:
print(f" ✅ Ya se encontraron {limit} videos válidos, deteniendo procesamiento")
break
if time.time() - start_time > PLAYLIST_TIMEOUT:
timed_out = True
print(f"[{time.strftime('%H:%M:%S')}] ⏱️ Tiempo máximo agotado ({PLAYLIST_TIMEOUT}s) en el video {idx}/{len(liked_videos)} del lote {batch_count}")
break
video_id = video['id']
url = video['url']
title = video['title']
# PRIMERO: Verificar si está rechazada o descargada (verificación rápida)
is_rejected = is_rejected_video(video_id)
# Buscar en BD por video_id directamente (sin verificar que el archivo exista
# en disco: la BD es la fuente de verdad para el filtrado de playlist; el check
# de archivo fallaría con rutas de Windows sincronizadas via OneDrive o si el
# usuario renombró/movió los archivos).
existing_song = db.get_song_by_video_id(video_id)
matched_by = 'video_id' if existing_song else None
# Si no la encuentra por video_id, intentar por artista+título.
# Esto permite reconocer canciones importadas manualmente (que se
# guardan con video_id="imported_<hash>") o redescargadas con otro id.
if not existing_song:
# Usar metadata cacheada si existe; si no, extraerla del título
cached_meta = db.get_cached_metadata(video_id) or {}
cand_artist = cached_meta.get('artist') or video.get('artist')
cand_title = cached_meta.get('title')
if not cand_title:
try:
extracted = extract_metadata_from_title(title, '', None) or {}
cand_artist = cand_artist or extracted.get('artist')
cand_title = extracted.get('title') or title
except Exception:
cand_title = title
if cand_artist and cand_title:
# Buscar en BD sin verificar existencia del archivo en disco
found = db.find_song(artist=cand_artist, title=cand_title)
existing_song = found[0] if found else None
if existing_song:
matched_by = f"artista+título: {cand_artist} / {cand_title}"
if hide_ignored and (is_rejected or existing_song):
skipped_count += 1
if existing_song:
reason = f"ya descargada [{matched_by}]"
else:
reason = "ignorada"
print(f"[{time.strftime('%H:%M:%S')}] ⏭️ [{skipped_count}] Omitida ({reason}): {(title or '')[:70]}")
continue
print(f"[{time.strftime('%H:%M:%S')}] [{idx}/{len(liked_videos)}] Procesando ({time.time() - start_time:.0f}s transcurridos): {(title or '')[:70]}")
# Info del video SOLO si ya está en caché. Aquí no se consulta a
# YouTube: la petición por canción tarda 18-50s (la extracción con
# cookies falla y sólo responde el reintento sin cookies), así que
# listar 20 canciones nuevas costaba minutos y parecía un cuelgue.
# Para pintar la lista basta con el título de la entrada plana y la
# miniatura estándar de YouTube; la info completa se obtiene al
# descargar, que es cuando de verdad hace falta.
video_info = db.get_cached_video_info(video_id)
if video_info:
print(f" → ✅ Info desde caché")
# Metadatos: de caché si existen; si no, del título (sin red).
# No se cachean los extraídos aquí: al no tener la descripción del
# vídeo son de peor calidad que los que calcula la descarga, y
# cachearlos empeoraría los tags del MP3.
metadata = db.get_cached_metadata(video_id)
if not metadata:
try:
title_from_info = video_info.get('title', title) if video_info else title
description = video_info.get('description', '') if video_info else ''
metadata = extract_metadata_from_title(title_from_info, description, video_info)
except Exception as e:
print(f" → ⚠️ Error extrayendo metadatos: {e}")
metadata = {}
# Asegurar que metadata nunca sea None
if metadata is None:
metadata = {}
# Miniatura: de la info cacheada o construida a partir del id
thumbnail = (video_info or {}).get('thumbnail') or ''
if not thumbnail and re.match(r'^[A-Za-z0-9_-]{11}$', video_id or ''):
thumbnail = f'https://i.ytimg.com/vi/{video_id}/hqdefault.jpg'
# Obtener género desde caché o detectar
# (metadata puede traer la clave con valor None: de ahí el `or`)
genre = db.get_cached_genre(video_id)
if not genre:
genre = (metadata.get('genre') if metadata else None) or 'Sin Clasificar'
# Artista: metadatos > canal de la entrada plana > desconocido
artist = (metadata.get('artist') if metadata else None) \
or video.get('artist') or 'Desconocido'
# Obtener información de progreso si está descargando
is_downloading = video_id in download_status and download_status[video_id].get('status') == 'downloading'
progress = 0
if is_downloading:
progress = download_status[video_id].get('progress', 0)
videos_data.append({
'id': video_id,
'title': title,
'url': url,
'thumbnail': thumbnail,
'genre': genre,
'artist': artist,
'is_rejected': is_rejected,
'is_downloaded': existing_song is not None,
'is_downloading': is_downloading,
'progress': progress
})
print(f" → ✅ Agregada a la lista ({len(videos_data)}/{limit})")
# Si no tenemos suficientes videos válidos y hide_ignored está activado, obtener el siguiente lote
if hide_ignored and len(videos_data) < limit:
start_index += len(liked_videos)
print(f" 📊 Progreso: {len(videos_data)}/{limit} válidos encontrados, {skipped_count} omitidas. Obteniendo siguiente lote...")
else:
# Si hide_ignored no está activado o ya tenemos suficientes, no necesitamos más lotes
break
elapsed = time.time() - start_time
print(f"[{time.strftime('%H:%M:%S')}] ✅ GET /api/playlist - Completado en {elapsed:.2f}s")
print(f" 📊 Resultado: {len(videos_data)}/{limit} videos válidos mostrados")
if skipped_count > 0:
print(f" ⏭️ {skipped_count} canciones omitidas (ya descargadas o ignoradas)")
print(f" 📦 Lotes procesados: {batch_count}")
if timed_out:
print(f" ⚠️ Resultado PARCIAL: se agotó el tiempo máximo ({PLAYLIST_TIMEOUT}s). "
f"Sube PLAYLIST_TIMEOUT en el .env o baja el número de canciones.")
return jsonify({
'success': True,
'videos': videos_data,
'count': len(videos_data),
'timed_out': timed_out,
'skipped': skipped_count,
'batches': batch_count,
'elapsed': round(elapsed, 2)
})
except Exception as e:
elapsed = time.time() - start_time
import traceback
print(f"[{time.strftime('%H:%M:%S')}] ❌ GET /api/playlist - Error después de {elapsed:.2f}s")
print(f" Error: {str(e)}")
traceback.print_exc()
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/api/download', methods=['POST'])
def download_song():
"""Descarga una canción."""
data = request.json
video_id = data.get('video_id')
video_url = data.get('url')
if not video_id or not video_url:
return jsonify({'success': False, 'error': 'Faltan parámetros'}), 400
def download_thread():
try:
download_status[video_id] = {'status': 'downloading', 'progress': 0, 'downloaded_bytes': 0, 'total_bytes': 0}
download_logs[video_id] = []
def add_log(msg):
"""Añade un mensaje al log de la descarga (lo verá la consola flotante)."""
download_logs[video_id].append(str(msg))
try:
print(f"[{time.strftime('%H:%M:%S')}] [{video_id[:8]}] {msg}")
except Exception:
pass
add_log(f"🚀 Iniciando descarga de {video_url}")
# Estado para evitar spam del callback de progreso (solo logueamos hitos)
progress_state = {'last_logged_pct': -10}
# Callback para actualizar el progreso
def update_progress(d):
status = d.get('status', '')
if status == 'downloading':
downloaded = d.get('downloaded_bytes', 0)
total = d.get('total_bytes') or d.get('total_bytes_estimate', 0)
if total and total > 0:
# Calcular progreso entre 20% y 80% (la descarga real)
download_progress = int((downloaded / total) * 60) # 0-60% de la descarga
progress = 20 + download_progress # 20% a 80%
download_status[video_id].update({
'status': 'downloading',
'progress': min(progress, 80),
'downloaded_bytes': downloaded,
'total_bytes': total,
'speed': d.get('speed', 0),
'eta': d.get('eta', 0)
})
# Log cada ~25% de la descarga real
real_pct = int((downloaded / total) * 100)
if real_pct - progress_state['last_logged_pct'] >= 25 or real_pct == 100:
progress_state['last_logged_pct'] = real_pct
mb_done = downloaded / (1024 * 1024)
mb_total = total / (1024 * 1024)
speed_mb = (d.get('speed') or 0) / (1024 * 1024)
add_log(f"⬇️ Descargando... {real_pct}% ({mb_done:.1f}/{mb_total:.1f} MB) a {speed_mb:.2f} MB/s")
else:
download_status[video_id].update({
'status': 'downloading',
'downloaded_bytes': downloaded,
'total_bytes': 0
})
elif status == 'finished':
download_status[video_id]['progress'] = 80
add_log("✅ Descarga del audio finalizada, procesando...")
# Obtener información del video
download_status[video_id]['progress'] = 5
add_log("🔎 Obteniendo información del video...")
video_info = get_video_info(video_url)
if not video_info:
add_log("❌ No se pudo obtener información del video")
download_status[video_id] = {'status': 'error', 'error': 'No se pudo obtener información del video'}
return
title = video_info.get('title', '')
description = video_info.get('description', '')
add_log(f"🎬 Título: {title}")
# Extraer metadatos
download_status[video_id]['progress'] = 10
add_log("🏷️ Extrayendo metadatos del título...")
metadata = extract_metadata_from_title(title, description, video_info)
if metadata.get('artist'):
add_log(f" 👤 Artista: {metadata.get('artist')}")
if metadata.get('title'):
add_log(f" 🎵 Tema: {metadata.get('title')}")
if metadata.get('year'):
add_log(f" 📅 Año: {metadata.get('year')}")
# Detectar género si no está
if not metadata.get('genre'):
download_status[video_id]['progress'] = 15
add_log("🎼 Detectando género online...")
detected_genre = detect_genre_online(
metadata.get('artist'),
metadata.get('title', title),
video_info=video_info,
title=title,
description=description
)
if detected_genre:
metadata['genre'] = detected_genre
add_log(f" ✓ Género detectado: {detected_genre}")
else:
metadata['genre'] = 'Sin Clasificar'
add_log(" ⚠️ No se pudo detectar género (Sin Clasificar)")
else:
add_log(f"🎼 Género ya definido: {metadata.get('genre')}")
# Obtener carpeta de salida
output_folder = get_output_folder(MUSIC_FOLDER, metadata.get('genre'), metadata.get('year'))
add_log(f"📁 Carpeta destino: {output_folder}")
# Crear nombre de archivo
if metadata.get('artist'):
filename = f"{metadata['artist']} - {metadata['title']}"
else:
filename = metadata.get('title', title)
filename = sanitize_filename(filename)
output_path = output_folder / filename
# Descargar (el progreso se actualizará automáticamente con el callback)
download_status[video_id]['progress'] = 20
add_log(f"⬇️ Descargando audio: {filename}.mp3")
if download_audio(video_url, str(output_path), metadata, progress_callback=update_progress):
download_status[video_id]['progress'] = 80
mp3_file = Path(str(output_path) + '.mp3')
if not mp3_file.exists():
mp3_files = list(output_folder.glob(f"{filename}*.mp3"))
if mp3_files:
mp3_file = mp3_files[0]
download_status[video_id]['progress'] = 85
download_status[video_id]['progress'] = 90
add_log("🏷️ Añadiendo metadatos ID3...")
add_id3_tags(str(mp3_file), metadata, video_info)
download_status[video_id]['progress'] = 95
add_log("💾 Registrando en base de datos...")
register_song_in_db(video_id, video_url, mp3_file, metadata, video_info, download_source='playlist')
add_log(f"✅ Descarga completada: {mp3_file.name}")
download_status[video_id] = {'status': 'completed', 'progress': 100, 'file': str(mp3_file)}
else:
add_log("❌ Error en la descarga del audio")
download_status[video_id] = {'status': 'error', 'error': 'Error en la descarga'}
except Exception as e:
import traceback
tb = traceback.format_exc()
try:
download_logs[video_id].append(f"❌ Excepción: {e}")
download_logs[video_id].append(tb)
except Exception:
pass
download_status[video_id] = {'status': 'error', 'error': str(e), 'error_detail': tb}
threading.Thread(target=download_thread, daemon=True).start()
return jsonify({'success': True, 'message': 'Descarga iniciada'})
@app.route('/api/download/status/<task_id>', methods=['GET'])
def get_download_status(task_id):
"""Obtiene el estado de una descarga."""
# Intentar como video_id primero
status = download_status.get(task_id, {})
if status:
status_type = status.get('status', 'unknown')
progress = status.get('progress', 0)
# Solo loguear cuando hay actividad relevante (no en cada polling)
# Loguear solo en cambios de estado o progreso significativo
if status_type in ['downloading', 'completed', 'error']:
if status_type == 'downloading' and progress > 0:
# Solo loguear cada 10% de progreso para no saturar
if progress % 10 == 0 or progress in [5, 20, 50, 80, 90, 95]:
print(f"[{time.strftime('%H:%M:%S')}] 📥 Estado descarga {task_id[:8]}...: {status_type} ({progress}%)")
elif status_type in ['completed', 'error']:
print(f"[{time.strftime('%H:%M:%S')}] {'✅' if status_type == 'completed' else '❌'} Descarga {task_id[:8]}...: {status_type}")
logs = download_logs.get(task_id, [])
return jsonify({
'status': status,
'logs': logs
})
# Si no, intentar como task_id de descarga directa
task_status = direct_download_tasks.get(task_id, {})
if task_status:
status_type = task_status.get('status', 'idle')
if status_type in ['completed', 'error']:
print(f"[{time.strftime('%H:%M:%S')}] {'✅' if status_type == 'completed' else '❌'} Descarga directa {task_id[:8]}...: {status_type}")
return jsonify({
'status': task_status.get('status', 'idle'),
'error': task_status.get('error'),
'error_detail': task_status.get('error_detail'),
'file': task_status.get('file')
})
# No loguear cuando el estado es 'idle' (polling normal)
return jsonify({'status': 'idle'})
@app.route('/api/reject', methods=['POST'])
def reject_song():
"""Marca una canción como rechazada."""
data = request.json
video_id = data.get('video_id')
video_url = data.get('url')
title = data.get('title', '')
if not video_id:
return jsonify({'success': False, 'error': 'Faltan parámetros'}), 400
save_rejected_video(video_id, url=video_url, title=title, reason="Ignorar siempre")
return jsonify({'success': True, 'message': 'Canción marcada como rechazada'})
@app.route('/api/download/direct', methods=['POST'])
def download_direct():
"""Descarga directa con metadatos completos."""
data = request.json
url = data.get('url')
if not url:
return jsonify({'success': False, 'error': 'Faltan parámetros'}), 400
task_id = str(uuid.uuid4())
direct_download_tasks[task_id] = {'status': 'downloading', 'url': url}
def download_thread():
try:
# Extraer video_id de la URL
match = re.search(r'(?:v=|\/)([0-9A-Za-z_-]{11})', url)
video_id = match.group(1) if match else None
if not video_id:
direct_download_tasks[task_id] = {'status': 'error', 'error': 'URL inválida'}
return
# Usar la misma lógica que download_song
download_status[video_id] = {'status': 'downloading'}
download_logs[video_id] = []
try:
video_info = get_video_info(url)
except Exception as e_info:
import traceback
tb = traceback.format_exc()
err_msg = f"No se pudo obtener información del video: {e_info}"
direct_download_tasks[task_id] = {'status': 'error', 'error': err_msg, 'error_detail': tb}
download_logs[video_id].append(f"[ERROR] {err_msg}\n{tb}")
return
if not video_info:
direct_download_tasks[task_id] = {'status': 'error', 'error': 'No se pudo obtener información del video (get_video_info devolvió vacío)'}
return
title = video_info.get('title', '')
description = video_info.get('description', '')
metadata = extract_metadata_from_title(title, description, video_info)
if not metadata.get('genre'):
detected_genre = detect_genre_online(
metadata.get('artist'),
metadata.get('title', title),
video_info=video_info,
title=title,
description=description
)
if detected_genre:
metadata['genre'] = detected_genre
else:
metadata['genre'] = 'Sin Clasificar'
output_folder = get_output_folder(MUSIC_FOLDER, metadata.get('genre'), metadata.get('year'))
if metadata.get('artist'):
filename = f"{metadata['artist']} - {metadata['title']}"
else:
filename = metadata.get('title', title)
filename = sanitize_filename(filename)
output_path = output_folder / filename
if download_audio(url, str(output_path), metadata):
mp3_file = Path(str(output_path) + '.mp3')
if not mp3_file.exists():
mp3_files = list(output_folder.glob(f"{filename}*.mp3"))
if mp3_files:
mp3_file = mp3_files[0]
add_id3_tags(str(mp3_file), metadata, video_info)
register_song_in_db(video_id, url, mp3_file, metadata, video_info, download_source='direct')
direct_download_tasks[task_id] = {'status': 'completed', 'file': str(mp3_file)}
download_status[video_id] = {'status': 'completed', 'file': str(mp3_file)}
else:
direct_download_tasks[task_id] = {'status': 'error', 'error': 'Error en la descarga (download_audio devolvió False)'}
except Exception as e:
import traceback
tb = traceback.format_exc()
direct_download_tasks[task_id] = {'status': 'error', 'error': str(e), 'error_detail': tb}
if video_id:
download_logs[video_id].append(tb)
threading.Thread(target=download_thread, daemon=True).start()
return jsonify({'success': True, 'task_id': task_id, 'message': 'Descarga iniciada'})
@app.route('/api/download/quick', methods=['POST'])
def download_quick_endpoint():
"""Descarga rápida sin metadatos avanzados. Devuelve task_id para poder consultar estado y errores."""
data = request.json
url = data.get('url')
if not url:
return jsonify({'success': False, 'error': 'Faltan parámetros'}), 400
task_id = str(uuid.uuid4())
direct_download_tasks[task_id] = {'status': 'downloading', 'url': url}
def quick_download_thread():
import traceback
try:
download_quick(url)
direct_download_tasks[task_id] = {'status': 'completed', 'file': ''}
except BaseException as e:
tb = traceback.format_exc()
err_msg = str(e)
direct_download_tasks[task_id] = {
'status': 'error',
'error': err_msg,
'error_detail': tb
}
print(f"[{time.strftime('%H:%M:%S')}] ❌ Error en descarga rápida: {err_msg}\n{tb}")
threading.Thread(target=quick_download_thread, daemon=True).start()
return jsonify({'success': True, 'task_id': task_id, 'message': 'Descarga rápida iniciada'})
@app.route('/api/video/info', methods=['POST'])
def get_video_info_endpoint():
"""Obtiene información de un video."""
data = request.json
url = data.get('url')
if not url:
return jsonify({'success': False, 'error': 'Faltan parámetros'}), 400
try:
video_info = get_video_info(url)
if video_info:
return jsonify({'success': True, 'info': video_info})
else:
return jsonify({'success': False, 'error': 'No se pudo obtener información del video'})
except Exception as e:
return jsonify({'success': False, 'error': str(e)})
def _format_duration_seconds(seconds):
"""Convierte segundos en una cadena tipo m:ss o h:mm:ss."""
try:
seconds = int(seconds) if seconds is not None else None
except (ValueError, TypeError):