# Gather CL arguments as variables token = args.token songwriter = args.songwriter numofsongs = args.numofsongs lyricfile = args.lyricfile # Added lyricsgenius functionality to change particulars about songs lg.verbose = True # Turn off status messages lg.remove_section_headers = True # Remove section headers (e.g. [Chorus]) from lyrics when searching lg.skip_non_songs = True # Include hits thought to be non-songs (e.g. track lists) lg.excluded_terms = ["(Remix)", "(Live)" ] # Exclude songs with these words in their titles # Create Genius object that allows us to search for artists genius = lg.Genius(token) artist = genius.search_artist(artist_name=songwriter, max_songs=numofsongs, sort="title") # Create list of songs then write to text file and clean it up song_list = addSongs(artist.songs) writeToFile(lyricfile, song_list) cleanTextFile(lyricfile) # JUNK # #song = lg.search_song("Come Together", artist.name) #print(song.lyrics)print(artist.songs) #artist.save_lyrics(extension='txt') #print(artist.songs)
import lyricsgenius import os from pandarallel import pandarallel def query_songs(stuff): try: return genius.search_song(stuff["Track Name"].split("-")[0], stuff["Artist Name"]).lyrics except: return None if __name__ == "__main__": pandarallel.initialize() df = pd.read_csv("red_river_gorge.csv") df = pd.concat([df["Track Name"], df["Artist Name"]], axis=1) genius = lyricsgenius.Genius("KEY") genius.verbose = True genius.remove_section_headers = True genius.skip_non_songs = False df["Lyrics"] = df.parallel_apply(query_songs, axis=1) df.dropna(subset=["Lyrics"]) df.to_csv("lyrics_RRG.csv")
import os import json import lyricsgenius genius = lyricsgenius.Genius("Insert Genius Token Here") from string import whitespace def spoty_scouting(path): file=open("singers_list.txt") for artist_name in file: numb_canzoni=10 artist = genius.search_artist(artist_name, numb_canzoni, sort="popularity", include_features=True) artist.save_lyrics() cartella = artist.name path_long = os.path.join(path, cartella) os.mkdir(path_long) range_song=len(artist.songs) try: with open("Lyrics_" + str(artist.name).replace(" ","").replace("$","").replace("-","") + ".json") as json_file: data = json.load(json_file) for i in range(range_song): album_name="" #aggiustamento che mi dovrebbe evitare bazze stranissime con i nomi degli album buggati if (str(data['songs'][i]['album']) == None or "https" in str(data['songs'][i]['album']) or "//" in str(data['songs'][i]['album'])):
import lyricsgenius GENIUS_CLIENT_ACCESS_TOKEN = "" genius = lyricsgenius.Genius(GENIUS_CLIENT_ACCESS_TOKEN) # returns lyrics from specified song and artist def get_song_lyrics(song_name, artist): song = genius.search_song(song_name, artist) if song is not None: return song.lyrics return ""
# Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.c (the "License"); # you may not use this file except in compliance with the License. # # import os import lyricsgenius from userbot.events import register from userbot import (CMD_HELP, GENIUS, lastfm, LASTFM_USERNAME) from pylast import User if GENIUS is not None: genius = lyricsgenius.Genius(GENIUS) @register(outgoing=True, pattern="^\.lcs (?:(now)|(.*) - (.*))") async def lyrics(lyric): await lyric.edit("`Getting information...`") if GENIUS is None: await lyric.edit( "`Provide genius access token to Heroku ConfigVars...`") return False if lyric.pattern_match.group(1) == "now": playing = User(LASTFM_USERNAME, lastfm).get_now_playing() if playing is None: await lyric.edit("`No information current lastfm scrobbling...`") return False artist = playing.get_artist() song = playing.get_title()
import os from os import listdir from os.path import isfile, join import json import lyricsgenius import re ''' Identifies missing data ''' genius = lyricsgenius.Genius(os.environ["GENIUS_ACCESS_TOKEN"]) genius.remove_section_headers = True genius.skip_non_songs = True genius.excluded_terms = ["(Instrumental)"] existingSongs = [] def alreadySearched(title, artist): for song in existingSongs: if song['title'] == title and song['artist'] == artist: return song return False counter = 0 data = [] with open("./billboard-cleaned.json") as f: data = json.load(f) for chart in data:
# Developed by: Calinescu Mihai <*****@*****.**> # Date: November 19th, 2021 import lyricsgenius # Generate api key and paste it # https://genius.com/api-clients genius = lyricsgenius.Genius("api-key-here") def save_lyrics(songs, artist_name, album_name): for i in range(len(songs )): song_title = songs[i] song = genius.search_song(song_title, artist_name) lyrics = song.lyrics with open('songs/{}/{}_{}_{}.txt'.format('_'.join(artist_name.split(' ')), i+1, album_name, '-'.join(''.join(song_title.split('\'')).split(' '))), 'w') as f: f.writelines(lyrics.split('\\n')) # Run if __name__ == '__main__': songs = [ 'the box', 'down below', 'project dreams', 'die young', 'boom boom room', 'high fashion', 'roll dice', 'war baby', 'every season' ]
def remove_squares(test_str): ret = '' skip1c = 0 for i in test_str: if i == '[': skip1c += 1 elif i == ']' and skip1c > 0: skip1c -= 1 elif skip1c == 0: ret += i return ret token = "YOUR TOKEN HERE" genius = lyricsgenius.Genius(token) f = open("songlist.txt") content = f.readlines() f.close() f = open("test_output.txt", "w") content = [x.strip() for x in content] for song in content: if song == '' or song is None: continue if song[0] == '#': artist = song[1:] else: result = genius.search_song(song, artist) temp = result.lyrics temp = remove_squares(temp) temp = "".join([s for s in temp.splitlines(True) if s.strip("\r\n")])
#Creating a dictionary of datasets for each playlist Songs_Df = {} for playll in list_of_playslists: Songs_Df[playll] = df_creation(playll) #Merging the Dictionary into one big dataset df = pd.concat(Songs_Df).reset_index(drop=True) df = df.mask(df.astype(object).eq('None')).dropna().reset_index(drop=True) df2 = df.drop(columns=["playlist"]).drop_duplicates().reset_index() df3 = pd.merge(df2,df['playlist'],how='left',left_on=df2['index'],right_index=True).drop(columns=['index']) #Pulling Lyrics api = genius.Genius('<GENIUS API CODE>') lyrics = [] for a in range(len(df3)): ss = api.search_song(df3.loc[a,'name'],df3.loc[a,'artists']) try: lyrics.append(ss.lyrics) except AttributeError: lyrics.append(" ") #Merging Lyrics to Dataset df3.insert(loc=5,column = 'lyrics',value = lyrics) df4 = df3.mask(df3.astype(object).eq('None')).dropna().reset_index(drop=True) #Create CSV to use later on df4.to_csv('pre-clean-dataset.csv')
Filters, CallbackContext, ConversationHandler ) import telegram switch = False updater = Updater(config.telegram_api_key, use_context=True) # Enter your telegram API key here dispatcher = updater.dispatcher logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') genius = lyricsgenius.Genius(config.genius_api_key) # Enter your genius API key here logger = logging.getLogger(__name__) def start(update: Update, context: CallbackContext) -> None: '''ENVOYER MESSAGE QUAND COMMANDE START EST RECUE''' update.message.reply_text('Yo big c moe denis') time.sleep(1) update.message.reply_text('Je suis une intelligence artificielle de ***très haute qualité***', parse_mode='MarkdownV2') time.sleep(1) update.message.reply_text("[Appuyez ici](pistacherigolo.com) *afin d'avoir plus d'informations*", parse_mode='MarkdownV2') time.sleep(1) update.message.reply_text("La commande /lyrics est utilisée afin de trouver les paroles d'une chanson.")
def main(): genius = lyricsgenius.Genius( "hu0VByrvYkRp8_UfZBOIl58Fho4_YnFY5RSs_Sh1tG2HwW9PY89P6MU13teEJtKV") artist = genius.search_artist("Andy Shauf", max_songs=1, sort="title") print([e.lyrics for e in artist.songs])
import lyricsgenius as genius # access Genius API access = '' api = genius.Genius(access) artist = api.search_artist('Death (metal band)') scream_bloody_gore = ['Infernal Death', 'Zombie Ritual', 'Denial of LIfe', 'Sacrificial', \ 'Mutilation', 'Regurgitated Guts', 'Baptized in Blood', 'Torn to Pieces', \ 'Evil Dead', 'Scream Bloody Gore', 'Beyond the Unholy Grave', 'Land of No Return'] leprosy = ['Leprosy', 'Born Dead', 'Forgotten Past', 'Left to Die', 'Pull the Plug', \ 'Open Casket', 'Primitive Ways', 'Choke on It'] spiritual_healing = ['Living Monstrosity', 'Altering the Future', 'Defensive Personalities', \ 'Within the Mind', 'Spiritual Healing', 'Low Life', 'Genetic Reconstruction', \ 'Killing Spree'] human = ['Flattening of Emotions', 'Suicide Machine', 'Together as One', 'Secret Face', \ 'Lack of Comprehension', 'See Through Dreams', 'Cosmic Sea', 'Vacant Planets'] individual_thought_patterns = ['Overactive Imagination', 'In Human Form', 'Jealousy', \ 'Trapped in a Corner', 'Nothing Is Everything', 'Mentally Blind', \ 'Individual Thought Patterns', 'Destiny', 'Out of Touch', \ 'The Philosopher'] symbolic = ['Symbolic', 'Zero Tolerance', 'Empty Words', 'Sacred Serenity', '1,000 Eyes', \ 'Without Judgement', 'Crystal Mountain', 'Misanthrope', 'Perennial Quest'] the_sound_of_perserverance = ['Scavenger of Human Sorrow', 'Bite the Pain', 'Spirit Crusher', \
os.chdir(os.path.dirname(os.path.abspath('gather-lyrics.py'))) import lyricsgenius # API wrapper for genius.com #import nltk for word processing from nltk.corpus import stopwords from nltk.tokenize import RegexpTokenizer import json # for saving artist:lyrics data import pandas as pd from keys import genius_api_key # set up Regular Expression tokenizer for lyric cleaning tokenizer = RegexpTokenizer(r'\w+') # keep all words. discard punctuation stop_words = set(stopwords.words('english')) # load genius API and settings api = lyricsgenius.Genius(genius_api_key) api.remove_section_headers = True api.verbose = False def main(): artist_list = pd.read_csv('artist_list.csv', usecols=['Artist']).values.tolist() # use this line instead of above to pare down failed_artists # artist_list = pd.read_csv('failed_artists.csv', # usecols = ['Failures']).values.tolist() # ensure we capture all artists whose queries fail failed_artists = [] failed_artists = getLyrics(artist_list, failed_artists)
if not os.path.exists('cache'): os.makedirs('cache') with open('spotify_secret.json', 'r') as f: data = json.load(f) reader = Reader(debug) session = requests.Session() client_id = data['second_id'] client_secret = data['second_secret'] genius_token = data['genius_secret'] spotify_authorize = 'Basic ' + str( base64.b64encode((client_id + ':' + client_secret).encode('ascii')))[2:-1] genius = lyricsgenius.Genius(genius_token) app = Flask(__name__, template_folder='templates') def verify_cookie(): uid = request.cookies.get('uid') session_hash = request.cookies.get('session') if uid is None or session_hash is None: return False return db.verify_login(uid, session_hash) def get_name(): uid = request.cookies.get('uid', None) return db.get_name(uid) if uid is not None else None
import boto3 import s3fs import lyricsgenius as genius import multiprocessing as mp import pandas as pd from optparse import OptionParser from selenium import webdriver from bs4.element import Tag from bs4 import BeautifulSoup from .utils import logger_init, worker_init genius = genius.Genius(os.environ.get("GENIUS_ACCESS_TOKEN"), timeout=10, sleep_time=1) pattern = re.compile("api_path.*?/artists/(\d+)") s3_client = boto3.client("s3") s3 = s3fs.S3FileSystem() lyrics_root = "genius-lyrics" class Artist: def __init__(self, name, url, songs=[]): self.name = name self.url = url self.songs = songs self.artist_id = None
import os import unittest import lyricsgenius from lyricsgenius.song import Song from lyricsgenius.artist import Artist # Import client access token from environment variable client_access_token = os.environ.get("GENIUS_CLIENT_ACCESS_TOKEN", None) assert client_access_token is not None, "Must declare environment variable: GENIUS_CLIENT_ACCESS_TOKEN" api = lyricsgenius.Genius(client_access_token, sleep_time=1) class TestArtist(unittest.TestCase): @classmethod def setUpClass(cls): print("\n---------------------\nSetting up Artist tests...\n") cls.artist_name = "The Beatles" cls.new_song = "Paperback Writer" cls.max_songs = 2 cls.artist = api.search_artist(cls.artist_name, max_songs=cls.max_songs) def test_artist(self): msg = "The returned object is not an instance of the Artist class." self.assertIsInstance(self.artist, Artist, msg) def test_name(self): msg = "The artist object name does not match the requested artist name." self.assertEqual(self.artist.name, self.artist_name, msg) def test_add_song_from_same_artist(self):
from useful import error_embed, str_limit import os import json import random import wikipedia import lyricsgenius as genius genius_token = os.environ.get('GENIUS-TOKEN') if genius_token is None: with open('config.json') as j: config = json.load(j) genius_token = config['genius_token'] genius_api = genius.Genius(genius_token) wiki_lang = 'en' class APIs(commands.Cog): def __init__(self, bot): self.bot = bot # wikipedia @commands.group(aliases=['wiki', 'wp'], case_insensitive=True) async def wikipedia(self, ctx, language: str): """Wikipedia based command. Do !help wp.""" global wiki_lang if language in wikipedia.languages():
def scrape_lyrics(artist_name_starts_with): """ Iterate through the musixmatch csv file and attempt to find the lyrics for each with the genius api service A csv is created with the artist-song pairs that this function fails to find lyrics for. Args: artist_name_starts_with: character or string used to filter which artists we attempt to download lyrics for """ start = time.time() api = genius.Genius(client_access_token=get_api_token(), verbose=False) df = pd.read_csv(CSV_MUSIXMATCH_MAPPING, encoding='utf-8', dtype={ 'msd_artist': str, 'msd_title': str }) logger.info('{0} songs in mapping file.'.format(len(df))) if artist_name_starts_with: df = df[df['msd_artist'].str.lower().str.startswith( artist_name_starts_with.lower())] logger.info( 'Filtered songs with startswith str "{0}". Mapping file now contains {1} songs.' .format(artist_name_starts_with, len(df))) # sort by artist so that we can df = df.sort_values('msd_artist') # would it be more efficient to groupby artist name? # maybe, but you run the risk of missing a song if msd_artist is incorrect spelling if not os.path.exists(CSV_NO_LYRICS): with open(CSV_NO_LYRICS, mode='w', encoding='utf-8', newline='') as csvfile: csvwriter = csv.writer(csvfile) csvwriter.writerow(CSV_HEADER) df_no_lyrics = pd.read_csv(CSV_NO_LYRICS, encoding='utf-8') df_no_lyrics = df_no_lyrics.sort_values('msd_artist') df_no_lyrics_update = pd.DataFrame(columns=CSV_HEADER) song_index = 0 songs_skipped = 0 songs_matched = 0 try: for index, row in df.iterrows(): song_index += 1 json_lyricfile = '{0}/{1}.json'.format( LYRICS_JSON_DIR, make_lyric_file_name(row['msd_artist'], row['msd_title'])) txt_lyricfile = '{0}/txt/{1}.txt'.format( LYRICS_TXT_DIR, make_lyric_file_name(row['msd_artist'], row['msd_title'])) # https://stackoverflow.com/questions/24761133/pandas-check-if-row-exists-with-certain-values if SKIP_LYRIC_CHECK_IF_KNOWN_BAD and (df_no_lyrics == row).all(1).any(): logger.debug( '{0}: (artist={1}, title={2}) matched in {3}. Skipping.'. format(song_index, row['msd_artist'], row['mxm_artist'], CSV_NO_LYRICS)) songs_skipped += 1 continue if os.path.exists(json_lyricfile): logger.debug('{0}: {1} already downloaded. Skipping.'.format( song_index, json_lyricfile)) songs_skipped += 1 continue try: song = api.search_song(row['msd_title'], row['msd_artist']) if not song: # lets try all of the combinations! artist_mismatch = row['msd_artist'] != row['mxm_artist'] title_mismatch = row['msd_title'] != row['mxm_title'] if artist_mismatch: song = api.search_song(row['msd_title'], row['mxm_artist']) if not song and title_mismatch: song = api.search_song(row['mxm_title'], row['msd_artist']) if not song and artist_mismatch and title_mismatch: song = api.search_song(row['mxm_title'], row['mxm_artist']) if not song: # no luck... on to the next one # https://stackoverflow.com/questions/24284342/insert-a-row-to-pandas-dataframe/24287210 df_no_lyrics_update.loc[-1] = row df_no_lyrics_update.index += 1 logger.debug( '{0}: No luck (artist={1}, title={2}). Saved to no lyrics csv.' .format(song_index, row['msd_artist'], row['mxm_artist'])) continue songs_matched += 1 # save_lyrics function: https://github.com/johnwmillr/LyricsGenius/blob/master/lyricsgenius/song.py song.save_lyrics(filename=json_lyricfile, overwrite=True, verbose=False, format_='json') song.save_lyrics(filename=txt_lyricfile, overwrite=True, verbose=False, format_='txt') logger.debug( '{0}: Success! (artist={1}, title={2}) saved to {3}.'. format(song_index, row['msd_artist'], row['msd_title'], json_lyricfile)) except Exception as exc: logger.warning('Problem: {0}'.format(songs_matched)) logger.warning(row) logger.warning(exc) except KeyboardInterrupt as kbi: logger.info(kbi) logger.info('saving no lyrics csv...') df_no_lyrics_update.to_csv(CSV_NO_LYRICS, encoding='utf-8', index=False, mode='a', header=False) logger.info('done.') end = time.time() elapsed_time = end - start logger.info('{0} / {1} Song Lyrics Obtained! ({2} skipped)'.format( songs_matched, song_index - songs_skipped, songs_skipped)) logger.info('Elapsed Time: {0} minutes'.format(elapsed_time / 60)) return
import lyricsgenius import csv genius = lyricsgenius.Genius("XWWEtd9o3o8Ul5MfqyEfksX0v5NZ59WdDstvcPeglauUxGJ8wre61z_wSe-Jt26I") #artist = genius.search_artist("Bruno Mars", max_songs=1, sort="title") #song = genius.search_song("Blinding Lights", "The Weeknd") #print(song.lyrics) with open("top10s.csv", newline='') as file: reader = csv.reader(file) with open("top10s_with_lyrics.csv", "w", newline='') as outputFile: writer = csv.writer(outputFile) for row in reader: title = row[1] artist = row[2] genre = row[3] key = str(title + " " + artist) try: writer.writerow([title, artist, genius.search_song(title, artist).lyrics, genre]) except: pass #print("\n===== Row Written to CSV =====") #print(songs) #print("===== END OF SONGS ====='n") #print("Song Title: " + row[1] + " Artist Name: " + row[2] + " Genre: " + row[3])
import pandas as pd import lyricsgenius import random import collections import math import time from multiprocessing.pool import ThreadPool from requests.exceptions import ConnectionError genius = lyricsgenius.Genius( "rJlw4RGpYqaGwxCtW9Tif-o3j6SnXjXSX-_xZi_2Hs8NMmgW17ULodXCfHfGCXW_") df = pd.read_csv("totTop100.csv") dfnew = pd.DataFrame(columns=['song', 'artist', 'text']) lis = [] for i, x in df.iterrows(): a = x['song'] a = a.replace("F**k", "F**k") a = a.replace("B****", "Bitch") a = a.replace("S**t", "Shit") a = a.replace("P****", "Pussy") a = a.replace("F*****g", "F*****g") a = a.replace("F***", "F**k") tup = (a, x['artist']) lis.append((i, tup))
def get_lyrics_from_genius(song, artist, token): genius = lyricsgenius.Genius(token, remove_section_headers=True) song_obj = genius.search_song(song,artist) return song_obj.lyrics
# 2019 Emir Erbasan (humanova) # MIT License, see LICENSE for more details #hmnBot sarki sozu import os import lyricsgenius as genius token = os.environ['GENIUS_TOKEN'] api = genius.Genius(token) def sozParse(artist, sarki): song = api.search_song(sarki, artist) if not song == None: sarkiAdi = song.title sarkiArtist = song.artist sarkiLink = song.url lyrics = song.save_lyrics(filename="lyrics_test.txt", format="txt", overwrite="no") return lyrics, sarkiAdi, sarkiArtist, sarkiLink else: lyrics = "hata" sarkiAdi = "hata" sarkiArtist = "hata"
import lyricsgenius genius = lyricsgenius.Genius("X") #artist = genius.search_artist("Sonic Youth", max_songs=1, sort="title") #print(artist.songs) #print(artist.to_json) #artist.save_lyrics() #artist = genius.search_artists('Sonic Youth') #print(artist) artist = genius.search_artist('29872', artist_id=29872, per_page=50) for song in artist.songs: print(song.title) r = requests.get('') html = r.text soup =Beautifulsoup(html, 'html.parser') consumer_key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" consumer_secret = "X" access_token = "X" access_token_secret = "X" auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) api.update_status('status=tweet')
import string import os import unidecode import pymongo from collections import Counter, OrderedDict myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["zumba_cafew3"] mycol = mydb["artists"] FILENAME = "artists.txt" string.punctuation += '’' genius = lyricsgenius.Genius( "BXGKadnQ5NCjtaEUJwfZ3SdVupRMyNW0B6endNpKPc3Awb46F8_4GpVzqe5mdw0M") def process_lycrics(lyrics): lyrics = lyrics.lower() lyrics = unidecode.unidecode(lyrics) lyrics = re.sub(r"\[(.*?)\]", " ", lyrics) lyrics = re.sub('[%s]' % re.escape(string.punctuation), " ", lyrics) lyrics = re.sub("\n", " ", lyrics) lyrics = lyrics.split(" ") return [l for l in lyrics if l != '' and l != ' '] def count_words_by_year(vocab): counter_vocab = {}
def config_complete(self): self.genius = lyricsgenius.Genius(self.config["GENIUS_API_TOKEN"])
import spotipy import spotipy.util as util import lyricsgenius import PySimpleGUI as sg import config # username = "******" # CLIENT_ID = "ENTER SPOTIFY CLIENT ID" # CLIENT_SECRET = "ENTER SPOTIFY CLIENT SECRET" # redirect_uri = "ENTER PRE-DETERMINED REDIRECT URI FROM SPOTIFY DASHBOARD" # genius_token = "ENTER GENIUS API TOKEN" scope = "user-read-currently-playing" genius = lyricsgenius.Genius(config.genius_token) token = util.prompt_for_user_token(config.username, scope, config.CLIENT_ID, config.CLIENT_SECRET, config.redirect_uri) sp = spotipy.Spotify(auth=token) def find_song(): full_song = sp.current_user_playing_track()['item'] song_name = full_song['name'] artist_names = [] for artist in sp.current_user_playing_track()['item']['artists']: artist_names.append(artist['name']) artist_name = artist_names[0] return song_name, artist_name def find_lyrics(song, artist): genius_song = genius.search_song(song, artist)
import lyricsgenius as genius geniusCreds = "XLFgo7rC1mmbKLLQKVnImOqwp7K0BccjrMtbbSBp1YWVIxELhWgjVBTG22r8VxM2" artist_name = "Taylor Swift" api = genius.Genius(geniusCreds) artist = api.search_artist(artist_name, max_songs=20) import os os.getcwd() artist.save_lyrics()
import requests import csv import time import timing import lyricsgenius as genius # Genius API handler import pandas as pd keyGet = open('Key.txt', 'r') # Reads key from separate file for privacy API_KEY = keyGet.read() api = genius.Genius(API_KEY) # Function to split list into chunks of a given size def chunker(seq, size): return (seq[pos:pos + size] for pos in range(0, len(seq), size)) # Performs search, gets song id and web link for first song def link_get(query): try: data = api.search_genius(query) song_id.append(data['hits'][0]['result']['id']) genius_link.append(data['hits'][0]['result']['path']) except IndexError: song_id.append('N/A') genius_link.append('N/A') # Grabs search terms from csv and saves as a list input_path = r'genius-files\genius-search-terms.csv'
import lyricsgenius as genius api = genius.Genius( 'J7SX419b2gYDrWYRYmI78IoZ9qUUVPjXPJhubOJ3yXScw7BxGqicsT1mjksrbw8s') model = api.search_song('Model', 'Gulddreng') print(model.lyrics) # gilli = api.search_song('Su Casa', 'Gilli') molo = api.search_song('Skejsen', 'MOLO') print(molo.lyrics) # print(gilli.lyrics) # artist = api.search_artist('Drake', max_songs=3) # song = api.search_song('Marvin\'s room',artist.name) # api.search_song('Drunk in the morning', 'Lukas Graham').save_lyrics() # api.search_song('Ked af Det', 'Gulddreng').save_lyrics() # artist.save_lyrics()
def get_lyrics(song_name: str, artist_name: str): ''' TODO Add some error handling for songs not found after searching in lyrics genius. Using the song name and the artist name, this function will add songs to their respective artist dictionary. TODO Review for accessing artist from the db properly. There are a few cases to conisder which are the following: Case 1 the given Artist already exist in the dictionary: - If the given song isn't in the artist dictionary then we use the lyricsgenius api and add that song to the artist dictionary. - If we already have the song then the results will be generated. - After not finding the song in the dict and then searching for it in using lyricsgeniius api we use that song name and check if it is in the dictionary Case 2 the user inputs case sesnstive or new artist name: - First the song will be searched using the given artist. - if after finding the song and the artist doesn't exist then we add it to the add that to the dict. - If they do exist then we simply check if the song provided exists in their dict, if it doesn't exist then it will be added if it doesn a result will be generated. Advantages: - Not 100% sure but I think we do less calls to the lyricgenius API here. Disadvantages: - A lot checks to the database to see if the song and artist exists before getting info from lyrcisgenius if not found then we use lyric genius and some more checks happen. Late NOTE this might not be needed at all check this out: https://lyricsgenius.readthedocs.io/en/master/reference/artist.html#lyricsgenius.artist.Artist.song ''' # no song name given then return if not song_name: return genius = lyricsgenius.Genius(GENIUS_ACCESS_TOKEN) # convert json file to dict with open("db.json") as json_file: lyricsJSON = json.load(json_file) # Case 1 if artist_name in lyricsJSON: print("here") # if the song isn't in the dict #TODO: Update the document for an artist using mongodb to add a song if not song_name in lyricsJSON[artist_name]: song = genius.search_song(song_name, artist_name) song_name = song.title.lower() if not song_name in lyricsJSON[artist_name]: album_name = song.album lyrics = song.lyrics song_dict = {song_name: [lyrics, album_name]} # update artist song list lyricsJSON[artist_name].update(song_dict) print(lyricsJSON) # else it is already in the dict then just process else: print("Already have lyrics.") # print (lyricsJSON[artist_name][song_name]) # Case 2 else: # case of user input artist name not being in dict song = genius.search_song(song_name, artist_name) artist_name = song.artist.lower() song_name = song.title.lower() # check if the arist name gotten from the song not in the dict if not artist_name in lyricsJSON: album_name = song.album lyrics = song.lyrics song_dict = {song_name: [lyrics, album_name]} artist_dict = {artist_name: song_dict} lyricsJSON.update(artist_dict) print(lyricsJSON) # check if the arist name gotten from the song is in the dict else: # if we don't have the song then we need to add it to the dict if not song_name in lyricsJSON[artist_name]: album_name = song.album lyrics = song.lyrics song_dict = {song.title: [lyrics, album_name]} lyricsJSON[artist_name].update(song_dict) # put the generated dict to the json with open("db.json", "w") as outfile: json.dump(lyricsJSON, outfile) # buildArtist(artist_name) # NOTE for testing comment everything above and uncomment this line return