Skip to content

Commit

Permalink
refactor get_lyrics to only return the lyrics or None
Browse files Browse the repository at this point in the history
Minor UX tweaks as well

Signed-off-by: Aadi Bajpai <[email protected]>
  • Loading branch information
aadibajpai committed Aug 7, 2019
1 parent 29191df commit 9c36db9
Show file tree
Hide file tree
Showing 5 changed files with 44 additions and 39 deletions.
2 changes: 1 addition & 1 deletion LICENSE.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

The MIT License (MIT)

Copyright (c) 2018
Copyright (c) 2018 Aadi Bajpai

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ distribution and usage easier.
## Why SwagLyrics?
SwagLyrics is THE fastest and the most accurate package for getting lyrics.<a href=#footnote1 id=a1><sup>1</sup></a>

Provided optimal internet, SwagLyrics can fetch lyrics for a track in as less as 0.38s.<a href=#footnote2 id=a2><sup>2</sup></a>
Provided optimal internet, SwagLyrics can fetch lyrics for a track in as less as 0.28s.<a href=#footnote2 id=a2><sup>2</sup></a>

It also does not require the user to generate any sort of API token (Spotify or Genius) and serves functionality
right off the bat. This is possible as the song identification is done using our in-house library
Expand Down
7 changes: 4 additions & 3 deletions swaglyrics/__main__.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import argparse
import os
import sys
import webbrowser
import threading
import requests
import time
from SwSpotify import spotify
Expand All @@ -16,7 +14,7 @@ def unsupported_precheck():
v = requests.get('https://aadibajpai.pythonanywhere.com/version')
ver = v.text
if ver > version:
print("Update SwagLyrics to the latest version {ver}\n".format(ver=ver))
print("New version of SwagLyrics available: v{ver}\nPlease update :)".format(ver=ver))
except requests.exceptions.RequestException:
pass
print('Updating unsupported.txt from server.')
Expand Down Expand Up @@ -54,6 +52,8 @@ def main():
unsupported_precheck()

