Minor Changes (#23)

* made code a little cleaner

* switched to requests from mechanize

* fixed sys.path error

* place list.txt with spotdl.py and not in Music/list.txt

* change a sub-heading to 'Instructions for Downloading Songs'

* remove mechanize

* change error message

* remove random comments

* no extra print

* remove random dots
This commit is contained in:
Ritiek Malhotra
2016-12-27 01:41:27 +05:30
committed by GitHub
parent ea26cf8cbd
commit 2624cdace9
3 changed files with 50 additions and 74 deletions

View File

@@ -1,46 +1,31 @@
#!/bin/python
from bs4 import BeautifulSoup
import mechanize
import pafy
import os
import sys
import spotipy
import eyed3
import requests
import pafy
import shutil
import os
import sys
#import spotipy.util as util
#print(sys.path[0])
os.chdir(sys.path[0] + '/')
os.chdir(sys.path[0])
if not os.path.exists("Music"):
os.makedirs("Music")
open('Music/list.txt', 'a').close()
open('list.txt', 'a').close()
spotify = spotipy.Spotify()
print('')
def loadMechanize():
global br
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")]
def searchYT(number):
#print(URL)
items = br.open(URL)
#print(items)
items = items.read()
#print(items)
items = (requests.request(method='GET', url=URL)).text
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)
global video
@@ -65,7 +50,7 @@ def checkExists(islist):
trimSong()
return True
else:
prompt = raw_input('Song with same name has already been downloaded.. re-download? (y/n/play): ')
prompt = raw_input('Song with same name has already been downloaded. Re-download? (y/n/play): ')
if prompt == "y":
os.remove("Music/" + title + ".mp3")
elif prompt =="play":
@@ -85,29 +70,28 @@ def getLyrics():
link = 'https://duckduckgo.com/html/?q=' + raw_title.replace(' ', '+') + '+musixmatch'
else:
link = 'https://duckduckgo.com/html/?q=' + (content['artists'][0]['name'] + ' - ' + content['name']).replace(' ', '+') + '+musixmatch'
loadMechanize()
page = br.open(link)
page = page.read()
page = requests.request(method='GET', url=link).text
soup = BeautifulSoup(page, 'html.parser')
link = soup.find('a', {'class':'result__url'})['href']
page = br.open(link).read()
page = requests.request(method='GET', url=link).text
soup = BeautifulSoup(page, 'html.parser')
for x in soup.find_all('p', {'class':'mxm-lyrics__content'}):
print(x.get_text()).encode('utf-8')
br.close()
else:
print('No log to read from..')
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()
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']
albumart = (requests.get(content['album']['images'][0]['url'], stream=True)).raw
with open('last_albumart.jpg', 'wb') as out_file:
shutil.copyfileobj(albumart, out_file)
albumart = open("last_albumart.jpg", "rb").read()
audiofile.tag.images.set(3,albumart,"image/jpeg")
audiofile.tag.save()
def playSong():
if not title == '':
@@ -117,9 +101,8 @@ def playSong():
print('Playing ' + title + '.mp3')
os.system('start ' + 'Music/' + title + '.mp3')
def convertSong():
print('Converting ' + title + '.m4a to mp3..')
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:
@@ -137,9 +120,9 @@ def isSpotify():
return False
def trimSong():
with open('Music/list.txt', 'r') as fin:
with open('list.txt', 'r') as fin:
data = fin.read().splitlines(True)
with open('Music/list.txt', 'w') as fout:
with open('list.txt', 'w') as fout:
fout.writelines(data[1:])
def trackPredict():
@@ -180,12 +163,10 @@ while True:
playSong()
elif raw_song == 'lyrics':
loadMechanize()
getLyrics()
elif raw_song == 'list':
loadMechanize()
f = open('Music/list.txt', 'r').read()
f = open('list.txt', 'r').read()
lines = f.splitlines()
for raw_song in lines:
if not len(raw_song) == 0:
@@ -212,13 +193,11 @@ while True:
except:
lines.append(raw_song)
trimSong()
with open('Music/list.txt', 'a') as myfile:
with open('list.txt', 'a') as myfile:
myfile.write(raw_song)
print('Could not complete a Song download, will try later..')
print('Failed to download song. Will retry after other songs.')
else:
try:
loadMechanize()
trackPredict()
searchYT(None)
if not checkExists(False):
@@ -229,7 +208,5 @@ while True:
fixSong()
except KeyboardInterrupt:
graceQuit()
br.close()
except KeyboardInterrupt:
graceQuit()