def test_returnLyricsNotFound(): responses.add(responses.GET, 'https://lyrics.wikia.com/wiki/Lyricwikia:Lyricwikia', body='') with pytest.raises(LyricsNotFound): get_lyrics('Lyricwikia', 'Lyricwikia') assert len(responses.calls) == 1
def tfidf_transform(self): for (artist,song) in self.songs_info: #print (artist,song) lyrics = lyricwikia.get_lyrics(artist,song) doc = " ".join(lyrics.split("\n")) self.corpus_df = self.corpus_df.append({'Song_name':song, 'Lyrics':doc},ignore_index=True) self.TfIdf_vec = self.tfidf_vectorizer.fit_transform(list(self.corpus_df['Lyrics']))
def getLyrics(self, artist, song): out = "" try: out = lyricwikia.get_lyrics(artist, song) except: return "No lyrics found. :(" return out
def get_lyrics_of_song(self): audio_path = self.fileName song_tags = self.tags actor_name = "" song_name = "" try: actor_song_name = audio_path().split("/")[-1].split(".mp3")[0] actor_name = actor_song_name.split("-")[0] song_name = actor_song_name.split("-")[1] except (IndexError, TypeError, AttributeError): pass if not (not (actor_name == "") or not (song_name == "") or not (song_tags != "") or not song_tags['ID3TagV1'][ 'album']) and \ song_tags["ID3TagV2"]["artist"]: actor_name = song_tags["ID3TagV2"]["artist"] song_name = song_tags["ID3TagV1"]["album"] msg = QMessageBox() fullText = '<table class="tftable" border="0">' try: lyrics = lyricwikia.get_lyrics(actor_name, song_name) lyrics_list = lyrics.split('\n') for lyrics in lyrics_list: fullText = fullText + '<tr><td>' + lyrics + '</td><td>' + "" + '</td></tr>' fullText = fullText + '</table>' except LyricsNotFound: fullText = fullText + '<tr><td>' + "Lyrics bulunamadı." + '</td><td>' + "" + '</td></tr>' fullText = fullText + '</table>' msg.setText(fullText) msg.about(self, "Lyrics", fullText)
def spotify_thread(stdscr, pad): global pos, lyrics, title old_song = '' while True: height, width = stdscr.getmaxyx() song = get_spotify_song_data() song_title = song['title'].split('-')[0] title = '{} - {}\n'.format(song_title, song['artist']) if old_song != title: pos = 0 old_song = title try: lyrics = lyricwikia.get_lyrics(song['artist'].strip(), song['title'].strip()) if 'Unfortunately, we are not licensed to display' in lyrics: lyrics = get_lyrics(title.strip()) except lyricwikia.LyricsNotFound: lyrics = get_lyrics(title) pad.clear() pad.addstr(title, curses.A_BOLD) pad.addstr(lyrics) pad.refresh(0, 0, 0, 0, height - 1, width) time.sleep(1)
def get_lyrics(self): try: lyrics = lyricwikia.get_lyrics(self.artist, self.song) except Exception: print("Error!") return print(lyrics)
def handleReq(self, session): id = self.params["id"] artist = self.params["artist"] title = self.params["title"] if id: track = session.query(Track).filter(Track.id == id).one_or_none() if not track: raise NotFound("Item not found") artist = track.artist.name title = track.title elif not artist and not title: raise NotFound("Item not found") try: resp = lyricwikia.get_lyrics(artist, title) except lyricwikia.LyricsNotFound: raise NotFound("Item not found") except Exception as e: log.error("Error talking to LyricWikia: " + str(e)) return self.makeResp(status=504) lyrics = ET.Element("lyrics") lyrics.set("artist", artist) lyrics.set("title", title) lyrics.text = resp return self.makeResp(child=lyrics)
def get_lyrics(self, linesep="\n", timeout=None): try: lyrics = lyricwikia.get_lyrics(self.artist, self.song, linesep, timeout) except lyricwikia.LyricsNotFound as e: raise LyricsNotFound(e.args[0]) else: return lyrics
def get_track_info(track_id): """ Get information about a specific track. :param track_id: A unique alphanumeric sequence for a spotify track. :returns: A dictionary containing track details """ items = spotify.track(track_id) name = items["name"] artists_names = ", ".join( [items["artists"][x]["name"] for x in range(len(items["artists"]))]) album_artists = ", ".join([ items["album"]["artists"][x]["name"] for x in range(len(items["album"]["artists"])) ]) album_type = items["album"]["album_type"] album_name = items["album"]["name"] album_release = items["album"]["release_date"] album_track_number = items["track_number"] track_duration = items["duration_ms"] images_link = items["album"]["images"] max_image_res = 0 max_icon_size = 0 image_link = "" icon_link = "" for image in images_link: if image["height"] * image["width"] > max_image_res: image_link = image["url"] max_image_res = image["height"] * image["width"] if image["height"] < 400: if image["height"] > max_icon_size: max_icon_size = image["height"] icon_link = image["url"] track = { "name": name, "Artist(s)": artists_names, "Album Artist(s)": album_artists, "Album Type": album_type, "Album Name": album_name, "Album Release": album_release, "Track Number": album_track_number, "Track Duration (ms)": track_duration, "Image Link": image_link, "Icon Link": icon_link } for artist in artists_names.split(', '): """ Checks for lyrics with song name and artist names combination until one is found. """ try: lyrics = lyricwikia.get_lyrics(artist, name) track['lyrics'] = lyrics break except lyricwikia.LyricsNotFound: pass return track
def from_artist_and_track(self, artist, track, linesep="\n", timeout=None): """ Returns the lyric string for the given artist and track. """ try: lyrics = lyricwikia.get_lyrics(artist, track, linesep, timeout) except lyricwikia.LyricsNotFound as e: raise LyricsNotFoundError(e.args[0]) return lyrics
def generate_metadata(raw_song): """ Fetch a song's metadata from Spotify. """ if internals.is_spotify(raw_song): # fetch track information directly if it is spotify link log.debug("Fetching metadata for given track URL") sys.stdout.flush() meta_tags = spotify.track(raw_song) else: # otherwise search on spotify and fetch information from first result log.debug('Searching for "{}" on Spotify'.format(raw_song)) sys.stdout.flush() try: meta_tags = spotify.search(raw_song, limit=1)["tracks"]["items"][0] except IndexError: return None artist = spotify.artist(meta_tags["artists"][0]["id"]) album = spotify.album(meta_tags["album"]["id"]) try: meta_tags[u"genre"] = titlecase(artist["genres"][0]) except IndexError: meta_tags[u"genre"] = None try: meta_tags[u"copyright"] = album["copyrights"][0]["text"] except IndexError: meta_tags[u"copyright"] = None try: meta_tags[u"external_ids"][u"isrc"] except KeyError: meta_tags[u"external_ids"][u"isrc"] = None meta_tags[u"release_date"] = album["release_date"] meta_tags[u"publisher"] = album["label"] meta_tags[u"total_tracks"] = album["tracks"]["total"] log.debug("Fetching lyrics") sys.stdout.flush() try: meta_tags["lyrics"] = lyricwikia.get_lyrics( meta_tags["artists"][0]["name"], meta_tags["name"] ) except lyricwikia.LyricsNotFound: meta_tags["lyrics"] = None # Some sugar meta_tags["year"], *_ = meta_tags["release_date"].split("-") meta_tags["duration"] = meta_tags["duration_ms"] / 1000.0 meta_tags["spotify_metadata"] = True # Remove unwanted parameters del meta_tags["duration_ms"] del meta_tags["available_markets"] del meta_tags["album"]["available_markets"] log.debug(pprint.pformat(meta_tags)) sys.stdout.flush() return meta_tags
def get_lyrics(artists, track): for artist in artists: try: artist_name = artist['name'] lyric = lyricwikia.get_lyrics(artist_name, track) lyric_lines = lyric.splitlines() return lyric_lines except Exception: continue
def download_lyrics(songs_list): for song in songs_list: print(f"Searching for {song} lyrics...") try: lyrics = lw.get_lyrics('the rolling stones', song) with open(f"data/lyrics/{song}.txt", 'w', encoding='utf-8') as f: f.write(lyrics) except LyricsNotFound: print("Lyrics not found.")
def test_returnLyrics(): responses.add(responses.GET, 'https://lyrics.wikia.com/wiki/Lyricwikia:Lyricwikia', body=('<div class="lyricbox">thank<br/>you.</div>')) lyrics = get_lyrics("Lyricwikia", "Lyricwikia") assert len(responses.calls) == 1 assert lyrics == "thank\nyou."
def find_lyrics(self, artist, title, progress): try: lyrics = lyricwikia.get_lyrics(artist, title) lyrics = lyrics.split() index = int(progress * len(lyrics)) sing_along = ' '.join(lyrics[index:(index + self.lyric_length)]) return sing_along except lyricwikia.LyricsNotFound: return (None)
def download_lyric(song): try: lyric = lyricwikia.get_lyrics(song['Artist'], song['Title']) filename = '_'.join([song['Mood'], song['Artist'], song['Title']]) filename = filename.replace('/', '-') # The '/' should never appear with open(os.path.join(args.output, filename), 'w') as sfile: sfile.write(lyric) return True except lyricwikia.LyricsNotFound: err('Could not download {}: {}, {}'.format(song['Index'], song['Artist'], song['Title'])) return False
def get_lyrics(artist_name, song_name): try: lyrics = lyricwikia.get_lyrics(artist_name, song_name) return clean(lyrics) except: print("Sorry, " + song_name + " by " + artist_name + " was not found in lyric database") return None #print(get_lyrics("Eminem", "lose yourself"))
def get_song_lyrics(): artist = artist_entry.get() global song song = song_entry.get() try: lyrics = lyricwikia.get_lyrics(artist, song) # gets the lyrics from the api except Exception: pyautogui.alert(title='Error!', text="Error! Song or Artist Not Found") else: song_lyrics.delete("1.0", "end") # "flashes" the text box song_lyrics.insert("1.0", lyrics) # putting in the new song lyrics
def show_details(): toplevel = Toplevel(root) toplevel.title("Lyrics") toplevel.geometry("1000x700") s = Scrollbar(toplevel) t = Text(toplevel, height=100, width=1000) s.pack(side=RIGHT, fill=Y) t.pack(side=LEFT, fill=Y) s.config(command=t.yview) t.config(yscrollcommand=s.set) t.insert(END, lyricwikia.get_lyrics(name.get(), song.get()))
def generate_metadata(raw_song): """ Fetch a song's metadata from Spotify. """ if internals.is_spotify(raw_song): # fetch track information directly if it is spotify link log.debug('Fetching metadata for given track URL') meta_tags = spotify.track(raw_song) else: # otherwise search on spotify and fetch information from first result log.debug('Searching for "{}" on Spotify'.format(raw_song)) try: meta_tags = spotify.search(raw_song, limit=1)['tracks']['items'][0] except IndexError: return None artist = spotify.artist(meta_tags['artists'][0]['id']) album = spotify.album(meta_tags['album']['id']) try: meta_tags[u'genre'] = titlecase(artist['genres'][0]) except IndexError: meta_tags[u'genre'] = None try: meta_tags[u'copyright'] = album['copyrights'][0]['text'] except IndexError: meta_tags[u'copyright'] = None try: meta_tags[u'external_ids'][u'isrc'] except KeyError: meta_tags[u'external_ids'][u'isrc'] = None meta_tags[u'release_date'] = album['release_date'] meta_tags[u'publisher'] = album['label'] meta_tags[u'total_tracks'] = album['tracks']['total'] log.debug('Fetching lyrics') try: meta_tags['lyrics'] = lyricwikia.get_lyrics( meta_tags['artists'][0]['name'], meta_tags['name']) except lyricwikia.LyricsNotFound: meta_tags['lyrics'] = None # Some sugar meta_tags['year'], *_ = meta_tags['release_date'].split('-') meta_tags['duration'] = meta_tags['duration_ms'] / 1000.0 # Remove unwanted parameters del meta_tags['duration_ms'] del meta_tags['available_markets'] del meta_tags['album']['available_markets'] log.debug(pprint.pformat(meta_tags)) return meta_tags
def download_lyric(artist, title, output_path): ''' Download the lyric given artist and title ''' try: lyric = lyricwikia.get_lyrics(artist, title) if lyric == COPYRITH_ERROR: err_msg = 'Copyright error for {}, {}'.format(artist, title) raise Exception(err_msg) with open(output_path, 'w') as sfile: sfile.write(lyric) except lyricwikia.LyricsNotFound: raise Exception('Could not download {}, {}'.format(artist, title))
def lyrics(): print() time.sleep(15.0) print("Oh Ooo Whoah-Ooo Whoah") time.sleep(2.0) print("Ohh Huuuh") time.sleep(5.0) lyrics = lyricwikia.get_lyrics('wham', 'careless whisper') #API for getting full song lyrics listLyrics = [] listLyrics = lyrics.split('\n') #places lyrics in listLyrics array listLyrics = listLyrics[9:68] #has only the lyrics from indexes 9 to 69 time.sleep(5.5) print(listLyrics[0]) #space print(listLyrics[1]) #I feel so unsure time.sleep(6.0) print(listLyrics[2]) #as I take your hand time.sleep(7.0) print(listLyrics[3])#as the music dies time.sleep(2.5) print(listLyrics[4]) #something in your eyes time.sleep(3.0) print(listLyrics[5]) #calls to mind the silver screen time.sleep(2.0) print(listLyrics[6]) #space time.sleep(5.0) print(listLyrics[7]) #I'm never gonna dance again time.sleep(3.0) print(listLyrics[8]) #guilty feet time.sleep(3.0) print(listLyrics[9]) #though it's easy to pretend time.sleep(2.5) print(listLyrics[10]) #I know you're not a fool time.sleep(2.0) print(listLyrics[11])#space time.sleep(2.0) print(listLyrics[12])#shouldve known better than to cheat a friend time.sleep(2.5) print(listLyrics[13]) #and waste the chance that I've been givem time.sleep(3.5) print(listLyrics[14]) #so I'm never gonna dance again time.sleep(3.0) print(listLyrics[15]) #the way I danced with you time.sleep(4.5) print("Ohhhh Huuuuh") time.sleep(11.0) print() print("Hope you enjoyed ヾ(*◎○◎)ノ♫♪♩")
def get_lyrics(query): if '-' not in query: return "How to search?" \ "\njust type: (artist) - (song)" \ "\nex) kendrick lamar - i" artist, song = query.split('-') if 'feat.' in artist: artist = artist.split('feat')[0] try: lyric = lyricwikia.get_lyrics(artist, song) return lyric except: return 0
def print_lyrics(artist: str, title: str) -> None: """ Using lyricwikia to get lyrics """ name = format_name(artist, title) if platform.system() == 'Windows': print(f">> {name}") else: print(f"\033[4m{name}\033[0m") try: print(lyricwikia.get_lyrics(artist, title) + "\n") except (lyricwikia.LyricsNotFound, AttributeError): print("No lyrics found\n")
def find(self): try: if self.provider == self.PROVIDER_GENIUS: song = self.genius.search_song(player.now_playing.title, player.now_playing.artist) return song.lyrics elif self.provider == self.PROVIDER_LYRICSWIKIA: return lyricwikia.get_lyrics(player.now_playing.artist, player.now_playing.title) elif self.provider == self.PROVIDER_PYLYRICS: return PyLyrics.getLyrics(player.now_playing.artist, player.now_playing.title) except Exception as e: return player.now_playing.artist + ': ' + player.now_playing.title + '\n' \ + self.provider + ' server error: ' + str(e)
def get_lyric(self, spid): lpath = os.path.join(self.outputFolder, spid) if os.path.isfile(lpath): with open(lpath, 'r') as f: return f.read() # Download the song song = self.spotify[spid] artist, title = song['artist_name'], song['track_name'] try: lyrics = lyricwikia.get_lyrics(artist, title) except lyricwikia.LyricsNotFound: return None with open(os.path.join(self.outputFolder, spid), 'w') as f: f.write(lyrics) return lyrics
def saveCSV(songArtistCSV): df = pandas.read_csv(songArtistCSV, encoding='latin-1') nf = 0 lyrArr = [] for index, row in df.iterrows(): try: lyrics = lw.get_lyrics( (row["Artist"] + ";")[:row["Artist"].find(";")], row["Song"]) lyrArr += [lyrics] except Exception as e: print(row["Song"], " not found.") nf += 1 lyrArr += [-1] print("Song Index ", index) print("Number of Songs not Found: ", nf) df["lyrics"] = lyrArr df.to_csv(songArtistCSV[:-4] + "lyrics.csv")
def getBestSong(): a_dict = {} for artist in artists: #print(artist.item) a_dict[str(artist.item)] = [] tracks = artist.item.get_top_tracks() for track in tracks: a_dict[str(artist.item)].append(str(track.item).split('-')[1].strip()) fout = open('artist-song.txt', 'w') lyrics = [] for a in a_dict: for t in a_dict[a]: #fout.write(a + "~" + t + '\n') try: lyric = lyricwikia.get_lyrics(a, t) lyrics.append(lyric) #print("Success!") except: print("This song was not found: " + t + "by " + a) for l in lyrics: in_dict = 0.0 total = 0.0 for w in nltk.word_tokenize(l): word = w.lower() if word in d: in_dict += 1 if word not in puncts: total += 1 perc = (in_dict / total) * 100 best_song = lyrics[0].split('\n') stresses = [] num_beats = [] for line in best_song: words, curr_stress = st.getBeatFromSentence(line) if len(curr_stress) > 0: stresses.append(curr_stress.split(' ')) num_beats.append(len(curr_stress.split(' '))) return stresses, num_beats
def generate_metadata(filename, raw_song): """ Fetch a song's metadata from Spotify. """ print('Fetching the song data for: ' + raw_song) try: meta_tags = spotify.search(raw_song, limit=1)['tracks']['items'][0] except IndexError: print('Index error') return None artist = spotify.artist(meta_tags['artists'][0]['id']) album = spotify.album(meta_tags['album']['id']) try: meta_tags[u'genre'] = titlecase(artist['genres'][0]) except IndexError: meta_tags[u'genre'] = None try: meta_tags[u'copyright'] = album['copyrights'][0]['text'] except IndexError: meta_tags[u'copyright'] = None try: meta_tags[u'external_ids'][u'isrc'] except KeyError: meta_tags[u'external_ids'][u'isrc'] = None meta_tags[u'release_date'] = album['release_date'] meta_tags[u'publisher'] = album['label'] meta_tags[u'total_tracks'] = album['tracks']['total'] #Fetching the lyrics try: meta_tags['lyrics'] = lyricwikia.get_lyrics( meta_tags['artists'][0]['name'], meta_tags['name']) except lyricwikia.LyricsNotFound: meta_tags['lyrics'] = None # Some sugar meta_tags['year'], *_ = meta_tags['release_date'].split('-') meta_tags['duration'] = meta_tags['duration_ms'] / 1000.0 # Remove unwanted parameters del meta_tags['duration_ms'] del meta_tags['available_markets'] del meta_tags['album']['available_markets'] writeMetadata.writeSongMeta(filename,raw_song,meta_tags)
def getLyrics(songs): i = -1 print("Total songs number:" + str(songs.shape[0])) for index, row in songs.iterrows(): i += 1 if i%100 == 0: print("Processing song [" + str(i) + "]") song = row['track_name'] #print(song) artist = row['artist'] try: lyric = ly.get_lyrics(artist, song, linesep='\n', timeout=None) songs.loc[index,'lyric'] = lyric except: continue #print(lyric) return songs
def test_integration(): lyrics = get_lyrics('Led Zeppelin', 'Stairway to Heaven') assert 'lady' in lyrics.lower()