if args.tab:
import webbrowser
import threading
print('Firing up a browser tab!')
app.template_folder = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')
app.static_folder = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static')
Expand Down Expand Up @@ -82,6 +82,7 @@ def main():
print(lyrics(song, artist, make_issue))
print('\n(Press Ctrl+C to quit)')
except KeyboardInterrupt:
print('\nSure boss, exiting.')
exit()
if os.environ.get("TESTING", "False") != "False":
break
Expand Down
52 changes: 32 additions & 20 deletions swaglyrics/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,22 +67,18 @@ def get_lyrics(song, artist, make_issue=True):
"""
url_data = stripper(song, artist) # generate url path using stripper()
url = 'https://genius.com/{}-lyrics'.format(url_data) # format the url with the url path
page = requests.get(url)
if page.status_code != 200:
url_data = requests.get('https://aadibajpai.pythonanywhere.com/stripper',
data={'song': song, 'artist': artist}).text
url = 'https://genius.com/{}-lyrics'.format(url_data)
page = requests.get(url)
html = BeautifulSoup(page.text, "html.parser")
# TODO: Add error handling
lyrics_path = html.find("div", class_="lyrics") # finding div on Genius containing the lyrics
if lyrics_path is None:
with open(unsupported_txt, 'a') as f:
f.write('{song} by {artist} \n'.format(song=song, artist=artist))
f.close()
lyrics = 'Couldn\'t get lyrics for {song} by {artist}.\n'.format(song=song, artist=artist)
try:
try:
page = requests.get(url).raise_for_status()
except requests.exceptions.HTTPError:
url_data = requests.get('https://aadibajpai.pythonanywhere.com/stripper', data={
'song': song,
'artist': artist}).text
if not url_data:
lyrics = None
# Log song and artist for which lyrics couldn't be obtained
with open(unsupported_txt, 'a') as f:
f.write('{song} by {artist} \n'.format(song=song, artist=artist))
f.close()
if make_issue:
r = requests.post('https://aadibajpai.pythonanywhere.com/unsupported', data={
'song': song,
Expand All @@ -91,10 +87,12 @@ def get_lyrics(song, artist, make_issue=True):
})
if r.status_code == 200:
lyrics += r.text
except requests.exceptions.RequestException:
pass
else:
lyrics = UnicodeDammit(lyrics_path.get_text().strip()).unicode_markup
url = 'https://genius.com/{}-lyrics'.format(url_data)
page = requests.get(url)

html = BeautifulSoup(page.text, "html.parser")
lyrics_path = html.find("div", class_="lyrics") # finding div on Genius containing the lyrics
lyrics = UnicodeDammit(lyrics_path.get_text().strip()).unicode_markup
return lyrics


Expand All @@ -114,8 +112,22 @@ def lyrics(song, artist, make_issue=True):
except FileNotFoundError:
pass
init(autoreset=True)
print(Fore.CYAN + '\nGetting lyrics for {song} by {artist}.\n'.format(song=song, artist=artist))
print(Fore.CYAN + 'Getting lyrics for {song} by {artist}.\n'.format(song=song, artist=artist))
lyrics = get_lyrics(song, artist, make_issue)
if not lyrics:
lyrics = 'Couldn\'t get lyrics for {song} by {artist}.\n'.format(song=song, artist=artist)
# Log song and artist for which lyrics couldn't be obtained
with open(unsupported_txt, 'a') as f:
f.write('{song} by {artist} \n'.format(song=song, artist=artist))
f.close()
if make_issue:
r = requests.post('https://aadibajpai.pythonanywhere.com/unsupported', data={
'song': song,
'artist': artist,
'version': __version__
})
if r.status_code == 200:
lyrics += r.text
return lyrics
else:
return 'Nothing playing at the moment.'
Expand Down
20 changes: 6 additions & 14 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,27 +70,19 @@ def test_that_get_lyrics_does_not_break_with_wrong_data(self):
Test that get_lyrics function does not break with wrong data
"""
self.assertEqual(get_lyrics(
"xyzzy", "Yeet", False), "Couldn't get lyrics for xyzzy by Yeet.\n")
self.assertEqual(get_lyrics("wiuegi", "Muhmello", False), "Couldn't get lyrics for wiuegi by Muhmello.\n")
self.assertEqual(get_lyrics("Pixel2XL", "Elgoog", False), "Couldn't get lyrics for Pixel2XL by Elgoog.\n")

# Deleting above songs and artists from unsupported.txt
with open(unsupported_txt, "r") as f:
lines = f.readlines()
with open(unsupported_txt, "w") as f:
for line in lines:
if line not in ["xyzzy by Yeet \n", "wiuegi by Muhmello \n", "Pixel2XL by Elgoog \n"]:
f.write(line)
"xyzzy", "Yeet", False), None)
self.assertEqual(get_lyrics("wiuegi", "Muhmello", False), None)
self.assertEqual(get_lyrics("Pixel2XL", "Elgoog", False), None)

def test_that_lyrics_works_for_unsupported_songs(self):
"""
Test that lyrics function gives 'unsupported' message to unsupported files
"""
get_lyrics("xyzzy", "Yeet", False)
lyrics("xyzzy", "Yeet", False)
self.assertEqual(lyrics("xyzzy", "Yeet"), "Lyrics unavailable for xyzzy by Yeet.\n")
get_lyrics("wiuegi", "Muhmello", False)
lyrics("wiuegi", "Muhmello", False)
self.assertEqual(lyrics("wiuegi", "Muhmello"), "Lyrics unavailable for wiuegi by Muhmello.\n")
get_lyrics("Pixel2XL", "Elgoog", False)
lyrics("Pixel2XL", "Elgoog", False)
self.assertEqual(lyrics("Pixel2XL", "Elgoog"), "Lyrics unavailable for Pixel2XL by Elgoog.\n")

# Deleting above songs and artists from unsupported.txt
Expand Down

0 comments on commit 9c36db9

Please sign in to comment.