mirror of
https://github.com/KevinMidboe/spotify-downloader.git
synced 2025-10-29 18:00:15 +00:00
Apply most best practices of PEP 8
This refactoring includes:
- Two empty lines before each global function
- Using '{0} {1}'.format(str1, str2) instead of str1 + ' ' + str2
Sometimes this will make lines longer, sometimes shorter.
- Starting all comments with # + space + comment
- Make lines not longer than 80 characters in most cases
- Renaming some variables to make more sense
- Add some missing code like returns and Exceptions
Not included, but follows:
- Make some comments docstrings
- Rename all 'file' variables, only for Python 2
- Remove some way too verbose comments ;)
This commit is contained in:
@@ -2,6 +2,7 @@ import subprocess
|
||||
import os
|
||||
import sys
|
||||
|
||||
|
||||
def song(input_song, output_song, avconv=False, verbose=False):
|
||||
if not input_song == output_song:
|
||||
if sys.version_info < (3, 0):
|
||||
@@ -11,10 +12,11 @@ def song(input_song, output_song, avconv=False, verbose=False):
|
||||
if avconv:
|
||||
exit_code = convert_with_avconv(input_song, output_song, verbose)
|
||||
else:
|
||||
exit_code = convert_with_FFmpeg(input_song, output_song, verbose)
|
||||
exit_code = convert_with_ffmpeg(input_song, output_song, verbose)
|
||||
return exit_code
|
||||
return None
|
||||
|
||||
|
||||
def convert_with_avconv(input_song, output_song, verbose):
|
||||
# different path for windows
|
||||
if os.name == 'nt':
|
||||
@@ -33,10 +35,10 @@ def convert_with_avconv(input_song, output_song, verbose):
|
||||
'-ab', '192k',
|
||||
'Music/' + output_song]
|
||||
|
||||
subprocess.call(command)
|
||||
return subprocess.call(command)
|
||||
|
||||
|
||||
def convert_with_FFmpeg(input_song, output_song, verbose):
|
||||
def convert_with_ffmpeg(input_song, output_song, verbose):
|
||||
# What are the differences and similarities between ffmpeg, libav, and avconv?
|
||||
# https://stackoverflow.com/questions/9477115
|
||||
# ffmeg encoders high to lower quality
|
||||
@@ -54,6 +56,7 @@ def convert_with_FFmpeg(input_song, output_song, verbose):
|
||||
if not verbose:
|
||||
ffmpeg_pre += '-hide_banner -nostats -v panic '
|
||||
|
||||
ffmpeg_params = ''
|
||||
input_ext = input_song.split('.')[-1]
|
||||
output_ext = output_song.split('.')[-1]
|
||||
|
||||
@@ -69,10 +72,8 @@ def convert_with_FFmpeg(input_song, output_song, verbose):
|
||||
elif output_ext == 'm4a':
|
||||
ffmpeg_params = '-cutoff 20000 -c:a libfdk_aac -b:a 192k -vn '
|
||||
|
||||
command = (ffmpeg_pre +
|
||||
'-i Music/' + input_song + ' ' +
|
||||
ffmpeg_params +
|
||||
'Music/' + output_song + '').split(' ')
|
||||
command = '{0}-i Music/{1} {2}Music/{4}'.format(
|
||||
ffmpeg_pre, input_song, ffmpeg_params, output_song).split(' ')
|
||||
|
||||
subprocess.call(command)
|
||||
return subprocess.call(command)
|
||||
|
||||
|
||||
@@ -9,8 +9,10 @@ try:
|
||||
except ImportError:
|
||||
import urllib.request as urllib2
|
||||
|
||||
|
||||
# check if input file title matches with expected title
|
||||
def compare(file, metadata):
|
||||
already_tagged = False
|
||||
try:
|
||||
if file.endswith('.mp3'):
|
||||
audiofile = EasyID3('Music/' + file)
|
||||
@@ -22,9 +24,10 @@ def compare(file, metadata):
|
||||
# fetch track title metadata
|
||||
already_tagged = audiofile[tags['title']] == metadata['name']
|
||||
except KeyError:
|
||||
already_tagged = False
|
||||
pass
|
||||
return already_tagged
|
||||
|
||||
|
||||
def embed(music_file, meta_tags):
|
||||
if sys.version_info < (3, 0):
|
||||
music_file = music_file.encode('utf-8')
|
||||
@@ -41,6 +44,7 @@ def embed(music_file, meta_tags):
|
||||
print('Cannot embed meta-tags into given output extension')
|
||||
return False
|
||||
|
||||
|
||||
def embed_mp3(music_file, meta_tags):
|
||||
# EasyID3 is fun to use ;)
|
||||
audiofile = EasyID3('Music/' + music_file)
|
||||
@@ -48,7 +52,8 @@ def embed_mp3(music_file, meta_tags):
|
||||
audiofile['albumartist'] = meta_tags['artists'][0]['name']
|
||||
audiofile['album'] = meta_tags['album']['name']
|
||||
audiofile['title'] = meta_tags['name']
|
||||
audiofile['tracknumber'] = [meta_tags['track_number'], meta_tags['total_tracks']]
|
||||
audiofile['tracknumber'] = [meta_tags['track_number'],
|
||||
meta_tags['total_tracks']]
|
||||
audiofile['discnumber'] = [meta_tags['disc_number'], 0]
|
||||
audiofile['date'] = meta_tags['release_date']
|
||||
audiofile['originaldate'] = meta_tags['release_date']
|
||||
@@ -68,11 +73,13 @@ def embed_mp3(music_file, meta_tags):
|
||||
audiofile.save(v2_version=3)
|
||||
audiofile = ID3('Music/' + music_file)
|
||||
albumart = urllib2.urlopen(meta_tags['album']['images'][0]['url'])
|
||||
audiofile["APIC"] = APIC(encoding=3, mime='image/jpeg', type=3, desc=u'Cover', data=albumart.read())
|
||||
audiofile["APIC"] = APIC(encoding=3, mime='image/jpeg', type=3,
|
||||
desc=u'Cover', data=albumart.read())
|
||||
albumart.close()
|
||||
audiofile.save(v2_version=3)
|
||||
return True
|
||||
|
||||
|
||||
def embed_m4a(music_file, meta_tags):
|
||||
# Apple has specific tags - see mutagen docs -
|
||||
# http://mutagen.readthedocs.io/en/latest/api/mp4.html
|
||||
@@ -98,7 +105,8 @@ def embed_m4a(music_file, meta_tags):
|
||||
audiofile[tags['albumartist']] = meta_tags['artists'][0]['name']
|
||||
audiofile[tags['album']] = meta_tags['album']['name']
|
||||
audiofile[tags['title']] = meta_tags['name']
|
||||
audiofile[tags['tracknumber']] = [(meta_tags['track_number'], meta_tags['total_tracks'])]
|
||||
audiofile[tags['tracknumber']] = [(meta_tags['track_number'],
|
||||
meta_tags['total_tracks'])]
|
||||
audiofile[tags['disknumber']] = [(meta_tags['disc_number'], 0)]
|
||||
audiofile[tags['date']] = meta_tags['release_date']
|
||||
audiofile[tags['originaldate']] = meta_tags['release_date']
|
||||
@@ -107,7 +115,8 @@ def embed_m4a(music_file, meta_tags):
|
||||
if meta_tags['copyright']:
|
||||
audiofile[tags['copyright']] = meta_tags['copyright']
|
||||
albumart = urllib2.urlopen(meta_tags['album']['images'][0]['url'])
|
||||
audiofile[tags['albumart']] = [ MP4Cover(albumart.read(), imageformat=MP4Cover.FORMAT_JPEG) ]
|
||||
audiofile[tags['albumart']] = [MP4Cover(
|
||||
albumart.read(), imageformat=MP4Cover.FORMAT_JPEG)]
|
||||
albumart.close()
|
||||
audiofile.save()
|
||||
return True
|
||||
|
||||
88
core/misc.py
88
core/misc.py
@@ -6,15 +6,16 @@ import spotipy.oauth2 as oauth2
|
||||
|
||||
try:
|
||||
from urllib2 import quote
|
||||
except:
|
||||
except ImportError:
|
||||
from urllib.request import quote
|
||||
|
||||
|
||||
# method to input (user playlists) and (track when using manual mode)
|
||||
def input_link(links):
|
||||
while True:
|
||||
try:
|
||||
the_chosen_one = int(user_input('>> Choose your number: '))
|
||||
if the_chosen_one >= 1 and the_chosen_one <= len(links):
|
||||
if 1 <= the_chosen_one <= len(links):
|
||||
return links[the_chosen_one - 1]
|
||||
elif the_chosen_one == 0:
|
||||
return None
|
||||
@@ -23,6 +24,7 @@ def input_link(links):
|
||||
except ValueError:
|
||||
print('Choose a valid number!')
|
||||
|
||||
|
||||
# take input correctly for both python2 & 3
|
||||
def user_input(string=''):
|
||||
if sys.version_info > (3, 0):
|
||||
@@ -30,41 +32,51 @@ def user_input(string=''):
|
||||
else:
|
||||
return raw_input(string)
|
||||
|
||||
|
||||
# remove first song from .txt
|
||||
def trim_song(file):
|
||||
with open(file, 'r') as fin:
|
||||
data = fin.read().splitlines(True)
|
||||
with open(file, 'w') as fout:
|
||||
fout.writelines(data[1:])
|
||||
with open(file, 'r') as file_in:
|
||||
data = file_in.read().splitlines(True)
|
||||
with open(file, 'w') as file_out:
|
||||
file_out.writelines(data[1:])
|
||||
|
||||
|
||||
def get_arguments():
|
||||
parser = argparse.ArgumentParser(description='Download and convert songs \
|
||||
from Spotify, Youtube etc.',
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
||||
parser = argparse.ArgumentParser(
|
||||
description='Download and convert songs from Spotify, Youtube etc.',
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
||||
group = parser.add_mutually_exclusive_group(required=True)
|
||||
|
||||
group.add_argument('-s', '--song',
|
||||
help='download song by spotify link or name')
|
||||
group.add_argument('-l', '--list',
|
||||
help='download songs from a file')
|
||||
group.add_argument('-u', '--username',
|
||||
help="load user's playlists into <playlist_name>.txt")
|
||||
parser.add_argument('-m', '--manual', default=False,
|
||||
help='choose the song to download manually', action='store_true')
|
||||
parser.add_argument('-nm', '--no-metadata', default=False,
|
||||
help='do not embed metadata in songs', action='store_true')
|
||||
parser.add_argument('-a', '--avconv', default=False,
|
||||
help='Use avconv for conversion otherwise set defaults to ffmpeg',
|
||||
action='store_true')
|
||||
parser.add_argument('-v', '--verbose', default=False,
|
||||
help='show debug output', action='store_true')
|
||||
parser.add_argument('-i', '--input_ext', default='.m4a',
|
||||
help='prefered input format .m4a or .webm (Opus)')
|
||||
parser.add_argument('-o', '--output_ext', default='.mp3',
|
||||
help='prefered output extension .mp3 or .m4a (AAC)')
|
||||
group.add_argument(
|
||||
'-s', '--song', help='download song by spotify link or name')
|
||||
group.add_argument(
|
||||
'-l', '--list', help='download songs from a file')
|
||||
group.add_argument(
|
||||
'-u', '--username',
|
||||
help="load user's playlists into <playlist_name>.txt")
|
||||
parser.add_argument(
|
||||
'-m', '--manual', default=False,
|
||||
help='choose the song to download manually', action='store_true')
|
||||
parser.add_argument(
|
||||
'-nm', '--no-metadata', default=False,
|
||||
help='do not embed metadata in songs', action='store_true')
|
||||
parser.add_argument(
|
||||
'-a', '--avconv', default=False,
|
||||
help='Use avconv for conversion otherwise set defaults to ffmpeg',
|
||||
action='store_true')
|
||||
parser.add_argument(
|
||||
'-v', '--verbose', default=False, help='show debug output',
|
||||
action='store_true')
|
||||
parser.add_argument(
|
||||
'-i', '--input_ext', default='.m4a',
|
||||
help='prefered input format .m4a or .webm (Opus)')
|
||||
parser.add_argument(
|
||||
'-o', '--output_ext', default='.mp3',
|
||||
help='prefered output extension .mp3 or .m4a (AAC)')
|
||||
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
# check if input song is spotify link
|
||||
def is_spotify(raw_song):
|
||||
if (len(raw_song) == 22 and raw_song.replace(" ", "%20") == raw_song) or (raw_song.find('spotify') > -1):
|
||||
@@ -72,6 +84,7 @@ def is_spotify(raw_song):
|
||||
else:
|
||||
return False
|
||||
|
||||
|
||||
# generate filename of the song to be downloaded
|
||||
def generate_filename(title):
|
||||
# IMO python2 sucks dealing with unicode
|
||||
@@ -82,40 +95,45 @@ def generate_filename(title):
|
||||
filename = slugify(title, ok='-_()[]{}', lower=False)
|
||||
return fix_encoding(filename)
|
||||
|
||||
|
||||
# please respect these credentials :)
|
||||
def generate_token():
|
||||
creds = oauth2.SpotifyClientCredentials(
|
||||
credentials = oauth2.SpotifyClientCredentials(
|
||||
client_id='4fe3fecfe5334023a1472516cc99d805',
|
||||
client_secret='0f02b7c483c04257984695007a4a8d5c')
|
||||
token = creds.get_access_token()
|
||||
token = credentials.get_access_token()
|
||||
return token
|
||||
|
||||
|
||||
def generate_search_url(song):
|
||||
# urllib2.quote() encodes URL with special characters
|
||||
url = "https://www.youtube.com/results?sp=EgIQAQ%253D%253D&q=" + quote(song)
|
||||
url = "https://www.youtube.com/results?sp=EgIQAQ%253D%253D&q={0}".format(
|
||||
quote(song))
|
||||
return url
|
||||
|
||||
|
||||
# fix encoding issues in python2
|
||||
def fix_encoding(query):
|
||||
if sys.version_info < (3, 0):
|
||||
query = query.encode('utf-8')
|
||||
return query
|
||||
|
||||
|
||||
def fix_decoding(query):
|
||||
if sys.version_info < (3, 0):
|
||||
query = query.decode('utf-8')
|
||||
return query
|
||||
|
||||
|
||||
def filter_path(path):
|
||||
os.chdir(sys.path[0])
|
||||
if not os.path.exists(path):
|
||||
os.makedirs(path)
|
||||
for temp in os.listdir(path):
|
||||
if temp.endswith('.temp'):
|
||||
os.remove(path + '/' + temp)
|
||||
os.remove('{0}/{1}'.format(path, temp))
|
||||
|
||||
|
||||
def grace_quit():
|
||||
print('')
|
||||
print('')
|
||||
print('Exitting..')
|
||||
print('\n\nExiting.')
|
||||
sys.exit()
|
||||
|
||||
Reference in New Issue
Block a user