Skip to content

Commit 8bc2362

Browse files
yezz123Silverarmorxnetcatphcreery
authored
🪶: Refactor Code Expression (spotDL#1390)
* 🪶: Refactor Code Expression (spotDL#1) * 🪶: Refactor Code Expression * 🪶: Refactor Code Expression * 🪶: Refactor Code Expression * Fix Linting Issue (Based on mypy & Flake8) * Using Black to Reformat Projects ✨(spotDL#2) * Revert Comments ✨ (spotDL#3) Co-authored-by: Silverarmor <[email protected]> Co-authored-by: Jakub Kot <[email protected]> Co-authored-by: Peyton Creery <[email protected]>
1 parent dba2fcc commit 8bc2362

13 files changed

+82
-110
lines changed

spotdl/download/downloader.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,7 @@ async def download_song(self, song_object: SongObject) -> None:
174174
audio_handler = YoutubeDL(
175175
{
176176
"format": ytdl_format,
177-
"outtmpl": f"{str(temp_folder)}/%(id)s.%(ext)s",
177+
"outtmpl": f"{temp_folder}/%(id)s.%(ext)s",
178178
"quiet": True,
179179
"no_warnings": True,
180180
"logger": YTDLLogger(),
@@ -270,14 +270,11 @@ def _perform_audio_download(
270270
# ! The actual download, if there is any error, it'll be here,
271271
try:
272272
data = audio_handler.extract_info(youtube_link)
273-
downloaded_file_path = Path(temp_folder / f"{data['id']}.{data['ext']}")
274-
275-
return downloaded_file_path
276-
except Exception as e: # noqa:E722
277273
# ! This is equivalent to a failed download, we do nothing, the song remains on
278274
# ! download_trackers download queue and all is well...
275+
return Path(temp_folder / f"{data['id']}.{data['ext']}")
276+
except Exception as e:
279277
temp_files = Path(temp_folder).glob(f"{converted_file_name}.*")
280278
for temp_file in temp_files:
281279
temp_file.unlink()
282-
283280
raise e

spotdl/download/embed_metadata.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,7 @@
3535
"explicit": "rtng",
3636
}
3737

38-
TAG_PRESET = {}
39-
for key in M4A_TAG_PRESET.keys():
40-
TAG_PRESET[key] = key
38+
TAG_PRESET = {key: key for key in M4A_TAG_PRESET}
4139

4240

4341
def _set_id3_mp3(converted_file_path: str, song_object: SongObject):
@@ -274,7 +272,7 @@ def _embed_cover(audio_file, song_object, encoding):
274272

275273
if encoding == "flac":
276274
audio_file.add_picture(image)
277-
elif encoding == "ogg" or encoding == "opus":
275+
elif encoding in ["ogg", "opus"]:
278276
# From the Mutagen docs (https://mutagen.readthedocs.io/en/latest/user/vcomment.html)
279277
image_data = image.write()
280278
encoded_data = base64.b64encode(image_data)

spotdl/download/ffmpeg.py

Lines changed: 26 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -20,36 +20,38 @@ def has_correct_version(
2020

2121
output = "".join(process.communicate())
2222

23-
if skip_version_check is False:
24-
result = re.search(r"ffmpeg version \w?(\d+\.)?(\d+)", output)
25-
26-
if result is not None:
27-
version = result.group(0).replace("ffmpeg version ", "")
28-
29-
# remove all non numeric characters from string example: n4.3
30-
version = re.sub(r"[a-zA-Z]", "", version)
23+
# remove all non numeric characters from string example: n4.3
24+
if skip_version_check:
25+
return True
3126

32-
if float(version) < 4.2:
33-
print(
34-
f"Your FFmpeg installation is too old ({version}), please update to 4.2+\n",
35-
file=sys.stderr,
36-
)
37-
return False
27+
result = re.search(r"ffmpeg version \w?(\d+\.)?(\d+)", output)
3828

39-
return True
40-
else:
41-
# fallback to copyright date check
42-
date_result = re.search(r"Copyright \(c\) \d\d\d\d\-\d\d\d\d", output)
29+
# fallback to copyright date check
30+
if result is not None:
31+
version = result.group(0).replace("ffmpeg version ", "")
4332

44-
if date_result is not None:
45-
date = date_result.group(0)
46-
if "2021" in date or "2020" in date:
47-
return True
33+
# remove all non numeric characters from string example: n4.3
34+
version = re.sub(r"[a-zA-Z]", "", version)
4835

49-
print("Your FFmpeg version couldn't be detected", file=sys.stderr)
36+
if float(version) < 4.2:
37+
print(
38+
f"Your FFmpeg installation is too old ({version}), please update to 4.2+\n",
39+
file=sys.stderr,
40+
)
5041
return False
51-
else:
42+
5243
return True
44+
else:
45+
# fallback to copyright date check
46+
date_result = re.search(r"Copyright \(c\) \d\d\d\d\-\d\d\d\d", output)
47+
48+
if date_result is not None:
49+
date = date_result.group(0)
50+
if "2021" in date or "2020" in date:
51+
return True
52+
53+
print("Your FFmpeg version couldn't be detected", file=sys.stderr)
54+
return False
5355

5456

5557
async def convert(

spotdl/download/progress_ui_handler.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -129,10 +129,7 @@ def print(self, *text, color="green"):
129129
if self.quiet:
130130
return
131131

132-
line = ""
133-
for item in text:
134-
line += str(item) + " "
135-
132+
line = "".join(str(item) + " " for item in text)
136133
if color:
137134
self._rich_progress_bar.console.print(f"[{color}]{line}")
138135
else:
@@ -271,7 +268,10 @@ def notify_error(self, e, tb):
271268
"""
272269
self.update(message="Error " + self.status)
273270

274-
message = f"Error: {e}\tWhile {self.status}: {self.song_object.display_name}\n {str(tb)}"
271+
message = (
272+
f"Error: {e}\tWhile {self.status}: {self.song_object.display_name}\n {tb}"
273+
)
274+
275275
self.parent.print(message, color="red")
276276

277277
def update(self, message=""):

spotdl/download/tracking_file_handler.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -72,10 +72,7 @@ def backup_to_disk(self):
7272
return None
7373

7474
# prepare datadumps of all songObj's yet to be downloaded
75-
song_data_dumps = []
76-
77-
for song in self.song_list:
78-
song_data_dumps.append(song.data_dump)
75+
song_data_dumps = [song.data_dump for song in self.song_list]
7976

8077
# ! the default naming of a tracking file is $nameOfFirstSOng.spotdlTrackingFile,
8178
# ! it needs a little fixing because of disallowed characters in file naming

spotdl/parsers/query_parser.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -115,10 +115,7 @@ def get_youtube_meta_track(
115115
)
116116

117117
song_name = raw_track_meta["name"]
118-
contributing_artist = []
119-
for artist in raw_track_meta["artists"]:
120-
contributing_artist.append(artist["name"])
121-
118+
contributing_artist = [artist["name"] for artist in raw_track_meta["artists"]]
122119
converted_file_name = SongObject.create_file_name(
123120
song_name, [artist["name"] for artist in raw_track_meta["artists"]]
124121
)

spotdl/providers/metadata_provider.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33

44
def from_url(spotify_url: str):
5-
if not ("open.spotify.com" in spotify_url and "track" in spotify_url):
5+
if "open.spotify.com" not in spotify_url or "track" not in spotify_url:
66
raise Exception(f"passed URL is not that of a track: {spotify_url}")
77

88
# query spotify for song, artist, album details

spotdl/providers/provider_utils.py

Lines changed: 12 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -26,17 +26,17 @@ def _match_percentage(str1: str, str2: str, score_cutoff: float = 0) -> float:
2626
# ! we build new strings that contain only alphanumerical characters and spaces
2727
# ! and return the partial_ratio of that
2828
except: # noqa:E722
29-
new_str1 = ""
30-
31-
for each_letter in str1:
32-
if each_letter.isalnum() or each_letter.isspace():
33-
new_str1 += each_letter
34-
35-
new_str2 = ""
36-
37-
for each_letter in str2:
38-
if each_letter.isalnum() or each_letter.isspace():
39-
new_str2 += each_letter
29+
new_str1 = "".join(
30+
each_letter
31+
for each_letter in str1
32+
if each_letter.isalnum() or each_letter.isspace()
33+
)
34+
35+
new_str2 = "".join(
36+
each_letter
37+
for each_letter in str2
38+
if each_letter.isalnum() or each_letter.isspace()
39+
)
4040

4141
return fuzz.partial_ratio(new_str1, new_str2, score_cutoff=score_cutoff)
4242

@@ -48,10 +48,7 @@ def _parse_duration(duration: str) -> float:
4848
try:
4949
# {(1, "s"), (60, "m"), (3600, "h")}
5050
mapped_increments = zip([1, 60, 3600], reversed(duration.split(":")))
51-
seconds = 0
52-
for multiplier, time in mapped_increments:
53-
seconds += multiplier * int(time)
54-
51+
seconds = sum(multiplier * int(time) for multiplier, time in mapped_increments)
5552
return float(seconds)
5653

5754
# ! This usually occurs when the wrong string is mistaken for the duration

spotdl/providers/ytm_provider.py

Lines changed: 19 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ def search_and_get_best_match(
5656
if (
5757
isrc_result is not None
5858
and "link" in isrc_result
59-
and name_match is True
59+
and name_match
6060
and time_match > 90
6161
):
6262
return isrc_result["link"]
@@ -97,7 +97,7 @@ def search_and_get_best_match(
9797
results = {**songs, **videos}
9898

9999
# No matches found
100-
if len(results) == 0:
100+
if not results:
101101
return None
102102

103103
result_items = list(results.items())
@@ -142,12 +142,11 @@ def _order_ytm_results(
142142

143143
sentence_words = lower_song_name.replace("-", " ").split(" ")
144144

145-
common_word = False
146-
147-
# ! check for common word
148-
for word in sentence_words:
149-
if word != "" and word in lower_result_name:
150-
common_word = True
145+
common_word = any(
146+
# ! check for common word
147+
word != "" and word in lower_result_name
148+
for word in sentence_words
149+
)
151150

152151
# ! if there are no common words, skip result
153152
if not common_word:
@@ -237,26 +236,25 @@ def _order_ytm_results(
237236
time_match = 100 - non_match_value
238237

239238
if result["type"] == "song":
240-
if album is not None:
239+
if album is None:
241240
# Don't add album_match to average_match if song_name == result and
242241
# result album name != song_album_name
243-
if (
244-
_match_percentage(album.lower(), result["name"].lower()) > 95
245-
and album.lower() != song_album_name.lower()
246-
):
247-
average_match = (artist_match + name_match + time_match) / 3
242+
average_match = (artist_match + name_match + time_match) / 3
243+
elif (
244+
_match_percentage(album.lower(), result["name"].lower()) > 95
245+
and album.lower() != song_album_name.lower()
246+
):
247+
average_match = (artist_match + name_match + time_match) / 3
248248
# Add album to average_match if song_name == result album
249249
# and result album name == song_album_name
250-
else:
251-
average_match = (
252-
artist_match + album_match + name_match + time_match
253-
) / 4
254250
else:
255-
average_match = (artist_match + name_match + time_match) / 3
256-
# Don't add album_match to average_match if we don't have information about the album
257-
# name in the metadata
251+
average_match = (
252+
artist_match + album_match + name_match + time_match
253+
) / 4
258254
else:
259255
average_match = (artist_match + name_match + time_match) / 3
256+
# Don't add album_match to average_match if we don't have information about the album
257+
# name in the metadata
260258

261259
# the results along with the avg Match
262260
links_with_match_value[result["link"]] = average_match

spotdl/search/song_gatherer.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ def from_spotify_url(http://github.com/%3C/div%3E%3C/code%3E%3C/div%3E%3C/td%3E%3C/tr%3E%3Ctr%20class=%22diff-line-row%22%3E%3Ctd%20data-grid-cell-id=%22diff-06e72073ce9e871a1fa2b825b4566e2489e26b4aee4603863f9dc82c777b4c95-64-64-0%22%20data-selected=%22false%22%20role=%22gridcell%22%20style=%22background-color:var(--bgColor-default);text-align:center" tabindex="-1" valign="top" class="focusable-grid-cell diff-line-number position-relative diff-line-number-neutral left-side">64
64
raise OSError(f"{converted_file_name} already downloaded")
6565

6666
# Get the song's downloadable audio link
67-
if use_youtube is True:
67+
if use_youtube:
6868
print(f'Searching YouTube for "{display_name}"', end="\r")
6969
youtube_link = yt_provider.search_and_get_best_match(
7070
song_name, contributing_artists, duration, isrc
@@ -112,13 +112,12 @@ def from_search_term(
112112
# return first result link or if no matches are found, raise Exception
113113
if result is None or len(result.get("tracks", {}).get("items", [])) == 0:
114114
raise Exception("No song matches found on Spotify")
115-
else:
116-
song_url = "http://open.spotify.com/track/" + result["tracks"]["items"][0]["id"]
117-
try:
118-
song = from_spotify_url(song_url, output_format, use_youtube)
119-
return [song] if song.youtube_link is not None else []
120-
except (LookupError, OSError, ValueError):
121-
return []
115+
song_url = "http://open.spotify.com/track/" + result["tracks"]["items"][0]["id"]
116+
try:
117+
song = from_spotify_url(song_url, output_format, use_youtube)
118+
return [song] if song.youtube_link is not None else []
119+
except (LookupError, OSError, ValueError):
120+
return []
122121

123122

124123
def from_album(

spotdl/search/song_object.py

Lines changed: 3 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,7 @@ def __init__(
1616
# Equals method
1717
# for example song_obj1 == song_obj2
1818
def __eq__(self, compared_song) -> bool:
19-
if compared_song.data_dump == self.data_dump:
20-
return True
21-
else:
22-
return False
19+
return compared_song.data_dump == self.data_dump
2320

2421
# ================================
2522
# === Interface Implementation ===
@@ -79,13 +76,7 @@ def contributing_artists(self) -> List[str]:
7976
# $contributingArtists + songName.mp3, we would want to end up with
8077
# 'Jetta, Mastubs - I'd love to change the world (Mastubs remix).mp3'
8178
# as a song name, it's dumb.
82-
83-
contributingArtists = []
84-
85-
for artist in self._raw_track_meta["artists"]:
86-
contributingArtists.append(artist["name"])
87-
88-
return contributingArtists
79+
return [artist["name"] for artist in self._raw_track_meta["artists"]]
8980

9081
@property
9182
def disc_number(self) -> int:
@@ -123,12 +114,7 @@ def album_artists(self) -> List[str]:
123114
artist.
124115
"""
125116

126-
albumArtists = []
127-
128-
for artist in self._raw_track_meta["album"]["artists"]:
129-
albumArtists.append(artist["name"])
130-
131-
return albumArtists
117+
return [artist["name"] for artist in self._raw_track_meta["album"]["artists"]]
132118

133119
@property
134120
def album_release(self) -> str:

tests/regressions.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
SONGS = {
77
"https://open.spotify.com/track/6CN3e26iQSj1N5lomh0mfO": "Eminem - Like Toy Soldiers.mp3",
8-
"https://open.spotify.com/track/3bNv3VuUOKgrf5hu3YcuRo": "Adele - Someone Like You.mp3"
8+
"https://open.spotify.com/track/3bNv3VuUOKgrf5hu3YcuRo": "Adele - Someone Like You.mp3",
99
}
1010

1111

tests/test_downloader.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,7 @@ def test_download_long_name_song(setup):
124124
with DownloadManager() as dm:
125125
dm.download_single_song(song_obj)
126126

127+
127128
def test_download_multiple_songs(pytestconfig, setup):
128129
if not "--disable-vcr" in pytestconfig.invocation_params.args:
129130
# this test is very similar to the other one, and the http request

0 commit comments

Comments
 (0)