Skip to content

Instantly share code, notes, and snippets.

@yodaluca23
Last active July 19, 2024 20:09
Show Gist options
  • Select an option

  • Save yodaluca23/5465128b2c622c95f790fb93e3532433 to your computer and use it in GitHub Desktop.

Select an option

Save yodaluca23/5465128b2c622c95f790fb93e3532433 to your computer and use it in GitHub Desktop.

Revisions

  1. yodaluca23 revised this gist Jul 19, 2024. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion Beautiful-Lyrics-API-Python.py
    Original file line number Diff line number Diff line change
    @@ -62,7 +62,7 @@ def fetch_lyrics(track_id):
    def convert_to_lrc_timestamp(timestamp):
    minutes = int(timestamp // 60)
    seconds = timestamp % 60
    return f"{minutes}:{seconds:05.2f}"
    return f"{minutes:02}:{seconds:05.2f}"

    def parse_lyrics(data, useA2):
    lyrics = []
  2. yodaluca23 revised this gist Jul 19, 2024. 1 changed file with 9 additions and 4 deletions.
    13 changes: 9 additions & 4 deletions Beautiful-Lyrics-API-Python.py
    Original file line number Diff line number Diff line change
    @@ -67,9 +67,14 @@ def convert_to_lrc_timestamp(timestamp):
    def parse_lyrics(data, useA2):
    lyrics = []
    if data['Type'] == 'Line':
    for line in data['Content']:
    if line['Type'] == 'Vocal':
    lyrics.append(line['Text'])
    for item in data['Content']:
    if item['Type'] == 'Vocal':
    line = item['Text']
    timestamp = convert_to_lrc_timestamp(item['StartTime'])
    line = f"[{timestamp}] " + line
    lyrics.append(line.strip())
    if 'Background' in item:
    print("This song has Background with Type Line, I was not able to find this in testing so I don't know the structure, please report this song, so I may add support for it.")
    elif data['Type'] == 'Syllable':
    if useA2:
    for item in data['Content']:
    @@ -167,4 +172,4 @@ def main():
    print("")

    if __name__ == "__main__":
    main()
    main()
  3. yodaluca23 revised this gist Jul 19, 2024. 1 changed file with 68 additions and 12 deletions.
    80 changes: 68 additions & 12 deletions Beautiful-Lyrics-API-Python.py
    Original file line number Diff line number Diff line change
    @@ -58,28 +58,77 @@ def fetch_lyrics(track_id):
    if response.status_code == 200 and response.headers.get('content-length') != '0':
    return response.json()
    return None

    def convert_to_lrc_timestamp(timestamp):
    minutes = int(timestamp // 60)
    seconds = timestamp % 60
    return f"{minutes}:{seconds:05.2f}"

    def parse_lyrics(data):
    def parse_lyrics(data, useA2):
    lyrics = []
    if data['Type'] == 'Line':
    for line in data['Content']:
    if line['Type'] == 'Vocal':
    lyrics.append(line['Text'])
    elif data['Type'] == 'Syllable':
    for item in data['Content']:
    if item['Type'] == 'Vocal':
    line = ''.join([
    f"{syllable['Text']}{' ' if not syllable['IsPartOfWord'] else ''}"
    for syllable in item['Lead']['Syllables']
    ])
    lyrics.append(line.strip())
    if 'Background' in item:
    for bg in item['Background']:
    if useA2:
    for item in data['Content']:
    if item['Type'] == 'Vocal':
    syllables = item['Lead']['Syllables']
    line = ''
    timestamp = convert_to_lrc_timestamp(item['Lead']['StartTime'])
    for syllable in syllables:
    syllable_text = syllable['Text']
    syllable_timestamp = convert_to_lrc_timestamp(syllable['StartTime'])
    if syllable['IsPartOfWord']:
    line += syllable_text
    else:
    line += f" <{syllable_timestamp}> {syllable_text}"
    line = f"[{timestamp}]" + line
    lyrics.append(line.strip())
    if 'Background' in item:
    for bg in item['Background']:
    syllables = bg['Syllables']
    line = ''
    timestamp = convert_to_lrc_timestamp(bg['StartTime'])
    for index, syllable in enumerate(syllables):
    syllable_text = syllable['Text']
    syllable_timestamp = convert_to_lrc_timestamp(syllable['StartTime'])
    if syllable['IsPartOfWord']:
    if index == 0:
    line += f"({syllable_text}"
    elif index == len(syllables) - 1:
    line += f"{syllable_text})"
    else:
    line += syllable_text
    else:
    if index == 0:
    line += f" <{syllable_timestamp}> ({syllable_text}"
    elif index == len(syllables) - 1:
    line += f" <{syllable_timestamp}> {syllable_text})"
    else:
    line += f" <{syllable_timestamp}> {syllable_text}"
    line = f"[{timestamp}]" + line
    lyrics.append(line.strip())
    else:
    for item in data['Content']:
    if item['Type'] == 'Vocal':
    line = ''.join([
    f"{syllable['Text']}{' ' if not syllable['IsPartOfWord'] else ''}"
    for syllable in bg['Syllables']
    for syllable in item['Lead']['Syllables']
    ])
    timestamp = item['Lead']['StartTime']
    line = f"[{convert_to_lrc_timestamp(timestamp)}]" + f" {line}"
    lyrics.append(line.strip())
    if 'Background' in item:
    for bg in item['Background']:
    line = ''.join([
    f"{syllable['Text']}{' ' if not syllable['IsPartOfWord'] else ''}"
    for syllable in bg['Syllables']
    ])
    timestamp = item['Background'][0]['StartTime']
    line = f"[{convert_to_lrc_timestamp(timestamp)}]" + f" ({line.rstrip()})"
    lyrics.append(line.strip())
    return lyrics

    def print_lyrics(lyrics):
    @@ -89,6 +138,13 @@ def print_lyrics(lyrics):
    def main():
    artist = input("Enter Artist Name: ").strip()
    song = input("Enter Song Title: ").strip()
    useA2_input = input("Should use A2 extension (Enhanced LRC format) if available? ")
    if useA2_input.lower() in ['true', '1', 't', 'y', 'yes']:
    useA2 = True
    elif useA2_input.lower() in ['false', '0', 'f', 'n', 'no']:
    useA2 = False
    else:
    raise ValueError("Invalid input. Please enter True or False.")

    # Search Spotify and get track ID
    track_id = search_spotify(artist, song)
    @@ -103,7 +159,7 @@ def main():
    return

    # Parse and print lyrics
    lyrics = parse_lyrics(data)
    lyrics = parse_lyrics(data, useA2)
    print("")
    print("Lyrics:")
    print("")
  4. yodaluca23 revised this gist Jul 17, 2024. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion Beautiful-Lyrics-API-Python.py
    Original file line number Diff line number Diff line change
    @@ -5,7 +5,7 @@
    import json

    def get_bearer_token():
    fetch_url = "https://open.spotify.com/playlist/6U7CJSEwgsrb41wXEPcr96"
    fetch_url = "https://open.spotify.com"

    response = requests.get(fetch_url)
    response.raise_for_status() # Check if the request was successful
  5. yodaluca23 revised this gist Jul 17, 2024. 1 changed file with 1 addition and 2 deletions.
    3 changes: 1 addition & 2 deletions Beautiful-Lyrics-API-Python.py
    Original file line number Diff line number Diff line change
    @@ -5,8 +5,7 @@
    import json

    def get_bearer_token():
    playlist_id = "6U7CJSEwgsrb41wXEPcr96"
    fetch_url = f"https://open.spotify.com/playlist/{playlist_id}"
    fetch_url = "https://open.spotify.com/playlist/6U7CJSEwgsrb41wXEPcr96"

    response = requests.get(fetch_url)
    response.raise_for_status() # Check if the request was successful
  6. yodaluca23 revised this gist Jul 17, 2024. 1 changed file with 15 additions and 5 deletions.
    20 changes: 15 additions & 5 deletions Beautiful-Lyrics-API-Python.py
    Original file line number Diff line number Diff line change
    @@ -23,7 +23,11 @@ def get_bearer_token():

    def search_spotify(artist, song):
    token = get_bearer_token()
    url = f'https://api.spotify.com/v1/search?q=remaster%2520track%3A{song}%2520artist%253A{artist}&type=track&limit=1'
    print("")
    print("Token:")
    print (token)
    print("")
    url = f'https://api.spotify.com/v1/search?query=artist%3A+{artist}+track%3A+{song}&type=track&offset=0&limit=1'
    headers = {
    'Authorization': f'Bearer {token}'
    }
    @@ -65,12 +69,18 @@ def parse_lyrics(data):
    elif data['Type'] == 'Syllable':
    for item in data['Content']:
    if item['Type'] == 'Vocal':
    line = ' '.join([syllable['Text'] for syllable in item['Lead']['Syllables']])
    lyrics.append(line)
    line = ''.join([
    f"{syllable['Text']}{' ' if not syllable['IsPartOfWord'] else ''}"
    for syllable in item['Lead']['Syllables']
    ])
    lyrics.append(line.strip())
    if 'Background' in item:
    for bg in item['Background']:
    line = ' '.join([syllable['Text'] for syllable in bg['Syllables']])
    lyrics.append(line)
    line = ''.join([
    f"{syllable['Text']}{' ' if not syllable['IsPartOfWord'] else ''}"
    for syllable in bg['Syllables']
    ])
    lyrics.append(line.strip())
    return lyrics

    def print_lyrics(lyrics):
  7. yodaluca23 revised this gist Jul 17, 2024. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions Beautiful-Lyrics-API-Python.py
    Original file line number Diff line number Diff line change
    @@ -99,6 +99,7 @@ def main():
    print("Lyrics:")
    print("")
    print_lyrics(lyrics)
    print("")

    if __name__ == "__main__":
    main()
  8. yodaluca23 revised this gist Jul 17, 2024. 1 changed file with 54 additions and 15 deletions.
    69 changes: 54 additions & 15 deletions Beautiful-Lyrics-API-Python.py
    Original file line number Diff line number Diff line change
    @@ -1,16 +1,50 @@
    import requests
    from bs4 import BeautifulSoup
    import urllib.parse
    import re
    import json

    def extract_track_id(spotify_input):
    # Check if the input is a full Spotify URL
    match = re.search(r'track/([a-zA-Z0-9]+)', spotify_input)
    if match:
    return match.group(1)
    # Check if the input is just the track ID
    elif re.match(r'^[a-zA-Z0-9]+$', spotify_input):
    return spotify_input
    def get_bearer_token():
    playlist_id = "6U7CJSEwgsrb41wXEPcr96"
    fetch_url = f"https://open.spotify.com/playlist/{playlist_id}"

    response = requests.get(fetch_url)
    response.raise_for_status() # Check if the request was successful

    html_content = response.text
    soup = BeautifulSoup(html_content, 'html.parser')
    session_element = soup.find(id="session")
    session_html = session_element.get_text()

    tokens = json.loads(session_html)
    access_token = tokens['accessToken']

    return access_token

    def search_spotify(artist, song):
    token = get_bearer_token()
    url = f'https://api.spotify.com/v1/search?q=remaster%2520track%3A{song}%2520artist%253A{artist}&type=track&limit=1'
    headers = {
    'Authorization': f'Bearer {token}'
    }

    response = requests.get(url, headers=headers)

    if response.status_code == 200:
    data = response.json()
    if data['tracks']['items']:
    href = data['tracks']['items'][0]['href']
    match = re.search(r'tracks/([a-zA-Z0-9]+)', href)
    if match:
    song_id = match.group(1)
    return song_id
    else:
    raise ValueError("Song ID not found in the href.")
    else:
    raise ValueError("No tracks found for the given artist and song.")
    else:
    return None
    raise Exception(f"Spotify API request failed with status code {response.status_code}")


    def fetch_lyrics(track_id):
    url = f'https://beautiful-lyrics.socalifornian.live/lyrics/{track_id}'
    @@ -44,22 +78,27 @@ def print_lyrics(lyrics):
    print(line)

    def main():
    spotify_input = input("Enter Spotify Track URL: ").strip()
    track_id = extract_track_id(spotify_input)
    artist = input("Enter Artist Name: ").strip()
    song = input("Enter Song Title: ").strip()

    # Search Spotify and get track ID
    track_id = search_spotify(artist, song)
    if not track_id:
    print("Invalid Spotify URL or ID")
    print("No track found on Spotify.")
    return


    # Fetch lyrics using track ID
    data = fetch_lyrics(track_id)
    if not data:
    print("No lyrics found for this track.")
    return


    # Parse and print lyrics
    lyrics = parse_lyrics(data)
    print("")
    print("Lyrics:")
    print("")
    print_lyrics(lyrics)

    if __name__ == "__main__":
    main()
    main()
  9. yodaluca23 revised this gist Jul 17, 2024. 1 changed file with 3 additions and 0 deletions.
    3 changes: 3 additions & 0 deletions Beautiful-Lyrics-API-Python.py
    Original file line number Diff line number Diff line change
    @@ -56,6 +56,9 @@ def main():
    return

    lyrics = parse_lyrics(data)
    print("")
    print("Lyrics:")
    print("")
    print_lyrics(lyrics)

    if __name__ == "__main__":
  10. yodaluca23 created this gist Jul 17, 2024.
    62 changes: 62 additions & 0 deletions Beautiful-Lyrics-API-Python.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,62 @@
    import requests
    import re

    def extract_track_id(spotify_input):
    # Check if the input is a full Spotify URL
    match = re.search(r'track/([a-zA-Z0-9]+)', spotify_input)
    if match:
    return match.group(1)
    # Check if the input is just the track ID
    elif re.match(r'^[a-zA-Z0-9]+$', spotify_input):
    return spotify_input
    else:
    return None

    def fetch_lyrics(track_id):
    url = f'https://beautiful-lyrics.socalifornian.live/lyrics/{track_id}'
    headers = {
    'authorization': 'Bearer litterallyAnythingCanGoHereItJustTakesItLOL'
    }
    response = requests.get(url, headers=headers)
    if response.status_code == 200 and response.headers.get('content-length') != '0':
    return response.json()
    return None

    def parse_lyrics(data):
    lyrics = []
    if data['Type'] == 'Line':
    for line in data['Content']:
    if line['Type'] == 'Vocal':
    lyrics.append(line['Text'])
    elif data['Type'] == 'Syllable':
    for item in data['Content']:
    if item['Type'] == 'Vocal':
    line = ' '.join([syllable['Text'] for syllable in item['Lead']['Syllables']])
    lyrics.append(line)
    if 'Background' in item:
    for bg in item['Background']:
    line = ' '.join([syllable['Text'] for syllable in bg['Syllables']])
    lyrics.append(line)
    return lyrics

    def print_lyrics(lyrics):
    for line in lyrics:
    print(line)

    def main():
    spotify_input = input("Enter Spotify Track URL: ").strip()
    track_id = extract_track_id(spotify_input)
    if not track_id:
    print("Invalid Spotify URL or ID")
    return

    data = fetch_lyrics(track_id)
    if not data:
    print("No lyrics found for this track.")
    return

    lyrics = parse_lyrics(data)
    print_lyrics(lyrics)

    if __name__ == "__main__":
    main()