muget 1.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- muget-1.0.0/LICENSE +21 -0
- muget-1.0.0/MANIFEST.in +2 -0
- muget-1.0.0/PKG-INFO +59 -0
- muget-1.0.0/README.md +28 -0
- muget-1.0.0/muget/__init__.py +1 -0
- muget-1.0.0/muget/__main__.py +3 -0
- muget-1.0.0/muget/cli.py +416 -0
- muget-1.0.0/muget/constants.py +30 -0
- muget-1.0.0/muget/custom_logger_formatter.py +24 -0
- muget-1.0.0/muget/downloader.py +563 -0
- muget-1.0.0/muget/enums.py +12 -0
- muget-1.0.0/muget/utils.py +31 -0
- muget-1.0.0/muget.egg-info/PKG-INFO +59 -0
- muget-1.0.0/muget.egg-info/SOURCES.txt +18 -0
- muget-1.0.0/muget.egg-info/dependency_links.txt +1 -0
- muget-1.0.0/muget.egg-info/entry_points.txt +2 -0
- muget-1.0.0/muget.egg-info/requires.txt +9 -0
- muget-1.0.0/muget.egg-info/top_level.txt +1 -0
- muget-1.0.0/pyproject.toml +48 -0
- muget-1.0.0/setup.cfg +4 -0
muget-1.0.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Meikoy-Chan
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
muget-1.0.0/MANIFEST.in
ADDED
muget-1.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: muget
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: YouTube Music downloader with tagging support
|
|
5
|
+
Author: Meikoy-Chan
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/meikoy-chan/muget
|
|
8
|
+
Project-URL: Bug Reports, https://github.com/meikoy-chan/muget/issues
|
|
9
|
+
Keywords: youtube-music,downloader,yt-dlp,music
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Requires-Python: >=3.8
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
License-File: LICENSE
|
|
21
|
+
Requires-Dist: click
|
|
22
|
+
Requires-Dist: colorama
|
|
23
|
+
Requires-Dist: mutagen
|
|
24
|
+
Requires-Dist: Pillow
|
|
25
|
+
Requires-Dist: requests
|
|
26
|
+
Requires-Dist: yt-dlp
|
|
27
|
+
Requires-Dist: ytmusicapi
|
|
28
|
+
Requires-Dist: InquirerPy
|
|
29
|
+
Requires-Dist: yt_dlp_ejs
|
|
30
|
+
Dynamic: license-file
|
|
31
|
+
|
|
32
|
+
# Muget
|
|
33
|
+
|
|
34
|
+
YouTube Music downloader with automatic tagging and cover art.
|
|
35
|
+
|
|
36
|
+
## Installation
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pip install muget
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Usage
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
muget "https://music.youtube.com/playlist?list=..."
|
|
46
|
+
muget -o "./Music" "https://music.youtube.com/album/..."
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Requirements
|
|
50
|
+
|
|
51
|
+
· FFmpeg (required)
|
|
52
|
+
· aria2c (optional, for faster downloads)
|
|
53
|
+
|
|
54
|
+
Features
|
|
55
|
+
|
|
56
|
+
· Download tracks, albums, and playlists
|
|
57
|
+
· Automatic metadata tagging
|
|
58
|
+
· Cover art embedding
|
|
59
|
+
· Synced lyrics support
|
muget-1.0.0/README.md
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# Muget
|
|
2
|
+
|
|
3
|
+
YouTube Music downloader with automatic tagging and cover art.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install muget
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Usage
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
muget "https://music.youtube.com/playlist?list=..."
|
|
15
|
+
muget -o "./Music" "https://music.youtube.com/album/..."
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Requirements
|
|
19
|
+
|
|
20
|
+
· FFmpeg (required)
|
|
21
|
+
· aria2c (optional, for faster downloads)
|
|
22
|
+
|
|
23
|
+
Features
|
|
24
|
+
|
|
25
|
+
· Download tracks, albums, and playlists
|
|
26
|
+
· Automatic metadata tagging
|
|
27
|
+
· Cover art embedding
|
|
28
|
+
· Synced lyrics support
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "1.0.0"
|
muget-1.0.0/muget/cli.py
ADDED
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import inspect
|
|
4
|
+
import json
|
|
5
|
+
import logging
|
|
6
|
+
import shutil
|
|
7
|
+
from enum import Enum
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
import click
|
|
11
|
+
import colorama
|
|
12
|
+
|
|
13
|
+
from . import __version__
|
|
14
|
+
from .constants import EXCLUDED_CONFIG_FILE_PARAMS, PREMIUM_FORMATS, X_NOT_FOUND_STRING
|
|
15
|
+
from .custom_logger_formatter import CustomLoggerFormatter
|
|
16
|
+
from .downloader import Downloader
|
|
17
|
+
from .enums import CoverFormat, DownloadMode
|
|
18
|
+
from .utils import color_text, prompt_path
|
|
19
|
+
|
|
20
|
+
logger = logging.getLogger("muget")
|
|
21
|
+
|
|
22
|
+
downloader_sig = inspect.signature(Downloader.__init__)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def get_param_string(param: click.Parameter) -> str:
|
|
26
|
+
if isinstance(param.default, Enum):
|
|
27
|
+
return param.default.value
|
|
28
|
+
elif isinstance(param.default, Path):
|
|
29
|
+
return str(param.default)
|
|
30
|
+
else:
|
|
31
|
+
return param.default
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def write_default_config_file(ctx: click.Context):
|
|
35
|
+
ctx.params["config_path"].parent.mkdir(parents=True, exist_ok=True)
|
|
36
|
+
config_file = {
|
|
37
|
+
param.name: get_param_string(param)
|
|
38
|
+
for param in ctx.command.params
|
|
39
|
+
if param.name not in EXCLUDED_CONFIG_FILE_PARAMS
|
|
40
|
+
}
|
|
41
|
+
ctx.params["config_path"].write_text(json.dumps(config_file, indent=4))
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def load_config_file(
|
|
45
|
+
ctx: click.Context,
|
|
46
|
+
param: click.Parameter,
|
|
47
|
+
no_config_file: bool,
|
|
48
|
+
) -> click.Context:
|
|
49
|
+
if no_config_file:
|
|
50
|
+
return ctx
|
|
51
|
+
if not ctx.params["config_path"].exists():
|
|
52
|
+
write_default_config_file(ctx)
|
|
53
|
+
config_file = dict(json.loads(ctx.params["config_path"].read_text()))
|
|
54
|
+
for param in ctx.command.params:
|
|
55
|
+
if (
|
|
56
|
+
config_file.get(param.name) is not None
|
|
57
|
+
and not ctx.get_parameter_source(param.name)
|
|
58
|
+
== click.core.ParameterSource.COMMANDLINE
|
|
59
|
+
):
|
|
60
|
+
ctx.params[param.name] = param.type_cast_value(ctx, config_file[param.name])
|
|
61
|
+
return ctx
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@click.command()
|
|
65
|
+
@click.help_option("-h", "--help")
|
|
66
|
+
@click.version_option(__version__, "-v", "--version")
|
|
67
|
+
# CLI specific options
|
|
68
|
+
@click.argument(
|
|
69
|
+
"urls",
|
|
70
|
+
nargs=-1,
|
|
71
|
+
type=str,
|
|
72
|
+
required=True,
|
|
73
|
+
)
|
|
74
|
+
@click.option(
|
|
75
|
+
"--save-cover",
|
|
76
|
+
"-s",
|
|
77
|
+
is_flag=True,
|
|
78
|
+
help="Save cover as a separate file.",
|
|
79
|
+
)
|
|
80
|
+
@click.option(
|
|
81
|
+
"--overwrite",
|
|
82
|
+
is_flag=True,
|
|
83
|
+
help="Overwrite existing files.",
|
|
84
|
+
)
|
|
85
|
+
@click.option(
|
|
86
|
+
"--read-urls-as-txt",
|
|
87
|
+
"-r",
|
|
88
|
+
is_flag=True,
|
|
89
|
+
help="Interpret URLs as paths to text files containing URLs separated by newlines.",
|
|
90
|
+
)
|
|
91
|
+
@click.option(
|
|
92
|
+
"--config-path",
|
|
93
|
+
type=Path,
|
|
94
|
+
default=Path.home() / ".muget" / "config.json",
|
|
95
|
+
help="Path to config file.",
|
|
96
|
+
)
|
|
97
|
+
@click.option(
|
|
98
|
+
"--log-level",
|
|
99
|
+
type=str,
|
|
100
|
+
default="INFO",
|
|
101
|
+
help="Log level.",
|
|
102
|
+
)
|
|
103
|
+
@click.option(
|
|
104
|
+
"--no-exceptions",
|
|
105
|
+
is_flag=True,
|
|
106
|
+
help="Don't print exceptions.",
|
|
107
|
+
)
|
|
108
|
+
# Downloader specific options
|
|
109
|
+
@click.option(
|
|
110
|
+
"--output-path",
|
|
111
|
+
"-o",
|
|
112
|
+
type=Path,
|
|
113
|
+
default=downloader_sig.parameters["output_path"].default,
|
|
114
|
+
help="Path to output directory.",
|
|
115
|
+
)
|
|
116
|
+
@click.option(
|
|
117
|
+
"--temp-path",
|
|
118
|
+
type=Path,
|
|
119
|
+
default=downloader_sig.parameters["temp_path"].default,
|
|
120
|
+
help="Path to temporary directory.",
|
|
121
|
+
)
|
|
122
|
+
@click.option(
|
|
123
|
+
"--cookies-path",
|
|
124
|
+
"-c",
|
|
125
|
+
type=Path,
|
|
126
|
+
default=downloader_sig.parameters["cookies_path"].default,
|
|
127
|
+
help="Path to .txt cookies file for yt-dlp (premium formats).",
|
|
128
|
+
)
|
|
129
|
+
@click.option(
|
|
130
|
+
"--browser-json-path", # NUEVA OPCIÓN
|
|
131
|
+
"-b",
|
|
132
|
+
type=Path,
|
|
133
|
+
default=None,
|
|
134
|
+
help="Path to browser.json file for ytmusicapi (private playlists).",
|
|
135
|
+
)
|
|
136
|
+
@click.option(
|
|
137
|
+
"--ffmpeg-path",
|
|
138
|
+
type=str,
|
|
139
|
+
default=downloader_sig.parameters["ffmpeg_path"].default,
|
|
140
|
+
help="Path to FFmpeg binary.",
|
|
141
|
+
)
|
|
142
|
+
@click.option(
|
|
143
|
+
"--aria2c-path",
|
|
144
|
+
type=str,
|
|
145
|
+
default=downloader_sig.parameters["aria2c_path"].default,
|
|
146
|
+
help="Path to aria2c binary.",
|
|
147
|
+
)
|
|
148
|
+
@click.option(
|
|
149
|
+
"--download-mode",
|
|
150
|
+
type=DownloadMode,
|
|
151
|
+
default=downloader_sig.parameters["download_mode"].default,
|
|
152
|
+
help="Download mode.",
|
|
153
|
+
)
|
|
154
|
+
@click.option(
|
|
155
|
+
"--po-token",
|
|
156
|
+
type=str,
|
|
157
|
+
default=downloader_sig.parameters["po_token"].default,
|
|
158
|
+
help="Proof of Origin (PO) Token.",
|
|
159
|
+
)
|
|
160
|
+
@click.option(
|
|
161
|
+
"--itag",
|
|
162
|
+
"-i",
|
|
163
|
+
type=str,
|
|
164
|
+
default=downloader_sig.parameters["itag"].default,
|
|
165
|
+
help="Itag (audio codec/quality).",
|
|
166
|
+
)
|
|
167
|
+
@click.option(
|
|
168
|
+
"--cover-size",
|
|
169
|
+
type=int,
|
|
170
|
+
default=downloader_sig.parameters["cover_size"].default,
|
|
171
|
+
help="Cover size.",
|
|
172
|
+
)
|
|
173
|
+
@click.option(
|
|
174
|
+
"--cover-format",
|
|
175
|
+
type=CoverFormat,
|
|
176
|
+
default=downloader_sig.parameters["cover_format"].default,
|
|
177
|
+
help="Cover format.",
|
|
178
|
+
)
|
|
179
|
+
@click.option(
|
|
180
|
+
"--cover-quality",
|
|
181
|
+
type=int,
|
|
182
|
+
default=downloader_sig.parameters["cover_quality"].default,
|
|
183
|
+
help="Cover JPEG quality.",
|
|
184
|
+
)
|
|
185
|
+
@click.option(
|
|
186
|
+
"--template-folder",
|
|
187
|
+
type=str,
|
|
188
|
+
default=downloader_sig.parameters["template_folder"].default,
|
|
189
|
+
help="Template of the album folders as a format string.",
|
|
190
|
+
)
|
|
191
|
+
@click.option(
|
|
192
|
+
"--template-file",
|
|
193
|
+
type=str,
|
|
194
|
+
default=downloader_sig.parameters["template_file"].default,
|
|
195
|
+
help="Template of the song files as a format string.",
|
|
196
|
+
)
|
|
197
|
+
@click.option(
|
|
198
|
+
"--template-date",
|
|
199
|
+
type=str,
|
|
200
|
+
default=downloader_sig.parameters["template_date"].default,
|
|
201
|
+
help="Date tag template.",
|
|
202
|
+
)
|
|
203
|
+
@click.option(
|
|
204
|
+
"--exclude-tags",
|
|
205
|
+
"-e",
|
|
206
|
+
type=str,
|
|
207
|
+
default=downloader_sig.parameters["exclude_tags"].default,
|
|
208
|
+
help="Comma-separated tags to exclude.",
|
|
209
|
+
)
|
|
210
|
+
@click.option(
|
|
211
|
+
"--no-synced-lyrics",
|
|
212
|
+
is_flag=True,
|
|
213
|
+
help="Don't save synced lyrics.",
|
|
214
|
+
)
|
|
215
|
+
@click.option(
|
|
216
|
+
"--synced-lyrics-only",
|
|
217
|
+
is_flag=True,
|
|
218
|
+
help="Skip track download and only save synced lyrics.",
|
|
219
|
+
)
|
|
220
|
+
@click.option(
|
|
221
|
+
"--truncate",
|
|
222
|
+
type=int,
|
|
223
|
+
default=downloader_sig.parameters["truncate"].default,
|
|
224
|
+
help="Maximum length of the file/folder names.",
|
|
225
|
+
)
|
|
226
|
+
# This option should always be last
|
|
227
|
+
@click.option(
|
|
228
|
+
"--no-config-file",
|
|
229
|
+
"-n",
|
|
230
|
+
is_flag=True,
|
|
231
|
+
callback=load_config_file,
|
|
232
|
+
help="Don't load the config file.",
|
|
233
|
+
)
|
|
234
|
+
def main(
|
|
235
|
+
urls: tuple[str],
|
|
236
|
+
save_cover: bool,
|
|
237
|
+
overwrite: bool,
|
|
238
|
+
read_urls_as_txt: bool,
|
|
239
|
+
config_path: Path,
|
|
240
|
+
log_level: str,
|
|
241
|
+
no_exceptions: bool,
|
|
242
|
+
output_path: Path,
|
|
243
|
+
temp_path: Path,
|
|
244
|
+
cookies_path: Path,
|
|
245
|
+
browser_json_path: Path, # NUEVO PARÁMETRO
|
|
246
|
+
ffmpeg_path: str,
|
|
247
|
+
aria2c_path: str,
|
|
248
|
+
download_mode: DownloadMode,
|
|
249
|
+
po_token: str,
|
|
250
|
+
itag: str,
|
|
251
|
+
cover_size: int,
|
|
252
|
+
cover_format: CoverFormat,
|
|
253
|
+
cover_quality: int,
|
|
254
|
+
template_folder: str,
|
|
255
|
+
template_file: str,
|
|
256
|
+
template_date: str,
|
|
257
|
+
exclude_tags: str,
|
|
258
|
+
no_synced_lyrics: bool,
|
|
259
|
+
synced_lyrics_only: bool,
|
|
260
|
+
truncate: int,
|
|
261
|
+
no_config_file: bool,
|
|
262
|
+
):
|
|
263
|
+
colorama.just_fix_windows_console()
|
|
264
|
+
logger.setLevel(log_level)
|
|
265
|
+
stream_handler = logging.StreamHandler()
|
|
266
|
+
stream_handler.setFormatter(CustomLoggerFormatter())
|
|
267
|
+
logger.addHandler(stream_handler)
|
|
268
|
+
|
|
269
|
+
if itag in PREMIUM_FORMATS and cookies_path is None and po_token is None:
|
|
270
|
+
logger.critical("Cookies file or PO Token is required for premium formats")
|
|
271
|
+
return
|
|
272
|
+
if po_token is None and cookies_path is not None:
|
|
273
|
+
logger.warning("PO Token not provided, downloading may fail")
|
|
274
|
+
|
|
275
|
+
if not shutil.which(ffmpeg_path):
|
|
276
|
+
logger.critical(X_NOT_FOUND_STRING.format("FFmpeg", ffmpeg_path))
|
|
277
|
+
return
|
|
278
|
+
if download_mode == DownloadMode.ARIA2C and not shutil.which(aria2c_path):
|
|
279
|
+
logger.critical(X_NOT_FOUND_STRING.format("aria2c", aria2c_path))
|
|
280
|
+
return
|
|
281
|
+
|
|
282
|
+
if cookies_path is not None:
|
|
283
|
+
cookies_path = prompt_path(
|
|
284
|
+
True,
|
|
285
|
+
cookies_path,
|
|
286
|
+
)
|
|
287
|
+
|
|
288
|
+
if browser_json_path is not None and not browser_json_path.exists():
|
|
289
|
+
logger.warning(f"browser.json not found at {browser_json_path}. YTMusic will work in anonymous mode.")
|
|
290
|
+
browser_json_path = None
|
|
291
|
+
|
|
292
|
+
if read_urls_as_txt:
|
|
293
|
+
_urls = []
|
|
294
|
+
for url in urls:
|
|
295
|
+
if Path(url).exists():
|
|
296
|
+
_urls.extend(Path(url).read_text().splitlines())
|
|
297
|
+
urls = _urls
|
|
298
|
+
|
|
299
|
+
logger.info("Starting Muget")
|
|
300
|
+
downloader = Downloader(
|
|
301
|
+
output_path,
|
|
302
|
+
temp_path,
|
|
303
|
+
cookies_path,
|
|
304
|
+
browser_json_path, # NUEVO ARGUMENTO
|
|
305
|
+
ffmpeg_path,
|
|
306
|
+
aria2c_path,
|
|
307
|
+
itag,
|
|
308
|
+
download_mode,
|
|
309
|
+
po_token,
|
|
310
|
+
cover_size,
|
|
311
|
+
cover_format,
|
|
312
|
+
cover_quality,
|
|
313
|
+
template_folder,
|
|
314
|
+
template_file,
|
|
315
|
+
template_date,
|
|
316
|
+
exclude_tags,
|
|
317
|
+
truncate,
|
|
318
|
+
)
|
|
319
|
+
|
|
320
|
+
error_count = 0
|
|
321
|
+
download_queue = []
|
|
322
|
+
for url_index, url in enumerate(urls, start=1):
|
|
323
|
+
url_progress = color_text(f"URL {url_index}/{len(urls)}", colorama.Style.DIM)
|
|
324
|
+
try:
|
|
325
|
+
logger.info(f'({url_progress}) Checking "{url}"')
|
|
326
|
+
download_queue = list(downloader.get_download_queue(url))
|
|
327
|
+
except Exception as e:
|
|
328
|
+
error_count += 1
|
|
329
|
+
logger.error(
|
|
330
|
+
f'({url_progress}) Failed to check "{url}"',
|
|
331
|
+
exc_info=not no_exceptions,
|
|
332
|
+
)
|
|
333
|
+
continue
|
|
334
|
+
|
|
335
|
+
for queue_index, queue_item in enumerate(download_queue, start=1):
|
|
336
|
+
queue_progress = color_text(
|
|
337
|
+
f"Track {queue_index}/{len(download_queue)} from URL {url_index}/{len(urls)}",
|
|
338
|
+
colorama.Style.DIM,
|
|
339
|
+
)
|
|
340
|
+
try:
|
|
341
|
+
# Si el título no está disponible (ej. desde URL directa), obtenerlo ahora
|
|
342
|
+
if not queue_item.get("title"):
|
|
343
|
+
watch_playlist_temp = downloader.get_ytmusic_watch_playlist(queue_item["id"])
|
|
344
|
+
if watch_playlist_temp and watch_playlist_temp.get("tracks"):
|
|
345
|
+
queue_item["title"] = watch_playlist_temp["tracks"][0].get("title", "Unknown Title")
|
|
346
|
+
else:
|
|
347
|
+
queue_item["title"] = "Unknown Title"
|
|
348
|
+
|
|
349
|
+
logger.info(f'({queue_progress}) Downloading "{queue_item["title"]}"')
|
|
350
|
+
logger.debug("Getting tags")
|
|
351
|
+
ytmusic_watch_playlist = downloader.get_ytmusic_watch_playlist(
|
|
352
|
+
queue_item["id"]
|
|
353
|
+
)
|
|
354
|
+
if not ytmusic_watch_playlist:
|
|
355
|
+
logger.warning(
|
|
356
|
+
f"({queue_progress}) Track doesn't have an album or is not available, skipping"
|
|
357
|
+
)
|
|
358
|
+
continue
|
|
359
|
+
tags = downloader.get_tags(ytmusic_watch_playlist)
|
|
360
|
+
final_path = downloader.get_final_path(tags)
|
|
361
|
+
synced_lyrics_path = downloader.get_synced_lyrics_path(final_path)
|
|
362
|
+
if synced_lyrics_only:
|
|
363
|
+
pass
|
|
364
|
+
elif final_path.exists() and not overwrite:
|
|
365
|
+
logger.warning(
|
|
366
|
+
f'({queue_progress}) Track already exists at "{final_path}", skipping'
|
|
367
|
+
)
|
|
368
|
+
else:
|
|
369
|
+
video_id = ytmusic_watch_playlist["tracks"][0]["videoId"]
|
|
370
|
+
track_temp_path = downloader.get_track_temp_path(video_id)
|
|
371
|
+
remuxed_path = downloader.get_remuxed_path(video_id)
|
|
372
|
+
cover_url = downloader.get_cover_url(ytmusic_watch_playlist)
|
|
373
|
+
cover_file_extension = downloader.get_cover_file_extension(
|
|
374
|
+
cover_url
|
|
375
|
+
)
|
|
376
|
+
cover_path = downloader.get_cover_path(
|
|
377
|
+
final_path, cover_file_extension
|
|
378
|
+
)
|
|
379
|
+
logger.debug(f'Downloading to "{track_temp_path}"')
|
|
380
|
+
downloader.download(video_id, track_temp_path)
|
|
381
|
+
logger.debug(f'Remuxing to "{remuxed_path}"')
|
|
382
|
+
downloader.remux(track_temp_path, remuxed_path)
|
|
383
|
+
logger.debug("Applying tags")
|
|
384
|
+
downloader.apply_tags(remuxed_path, tags, cover_url)
|
|
385
|
+
logger.debug(f'Moving to "{final_path}"')
|
|
386
|
+
downloader.move_to_output_path(remuxed_path, final_path)
|
|
387
|
+
if no_synced_lyrics or not tags.get("lyrics"):
|
|
388
|
+
pass
|
|
389
|
+
elif synced_lyrics_path.exists() and not overwrite:
|
|
390
|
+
logger.debug(
|
|
391
|
+
f'Synced lyrics already exists at "{synced_lyrics_path}", skipping'
|
|
392
|
+
)
|
|
393
|
+
else:
|
|
394
|
+
logger.debug("Getting synced lyrics")
|
|
395
|
+
synced_lyrics = downloader.get_synced_lyrics(ytmusic_watch_playlist)
|
|
396
|
+
if synced_lyrics:
|
|
397
|
+
logger.debug(f'Saving synced lyrics to "{synced_lyrics_path}"')
|
|
398
|
+
downloader.save_synced_lyrics(synced_lyrics_path, synced_lyrics)
|
|
399
|
+
if not save_cover:
|
|
400
|
+
pass
|
|
401
|
+
elif cover_path.exists() and not overwrite:
|
|
402
|
+
logger.debug(f'Cover already exists at "{cover_path}", skipping')
|
|
403
|
+
else:
|
|
404
|
+
logger.debug(f'Saving cover to "{cover_path}"')
|
|
405
|
+
downloader.save_cover(cover_path, cover_url)
|
|
406
|
+
except Exception as e:
|
|
407
|
+
error_count += 1
|
|
408
|
+
logger.error(
|
|
409
|
+
f'({queue_progress}) Failed to download "{queue_item["title"]}"',
|
|
410
|
+
exc_info=not no_exceptions,
|
|
411
|
+
)
|
|
412
|
+
finally:
|
|
413
|
+
if temp_path.exists():
|
|
414
|
+
logger.debug(f'Cleaning up "{temp_path}"')
|
|
415
|
+
downloader.cleanup_temp_path()
|
|
416
|
+
logger.info(f"Done ({error_count} error(s))")
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
EXCLUDED_CONFIG_FILE_PARAMS = (
|
|
2
|
+
"urls",
|
|
3
|
+
"config_path",
|
|
4
|
+
"read_urls_as_txt",
|
|
5
|
+
"no_config_file",
|
|
6
|
+
"version",
|
|
7
|
+
"help",
|
|
8
|
+
"browser_json_path", # AÑADIDO: Excluir esta opción del archivo de configuración
|
|
9
|
+
)
|
|
10
|
+
|
|
11
|
+
MP4_TAGS_MAP = {
|
|
12
|
+
"album": "\xa9alb",
|
|
13
|
+
"album_artist": "aART",
|
|
14
|
+
"artist": "\xa9ART",
|
|
15
|
+
"date": "\xa9day",
|
|
16
|
+
"lyrics": "\xa9lyr",
|
|
17
|
+
"media_type": "stik",
|
|
18
|
+
"rating": "rtng",
|
|
19
|
+
"title": "\xa9nam",
|
|
20
|
+
"url": "\xa9url",
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
X_NOT_FOUND_STRING = '{} not found at "{}"'
|
|
24
|
+
|
|
25
|
+
IMAGE_FILE_EXTENSION_MAP = {
|
|
26
|
+
"jpeg": ".jpg",
|
|
27
|
+
"tiff": ".tif",
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
PREMIUM_FORMATS = ["141", "774"]
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
|
|
3
|
+
import colorama
|
|
4
|
+
|
|
5
|
+
from .utils import color_text
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class CustomLoggerFormatter(logging.Formatter):
|
|
9
|
+
base_format = "[%(levelname)-8s %(asctime)s]"
|
|
10
|
+
format_colors = {
|
|
11
|
+
logging.DEBUG: colorama.Style.DIM,
|
|
12
|
+
logging.INFO: colorama.Fore.GREEN,
|
|
13
|
+
logging.WARNING: colorama.Fore.YELLOW,
|
|
14
|
+
logging.ERROR: colorama.Fore.RED,
|
|
15
|
+
logging.CRITICAL: colorama.Fore.RED,
|
|
16
|
+
}
|
|
17
|
+
date_format = "%H:%M:%S"
|
|
18
|
+
|
|
19
|
+
def format(self, record: logging.LogRecord) -> str:
|
|
20
|
+
return logging.Formatter(
|
|
21
|
+
color_text(self.base_format, self.format_colors.get(record.levelno))
|
|
22
|
+
+ " %(message)s",
|
|
23
|
+
datefmt=self.date_format,
|
|
24
|
+
).format(record)
|
|
@@ -0,0 +1,563 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import datetime
|
|
4
|
+
import functools
|
|
5
|
+
import io
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
import re
|
|
9
|
+
import shutil
|
|
10
|
+
import subprocess
|
|
11
|
+
import typing
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
import requests
|
|
15
|
+
from InquirerPy import inquirer
|
|
16
|
+
from InquirerPy.base.control import Choice
|
|
17
|
+
from mutagen.mp4 import MP4, MP4Cover
|
|
18
|
+
from PIL import Image
|
|
19
|
+
from yt_dlp import YoutubeDL
|
|
20
|
+
from ytmusicapi import YTMusic
|
|
21
|
+
|
|
22
|
+
from .constants import IMAGE_FILE_EXTENSION_MAP, MP4_TAGS_MAP
|
|
23
|
+
from .enums import CoverFormat, DownloadMode
|
|
24
|
+
|
|
25
|
+
logger = logging.getLogger("muget")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class Downloader:
|
|
29
|
+
def __init__(
|
|
30
|
+
self,
|
|
31
|
+
output_path: Path = Path("./YouTube Music"),
|
|
32
|
+
temp_path: Path = Path("./temp"),
|
|
33
|
+
cookies_path: Path = None,
|
|
34
|
+
browser_json_path: Path = None,
|
|
35
|
+
ffmpeg_path: str = "ffmpeg",
|
|
36
|
+
aria2c_path: str = "aria2c",
|
|
37
|
+
itag: str = "140",
|
|
38
|
+
download_mode: DownloadMode = DownloadMode.YTDLP,
|
|
39
|
+
po_token: str = None,
|
|
40
|
+
cover_size: int = 16383,
|
|
41
|
+
cover_format: CoverFormat = CoverFormat.JPG,
|
|
42
|
+
cover_quality: int = 94,
|
|
43
|
+
template_folder: str = "{album_artist}/{album}",
|
|
44
|
+
template_file: str = "{track:02d} {title}",
|
|
45
|
+
template_date: str = "%Y-%m-%dT%H:%M:%SZ",
|
|
46
|
+
exclude_tags: str = None,
|
|
47
|
+
truncate: int = None,
|
|
48
|
+
silent: bool = False,
|
|
49
|
+
):
|
|
50
|
+
self.output_path = output_path
|
|
51
|
+
self.temp_path = temp_path
|
|
52
|
+
self.cookies_path = cookies_path
|
|
53
|
+
self.browser_json_path = browser_json_path
|
|
54
|
+
self.ffmpeg_path = ffmpeg_path
|
|
55
|
+
self.aria2c_path = aria2c_path
|
|
56
|
+
self.itag = itag
|
|
57
|
+
self.download_mode = download_mode
|
|
58
|
+
self.po_token = po_token
|
|
59
|
+
self.cover_size = cover_size
|
|
60
|
+
self.cover_format = cover_format
|
|
61
|
+
self.cover_quality = cover_quality
|
|
62
|
+
self.template_folder = template_folder
|
|
63
|
+
self.template_file = template_file
|
|
64
|
+
self.template_date = template_date
|
|
65
|
+
self.exclude_tags = exclude_tags
|
|
66
|
+
self.truncate = truncate
|
|
67
|
+
self.silent = silent
|
|
68
|
+
self._set_ytmusic_instance()
|
|
69
|
+
self._set_ytdlp_options()
|
|
70
|
+
self._set_exclude_tags()
|
|
71
|
+
self._set_truncate()
|
|
72
|
+
|
|
73
|
+
def _set_ytmusic_instance(self):
|
|
74
|
+
"""Configura la instancia de YTMusic usando browser.json si está disponible."""
|
|
75
|
+
if self.browser_json_path and self.browser_json_path.exists():
|
|
76
|
+
try:
|
|
77
|
+
with open(self.browser_json_path, 'r', encoding='utf-8') as f:
|
|
78
|
+
json.load(f) # Validar que es JSON válido
|
|
79
|
+
self.ytmusic = YTMusic(str(self.browser_json_path))
|
|
80
|
+
logger.debug(f"YTMusic autenticado con browser.json desde {self.browser_json_path}")
|
|
81
|
+
except Exception as e:
|
|
82
|
+
logger.warning(f"Error cargando browser.json: {e}. Usando modo anónimo.")
|
|
83
|
+
self.ytmusic = YTMusic()
|
|
84
|
+
else:
|
|
85
|
+
if self.browser_json_path:
|
|
86
|
+
logger.warning(f"browser.json no encontrado en {self.browser_json_path}. Usando modo anónimo.")
|
|
87
|
+
self.ytmusic = YTMusic()
|
|
88
|
+
|
|
89
|
+
def _set_ytdlp_options(self):
|
|
90
|
+
"""Configura opciones de yt-dlp SOLO para descarga de audio."""
|
|
91
|
+
self.ytdlp_options = {
|
|
92
|
+
"quiet": True,
|
|
93
|
+
"no_warnings": True,
|
|
94
|
+
"noprogress": self.silent,
|
|
95
|
+
"extract_flat": False,
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
if self.cookies_path is not None or self.po_token is not None:
|
|
99
|
+
self.ytdlp_options["extractor_args"] = {
|
|
100
|
+
"youtube": {
|
|
101
|
+
"player_client": ["web_music"],
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
if self.po_token is not None:
|
|
105
|
+
self.ytdlp_options["extractor_args"]["youtube"]["po_token"] = [
|
|
106
|
+
f"web_music.gvs+{self.po_token}"
|
|
107
|
+
]
|
|
108
|
+
|
|
109
|
+
if self.cookies_path is not None:
|
|
110
|
+
self.ytdlp_options["cookiefile"] = str(self.cookies_path)
|
|
111
|
+
|
|
112
|
+
def _set_exclude_tags(self):
|
|
113
|
+
self.exclude_tags = (
|
|
114
|
+
[i.lower() for i in self.exclude_tags.split(",")]
|
|
115
|
+
if self.exclude_tags is not None
|
|
116
|
+
else []
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
def _set_truncate(self):
|
|
120
|
+
if self.truncate is not None:
|
|
121
|
+
self.truncate = None if self.truncate < 4 else self.truncate
|
|
122
|
+
|
|
123
|
+
def get_download_queue(
|
|
124
|
+
self,
|
|
125
|
+
url: str,
|
|
126
|
+
) -> typing.Generator[dict, None, None]:
|
|
127
|
+
"""Obtiene la cola de descarga usando SOLO ytmusicapi."""
|
|
128
|
+
# Detectar tipo de URL
|
|
129
|
+
if "browse" in url:
|
|
130
|
+
browse_id = url.split("browse/")[-1].split("?")[0]
|
|
131
|
+
yield from self._get_download_queue_from_browse_id(browse_id)
|
|
132
|
+
elif "playlist" in url:
|
|
133
|
+
playlist_id = self._extract_playlist_id(url)
|
|
134
|
+
yield from self._get_download_queue_from_playlist_id(playlist_id)
|
|
135
|
+
elif "watch" in url or "v=" in url:
|
|
136
|
+
video_id = self._extract_video_id(url)
|
|
137
|
+
yield from self._get_download_queue_from_video_id(video_id)
|
|
138
|
+
elif "channel" in url:
|
|
139
|
+
channel_id = self._extract_channel_id(url)
|
|
140
|
+
yield from self._get_download_queue_artist(channel_id)
|
|
141
|
+
else:
|
|
142
|
+
yield from self._get_download_queue_from_browse_id(url)
|
|
143
|
+
|
|
144
|
+
def _extract_video_id(self, url: str) -> str:
|
|
145
|
+
if "v=" in url:
|
|
146
|
+
return url.split("v=")[1].split("&")[0]
|
|
147
|
+
return url.split("/")[-1].split("?")[0]
|
|
148
|
+
|
|
149
|
+
def _extract_playlist_id(self, url: str) -> str:
|
|
150
|
+
if "list=" in url:
|
|
151
|
+
return url.split("list=")[1].split("&")[0]
|
|
152
|
+
return url.split("/")[-1].split("?")[0]
|
|
153
|
+
|
|
154
|
+
def _extract_channel_id(self, url: str) -> str:
|
|
155
|
+
if "channel/" in url:
|
|
156
|
+
return url.split("channel/")[1].split("?")[0]
|
|
157
|
+
return url.split("/")[-1].split("?")[0]
|
|
158
|
+
|
|
159
|
+
def _get_download_queue_from_browse_id(
|
|
160
|
+
self,
|
|
161
|
+
browse_id: str,
|
|
162
|
+
) -> typing.Generator[dict, None, None]:
|
|
163
|
+
"""Procesa browse_id como álbum o playlist."""
|
|
164
|
+
# Intentar como álbum
|
|
165
|
+
try:
|
|
166
|
+
album = self.ytmusic.get_album(browse_id)
|
|
167
|
+
if album and album.get("tracks"):
|
|
168
|
+
for track in album["tracks"]:
|
|
169
|
+
if track.get("videoId"):
|
|
170
|
+
yield {
|
|
171
|
+
"id": track["videoId"],
|
|
172
|
+
"title": track.get("title"),
|
|
173
|
+
"artists": track.get("artists", []),
|
|
174
|
+
"album": album,
|
|
175
|
+
}
|
|
176
|
+
return
|
|
177
|
+
except Exception:
|
|
178
|
+
pass
|
|
179
|
+
|
|
180
|
+
# Intentar como playlist
|
|
181
|
+
try:
|
|
182
|
+
playlist = self.ytmusic.get_playlist(browse_id, limit=1000)
|
|
183
|
+
if playlist and playlist.get("tracks"):
|
|
184
|
+
for track in playlist["tracks"]:
|
|
185
|
+
if track.get("videoId"):
|
|
186
|
+
yield {
|
|
187
|
+
"id": track["videoId"],
|
|
188
|
+
"title": track.get("title"),
|
|
189
|
+
"artists": track.get("artists", []),
|
|
190
|
+
"playlist": playlist,
|
|
191
|
+
}
|
|
192
|
+
return
|
|
193
|
+
except Exception as e:
|
|
194
|
+
logger.debug(f"Error procesando browse_id {browse_id}: {e}")
|
|
195
|
+
|
|
196
|
+
def _get_download_queue_from_playlist_id(
|
|
197
|
+
self,
|
|
198
|
+
playlist_id: str,
|
|
199
|
+
) -> typing.Generator[dict, None, None]:
|
|
200
|
+
"""Obtiene tracks de una playlist (soporta privadas con browser.json)."""
|
|
201
|
+
try:
|
|
202
|
+
playlist = self.ytmusic.get_playlist(playlist_id, limit=1000)
|
|
203
|
+
if playlist and playlist.get("tracks"):
|
|
204
|
+
for track in playlist["tracks"]:
|
|
205
|
+
if track.get("videoId"):
|
|
206
|
+
yield {
|
|
207
|
+
"id": track["videoId"],
|
|
208
|
+
"title": track.get("title"),
|
|
209
|
+
"artists": track.get("artists", []),
|
|
210
|
+
"playlist": playlist,
|
|
211
|
+
}
|
|
212
|
+
else:
|
|
213
|
+
logger.warning(f"No se encontraron tracks en la playlist {playlist_id}")
|
|
214
|
+
except Exception as e:
|
|
215
|
+
logger.error(f"Error accediendo a la playlist {playlist_id}: {e}")
|
|
216
|
+
if "private" in str(e).lower():
|
|
217
|
+
logger.error("La playlist puede ser privada. Usa --browser-json-path con autenticación válida.")
|
|
218
|
+
|
|
219
|
+
def _get_download_queue_from_video_id(
|
|
220
|
+
self,
|
|
221
|
+
video_id: str,
|
|
222
|
+
) -> typing.Generator[dict, None, None]:
|
|
223
|
+
yield {
|
|
224
|
+
"id": video_id,
|
|
225
|
+
"title": None,
|
|
226
|
+
"artists": [],
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
def _get_download_queue_artist(
|
|
230
|
+
self,
|
|
231
|
+
channel_id: str,
|
|
232
|
+
) -> typing.Generator[dict, None, None]:
|
|
233
|
+
"""Interactúa con el usuario para seleccionar álbumes/singles de un artista."""
|
|
234
|
+
artist = self.ytmusic.get_artist(channel_id)
|
|
235
|
+
media_type = inquirer.select(
|
|
236
|
+
message=f'Select which type to download for artist "{artist["name"]}":',
|
|
237
|
+
choices=[
|
|
238
|
+
Choice(name="Albums", value="albums"),
|
|
239
|
+
Choice(name="Singles", value="singles"),
|
|
240
|
+
],
|
|
241
|
+
validate=lambda result: artist.get(result, {}).get("results"),
|
|
242
|
+
invalid_message="The artist doesn't have any items of this type",
|
|
243
|
+
).execute()
|
|
244
|
+
|
|
245
|
+
artist_items = (
|
|
246
|
+
self.ytmusic.get_artist_albums(
|
|
247
|
+
artist[media_type]["browseId"], artist[media_type]["params"]
|
|
248
|
+
)
|
|
249
|
+
if artist[media_type].get("browseId") and artist[media_type].get("params")
|
|
250
|
+
else artist[media_type]["results"]
|
|
251
|
+
)
|
|
252
|
+
|
|
253
|
+
choices = [
|
|
254
|
+
Choice(
|
|
255
|
+
name=" | ".join(
|
|
256
|
+
[
|
|
257
|
+
item.get("year", "Unknown"),
|
|
258
|
+
item["title"],
|
|
259
|
+
]
|
|
260
|
+
),
|
|
261
|
+
value=item,
|
|
262
|
+
)
|
|
263
|
+
for item in artist_items
|
|
264
|
+
]
|
|
265
|
+
|
|
266
|
+
selected = inquirer.select(
|
|
267
|
+
message="Select which items to download: (Year | Title)",
|
|
268
|
+
choices=choices,
|
|
269
|
+
multiselect=True,
|
|
270
|
+
).execute()
|
|
271
|
+
|
|
272
|
+
for item in selected:
|
|
273
|
+
yield from self._get_download_queue_from_browse_id(item["browseId"])
|
|
274
|
+
|
|
275
|
+
@staticmethod
|
|
276
|
+
def _get_artist(artist_list: list) -> str:
|
|
277
|
+
if not artist_list:
|
|
278
|
+
return "Unknown Artist"
|
|
279
|
+
if len(artist_list) == 1:
|
|
280
|
+
return artist_list[0]["name"]
|
|
281
|
+
return (
|
|
282
|
+
", ".join([i["name"] for i in artist_list][:-1])
|
|
283
|
+
+ f' & {artist_list[-1]["name"]}'
|
|
284
|
+
)
|
|
285
|
+
|
|
286
|
+
def get_ytmusic_watch_playlist(self, video_id: str) -> dict | None:
|
|
287
|
+
"""Obtiene watch playlist para un video."""
|
|
288
|
+
try:
|
|
289
|
+
ytmusic_watch_playlist = self.ytmusic.get_watch_playlist(video_id)
|
|
290
|
+
if not ytmusic_watch_playlist or not ytmusic_watch_playlist.get("tracks"):
|
|
291
|
+
return None
|
|
292
|
+
if not ytmusic_watch_playlist["tracks"][0].get("album"):
|
|
293
|
+
return None
|
|
294
|
+
return ytmusic_watch_playlist
|
|
295
|
+
except Exception as e:
|
|
296
|
+
logger.debug(f"Error obteniendo watch playlist para {video_id}: {e}")
|
|
297
|
+
return None
|
|
298
|
+
|
|
299
|
+
@functools.lru_cache()
|
|
300
|
+
def get_ytmusic_album(self, browse_id: str) -> dict:
|
|
301
|
+
"""Obtiene información de un álbum."""
|
|
302
|
+
try:
|
|
303
|
+
return self.ytmusic.get_album(browse_id)
|
|
304
|
+
except Exception as e:
|
|
305
|
+
logger.debug(f"Error obteniendo álbum {browse_id}: {e}")
|
|
306
|
+
return {}
|
|
307
|
+
|
|
308
|
+
@staticmethod
|
|
309
|
+
def _get_datetime_obj(date: str) -> datetime.datetime | None:
|
|
310
|
+
try:
|
|
311
|
+
return datetime.datetime.strptime(date, "%Y")
|
|
312
|
+
except ValueError:
|
|
313
|
+
return None
|
|
314
|
+
|
|
315
|
+
def get_tags(self, ytmusic_watch_playlist: dict) -> dict:
|
|
316
|
+
"""Extrae tags completas de un track usando ytmusicapi."""
|
|
317
|
+
video_id = ytmusic_watch_playlist["tracks"][0]["videoId"]
|
|
318
|
+
album_info = self.get_ytmusic_album(
|
|
319
|
+
ytmusic_watch_playlist["tracks"][0]["album"]["id"]
|
|
320
|
+
)
|
|
321
|
+
|
|
322
|
+
track_number = 1
|
|
323
|
+
is_explicit = False
|
|
324
|
+
if album_info and album_info.get("tracks"):
|
|
325
|
+
for idx, track in enumerate(album_info["tracks"], start=1):
|
|
326
|
+
if track.get("videoId") == video_id:
|
|
327
|
+
track_number = idx
|
|
328
|
+
is_explicit = track.get("isExplicit", False)
|
|
329
|
+
break
|
|
330
|
+
|
|
331
|
+
tags = {
|
|
332
|
+
"album": album_info.get("title", "Unknown Album") if album_info else "Unknown Album",
|
|
333
|
+
"album_artist": self._get_artist(album_info.get("artists", [])) if album_info else "Unknown Artist",
|
|
334
|
+
"artist": self._get_artist(ytmusic_watch_playlist["tracks"][0].get("artists", [])),
|
|
335
|
+
"url": f"https://music.youtube.com/watch?v={video_id}",
|
|
336
|
+
"media_type": 1,
|
|
337
|
+
"title": ytmusic_watch_playlist["tracks"][0].get("title", "Unknown Title"),
|
|
338
|
+
"track_total": album_info.get("trackCount", 0) if album_info else 0,
|
|
339
|
+
"track": track_number,
|
|
340
|
+
"video_id": video_id,
|
|
341
|
+
"rating": 1 if is_explicit else 0,
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
# Letras no sincronizadas
|
|
345
|
+
if ytmusic_watch_playlist.get("lyrics"):
|
|
346
|
+
try:
|
|
347
|
+
lyrics_data = self.ytmusic.get_lyrics(ytmusic_watch_playlist["lyrics"])
|
|
348
|
+
if lyrics_data and lyrics_data.get("lyrics"):
|
|
349
|
+
tags["lyrics"] = lyrics_data["lyrics"]
|
|
350
|
+
except Exception as e:
|
|
351
|
+
logger.debug(f"No se pudieron obtener letras: {e}")
|
|
352
|
+
|
|
353
|
+
# Fecha
|
|
354
|
+
if album_info and album_info.get("year"):
|
|
355
|
+
dt_obj = self._get_datetime_obj(album_info["year"])
|
|
356
|
+
if dt_obj:
|
|
357
|
+
tags["date"] = dt_obj.strftime(self.template_date)
|
|
358
|
+
|
|
359
|
+
return tags
|
|
360
|
+
|
|
361
|
+
def get_synced_lyrics(self, ytmusic_watch_playlist: dict) -> str | None:
|
|
362
|
+
"""Obtiene letras sincronizadas usando una instancia anónima."""
|
|
363
|
+
if not ytmusic_watch_playlist.get("lyrics"):
|
|
364
|
+
return None
|
|
365
|
+
|
|
366
|
+
try:
|
|
367
|
+
# Crear una instancia anónima SOLO para letras
|
|
368
|
+
yt_anonymous = YTMusic() # Sin autenticación
|
|
369
|
+
|
|
370
|
+
lyrics_data = yt_anonymous.get_lyrics(
|
|
371
|
+
ytmusic_watch_playlist["lyrics"],
|
|
372
|
+
True # Con timestamps
|
|
373
|
+
)
|
|
374
|
+
|
|
375
|
+
if (lyrics_data is not None
|
|
376
|
+
and lyrics_data.get("lyrics")
|
|
377
|
+
and lyrics_data.get("hasTimestamps")):
|
|
378
|
+
|
|
379
|
+
lines = []
|
|
380
|
+
for line in lyrics_data["lyrics"]:
|
|
381
|
+
timestamp = datetime.datetime.fromtimestamp(
|
|
382
|
+
line.start_time / 1000.0,
|
|
383
|
+
tz=datetime.timezone.utc
|
|
384
|
+
)
|
|
385
|
+
lrc_timestamp = timestamp.strftime("%M:%S.%f")[:-4]
|
|
386
|
+
lines.append(f"[{lrc_timestamp}]{line.text}")
|
|
387
|
+
|
|
388
|
+
return "\n".join(lines) + "\n"
|
|
389
|
+
|
|
390
|
+
except Exception as e:
|
|
391
|
+
logger.debug(f"No se pudieron obtener letras sincronizadas: {e}")
|
|
392
|
+
|
|
393
|
+
return None
|
|
394
|
+
|
|
395
|
+
def get_synced_lyrics_path(self, final_path: Path) -> Path:
|
|
396
|
+
return final_path.with_suffix(".lrc")
|
|
397
|
+
|
|
398
|
+
def save_synced_lyrics(self, synced_lyrics_path: Path, synced_lyrics: str):
|
|
399
|
+
if synced_lyrics:
|
|
400
|
+
synced_lyrics_path.parent.mkdir(parents=True, exist_ok=True)
|
|
401
|
+
synced_lyrics_path.write_text(synced_lyrics, encoding="utf8")
|
|
402
|
+
|
|
403
|
+
def get_sanitized_string(self, dirty_string: str, is_folder: bool) -> str:
|
|
404
|
+
dirty_string = re.sub(r'[\\/:*?"<>|;]', "_", dirty_string)
|
|
405
|
+
if is_folder:
|
|
406
|
+
if self.truncate:
|
|
407
|
+
dirty_string = dirty_string[:self.truncate]
|
|
408
|
+
if dirty_string.endswith("."):
|
|
409
|
+
dirty_string = dirty_string[:-1] + "_"
|
|
410
|
+
else:
|
|
411
|
+
if self.truncate:
|
|
412
|
+
dirty_string = dirty_string[:self.truncate - 4]
|
|
413
|
+
return dirty_string.strip()
|
|
414
|
+
|
|
415
|
+
def get_track_temp_path(self, video_id: str) -> Path:
|
|
416
|
+
return self.temp_path / f"{video_id}_temp.m4a"
|
|
417
|
+
|
|
418
|
+
def get_remuxed_path(self, video_id: str) -> Path:
|
|
419
|
+
return self.temp_path / f"{video_id}_remuxed.m4a"
|
|
420
|
+
|
|
421
|
+
def get_cover_path(self, final_path: Path, file_extension: str) -> Path:
|
|
422
|
+
return final_path.parent / ("Cover" + file_extension)
|
|
423
|
+
|
|
424
|
+
def get_final_path(self, tags: dict) -> Path:
|
|
425
|
+
tags_for_filename = tags.copy()
|
|
426
|
+
|
|
427
|
+
# Asegurar tipos numéricos
|
|
428
|
+
for key in ['track', 'track_total', 'disc', 'disc_total']:
|
|
429
|
+
if key in tags_for_filename:
|
|
430
|
+
value = tags_for_filename[key]
|
|
431
|
+
try:
|
|
432
|
+
if isinstance(value, str) and '/' in value:
|
|
433
|
+
value = value.split('/')[0]
|
|
434
|
+
tags_for_filename[key] = int(value) if value is not None else 0
|
|
435
|
+
except (ValueError, TypeError):
|
|
436
|
+
tags_for_filename[key] = 0
|
|
437
|
+
|
|
438
|
+
tags_for_filename.setdefault('track', 0)
|
|
439
|
+
tags_for_filename.setdefault('title', 'Unknown Title')
|
|
440
|
+
tags_for_filename.setdefault('artist', 'Unknown Artist')
|
|
441
|
+
|
|
442
|
+
folder_parts = self.template_folder.split("/")
|
|
443
|
+
file_parts = self.template_file.split("/")
|
|
444
|
+
|
|
445
|
+
processed_folders = []
|
|
446
|
+
for part in folder_parts:
|
|
447
|
+
try:
|
|
448
|
+
formatted = part.format(**tags_for_filename)
|
|
449
|
+
except (KeyError, ValueError):
|
|
450
|
+
formatted = part
|
|
451
|
+
processed_folders.append(self.get_sanitized_string(formatted, True))
|
|
452
|
+
|
|
453
|
+
processed_file_parts = []
|
|
454
|
+
for part in file_parts[:-1]:
|
|
455
|
+
try:
|
|
456
|
+
formatted = part.format(**tags_for_filename)
|
|
457
|
+
except (KeyError, ValueError):
|
|
458
|
+
formatted = part
|
|
459
|
+
processed_file_parts.append(self.get_sanitized_string(formatted, True))
|
|
460
|
+
|
|
461
|
+
try:
|
|
462
|
+
last_part = file_parts[-1].format(**tags_for_filename)
|
|
463
|
+
except (KeyError, ValueError):
|
|
464
|
+
last_part = file_parts[-1]
|
|
465
|
+
|
|
466
|
+
final_filename = self.get_sanitized_string(last_part, False) + ".m4a"
|
|
467
|
+
processed_file_parts.append(final_filename)
|
|
468
|
+
|
|
469
|
+
return self.output_path.joinpath(*processed_folders).joinpath(*processed_file_parts)
|
|
470
|
+
|
|
471
|
+
def download(self, video_id: str, temp_path: Path):
|
|
472
|
+
"""Descarga SOLO el audio usando yt-dlp."""
|
|
473
|
+
with YoutubeDL(
|
|
474
|
+
{
|
|
475
|
+
**self.ytdlp_options,
|
|
476
|
+
"external_downloader": (
|
|
477
|
+
{"default": self.aria2c_path} if self.download_mode == DownloadMode.ARIA2C else None
|
|
478
|
+
),
|
|
479
|
+
"fixup": "never",
|
|
480
|
+
"format": self.itag,
|
|
481
|
+
"outtmpl": str(temp_path),
|
|
482
|
+
}
|
|
483
|
+
) as ydl:
|
|
484
|
+
ydl.download(f"https://music.youtube.com/watch?v={video_id}")
|
|
485
|
+
|
|
486
|
+
def remux(self, temp_path: Path, remuxed_path: Path):
|
|
487
|
+
command = [self.ffmpeg_path, "-loglevel", "error", "-i", temp_path]
|
|
488
|
+
if self.itag not in ("141", "140", "139"):
|
|
489
|
+
command.extend(["-f", "mp4"])
|
|
490
|
+
subprocess.run(
|
|
491
|
+
[
|
|
492
|
+
*command,
|
|
493
|
+
"-movflags",
|
|
494
|
+
"+faststart",
|
|
495
|
+
"-c",
|
|
496
|
+
"copy",
|
|
497
|
+
remuxed_path,
|
|
498
|
+
],
|
|
499
|
+
check=True,
|
|
500
|
+
)
|
|
501
|
+
|
|
502
|
+
@staticmethod
|
|
503
|
+
@functools.lru_cache()
|
|
504
|
+
def get_url_response_bytes(url: str) -> bytes:
|
|
505
|
+
return requests.get(url).content
|
|
506
|
+
|
|
507
|
+
def get_cover_url(self, ytmusic_watch_playlist: dict) -> str:
|
|
508
|
+
thumb_url = ytmusic_watch_playlist["tracks"][0]["thumbnail"][0]["url"].split("=")[0]
|
|
509
|
+
if self.cover_format == CoverFormat.RAW:
|
|
510
|
+
return thumb_url + "=d"
|
|
511
|
+
return thumb_url + f'=w{self.cover_size}-l{self.cover_quality}-{"rj" if self.cover_format == CoverFormat.JPG else "rp"}'
|
|
512
|
+
|
|
513
|
+
def get_cover_file_extension(self, cover_url: str) -> str:
|
|
514
|
+
img = Image.open(io.BytesIO(self.get_url_response_bytes(cover_url)))
|
|
515
|
+
fmt = img.format.lower()
|
|
516
|
+
return IMAGE_FILE_EXTENSION_MAP.get(fmt, f".{fmt}")
|
|
517
|
+
|
|
518
|
+
def apply_tags(self, path: Path, tags: dict, cover_url: str):
|
|
519
|
+
to_apply = [k for k in tags.keys() if k not in self.exclude_tags]
|
|
520
|
+
mp4_tags = {}
|
|
521
|
+
|
|
522
|
+
for tag in to_apply:
|
|
523
|
+
if tag in ("disc", "disc_total"):
|
|
524
|
+
if "disk" not in mp4_tags:
|
|
525
|
+
mp4_tags["disk"] = [[0, 0]]
|
|
526
|
+
if tag == "disc":
|
|
527
|
+
mp4_tags["disk"][0][0] = tags[tag]
|
|
528
|
+
elif tag == "disc_total":
|
|
529
|
+
mp4_tags["disk"][0][1] = tags[tag]
|
|
530
|
+
elif tag in ("track", "track_total"):
|
|
531
|
+
if "trkn" not in mp4_tags:
|
|
532
|
+
mp4_tags["trkn"] = [[0, 0]]
|
|
533
|
+
if tag == "track":
|
|
534
|
+
mp4_tags["trkn"][0][0] = tags[tag]
|
|
535
|
+
elif tag == "track_total":
|
|
536
|
+
mp4_tags["trkn"][0][1] = tags[tag]
|
|
537
|
+
elif MP4_TAGS_MAP.get(tag) and tags.get(tag) is not None:
|
|
538
|
+
mp4_tags[MP4_TAGS_MAP[tag]] = [tags[tag]]
|
|
539
|
+
|
|
540
|
+
if "cover" not in self.exclude_tags and self.cover_format != CoverFormat.RAW:
|
|
541
|
+
mp4_tags["covr"] = [
|
|
542
|
+
MP4Cover(
|
|
543
|
+
self.get_url_response_bytes(cover_url),
|
|
544
|
+
MP4Cover.FORMAT_JPEG if self.cover_format == CoverFormat.JPG else MP4Cover.FORMAT_PNG,
|
|
545
|
+
)
|
|
546
|
+
]
|
|
547
|
+
|
|
548
|
+
mp4 = MP4(path)
|
|
549
|
+
mp4.clear()
|
|
550
|
+
mp4.update(mp4_tags)
|
|
551
|
+
mp4.save()
|
|
552
|
+
|
|
553
|
+
def move_to_output_path(self, remuxed_path: Path, final_path: Path):
|
|
554
|
+
final_path.parent.mkdir(parents=True, exist_ok=True)
|
|
555
|
+
shutil.move(remuxed_path, final_path)
|
|
556
|
+
|
|
557
|
+
@functools.lru_cache()
|
|
558
|
+
def save_cover(self, cover_path: Path, cover_url: str):
|
|
559
|
+
cover_path.write_bytes(self.get_url_response_bytes(cover_url))
|
|
560
|
+
|
|
561
|
+
def cleanup_temp_path(self):
|
|
562
|
+
if self.temp_path.exists():
|
|
563
|
+
shutil.rmtree(self.temp_path)
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
|
|
3
|
+
import click
|
|
4
|
+
import colorama
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def color_text(text: str, color) -> str:
|
|
8
|
+
return color + text + colorama.Style.RESET_ALL
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def prompt_path(is_file: bool, initial_path: Path) -> Path:
|
|
12
|
+
path_validator = click.Path(
|
|
13
|
+
exists=True,
|
|
14
|
+
file_okay=is_file,
|
|
15
|
+
dir_okay=not is_file,
|
|
16
|
+
path_type=Path,
|
|
17
|
+
)
|
|
18
|
+
while True:
|
|
19
|
+
try:
|
|
20
|
+
path_obj = path_validator.convert(initial_path.absolute(), None, None)
|
|
21
|
+
break
|
|
22
|
+
except click.BadParameter as e:
|
|
23
|
+
path_str = click.prompt(
|
|
24
|
+
str(e)
|
|
25
|
+
+ " Move it to that location, type the path or drag and drop it here. Then, press enter to continue",
|
|
26
|
+
default=str(initial_path),
|
|
27
|
+
show_default=False,
|
|
28
|
+
)
|
|
29
|
+
path_str = path_str.strip('"')
|
|
30
|
+
initial_path = Path(path_str)
|
|
31
|
+
return path_obj
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: muget
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: YouTube Music downloader with tagging support
|
|
5
|
+
Author: Meikoy-Chan
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/meikoy-chan/muget
|
|
8
|
+
Project-URL: Bug Reports, https://github.com/meikoy-chan/muget/issues
|
|
9
|
+
Keywords: youtube-music,downloader,yt-dlp,music
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Requires-Python: >=3.8
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
License-File: LICENSE
|
|
21
|
+
Requires-Dist: click
|
|
22
|
+
Requires-Dist: colorama
|
|
23
|
+
Requires-Dist: mutagen
|
|
24
|
+
Requires-Dist: Pillow
|
|
25
|
+
Requires-Dist: requests
|
|
26
|
+
Requires-Dist: yt-dlp
|
|
27
|
+
Requires-Dist: ytmusicapi
|
|
28
|
+
Requires-Dist: InquirerPy
|
|
29
|
+
Requires-Dist: yt_dlp_ejs
|
|
30
|
+
Dynamic: license-file
|
|
31
|
+
|
|
32
|
+
# Muget
|
|
33
|
+
|
|
34
|
+
YouTube Music downloader with automatic tagging and cover art.
|
|
35
|
+
|
|
36
|
+
## Installation
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pip install muget
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Usage
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
muget "https://music.youtube.com/playlist?list=..."
|
|
46
|
+
muget -o "./Music" "https://music.youtube.com/album/..."
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Requirements
|
|
50
|
+
|
|
51
|
+
· FFmpeg (required)
|
|
52
|
+
· aria2c (optional, for faster downloads)
|
|
53
|
+
|
|
54
|
+
Features
|
|
55
|
+
|
|
56
|
+
· Download tracks, albums, and playlists
|
|
57
|
+
· Automatic metadata tagging
|
|
58
|
+
· Cover art embedding
|
|
59
|
+
· Synced lyrics support
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
MANIFEST.in
|
|
3
|
+
README.md
|
|
4
|
+
pyproject.toml
|
|
5
|
+
muget/__init__.py
|
|
6
|
+
muget/__main__.py
|
|
7
|
+
muget/cli.py
|
|
8
|
+
muget/constants.py
|
|
9
|
+
muget/custom_logger_formatter.py
|
|
10
|
+
muget/downloader.py
|
|
11
|
+
muget/enums.py
|
|
12
|
+
muget/utils.py
|
|
13
|
+
muget.egg-info/PKG-INFO
|
|
14
|
+
muget.egg-info/SOURCES.txt
|
|
15
|
+
muget.egg-info/dependency_links.txt
|
|
16
|
+
muget.egg-info/entry_points.txt
|
|
17
|
+
muget.egg-info/requires.txt
|
|
18
|
+
muget.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
muget
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "muget"
|
|
7
|
+
version = "1.0.0"
|
|
8
|
+
description = "YouTube Music downloader with tagging support"
|
|
9
|
+
authors = [
|
|
10
|
+
{name="Meikoy-Chan"}
|
|
11
|
+
]
|
|
12
|
+
readme = "README.md"
|
|
13
|
+
requires-python = ">=3.8"
|
|
14
|
+
license = {text = "MIT"}
|
|
15
|
+
keywords = ["youtube-music", "downloader", "yt-dlp", "music"]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Programming Language :: Python :: 3.8",
|
|
19
|
+
"Programming Language :: Python :: 3.9",
|
|
20
|
+
"Programming Language :: Python :: 3.10",
|
|
21
|
+
"Programming Language :: Python :: 3.11",
|
|
22
|
+
"Programming Language :: Python :: 3.12",
|
|
23
|
+
"License :: OSI Approved :: MIT License",
|
|
24
|
+
"Operating System :: OS Independent",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
dependencies = [
|
|
28
|
+
"click",
|
|
29
|
+
"colorama",
|
|
30
|
+
"mutagen",
|
|
31
|
+
"Pillow",
|
|
32
|
+
"requests",
|
|
33
|
+
"yt-dlp",
|
|
34
|
+
"ytmusicapi",
|
|
35
|
+
"InquirerPy",
|
|
36
|
+
"yt_dlp_ejs"
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
[project.scripts]
|
|
40
|
+
muget = "muget.cli:main"
|
|
41
|
+
|
|
42
|
+
[project.urls]
|
|
43
|
+
"Homepage" = "https://github.com/meikoy-chan/muget"
|
|
44
|
+
"Bug Reports" = "https://github.com/meikoy-chan/muget/issues"
|
|
45
|
+
|
|
46
|
+
[tool.setuptools.packages.find]
|
|
47
|
+
where = ["."]
|
|
48
|
+
include = ["muget*"]
|
muget-1.0.0/setup.cfg
ADDED