Merge pull request #2 from Doublefire-Chen/main

v1.2.0 - help with multiplatform directories and ease of access to get tokens needed - Special thanks to Doublefire-Chen!
This commit is contained in:
~noah~
2022-11-07 01:28:12 -07:00
committed by GitHub
5 changed files with 90 additions and 276 deletions
Vendored
BIN
View File
Binary file not shown.
+16 -13
View File
@@ -1,36 +1,39 @@
# **spotify-lyric-downloader** # **spotify-lyric-downloader**
Rips lyrics from currently playing song on Spotify, converts to LRC format for offline playback (e.g Plex, Kodi, MusicBee) Rips lyrics from currently playing song on Spotify, converts to LRC format for offline playback (e.g Plex, Kodi, MusicBee)
# Disclaimer!!! (Read before use, thanks)
This software is totally open source code permanently,which is only used for study and conmunication. Any forms of commercial usings is not allowed. Anyone will offered all outcomes if he or she doesn't obey this rule.
--------------------------------------------------------------------- ---------------------------------------------------------------------
# Requisites: # Requisites:
> pip install os re sys spotipy itertools json requests base64 linecache webbrowser bs4 time pyautogui pyperclip urllib3 pprint datetime shutil platform subprocess importlib > pip install spotipy requests bs4 pyautogui pyperclip datetime importlib
Forgive my carelessness please if there are some modules I forgot to mention, just install it by yourself.
--------------------------------------------------------------------- ---------------------------------------------------------------------
# How to set up: # How to set up:
· Go to the [Spotify API Dashboard](https://developer.spotify.com/dashboard/applications) · Go to the [Spotify API Dashboard](https://developer.spotify.com/dashboard/applications)
· Create an app and enter "example.com/example" as the Redirect URI in the settings · Create an app and enter ```http://example.com/example``` as the Redirect URI in the settings
· copy client ID, secret, and "example.com/example" from Spotify API Dashboard and put them into lyricdownloader.py · copy client ID and secret from Spotify API Dashboard and put them into lyricdownloader.py
· Run converter.py · Sign into Spotify and listen to any song you like.
· Sign into Spotify · open the browser and open the developer tool(Hot key is F12 in Chrome), and go to https://open.spotify.com/lyrics, find the authrization value following the picture below. Then close the browser. Remember, once you get the authrization, don't open https://open.spotify.com/lyrics in a new web, or it will generate a new one and the old one will be expired. As long as you don't open a new web, this can maintain a long time. Just use client or the web you first opened to listen to music.
![Image load fail](./picture/get_authrization.png)
· It will redirect you to a link based off your URI, copy everything but "example.com/example" from the url and paste it into the console · Run converter.py in a cmd or git-bash terminal.
· It will redirect you to a link based off your URI, copy everything but ```http://example.com/example``` from the url and paste it into the console. Then you can close the browser.
· Close it out
--------------------------------------------------------------------- ---------------------------------------------------------------------
# How to use: # How to use:
· Listen to a song on Spotify (any client works) and be signed in on the normal https://open.spotify.com/ site · Listen to a song on Spotify (any client works).
· open converter.py in a cmd or git-bash terminal · run converter.py in Windows cmd or Mac terminal.
· Wait about 10 seconds · Wait about 10 seconds.
· Once complete, check "Lyrics" folder for grouping by artist, album, and track number and title. · Once complete, check "Lyrics" folder for grouping by artist, album, and track number and title. Enjoy yourself!
+14 -27
View File
@@ -1,13 +1,13 @@
import os, re, sys, itertools, json, requests, base64, linecache, time, requests, webbrowser, bs4, time, pyautogui, pyperclip, urllib3, pprint, shutil, platform, subprocess # coding:utf-8
import urllib.request import os, re, sys, itertools, json, requests, base64, linecache, time, requests, bs4, time, pyautogui, pyperclip, pprint, shutil, platform, subprocess
import downloader import downloader
from pathlib import Path #using this module to solve difference path syntax between Mac OS and Windows
host_folder = downloader.host_dir host_folder = downloader.host_dir #get work path
os.chdir(host_folder) os.chdir(host_folder) #change path to work path
lyrics_url = downloader.lyrics_url lyrics_url = downloader.lyrics_url
# Read in the jumbled Spotify lyric text # Read in the jumbled Spotify lyric text
with open('lyrics.txt', 'r') as file : with open('lyrics.txt', 'r',encoding='UTF-8') as file :
filedata = file.read() filedata = file.read()
fullstring = filedata fullstring = filedata
substring_403 = "HTTP ERROR 403" substring_403 = "HTTP ERROR 403"
@@ -26,22 +26,9 @@ if substring_403 in fullstring:
quit() quit()
# exception with no token, just redownloads it based on lyrics_url # exception with no token, just redownloads it based on lyrics_url
elif substring_401 in fullstring: elif substring_401 in fullstring:
print("Error, no token found, retrying once") print("Error, token has been expired, please open the browser to get a new one and restart the program")
link_for_cookie = "https://open.spotify.com/lyrics" os._exit(0)
lyrics = webbrowser.open(link_for_cookie, new=0, autoraise=True)
time.sleep(10)
lyrics = webbrowser.open(lyrics_url, new=0, autoraise=True)
time.sleep(1.2)
pyautogui.hotkey('ctrl', 'a')
pyautogui.hotkey('ctrl', 'c')
time.sleep(0.1)
pyautogui.hotkey('ctrl', 'w')
pyautogui.hotkey('ctrl', 'w')
print("tab closed")
lyricdata = pyperclip.paste()
z = open("lyrics.txt", "w", encoding="utf-8")
z.write(lyricdata)
z.close()
#exception for successful lyric grab #exception for successful lyric grab
elif substring_success in fullstring: elif substring_success in fullstring:
print("Lyric grab was success, converting now...") print("Lyric grab was success, converting now...")
@@ -60,6 +47,7 @@ filedata = filedata.replace('"', '')
filedata = filedata.replace('hasVocalRemoval:false}', '') filedata = filedata.replace('hasVocalRemoval:false}', '')
filedata = filedata.replace(']', '] ') filedata = filedata.replace(']', '] ')
filedata = filedata.replace('\\', '*') filedata = filedata.replace('\\', '*')
filedata = filedata.replace(',syllables:[] ,endTimeMs:0}', '')
# Write the file out # Write the file out
with open('lyricsfixed.lrc', 'w') as file: with open('lyricsfixed.lrc', 'w') as file:
@@ -262,8 +250,8 @@ os.remove("lyricsfixed.lrc")
os.remove("lyricstimingsremoved.txt") os.remove("lyricstimingsremoved.txt")
os.remove("timingsfixed.lrc") os.remove("timingsfixed.lrc")
os.remove("lyrics.txt") os.remove("lyrics.txt")
os.remove("currentsong.txt")
print(downloader)
#set up variables for moving lyric and setting up cover.jpg location #set up variables for moving lyric and setting up cover.jpg location
host_folder = downloader.host_dir host_folder = downloader.host_dir
lyrics = "Lyrics" lyrics = "Lyrics"
@@ -271,9 +259,9 @@ artist_name = downloader.artist_name
albumdir = downloader.albumdir albumdir = downloader.albumdir
song = downloader.song song = downloader.song
cover = downloader.lyrics_url cover = downloader.lyrics_url
originallyricsfile = (host_folder + "\\output.lrc") originallyricsfile = (Path(host_folder)/"output.lrc")
movedlyricsfile = (albumdir + "\\" + downloader.track_number + ". " + song + ".lrc") movedlyricsfile = (Path(albumdir)/(str(downloader.track_number) + ". " + str(song) + ".lrc"))
movedcoverjpg = (albumdir + "\\" + "cover.jpg") movedcoverjpg = (Path(albumdir)/"cover.jpg")
#prints folder where lyric went #prints folder where lyric went
print("\n") print("\n")
@@ -290,4 +278,3 @@ def open_file(path):
subprocess.Popen(["xdg-open", path]) subprocess.Popen(["xdg-open", path])
open_file(albumdir) open_file(albumdir)
+48 -224
View File
@@ -1,14 +1,17 @@
import os, re, sys, spotipy, itertools, json, requests, base64, linecache, webbrowser, bs4, time, pyautogui, pyperclip, urllib3, pprint, datetime, shutil, platform, subprocess # coding:utf-8
import os, re, sys, spotipy, itertools, json, requests, base64, linecache, bs4, time, pyautogui, pyperclip, pprint, datetime, shutil, platform, subprocess
import spotipy.util as util import spotipy.util as util
import urllib.request import requests
from os import path from os import path
from spotipy.oauth2 import SpotifyOAuth from spotipy.oauth2 import SpotifyOAuth
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
from pathlib import Path #using this module to solve difference path syntax between Mac OS and Windows
# MAKE SURE THESE ARE CORRECT # MAKE SURE THESE ARE CORRECT
CLIENT_ID = '(spotify API client ID here)' CLIENT_ID = '(spotify API client ID here)'
CLIENT_SECRET = '(spotify API client SECRET here)' CLIENT_SECRET = '(spotify API client SECRET here)'
REDIRECT_URI = '(spotify API REDIRECT URI here)' REDIRECT_URI = 'http://example.com/example'
authorization='(spotify authorization here)'
# MAKE SURE THESE ARE CORRECT # MAKE SURE THESE ARE CORRECT
os.environ['SPOTIPY_CLIENT_ID'] = CLIENT_ID os.environ['SPOTIPY_CLIENT_ID'] = CLIENT_ID
@@ -19,47 +22,6 @@ scope = "user-read-currently-playing"
sp = spotipy.Spotify(auth_manager = SpotifyOAuth(scope = scope)) sp = spotipy.Spotify(auth_manager = SpotifyOAuth(scope = scope))
current_track = sp.current_user_playing_track() current_track = sp.current_user_playing_track()
# saves currently playing song info to txt file
result = json.dumps(current_track)
z = open("currentsong.txt", "w")
z.write(result)
z.close()
with open('currentsong.txt', 'r') as handle:
parsed = json.load(handle)
parsed2 = (json.dumps(parsed, indent=0, sort_keys=True))
with open('currentsong.txt', 'w') as file: # line breaks
file.write(parsed2)
file.close()
#reading for short line removal
with open('currentsong.txt', 'r') as f:
lines = f.readlines()
# Removes region codes by removing all short lines
filtered_lines = [line for line in lines if len(line) > 10]
# writing out file w no 2-character country codes
#with open('filtered.txt', 'w') as f:
# for line in filtered_lines:
# f.write(line)
database = "currentsong.txt"
def search_string_in_file(database, string_to_search):
# Search for the given string in file and return lines containing that string,
# along with line numbers
line_number = 0
list_of_results = []
# Open the file in read only mode
with open(database, 'r') as read_obj:
# Read all lines in the file one by one
for line in read_obj:
# For each line, check if line contains the string
line_number += 1
if string_to_search in line:
# If yes, then add the line number & line as a tuple in the list
list_of_results.append((line_number, line.rstrip()))
# Return list of tuples containing line numbers and lines where string is found
return list_of_results
def replace_line(database, line_num, text): def replace_line(database, line_num, text):
lines = open(database, 'r').readlines() lines = open(database, 'r').readlines()
@@ -77,162 +39,19 @@ def open_file(path):
else: else:
subprocess.Popen(["xdg-open", path]) subprocess.Popen(["xdg-open", path])
#i dont know how to make tables so this finds text and finds the line below which is the string needed #see if song is playing
song_uri_link = search_string_in_file(database, 'spotify:track:') if current_track == None:
song_name = search_string_in_file(database, '"preview_url": "https://p.scdn.co/mp3-preview/') print("No song detected, make sure you're actively playing a song!")
cover_link = search_string_in_file(database,'"width": 640') os._exit(0)
release_date = search_string_in_file(database,'"release_date":') song_uri_link = current_track.get("item").get("uri").replace('spotify:track:','')
album_name = search_string_in_file(database,'"release_date":') song_name = current_track.get("item").get("name")
artist_name = search_string_in_file(database,'"artists": [') cover_link = current_track.get("item").get("album").get("images")[0].get("url")
track_number = search_string_in_file(database,'"track_number":') release_date = current_track.get("item").get("album").get("release_date")
album_uri_link = search_string_in_file(database, 'spotify:album:') album_name = current_track.get("item").get("album").get("name")
artist_name = current_track.get("item").get("album").get("artists")[0].get("name")
track_number = current_track.get("item").get("track_number")
album_uri_link = current_track.get("item").get("album").get("uri")
#song name
for elem in song_name:
song_name = elem[0] - 3
f = open("currentsong.txt","r")
lines = f.readlines()
# logic for finding song name, and assigning it to some variable
x = lines[song_name]
x = x.replace('"name": "', '')
x = x.replace('\\u00e9', 'é')
x = x.replace('\\u00e0', 'à')
x = x.replace('\\u2019', "'")
x = x.replace('\\u0027', '\'')
x = x.replace('\\u2022', '·')
x = x.replace('?', '')
x = x.replace('"', '')
x = x.replace('/', '-')
x = x.replace('|', '-')
x = x.replace('\\', '')
x = x.replace(':', ' =')
x = x.replace(';', '-')
size = len(x)
minus_quote_and_comma = x[:size - 2]
song_name = minus_quote_and_comma
#cover URL
for elem in cover_link:
cover_link = elem[0] - 2
f = open("currentsong.txt","r")
lines = f.readlines()
# logic for finding song name, and assigning it to some variable
x = lines[cover_link]
x = x.replace('"url": "https:', 'https:')
size = len(x)
minus_quote_and_comma = x[:size - 3]
cover_link = minus_quote_and_comma
# Song URI
for elem in song_uri_link:
song_uri_link = elem[0] - 1
f = open("currentsong.txt","r")
lines = f.readlines()
# logic for finding song name, and assigning it to some variable
x = lines[song_uri_link]
x = x.replace('"uri": "spotify:track:', '')
size = len(x)
minus_quote = x[:size - 2]
song_uri_link = minus_quote
# Album URI
for elem in album_uri_link:
album_uri_link = elem[0] - 1
f = open("currentsong.txt","r")
lines = f.readlines()
# logic for finding song name, and assigning it to some variable
x = lines[album_uri_link]
x = x.replace('"uri": "spotify:album:', 'spotify:album:')
size = len(x)
minus_quote = x[:size - 2]
album_uri_link = minus_quote
# Track Number
for elem in track_number:
track_number = elem[0] - 1
f = open("currentsong.txt","r")
lines = f.readlines()
# logic for finding song name, and assigning it to some variable
x = lines[track_number]
x = x.replace('"track_number": ', '')
size = len(x)
minus_quote = x[:size - 2]
track_number = minus_quote
# Release Date
for elem in release_date:
release_date = elem[0] - 1
f = open("currentsong.txt","r")
lines = f.readlines()
# logic for finding song name, and assigning it to some variable
x = lines[release_date]
x = x.replace('\\u00e9', 'é')
x = x.replace('\\u00e0', 'à')
x = x.replace('\\u2019', "'")
x = x.replace('\\u0027', '\'')
x = x.replace('\\u2022', '·')
x = x.replace('"name": "', '')
x = x.replace('?', '')
x = x.replace('"', '')
x = x.replace('/', '')
x = x.replace('|', '-')
x = x.replace('\\', '')
x = x.replace(':', ' -')
x = x.replace(';', '-')
x = x.replace('release_date - ', '')
size = len(x)
minus_quote_and_comma = x[:size - 2]
release_date = minus_quote_and_comma
# Album Name
for elem in album_name:
album_name = elem[0] - 2
f = open("currentsong.txt","r")
lines = f.readlines()
# logic for finding song name, and assigning it to some variable
x = lines[album_name]
x = x.replace('\\u00e9', 'é')
x = x.replace('\\u00e0', 'à')
x = x.replace('\\u2019', "'")
x = x.replace('\\u0027', '\'')
x = x.replace('\\u2022', '·')
x = x.replace('"name": "', '')
x = x.replace('?', '')
x = x.replace('"', '')
x = x.replace('/', '')
x = x.replace('|', '-')
x = x.replace('\\', '')
x = x.replace(':)', ' =)')
x = x.replace(': ', ' - ')
x = x.replace(';', '-')
x = x.replace(',\n', '')
album_name = x
# Artist Name
for elem in artist_name:
artist_name = elem[0] + 6
f = open("currentsong.txt","r")
lines = f.readlines()
# logic for finding song name, and assigning it to some variable
x = lines[artist_name]
x = x.replace('\\u00e9', 'é')
x = x.replace('\\u00e0', 'à')
x = x.replace('\\u2019', "'")
x = x.replace('\\u0027', '\'')
x = x.replace('\\u2022', '·')
x = x.replace('"name": "', '')
x = x.replace('?', '')
x = x.replace('"', '')
x = x.replace('/', '')
x = x.replace('|', '-')
x = x.replace('\\', '')
x = x.replace(':', ' -')
x = x.replace(';', '-')
x = x.replace(':)', ' =)')
size = len(x)
minus_quote_and_comma = x[:size - 2]
artist_name = minus_quote_and_comma
f.close()
# generate lyrics link # generate lyrics link
original_link = cover_link original_link = cover_link
@@ -244,13 +63,6 @@ link_start = "https://spclient.wg.spotify.com/color-lyrics/v2/track/"
lyrics_url = (link_start + song_uri_link + "/image/" + cover_link + "?format=json&vocalRemoval=false&market=from_token") lyrics_url = (link_start + song_uri_link + "/image/" + cover_link + "?format=json&vocalRemoval=false&market=from_token")
lyrics_url_no_access = (link_start + song_uri_link + "/image/" + cover_link) lyrics_url_no_access = (link_start + song_uri_link + "/image/" + cover_link)
#see if song is playing
filesize = os.path.getsize("currentsong.txt")
if filesize == 4:
print("No song detected, make sure you're actively playing a song!")
os.remove("currentsong.txt")
quit()
else:
print("Success! Song detected! \n") print("Success! Song detected! \n")
print("Song: ", song_name) print("Song: ", song_name)
print("Album name:", album_name) print("Album name:", album_name)
@@ -339,9 +151,9 @@ artist_name = artist_name
albumdir = albumdir albumdir = albumdir
song = song song = song
cover = lyrics_url cover = lyrics_url
originallyricsfile = (host_folder + "\\output.lrc") originallyricsfile = (Path(host_folder)/"output.lrc")
movedlyricsfile = (albumdir + "\\" + track_number + ". " + song + ".lrc") movedlyricsfile = (Path(albumdir)/(str(track_number) + ". " + str(song) + ".lrc"))
movedcoverjpg = (albumdir + "\\" + "cover.jpg") movedcoverjpg = (Path(albumdir)/"cover.jpg")
#checks if cover exists, if not it downloads #checks if cover exists, if not it downloads
os.chdir(albumdir) os.chdir(albumdir)
@@ -351,9 +163,9 @@ try:
f.close() f.close()
except IOError: except IOError:
print("No cover.jpg detected, downloading now") print("No cover.jpg detected, downloading now")
cover = original_link cover =requests.get(original_link).content
f = open(movedcoverjpg,'wb') f = open(movedcoverjpg,'wb')
f.write(urllib.request.urlopen(cover).read()) f.write(cover)
f.close() f.close()
print("Cover downloaded!") print("Cover downloaded!")
@@ -370,19 +182,31 @@ try:
except IOError: except IOError:
print("No lyric detected, downloading now") print("No lyric detected, downloading now")
headers = {
link_for_cookie = "https://open.spotify.com/lyrics" 'Host': 'spclient.wg.spotify.com',
lyrics = webbrowser.open(link_for_cookie, new=0, autoraise=True) 'sec-ch-ua': '"Google Chrome";v="107", "Chromium";v="107", "Not=A?Brand";v="24"',
time.sleep(10) 'accept-language': 'en',
lyrics = webbrowser.open(lyrics_url, new=0, autoraise=True) 'sec-ch-ua-mobile': '?0',
time.sleep(1.2) 'app-platform': 'WebPlayer',
pyautogui.hotkey('ctrl', 'a') 'authorization': authorization,
pyautogui.hotkey('ctrl', 'c') 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36',
time.sleep(0.1) 'accept': 'application/json',
pyautogui.hotkey('ctrl', 'w') 'spotify-app-version': '1.1.98.597.g7f2ab0d4',
pyautogui.hotkey('ctrl', 'w') 'sec-ch-ua-platform': '"macOS"',
print("Tab closed and contents copied! \n") 'origin': 'https://open.spotify.com',
lyricdata = pyperclip.paste() 'sec-fetch-site': 'same-site',
'sec-fetch-mode': 'cors',
'sec-fetch-dest': 'empty',
'referer': 'https://open.spotify.com/',
}
params = {
'format': 'json',
'vocalRemoval': 'false',
'market': 'from_token',
}
response = requests.get(lyrics_url, params=params, headers=headers)
lyricdata=response.text
#print(lyricdata)
z = open("lyrics.txt", "w", encoding="utf-8") z = open("lyrics.txt", "w", encoding="utf-8")
z.write(lyricdata) z.write(lyricdata)
z.close() z.close()
Binary file not shown.

After

Width:  |  Height:  |  Size: 812 KiB