improved code quality

This commit is contained in:
Ritiek Malhotra
2016-12-01 09:57:09 +05:30
committed by GitHub
parent 44528217e0
commit 0fbaad4153

435
spotdl.py
View File

@@ -1,7 +1,7 @@
#!/bin/python #!/bin/python
import mechanize
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
import mechanize
import pafy import pafy
import os import os
import sys import sys
@@ -9,13 +9,8 @@ import spotipy
import eyed3 import eyed3
#import spotipy.util as util #import spotipy.util as util
#print sys.path[0] #print(sys.path[0])
if not os.name == 'nt': os.chdir(sys.path[0] + '/')
script_dir = sys.path[0] + '/'
else:
script_dir = sys.path[0] + '\\'
os.chdir(script_dir)
if not os.path.exists("Music"): if not os.path.exists("Music"):
os.makedirs("Music") os.makedirs("Music")
@@ -23,229 +18,217 @@ open('Music/list.txt', 'a').close()
spotify = spotipy.Spotify() spotify = spotipy.Spotify()
print '' print('')
def Main(): def loadMechanize():
Title = '' global br
song = '' br = mechanize.Browser()
while True: br.set_handle_robots(False)
try: br.addheaders = [("User-agent","Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.13) Gecko/20101206 Ubuntu/10.10 (maverick) Firefox/3.6.13")]
for m in os.listdir('Music/'):
if m.endswith(".temp") or m.endswith(".m4a"):
os.remove('Music/' + m)
print('')
print('')
raw_song = raw_input('>> Enter a song/cmd: ').decode('utf-8').encode('utf-8')
print ''
if raw_song == "exit":
exit()
elif raw_song == "play":
if not Title == '':
if not os.name == 'nt':
os.system('mplayer "' + script_dir + 'Music/' + Title + '.mp3"')
else:
print 'Playing..'
os.system('start ' + script_dir + 'Music\\' + Title + '.mp3')
elif raw_song == "lyrics": def searchYT(number):
br = mechanize.Browser() #print(URL)
br.set_handle_robots(False) items = br.open(URL)
br.addheaders = [("User-agent","Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.13) Gecko/20101206 Ubuntu/10.10 (maverick) Firefox/3.6.13")] #print(items)
if not Title == '': items = items.read()
if song == '': #print(items)
link = 'https://duckduckgo.com/html/?q=' + Title.replace(' ', '+') + '+musixmatch' zoom1 = items.find('yt-uix-tile-link')
else: zoom2 = items.find('yt-uix-tile-link', zoom1+1)
link = 'https://duckduckgo.com/html/?q=' + song.replace(' ', '+') + '+musixmatch' zoom3 = items.find('yt-uix-tile-link', zoom2+1)
page = br.open(link) part = items[zoom1-100: zoom2]
page = page.read() items_parse = BeautifulSoup(part, "html.parser")
soup = BeautifulSoup(page, 'html.parser')
link = soup.find('a', {'class':'result__url'})['href']
page = br.open(link).read()
soup = BeautifulSoup(page, 'html.parser')
for x in soup.find_all('p', {'class':'mxm-lyrics__content'}):
print x.get_text()
else:
print 'No log to read from..'
br.close()
elif raw_song == "list": #items_parse = soup(items, "html.parser")
f = open('Music/list.txt', 'r').read() first_result = items_parse.find(attrs={'class':'yt-uix-tile-link'})['href']
lines = f.splitlines()
x = 0
y = 0
for songie in lines:
if not len(songie) == 0:
x = x + 1
print 'Total songs in list = ' + str(x) + ' songs'
for songie in lines:
try:
if not len(songie) == 0:
if (len(songie) == 22 and songie.replace(" ", "%20") == songie) or (songie.find('spotify') > -1):
#song = songie.replace(songie[-1:], "")
song = songie
content = spotify.track(song)
song = (content['artists'][0]['name'] + ' - ' + content['name']).replace(" ", "%20").encode('utf-8')
URL = "https://www.youtube.com/results?sp=EgIQAQ%253D%253D&q=" + song
else:
song = songie.replace(" ", "%20")
URL = "https://www.youtube.com/results?sp=EgIQAQ%253D%253D&q=" + song
song = ''
print '' full_link = "youtube.com" + first_result
br = mechanize.Browser() #print(full_link)
br.set_handle_robots(False) global video
br.addheaders = [("User-agent","Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.13) Gecko/20101206 Ubuntu/10.10 (maverick) Firefox/3.6.13")] video = pafy.new(full_link)
#print URL global title
items = br.open(URL) title = ((video.title).replace("\\", "_").replace("/", "_").replace(":", "_").replace("*", "_").replace("?", "_").replace('"', "_").replace("<", "_").replace(">", "_").replace("|", "_").replace(" ", "_")).encode('utf-8')
#print items if not number == None:
items = items.read() print(str(number) + '. ' + (video.title).encode("utf-8"))
#print items else:
zoom1 = items.find('yt-uix-tile-link') print(video.title).encode("utf-8")
zoom2 = items.find('yt-uix-tile-link', zoom1+1)
zoom3 = items.find('yt-uix-tile-link', zoom2+1)
part = items[zoom1-100: zoom2]
items_parse = BeautifulSoup(part, "html.parser")
#items_parse = soup(items, "html.parser")
first_result = items_parse.find(attrs={'class':'yt-uix-tile-link'})['href']
full_link = "youtube.com" + first_result
#print full_link
video = pafy.new(full_link)
Title = ((video.title).replace("\\", "_").replace("/", "_").replace(":", "_").replace("*", "_").replace("?", "_").replace('"', "_").replace("<", "_").replace(">", "_").replace("|", "_").replace(" ", "_")).encode('utf-8')
y = y + 1
print str(y) + '. ' + ((video.title).encode("utf-8"))
if os.path.exists("Music/" + Title + ".m4a.temp"):
os.remove("Music/" + Title + ".m4a.temp")
download = 1
if os.path.exists("Music/" + Title + ".mp3"):
audiofile = eyed3.load("Music/" + Title + '.mp3')
if ((len(raw_song) == 22 and raw_song.replace(" ", "%20") == raw_song) or (raw_song.find('spotify') > -1)) and not audiofile.tag.title == content['name']:
os.remove("Music/" + Title + '.mp3')
else:
with open('Music/list.txt', 'r') as fin:
data = fin.read().splitlines(True)
with open('Music/list.txt', 'w') as fout:
fout.writelines(data[1:])
download = 0
if download == 1:
a = video.getbestaudio(preftype='m4a')
a.download(filepath="Music/" + Title + ".m4a")
with open('Music/list.txt', 'r') as fin:
data = fin.read().splitlines(True)
with open('Music/list.txt', 'w') as fout:
fout.writelines(data[1:])
print ''
print 'Converting ' + Title + '.m4a' + ' to mp3..'
if not os.name == 'nt':
os.system('avconv -loglevel 0 -i "' + script_dir + 'Music/' + Title + '.m4a" -ab 192k "' + script_dir + 'Music/' + Title + '.mp3"')
else:
os.system('Scripts\\avconv.exe -loglevel 0 -i "' + script_dir + 'Music/' + Title + '.m4a" -ab 192k "' + script_dir + 'Music/' + Title + '.mp3"')
os.remove('Music/' + Title + '.m4a')
if (len(songie) == 22 and songie.replace(" ", "%20") == songie) or (songie.find('spotify') > -1):
print 'Fixing meta-tags..'
audiofile = eyed3.load("Music/" + Title + '.mp3')
audiofile.tag.artist = content['artists'][0]['name']
audiofile.tag.album = content['album']['name']
audiofile.tag.title = content['name']
br.retrieve(content['album']['images'][0]['url'], 'Music/last_albumart.jpg')
bla = open("Music/last_albumart.jpg","rb").read()
audiofile.tag.images.set(3,bla,"image/jpeg")
audiofile.tag.save()
else:
with open('Music/list.txt', 'r') as fin:
data = fin.read().splitlines(True)
with open('Music/list.txt', 'w') as fout:
fout.writelines(data[1:])
except KeyboardInterrupt:
Main()
except:
lines.append(songie)
with open('Music/list.txt', 'r') as fin:
data = fin.read().splitlines(True)
with open('Music/list.txt', 'w') as fout:
fout.writelines(data[1:])
with open("Music/list.txt", "a") as myfile:
myfile.write(songie)
print 'Could not complete a Song download, will try later..'
br.close()
else:
song = raw_song.replace(" ", "%20")
br = mechanize.Browser()
br.set_handle_robots(False)
br.addheaders = [("User-agent","Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.13) Gecko/20101206 Ubuntu/10.10 (maverick) Firefox/3.6.13")]
if (len(raw_song) == 22 and raw_song == song) or (raw_song.find('spotify') > -1):
content = spotify.track(song)
song = (content['artists'][0]['name'] + ' - ' + content['name']).replace(" ", "%20").encode('utf-8')
URL = "https://www.youtube.com/results?sp=EgIQAQ%253D%253D&q=" + song
else:
URL = "https://www.youtube.com/results?sp=EgIQAQ%253D%253D&q=" + song
song = ''
items = br.open(URL)
items = items.read()
zoom1 = items.find('yt-uix-tile-link')
zoom2 = items.find('yt-uix-tile-link', zoom1+1)
zoom3 = items.find('yt-uix-tile-link', zoom2+1)
part = items[zoom1-100: zoom2]
items_parse = BeautifulSoup(part, "html.parser")
#items_parse = soup(items, "html.parser")
first_result = items_parse.find(attrs={'class':'yt-uix-tile-link'})['href']
full_link = "youtube.com" + first_result
#print full_link
video = pafy.new(full_link)
Title = ((video.title).replace("\\", "_").replace("/", "_").replace(":", "_").replace("*", "_").replace("?", "_").replace('"', "_").replace("<", "_").replace(">", "_").replace("|", "_").replace(" ", "_")).encode('utf-8')
print ((video.title).encode("utf-8"))
if os.path.exists("Music/" + Title + ".m4a.temp"):
os.remove("Music/" + Title + ".m4a.temp")
def checkExists(islist):
if os.path.exists("Music/" + title + ".m4a.temp"):
os.remove("Music/" + title + ".m4a.temp")
if os.path.exists("Music/" + title + ".mp3"):
audiofile = eyed3.load("Music/" + title + '.mp3')
if isSpotify() and not audiofile.tag.title == content['name']:
os.remove("Music/" + title + '.mp3')
elif islist:
trimSong()
return True
else:
prompt = raw_input('Song with same name has already been downloaded.. re-download? (y/n/play): ')
if prompt == "y":
os.remove("Music/" + title + ".mp3")
download = 1 download = 1
elif prompt =="play":
if not os.name == 'nt':
os.system('mplayer "' + 'Music/' + title + '.mp3"')
else:
print('Playing ' + title + '.mp3')
os.system('start ' + 'Music/' + title + '.mp3')
return True
else:
return True
return False
if os.path.exists("Music/" + Title + ".mp3"): def getLyrics():
audiofile = eyed3.load("Music/" + Title + '.mp3') if not title == '':
if ((len(raw_song) == 22 and raw_song.replace(" ", "%20") == raw_song) or (raw_song.find('spotify') > -1)) and not audiofile.tag.title == content['name']: if song == '':
os.remove("Music/" + Title + '.mp3') link = 'https://duckduckgo.com/html/?q=' + title.replace(' ', '+') + '+musixmatch'
else: else:
prompt = raw_input('Song with same name has already been downloaded.. re-download? (y/n/play): ') link = 'https://duckduckgo.com/html/?q=' + song.replace(' ', '+') + '+musixmatch'
if prompt == "y": loadMechanize()
os.remove("Music/" + Title + ".mp3") page = br.open(link)
download = 1 page = page.read()
elif prompt =="play": soup = BeautifulSoup(page, 'html.parser')
if not os.name == 'nt': link = soup.find('a', {'class':'result__url'})['href']
os.system('mplayer "' + script_dir + 'Music/' + Title + '.mp3"') page = br.open(link).read()
else: soup = BeautifulSoup(page, 'html.parser')
print 'Playing..' for x in soup.find_all('p', {'class':'mxm-lyrics__content'}):
os.system('start ' + script_dir + 'Music\\' + Title + '.mp3') print(x.get_text()).encode('utf-8')
download = 0 br.close()
else: else:
download = 0 print('No log to read from..')
if download == 1:
a = video.getbestaudio(preftype="m4a")
a.download(filepath="Music/" + Title + ".m4a")
print ''
print 'Converting ' + Title + '.m4a' + ' to mp3..'
if not os.name == 'nt':
os.system('avconv -loglevel 0 -i "' + script_dir + 'Music/' + Title + '.m4a" -ab 192k "' + script_dir + 'Music/' + Title + '.mp3"')
else:
os.system('Scripts\\avconv.exe -loglevel 0 -i "' + script_dir + 'Music/' + Title + '.m4a" -ab 192k "' + script_dir + 'Music/' + Title + '.mp3"')
os.remove('Music/' + Title + '.m4a')
if (len(raw_song) == 22 and raw_song.replace(" ", "%20") == raw_song) or (raw_song.find('spotify') > -1):
print 'Fixing meta-tags..'
audiofile = eyed3.load("Music/" + Title + '.mp3')
audiofile.tag.artist = content['artists'][0]['name']
audiofile.tag.album = content['album']['name']
audiofile.tag.title = content['name']
br.retrieve(content['album']['images'][0]['url'], 'Music/last_albumart.jpg')
bla = open("Music/last_albumart.jpg","rb").read()
audiofile.tag.images.set(3,bla,"image/jpeg")
audiofile.tag.save()
br.close()
except KeyboardInterrupt:
pass
Main() def fixSong():
print 'Fixing meta-tags..'
audiofile = eyed3.load("Music/" + title + '.mp3')
audiofile.tag.artist = content['artists'][0]['name']
audiofile.tag.album = content['album']['name']
audiofile.tag.title = content['name']
br.retrieve(content['album']['images'][0]['url'], 'Music/last_albumart.jpg')
bla = open("Music/last_albumart.jpg","rb").read()
audiofile.tag.images.set(3,bla,"image/jpeg")
audiofile.tag.save()
def playSong():
if not title == '':
if not os.name == 'nt':
os.system('mplayer "' + 'Music/' + title + '.mp3"')
else:
print('Playing ' + title + '.mp3')
os.system('start ' + 'Music/' + title + '.mp3')
def convertSong():
print('Converting ' + title + '.m4a to mp3..')
if not os.name == 'nt':
os.system('avconv -loglevel 0 -i "' + 'Music/' + title + '.m4a" -ab 192k "' + 'Music/' + title + '.mp3"')
else:
os.system('Scripts\\avconv.exe -loglevel 0 -i "' + 'Music/' + title + '.m4a" -ab 192k "' + 'Music/' + title + '.mp3"')
os.remove('Music/' + title + '.m4a')
def downloadSong():
a = video.getbestaudio(preftype="m4a")
a.download(filepath="Music/" + title + ".m4a")
def isSpotify():
if (len(raw_song) == 22 and raw_song.replace(" ", "%20") == raw_song) or (raw_song.find('spotify') > -1):
return True
else:
return False
def trimSong():
with open('Music/list.txt', 'r') as fin:
data = fin.read().splitlines(True)
with open('Music/list.txt', 'w') as fout:
fout.writelines(data[1:])
def trackPredict():
global URL
if isSpotify():
global content
content = spotify.track(raw_song)
song = (content['artists'][0]['name'] + ' - ' + content['name']).replace(" ", "%20").encode('utf-8')
URL = "https://www.youtube.com/results?sp=EgIQAQ%253D%253D&q=" + song
else:
song = raw_song.replace(" ", "%20")
URL = "https://www.youtube.com/results?sp=EgIQAQ%253D%253D&q=" + song
song = ''
def graceQuit():
print('')
print('')
print('Exitting..')
exit()
title = ''
song = ''
while True:
x = 0
y = 0
try:
for m in os.listdir('Music/'):
if m.endswith('.temp') or m.endswith('.m4a'):
os.remove('Music/' + m)
print('')
print('')
raw_song = raw_input('>> Enter a song/cmd: ').decode('utf-8').encode('utf-8')
print('')
if raw_song == 'exit':
exit()
elif raw_song == 'play':
playSong()
elif raw_song == 'lyrics':
loadMechanize()
getLyrics()
elif raw_song == 'list':
loadMechanize()
f = open('Music/list.txt', 'r').read()
lines = f.splitlines()
for raw_song in lines:
if not len(raw_song) == 0:
x = x + 1
print('Total songs in list = ' + str(x) + ' songs')
for raw_song in lines:
try:
if not len(raw_song) == 0:
trackPredict()
print('')
y = y + 1
searchYT(y)
if not checkExists(True):
downloadSong()
trimSong()
print('')
convertSong()
if isSpotify():
fixSong()
else:
trimSong()
except KeyboardInterrupt:
graceQuit()
except:
lines.append(raw_song)
trimSong()
with open('Music/list.txt', 'a') as myfile:
myfile.write(raw_song)
print('Could not complete a Song download, will try later..')
else:
try:
loadMechanize()
trackPredict()
searchYT(None)
if not checkExists(False):
downloadSong()
print('')
convertSong()
if isSpotify():
fixSong()
except KeyboardInterrupt:
graceQuit()
br.close()
except KeyboardInterrupt:
graceQuit()