Merge pull request #77 from nathom/master

Fixed bug where genre tag looked weird
This commit is contained in:
Vitiko 2021-02-26 23:02:07 -04:00 committed by GitHub
commit 24497d19b8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 55 additions and 26 deletions

View File

@ -30,13 +30,15 @@ def tqdm_download(url, fname, track_name):
def get_description(u: dict, track_title, multiple=None): def get_description(u: dict, track_title, multiple=None):
downloading_title = f'{track_title} [{u["bit_depth"]}/{u["sampling_rate"]}]' downloading_title = f'{track_title} '
f'[{u["bit_depth"]}/{u["sampling_rate"]}]'
if multiple: if multiple:
downloading_title = f"[Disc {multiple}] {downloading_title}" downloading_title = f"[Disc {multiple}] {downloading_title}"
return downloading_title return downloading_title
def get_format(client, item_dict, quality, is_track_id=False, track_url_dict=None): def get_format(client, item_dict, quality,
is_track_id=False, track_url_dict=None):
quality_met = True quality_met = True
if int(quality) == 5: if int(quality) == 5:
return "MP3", quality_met return "MP3", quality_met
@ -53,7 +55,8 @@ def get_format(client, item_dict, quality, is_track_id=False, track_url_dict=Non
restrictions = new_track_dict.get("restrictions") restrictions = new_track_dict.get("restrictions")
if isinstance(restrictions, list): if isinstance(restrictions, list):
if any( if any(
restriction.get("code") == QL_DOWNGRADE for restriction in restrictions restriction.get("code") == QL_DOWNGRADE
for restriction in restrictions
): ):
quality_met = False quality_met = False
if ( if (
@ -62,7 +65,8 @@ def get_format(client, item_dict, quality, is_track_id=False, track_url_dict=Non
): ):
return "FLAC", quality_met return "FLAC", quality_met
return ( return (
f'{new_track_dict["bit_depth"]}B-{new_track_dict["sampling_rate"]}Khz', f'{new_track_dict["bit_depth"]}B-'
f'{new_track_dict["sampling_rate"]}Khz',
quality_met, quality_met,
) )
except (KeyError, requests.exceptions.HTTPError): except (KeyError, requests.exceptions.HTTPError):
@ -112,7 +116,7 @@ def download_and_tag(
:param int tmp_count: Temporal download file number :param int tmp_count: Temporal download file number
:param dict track_url_dict: get_track_url dictionary from Qobuz client :param dict track_url_dict: get_track_url dictionary from Qobuz client
:param dict track_metadata: Track item dictionary from Qobuz client :param dict track_metadata: Track item dictionary from Qobuz client
:param dict album_or_track_metadata: Album/track dictionary from Qobuz client :param dict album_or_track_metadata: Album/track dict from Qobuz client
:param bool is_track :param bool is_track
:param bool is_mp3 :param bool is_mp3
:param bool embed_art: Embed cover art into file (FLAC-only) :param bool embed_art: Embed cover art into file (FLAC-only)
@ -135,13 +139,15 @@ def download_and_tag(
# Determine the filename # Determine the filename
artist = track_metadata.get("performer", {}).get("name") artist = track_metadata.get("performer", {}).get("name")
album_artist = track_metadata.get("album", {}).get("artist", {}).get("name") album_artist = track_metadata.get("album", {}).get("artist",
{}).get("name")
new_track_title = track_metadata.get("title") new_track_title = track_metadata.get("title")
version = track_metadata.get("version") version = track_metadata.get("version")
if artist or album_artist: if artist or album_artist:
new_track_title = ( new_track_title = (
f"{artist if artist else album_artist}" f' - {track_metadata["title"]}' f"{artist if artist else album_artist}"
f' - {track_metadata["title"]}'
) )
if version: if version:
new_track_title = f"{new_track_title} ({version})" new_track_title = f"{new_track_title} ({version})"
@ -215,11 +221,13 @@ def download_id_by_type(
album_format, quality_met = get_format(client, meta, quality) album_format, quality_met = get_format(client, meta, quality)
if not downgrade_quality and not quality_met: if not downgrade_quality and not quality_met:
logger.info( logger.info(
f"{OFF}Skipping {album_title} as doesn't met quality requirement" f"{OFF}Skipping {album_title} as it doesn't "
"meet quality requirement"
) )
return return
logger.info(f"\n{YELLOW}Downloading: {album_title}\nQuality: {album_format}\n") logger.info(f"\n{YELLOW}Downloading: {album_title}\n"
f"Quality: {album_format}\n")
dirT = ( dirT = (
meta["artist"]["name"], meta["artist"]["name"],
album_title, album_title,
@ -233,14 +241,16 @@ def download_id_by_type(
if no_cover: if no_cover:
logger.info(f"{OFF}Skipping cover") logger.info(f"{OFF}Skipping cover")
else: else:
get_extra(meta["image"]["large"], dirn, og_quality=cover_og_quality) get_extra(meta["image"]["large"], dirn,
og_quality=cover_og_quality)
if "goodies" in meta: if "goodies" in meta:
try: try:
get_extra(meta["goodies"][0]["url"], dirn, "booklet.pdf") get_extra(meta["goodies"][0]["url"], dirn, "booklet.pdf")
except: # noqa except: # noqa
pass pass
media_numbers = [track["media_number"] for track in meta["tracks"]["items"]] media_numbers = [track["media_number"] for track in
meta["tracks"]["items"]]
is_multiple = True if len([*{*media_numbers}]) > 1 else False is_multiple = True if len([*{*media_numbers}]) > 1 else False
for i in meta["tracks"]["items"]: for i in meta["tracks"]["items"]:
parse = client.get_track_url(i["id"], quality) parse = client.get_track_url(i["id"], quality)
@ -267,10 +277,12 @@ def download_id_by_type(
meta = client.get_track_meta(item_id) meta = client.get_track_meta(item_id)
track_title = get_title(meta) track_title = get_title(meta)
logger.info(f"\n{YELLOW}Downloading: {track_title}") logger.info(f"\n{YELLOW}Downloading: {track_title}")
track_format, quality_met = get_format(client, meta, quality, True, parse) track_format, quality_met = get_format(client, meta,
quality, True, parse)
if not downgrade_quality and not quality_met: if not downgrade_quality and not quality_met:
logger.info( logger.info(
f"{OFF}Skipping {track_title} as doesn't met quality requirement" f"{OFF}Skipping {track_title} as it doesn't "
"meet quality requirement"
) )
return return
dirT = ( dirT = (
@ -279,17 +291,21 @@ def download_id_by_type(
meta["album"]["release_date_original"].split("-")[0], meta["album"]["release_date_original"].split("-")[0],
track_format, track_format,
) )
sanitized_title = sanitize_filename("{} - {} [{}] [{}]".format(*dirT)) sanitized_title = sanitize_filename(
"{} - {} [{}] [{}]".format(*dirT)
)
dirn = os.path.join(path, sanitized_title) dirn = os.path.join(path, sanitized_title)
os.makedirs(dirn, exist_ok=True) os.makedirs(dirn, exist_ok=True)
if no_cover: if no_cover:
logger.info(f"{OFF}Skipping cover") logger.info(f"{OFF}Skipping cover")
else: else:
get_extra( get_extra(
meta["album"]["image"]["large"], dirn, og_quality=cover_og_quality meta["album"]["image"]["large"], dirn,
og_quality=cover_og_quality
) )
is_mp3 = True if int(quality) == 5 else False is_mp3 = True if int(quality) == 5 else False
download_and_tag(dirn, count, parse, meta, meta, True, is_mp3, embed_art) download_and_tag(dirn, count, parse, meta,
meta, True, is_mp3, embed_art)
else: else:
logger.info(f"{OFF}Demo. Skipping") logger.info(f"{OFF}Demo. Skipping")
logger.info(f"{GREEN}Completed") logger.info(f"{GREEN}Completed")

View File

@ -30,6 +30,19 @@ def _format_copyright(s: str) -> str:
return s return s
def _format_genres(genres: list) -> str:
'''Fixes the weirdly formatted genre lists returned by the API.
>>> g = ['Pop/Rock', 'Pop/Rock→Rock', 'Pop/Rock→Rock→Alternatif et Indé']
>>> _format_genres(g)
'Pop/Rock, Rock, Alternatif et Indé'
'''
if genres == []:
return ''
else:
return ', '.join(genres[-1].split('\u2192'))
# Use KeyError catching instead of dict.get to avoid empty tags # Use KeyError catching instead of dict.get to avoid empty tags
def tag_flac(filename, root_dir, final_name, d, album, def tag_flac(filename, root_dir, final_name, d, album,
istrack=True, em_image=False): istrack=True, em_image=False):
@ -72,17 +85,17 @@ def tag_flac(filename, root_dir, final_name, d, album,
pass pass
if istrack: if istrack:
audio["GENRE"] = ", ".join(d["album"]["genres_list"]) # GENRE audio["GENRE"] = _format_genres(d["album"]["genres_list"])
audio["ALBUMARTIST"] = d["album"]["artist"]["name"] # ALBUM ARTIST audio["ALBUMARTIST"] = d["album"]["artist"]["name"]
audio["TRACKTOTAL"] = str(d["album"]["tracks_count"]) # TRACK TOTAL audio["TRACKTOTAL"] = str(d["album"]["tracks_count"])
audio["ALBUM"] = d["album"]["title"] # ALBUM TITLE audio["ALBUM"] = d["album"]["title"]
audio["DATE"] = d["album"]["release_date_original"] audio["DATE"] = d["album"]["release_date_original"]
audio["COPYRIGHT"] = _format_copyright(d["copyright"]) audio["COPYRIGHT"] = _format_copyright(d["copyright"])
else: else:
audio["GENRE"] = ", ".join(album["genres_list"]) # GENRE audio["GENRE"] = _format_genres(album["genres_list"])
audio["ALBUMARTIST"] = album["artist"]["name"] # ALBUM ARTIST audio["ALBUMARTIST"] = album["artist"]["name"]
audio["TRACKTOTAL"] = str(album["tracks_count"]) # TRACK TOTAL audio["TRACKTOTAL"] = str(album["tracks_count"])
audio["ALBUM"] = album["title"] # ALBUM TITLE audio["ALBUM"] = album["title"]
audio["DATE"] = album["release_date_original"] audio["DATE"] = album["release_date_original"]
audio["COPYRIGHT"] = _format_copyright(album["copyright"]) audio["COPYRIGHT"] = _format_copyright(album["copyright"])
@ -161,14 +174,14 @@ def tag_mp3(filename, root_dir, final_name, d, album,
tags['artist'] = album["artist"]["name"] tags['artist'] = album["artist"]["name"]
if istrack: if istrack:
tags["genre"] = ", ".join(d["album"]["genres_list"]) tags["genre"] = _format_genres(d["album"]["genres_list"])
tags["albumartist"] = d["album"]["artist"]["name"] tags["albumartist"] = d["album"]["artist"]["name"]
tags["album"] = d["album"]["title"] tags["album"] = d["album"]["title"]
tags["date"] = d["album"]["release_date_original"] tags["date"] = d["album"]["release_date_original"]
tags["copyright"] = _format_copyright(d["copyright"]) tags["copyright"] = _format_copyright(d["copyright"])
tracktotal = str(d["album"]["tracks_count"]) tracktotal = str(d["album"]["tracks_count"])
else: else:
tags["genre"] = ", ".join(album["genres_list"]) tags["genre"] = _format_genres(album["genres_list"])
tags["albumartist"] = album["artist"]["name"] tags["albumartist"] = album["artist"]["name"]
tags["album"] = album["title"] tags["album"] = album["title"]
tags["date"] = album["release_date_original"] tags["date"] = album["release_date_original"]