class Lyrics: def __init__(self): self.genius = Genius(data["geniusAPI"]["token"]) def searchLyrics(self, name): try: song, artist = (name.strip()).split(',') except: song, artist = name.strip(), "" self.song = self.genius.search_song(song, artist) song_info = { "title": self.song.title, "artist": self.song.artist, "lyrics": self.song.lyrics, "thumbnail": self.song.song_art_image_thumbnail_url, "linecount": (self.song.lyrics).count('\n') } return song_info def serachSongByLyrics(self, lyr): request = self.genius.search_lyrics(lyr) ans = [] for hit in request['sections'][0]['hits']: ans.append((hit['result']['full_title']).split(' by')) return ans def saveLyrics(self, songName, songLyrics): with open(f'{songName }.txt', 'w') as f: f.write(songLyrics)
def get_tweet_info(): # Create a new genius object genius = Genius(genius_client_access_token) # Pick a random song until we find one that has annotations (shouldn't take long) print("Looking for annotations ...") while True: # Narrow selection by picking an album albums = genius.artist_albums(DOOM_ARTIST_ID) selected_album = random.choice(albums['albums']) print("\tALBUM: " + selected_album['name']) # Get the songs from the album and pick one tracks = genius.album_tracks(selected_album['id']) selected_track = random.choice(tracks['tracks']) selected_song = selected_track['song'] print("\tSONG: " + selected_song['title_with_featured']) # Check that the song has a "qualifying" number of annotations and they are of right length annotation_count = selected_song['annotation_count'] print("\t\t" + str(annotation_count) + " annotations found...") # If we found a song with sufficient annotations, continue; otherwise, try again if selected_song['annotation_count'] >= MIN_ANNOTATIONS: # Pick a random annotation for the selected song selected_lyric = random.choice(genius.song_annotations(selected_song['id']))[0] tweet_text = selected_lyric + "\n\n(" + selected_song['title_with_featured'] + ", " + selected_album[ 'name'] + ")" return tweet_text else: print("Trying again...")
def get_song_genius(track_name, artist_name): genius = Genius(GENIUS_TOKEN, verbose=False) song = genius.search_song(track_name, artist_name) if not song: return None song = json.loads(song.to_json()) if not valid_song(track_name, song['title'], artist_name, song['primary_artist']['name']): return None try: meaning = song['description']['plain'].split('\n') assert (meaning != ["?"] and meaning != [""]) except: meaning = None response = { 'lyrics': add_line_breaks(song['lyrics'].split('\n')), 'meaning': meaning, 'source': 'Genius', 'source_url': song['url'], } for item in song['media']: if item['provider'] == 'youtube': response['youtube_embed_url'] = 'https://www.youtube.com/embed/' + \ item['url'].split('=')[1] break return response
def search_lyrics(call): """Handle searching for a song's lyrics.""" data = call.data artist = data[ATTR_ARTIST_NAME] title = data[ATTR_SONG_TITLE] entity_id = data.get(CONF_ENTITY_ID) state = data.get("state") old_state = hass.states.get(entity_id) if old_state: attrs = old_state.attributes else: attrs = {} # get lyrics from lyricsgenius import Genius genius = Genius(genius_access_token) #_LOGGER.debug("Searching for lyrics with artist '{}' and title '{}'".format(artist, title)) song = genius.search_song(title, artist, get_full_info=False) if song is None: #_LOGGER.debug("Song not found.") attrs = { 'artist': artist.title(), # title case until we have a preformatted name 'title': title, 'lyrics': None } else: #_LOGGER.debug("Song data: \n{}".format(song.to_dict())) attrs = song.to_dict() attrs['artist'] = artist.title( ) # title case until we have a preformatted name if entity_id is not None: hass.states.set(entity_id, state, attrs)
def get_lyrics(interpret): if not os.path.exists(f"Lyrics_{interpret}.json"): with open("token", "r") as f: token = f.read().strip() genius = Genius(token) artist = genius.search_artist(interpret) artist.save_lyrics() with open(f"Lyrics_{interpret}.json", "r") as f: lyrics = json.loads(f.read()) return lyrics
def __init__(self, genius_auth_path="data/genius.auth", minsleep=0.5): # gets client access token with open("data/genius.auth", "r") as file: client_access_token = file.read().strip() self.minsleep = minsleep self.api = Genius(client_access_token, remove_section_headers=True) self.lyrics = MongoClient().billboard["lyrics"] self.errlog = MongoClient().billboard["lyrics_errlog"] print("Initialized")
def __init__(self, access_token, genius=None): self.__artist = None self.__title = None self.__lyrics = None self.__genius = None from lyricsgenius import Genius # use or create Genius class if isinstance(genius, Genius): self.__genius = genius else: self.__genius = Genius(access_token, skip_non_songs=True)
def lyrics_grabber(access_token, search_term, base_url='https://genius.com'): # instantiate genius object genius = Genius(access_token) # search for song song = genius.search(search_term) # find url for top hit url_addon = song['hits'][0]['result']['path'] # retrieve lyrics lyrics = genius.lyrics(base_url + url_addon) return lyrics
def lyrics(message): args = extract_args(message) if r"-" in args: pass else: edit(message, f'`{get_translation("lyricsError")}`') return if not GENIUS_TOKEN: edit(message, f'`{get_translation("geniusToken")}`') else: genius = Genius(GENIUS_TOKEN) try: args = args.split('-') artist = args[0].strip() song = args[1].strip() except BaseException: edit(message, f'`{get_translation("lyricsError2")}`') return if len(args) < 1: edit(message, f'`{get_translation("lyricsError2")}`') return edit(message, get_translation('lyricsSearch', ['`', artist, song])) try: songs = genius.search_song(song, artist) except TypeError: songs = None if not songs: edit(message, get_translation('lyricsNotFound', ['**', artist, song])) return if len(songs.lyrics) > 4096: edit(message, f'`{get_translation("lyricsOutput")}`') with open('lyrics.txt', 'w+') as f: f.write( get_translation('lyricsQuery', ['', '', artist, song, songs.lyrics])) reply_doc(message, 'lyrics.txt', delete_after_send=True) else: edit( message, get_translation('lyricsQuery', ['**', '`', artist, song, songs.lyrics]), ) return
class GeniusProvider(LyricsProviderABC): NAME = 'genius.com' API_BASE_URL = 'https://api.genius.com/' LYRICS_BASE_URL = 'https://genius.com/' def __init__(self): super().__init__() self.api = GeniusAPI(constants.Genius.TOKEN, verbose=False) def _requests_lyrics(self, track: 'Track') -> Optional[str]: try: track_genius = self.api.search_song( f'{track.title.replace(" - Bonus Track", "")} by {track.artists[0]}' ) if track_genius is None: self.logger.info( f'GeniusProvider: Track not found: {track_genius}') return self.logger.debug( f'GeniusProvider: Found track: {track_genius.title}') return track_genius.lyrics except requests.exceptions.HTTPError as e: raise HTTPError(self.__class__, e) except requests.exceptions.RequestException as e: raise NetworkError(self.__class__, e)
def songComparison(model, song1, artist1, song2, artist2): genius = Genius(API_Keys.genius_access_token) genius.timeout = 15 genius.sleep_time = 2 lyrics1 = getLyrics(song1, artist1, genius) lyrics2 = getLyrics(song2, artist2, genius) if lyrics1 is None: print(song1) return (None) if lyrics2 is None: print(song2) return (None) docs = [lyrics1, lyrics2] dist = getSongDivergence(model, docs) return (dist)
def get_genius_obj(): """ Get genius object :return: """ genius = Genius(genius_token) return genius
def start_genius_api(api_key: str): """load the genius api object using client key""" api_obj = Genius( api_key, sleep_time=0.2, timeout=20 ) # note sleep time between api calls could be further reduced only # by changing package directly to change the min_sleep_time param in API Class # check it has worked? return api_obj
def __init__(self, config_entry): remove_section_headers = config_entry.getboolean( 'remove_section_headers', False) self.genius = LyrGenius( config_entry['token'], verbose=False, remove_section_headers=remove_section_headers, )
async def test_token(self) -> bool: loop = asyncio.get_event_loop() genius = Genius(self.GENIUS_TOKEN, verbose=False) import requests try: await loop.run_in_executor(self._executor, genius.search_song, "chevy uwu") return True except requests.exceptions.HTTPError: return False
class OpenSongLyrics: def __init__(self): self.sclient_id = spotify_client_id self.sclient_secret = spotify_client_secret self.redirect_uri = 'http://localhost:8080' self.scope = 'user-read-playback-state' self.username = '******' self.client_credentials_manager = SpotifyOAuth( username=self.username, redirect_uri=self.redirect_uri, scope=self.scope, client_id=self.sclient_id, client_secret=self.sclient_secret, open_browser=False) self.genius_token = genius_token self.lyrics = None self.genius = Genius(client_access_token=self.genius_token, response_format='dom', verbose=True, skip_non_songs=True) def get_song_info(self): sp = spotipy.Spotify( client_credentials_manager=self.client_credentials_manager) playback_read = sp.current_playback() if playback_read is not None: get_title = playback_read['item']['name'] get_artists = playback_read['item']['artists'] artists = [] for artist in get_artists: name = artist['name'] artists.append(name) album = playback_read['item']['album']['name'] song_info = { 'title': get_title, 'artists': artists, 'album': album } print(song_info) else: song_info = {} return song_info def get_current_lyrics(self): song_info = self.get_song_info() print(song_info) song_title = clean_title(artists=song_info['artists'], song_title=song_info['title']) self.lyrics = self.genius.search_song( title=song_title, artist=song_info['artists'][0]).lyrics # artists = " ".join(song_info['artists']) # term = song_title + " " + artists # a = genius.search_all(term, per_page=5, page=1) # aa = genius._get_item_from_search_response(a, term, type_='song', result_type='song_title') # album = genius.search_lyrics() return self.lyrics
def __init__(self): self.sclient_id = spotify_client_id self.sclient_secret = spotify_client_secret self.redirect_uri = 'http://localhost:8080' self.scope = 'user-read-playback-state' self.username = '******' self.client_credentials_manager = SpotifyOAuth( username=self.username, redirect_uri=self.redirect_uri, scope=self.scope, client_id=self.sclient_id, client_secret=self.sclient_secret, open_browser=False) self.genius_token = genius_token self.lyrics = None self.genius = Genius(client_access_token=self.genius_token, response_format='dom', verbose=True, skip_non_songs=True)
def __init__(self, bot): self.bot = bot self.YTDL_OPTIONS = { 'format': 'bestaudio', 'noplaylist': True, 'default-search': 'auto', 'quiet': True, 'extractaudio': True, 'audioformat': 'mp3', 'rm-cache-dir': True, 'skip_download': True } self.YTDL_OPTIONS_PLAYLIST_FIRSTSONG = { 'format': 'bestaudio', 'extractaudio': True, 'skip_download': True, 'playlistend': 1, 'noplaylist': False, 'quiet': True, '-yes_playlist': True } self.YTDL_OPTIONS_PLAYLIST_RESTOFSONGS = { 'format': 'bestaudio', 'extractaudio': True, 'skip_download': True, 'playliststart': 2, 'playlistend': 20, 'quiet': True, 'noplaylist': False, '-yes_playlist': True } self.FFMPEG_OPTIONS = { 'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn' } conn = sqlite.connect("data/internal.db") conn.execute( "CREATE TABLE IF NOT EXISTS music(id INTEGER PRIMARY KEY, guild_id INTEGER NOT NULL, current_song TEXT, queued_songs TEXT, loop INTEGER NOT NULL)" ) conn.commit() conn.close() self.lyrics_finder = Genius(GENIUS_TOKEN)
def get_lyrics(artist, song_title): """ Retrieves lyrics from Genius.com using a python """ artist = artist.lower() song_title = song_title.lower() genius = Genius(LYRICS_SECRET_KEY) # genius = lyricsgenius.Genius(LYRICS_SECRET_KEY) try: # import pdb; pdb.set_trace() song = genius.search_song(song_title, artist) # song = genius.song(song_title, artist) if (song): lyrics = song.lyrics.replace('\n', '<br>') return {'status': 'success', 'msg': 'ok', 'lyrics': lyrics} else: # No matching lyrics were found status = 'error' msg = NO_MATCHING_LYRICS lyrics = None return {'status': status, 'msg': msg, 'lyrics': lyrics} except Exception as e: print(f"Exception occurred in retrieving lyrics: {str(e)}") status = 'error' lyrics = None if e.status == 404: msg = f"{NO_MATCHING_LYRICS} (error-code ={e.status})" elif e.status == 403: msg = f"{LYRICS_SERVICE_NOT_RESPONDiNG} (error code={e.status}) " elif e.status == 500: msg = f"Server error occurred (error-code={e.status})" else: # Catch all for all other errors msg = f"{MISC_SERVER_ERROR} (error-code={e.status})" # import pdb; pdb.set_trace() return {'status': status, 'msg': msg, 'lyrics': lyrics}
class GetGenius: def __init__(self): # init Genius GENIUS_ACCESS_TOKEN = os.getenv('GENIUS_ACCESS_TOKEN') self.genius = Genius(GENIUS_ACCESS_TOKEN) def get_lyrics(self, query): lyrics = [] results = self.genius.search_lyrics(query) for hit in results['sections'][0]['hits']: if hit['result']['title'][-4:] != 'list': docid = hit['result']['id'] title = str(hit['result']['title']).replace('/', ' ').replace( '?', ' ') artist = hit['result']['primary_artist']['name'] url_img = hit['result']['song_art_image_url'] lyric = self.genius.search_song(title, artist).lyrics lyrics.append([docid, title, artist, url_img, lyric]) return (lyrics)
def retrieve_song_lyrics(update, context): '''get song lyrics''' text = update.message.text genius = Genius(LYRICS_TOKEN) genius.skip_non_songs = True song = genius.search_song(text, artist='', get_full_info=False) if not song: update.message.reply_text("Unable to find lyrics for the given song.") else: lyrics = song.lyrics song_length = len(lyrics) count = 0 try: while song_length > 4096: update.message.reply_text(lyrics[:4096]) song_length -= 4096 count += 1 update.message.reply_text(lyrics[4096 * count:]) except: update.message.reply_text( "Unable to find lyrics for the given song.") update.message.reply_text("Use /help to list available actions.") return ConversationHandler.END
def cmd_lyrics(arg): token = "47eX0yhBx2cDhrs1n7530NrDmSVJbuCmgCORJRDv9wvIbtbKRAK4BPP2_uoKVaN3" genius = Genius(token) search_phrase = str(arg) try: full_input = search_phrase.lower() full_input = full_input.split(",") artist_input = full_input[0] song_input = full_input[1] result = genius.search_song(song_input, artist_input) text_data = result.lyrics except Exception as E: text_data = ( "Lyric search failed, please check the spelling of the artist and song title. Please note, " "there are millions of songs and artist in the database, your query has to be exactly right to " "retrieve the lyrics.") text_data += "Your body of the message should look like one of the following examples: \r" text_data += "Ariana Grande, Imagine \r" text_data += "Lady Gaga, Shallow \r" text_data += "Mariah Carey, All I want for Christmas is Your \r" text_data += "Chainsmokers, Hope \r" text_data += "Error: " + str(E) return text_data
def init_genius(token): # get the genius instanse genius = Genius(token) # Turn off status messages genius.verbose = False # Remove section headers (e.g. [Chorus]) from lyrics when searching genius.remove_section_headers = True # Include hits thought to be non-songs (e.g. track lists) genius.skip_non_songs = False # Exclude songs with these words in their title genius.excluded_terms = ["(Remix)", "(Live)"] return genius
class Genius(Provider): name = 'genius' synchronized = False def __init__(self, config_entry): remove_section_headers = config_entry.getboolean( 'remove_section_headers', False) self.genius = LyrGenius( config_entry['token'], verbose=False, remove_section_headers=remove_section_headers, ) def get_lyrics(self, artist: str, title: str, _: int) -> Lyrics: lyrics = Lyrics() song = self.genius.search_song(title, artist, get_full_info=False) if song: lyrics.unsynchronized = song.lyrics return lyrics
def get_top_songs_for_artist(genius: lyricsgenius.Genius, artist: str, max_songs: int = None) -> List[dict]: """Searches Genius for the top songs for a given artist. Args: genius (lyricsgenius.Genius): LyricsGenius object to use for query. artist (str): Name of artist max_songs (int, optional): Maximum number of songs to return. Returns: List[dict]: List of songs or empty if no results. """ artist_obj = genius.search_artist(artist, max_songs=max_songs, sort='popularity') if artist_obj: return [song.to_dict() for song in artist_obj.songs] else: return []
def get_song_lyrics(genius: lyricsgenius.Genius, song: str, artist: str) -> Union[dict, None]: """Searches Genius for song details based on song name and artist. Args: genius (lyricsgenius.Genius): LyricsGenius object to use for query. song (str): Title of song artist (str): Name of artist Returns: Union[dict,None]: Song details (from JSON) or `None` if no results. """ songdetails = genius.search_song( title=song, artist=artist, get_full_info=True, ) if songdetails: return songdetails.to_dict() else: return None
def __init__(self, deck_name, deck_id): self.deck_name = deck_name self.deck_id = deck_id self.genius = Genius("DhLgBRFiLg4HOiABUzSJvGjpTDgX6vwVSFvyV3P6igiKdAhNdvq0VbwnF8QEXxa0") self.translator = Translator() self.songs = [] self.translated = {} self.model = genanki.Model( 1313562696, "lyrics-model", fields=[ {"name": "Term"}, {"name": "Translation"} ], templates=[ { "name": "term card", "qfmt": "{{Term}}", "afmt": "{{FrontSide}}<hr id='answer'>{{Translation}}" } ] )
def main(): genius = Genius(apikeys.genius) genius.excluded_terms = ['(How to pronounce)'] genius.remove_section_headers = True genius.skip_non_songs = True pinyin = Pinyin() song_info = [ input("Enter the song name\n"), input( "Enter the artist name (recommended, leave blank if you don't know)\n" ) ] song = genius.search_song(song_info[0], song_info[1]) lyrics = song.lyrics pinyin_lyrics = pinyin.get_pinyin(lyrics, splitter=' ', tone_marks='marks') pinyin_lyrics = cleanup(pinyin_lyrics) print(pinyin_lyrics) outfile_path = "C:\\Users\\Declan\\Desktop\\" + song.title + ', ' + song.artist + '-Pinyin.txt' outfile = open(outfile_path, 'w', encoding='utf-8') outfile.write(pinyin_lyrics) outfile.close()
class GeniusLyrics: def __init__(self, access_token, genius=None): self.__artist = None self.__title = None self.__lyrics = None self.__genius = None from lyricsgenius import Genius # use or create Genius class if isinstance(genius, Genius): self.__genius = genius else: self.__genius = Genius(access_token, skip_non_songs=True) @property def artist(self): return self.__artist @artist.setter def artist(self, new_artist): self.__artist = new_artist _LOGGER.debug(f"Artist set to: {self.__artist}") @property def title(self): return self.__title @title.setter def title(self, new_title): # filter out terms from title # TODO: move to CONFIG_SCHEMA exclude_terms = [ '(explicit', '(feat', ] _new_title = str(new_title).lower() for term in exclude_terms: if term in _new_title: pos = _new_title.find(term) self.__title = new_title[0:pos].strip() break else: self.__title = new_title _LOGGER.debug(f"Title set to: {self.__title}") @property def lyrics(self): return self.__lyrics def fetch_lyrics(self, artist=None, title=None): if artist: self.__artist = artist if title: self.__title = title if self.__artist is None or self.__title is None: _LOGGER.error("Missing artist and/or title") return _LOGGER.info( f"Search lyrics for artist='{self.__artist}' and title='{self.__title}'" ) song = self.__genius.search_song(self.__title, self.__artist, get_full_info=False) if song: _LOGGER.debug( f"Found song: artist = {song.artist}, title = {song.title}") # FIXME: need to avoid incorrectly found song lyrics # for now..comparing artist names suffices. Titles may differ (e.g. 'feat. John Doe') # if self.__title == song.title: # _LOGGER.debug(f"Found lyrics: {song.lyrics}") # if str(self.__artist).lower() == str(song.artist).lower() \ # or str(song.title).lower() in str(self.__title).lower(): self.__title = song.title self.__lyrics = song.lyrics return True else: self.__lyrics = "Lyrics not found" return False def reset(self): self.__artist = None self.__title = None self.__lyrics = None
from kivy.uix.recycleview.layout import LayoutSelectionBehavior from kivy.uix.popup import Popup from tkinter import Tk from tkinter.filedialog import askopenfilenames # Discog API Info header = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1"} discogs_token = 'DISCOG_TOKEN' d = discogs_client.Client('LibraryApp/0.1', user_token=discogs_token) # Genius Lyrics API Info genius_client_ID = 'GENIUS_ID' genius_client_secret = 'GENIUS_SECRET' genius_access_token = 'GENIUS_TOKEN' genius = Genius(genius_access_token) def get_lyrics(tags, filename=""): song_info = genius.search_song(tags.song, tags.artist) if not song_info: other_name = filename.lower().replace(tags.artist.lower(), "").replace(" - ", "") other_name = string.capwords(other_name) song_info = genius.search_song(other_name, tags.artist) if not song_info: song_info = genius.search_genius(search_term=filename) try: song_info.lyrics except AttributeError: return "" if not song_info: