def get_song_ids_from_db(): con = mdb.connect(ADDRESS, USERNAME, PASSWORD, SCHEMA) musixmatch = Musixmatch(MM_API_KEY) with con: cur = con.cursor() cur.execute( "SELECT DISTINCT song_name, artist_name, artist_id FROM popular_songs, artists WHERE popular_songs.artist_name = artists.name AND song_id = -1") set_of_new_songs = set() dict_of_updates_popular = dict() for i in range(cur.rowcount): row = cur.fetchone() song_name, artist_name, artist_id = row[0], row[1], row[2] set_of_new_songs.add((song_name, artist_name, artist_id)) for song_name, artist_name, artist_id in set_of_new_songs: cur.execute( "SELECT song_id FROM songs WHERE title = %s AND artist_id = %s", (song_name, artist_id)) if cur.rowcount > 0: song_id = cur.fetchone()[0] dict_of_updates_popular.update({(song_name, artist_name): song_id}) else: try: message = musixmatch.matcher_track_get(song_name, artist_name).get('message') if message.get('header').get('status_code') == 200: track = message.get('body').get('track') song_id = track.get('track_id') lyrics_id = track.get('lyrics_id') album_id = track.get('album_id') rating = track.get('track_rating') insert_new_song_mm(con, song_id, song_name, lyrics_id, album_id, artist_id, rating) except Exception as e: print "error occurred: couldn't get song " + song_name print e.message update_popular_songs(cur, dict_of_updates_popular)
def run(): musixMatch = Musixmatch(environ["API_KEY"]) dataService = DataService() countryService = CountryService() # LANGUAGE languagetable = LanguageDetectionService().get_language_table( dataService.all_lyrics) languagetable.name = "language" # MUSIXMATCH entries = dataService.all_entries track_info = musixMatch.label_entries(entries) tracktable = DataCleanUpService.make_track_information_table(track_info) # COUNTRY countries = dataService.all_countries country_info = countryService.get_country_info(countries) countrytable = DataCleanUpService.make_country_information_table( dataService.all_countries, country_info) # COMBINE df = (dataService.contestants.join(languagetable, how="left").join( tracktable, how="left").merge(countrytable, how="left", left_on="to_country", right_on="to_country")) # OUTPUT df.to_pickle("contestdata.pickle") df.to_feather("contestdata.arrow") df.to_csv("contestantdata.csv", quoting=csv.QUOTE_NONNUMERIC)
def get_release_dates_albums_and_types(): musixmatch = Musixmatch(MM_API_KEY) con = mdb.connect(ADDRESS, USERNAME, PASSWORD, SCHEMA) with con: cur = con.cursor() dict_of_dates = dict() try: cur.execute("SELECT album_id FROM albums WHERE type IS NULL") for i in range(cur.rowcount): album_id = cur.fetchone()[0] album = musixmatch.album_get(album_id).get('message').get('body').get('album') release_date = album.get('album_release_date') album_type = album.get('album_release_type') release_date = release_date.split('-') year = -1 month = -1 if len(release_date) > 0: year = release_date[0] if len(release_date) > 1: month = release_date[1] dict_of_dates.update({album_id: (month, year, album_type)}) update_albums_release_date_and_type(cur, dict_of_dates) except Exception as e: print "error occurred: " print e.message print "size of dict: " + str(len(dict_of_dates)) update_albums_release_date_and_type(cur, dict_of_dates)
def get_lyrics_of_tracks(): musixmatch = Musixmatch(MM_API_KEY) con = mdb.connect(ADDRESS, USERNAME, PASSWORD, SCHEMA) con.set_character_set('utf8') with con: cur = con.cursor() cur.execute('SET CHARACTER SET utf8') cur.execute('SET character_set_connection=utf8') dict_of_lyrics = dict() set_of_existing_ids = get_existing_lyrics(con) try: cur.execute("SELECT song_id FROM songs") for i in range(cur.rowcount): song_id = cur.fetchone()[0] if song_id not in set_of_existing_ids: message = musixmatch.track_lyrics_get(song_id).get('message') if message.get('header').get('status_code') == 200: lyrics = message.get('body').get('lyrics') text = lyrics.get('lyrics_body') src_language = lyrics.get('lyrics_language') dict_of_lyrics.update({song_id: (text, src_language)}) except Exception as e: print "error occurred: " print e.message print "size of dict: " + str(len(dict_of_lyrics)) insert_into_lyrics(cur, dict_of_lyrics)
def get_album_ratings(): musixmatch = Musixmatch(MM_API_KEY) con = mdb.connect(ADDRESS, USERNAME, PASSWORD, SCHEMA) with con: cur = con.cursor() cur.execute("SELECT album_id FROM albums WHERE rating IS NULL") everything_list = [] for i in range(cur.rowcount): id = cur.fetchone()[0] album = musixmatch.album_get(id) rating = album.get('message').get('body').get('album').get('album_rating') everything_list.append((rating, id)) for item in everything_list: cur.execute("UPDATE albums SET rating = %s WHERE album_id = %s", item)
def get_song_musixmatch(track_name, artist_name): musixmatch = Musixmatch(MUSIXMATCH_TOKEN) response = musixmatch.matcher_lyrics_get(track_name, artist_name) if response['message']['header']['status_code'] != 200: return None lyrics = add_line_breaks( response['message']['body']['lyrics']['lyrics_body'].split('\n')) return { 'lyrics': lyrics if lyrics != [""] else None, 'source': 'Musixmatch', }
def get_lyrics_mus(artist, artist2, song): credentials = json.load(open("authorization.json")) musixmatch_key = credentials['musixmatch_key'] if artist2 is not None: artist_details = artist + ' feat ' + artist2 else: artist_details = artist mus = Musixmatch(musixmatch_key) response = mus.matcher_lyrics_get(q_track=song, q_artist=artist_details) if len(response['message']['body']) != 0: print(response['message']['body']['lyrics']['lyrics_body']) return response['message']['body']['lyrics']['lyrics_body'] return None
def get_lyric_by_track_id(musixmatch_api: Musixmatch, track_id: int): response: dict = {} try: response: dict = musixmatch_api.track_lyrics_get(track_id) response = response.get("message") except Exception as e: logger.error(e) return response
def get_mbid_from_albums(): musixmatch = Musixmatch(MM_API_KEY) con = mdb.connect(ADDRESS, USERNAME, PASSWORD, SCHEMA) with con: cur = con.cursor() dict_of_mbids = dict() try: cur.execute("SELECT album_id FROM albums WHERE albums.album_mbid IS NULL") for i in range(cur.rowcount): album_id = cur.fetchone()[0] album = musixmatch.album_get(album_id).get('message').get('body').get('album') album_mbid = album.get('album_mbid') dict_of_mbids.update({album_id: album_mbid}) except Exception as e: print "error occurred: " print e.message print "size of dict: " + str(len(dict_of_mbids)) update_album_mbid(cur, dict_of_mbids)
def get_lyrics_by_match_query(musixmatch_api: Musixmatch, q_track: str, q_artist: str): response: dict = {} try: response: dict = musixmatch_api.matcher_lyrics_get( q_track=q_track, q_artist=q_artist) response = response.get("message") except Exception as e: logger.error(e) return response
def get_all_tracks_from_albums(): musixmatch = Musixmatch(MM_API_KEY) con = mdb.connect(ADDRESS, USERNAME, PASSWORD, SCHEMA) with con: cur = con.cursor() list_of_lists_of_songs = list() try: cur.execute( "SELECT album_id, album_mbid FROM albums WHERE album_mbid IS NOT NULL") for i in range(cur.rowcount): row = cur.fetchone() album_id, album_mbid = row[0], row[1] ll = musixmatch.album_tracks_get(album_id, 1, 100, album_mbid).get('message') list_of_lists_of_songs.append(ll.get('body').get('track_list')) insert_new_tracks_from_list(con, list_of_lists_of_songs) except Exception as e: print "error occurred: " print e.message print "size of list of lists: " + str(len(list_of_lists_of_songs)) insert_new_tracks_from_list(con, list_of_lists_of_songs)
def get_all_albums_from_artists(): musixmatch = Musixmatch(MM_API_KEY) con = mdb.connect(ADDRESS, USERNAME, PASSWORD, SCHEMA) with con: cur = con.cursor() cur.execute("SELECT artist_id FROM artists") list_of_lists_of_albums = list() for i in range(cur.rowcount): id = cur.fetchone()[0] for j in range(1, 5): list_of_lists_of_albums.append( musixmatch.artist_albums_get(id, 1, j, 100, 'desc').get('message').get('body').get('album_list')) for lst in list_of_lists_of_albums: for album in lst: album = album.get('album') artist_id = album.get('artist_id') album_id = album.get('album_id') album_name = album.get('album_name') rating = album.get('album_rating') album_cover = album.get('album_coverart_100x100') insert_new_album_mm(con, album_id, album_name, artist_id, album_cover, rating)
def test_song(self): song_id = '3nWzRkoCa44adZZ00li9sF' track = spotify.track(song_id) track_name = track['name'] musixmatch = Musixmatch('a4eb641afe366d7ce6d2013779c11916') lyrics_res = musixmatch.matcher_lyrics_get( q_artist='Big Sean', q_track=track_name)['message'] if lyrics_res['header']['status_code'] == 200: lyrics = lyrics_res['body']['lyrics']['lyrics_body'] else: lyrics = 'Lyrics Not Available for This Song' cor_song_res = [ 'Go Legend (& Metro Boomin)', "If young Metro don't trust you, I'm gon' shoot you\nDo you know where you're going to?\nDo you like the things that life is showing you?\nWhere are you going to? (straight)\nDo you know?\n\n[Chorus: Travis Scott & Big Sean]\nMe and my best friend, 7-Eleven (yeah)\nWe go legend, we go legend (yeah, yeah)\nWe go legend, we go legend (alright)\nWe go legend, we go legend, yeah\nMe and my best friend, 7-Eleven, yeah\nWe go legend (go), we go legend (go), yeah (yeah)\nWe go legend (go), we go legend (go legend)\nWe go legend, we go legend, yeah\nWith my best friend (alright), 7-Eleven (whoa)\nWe go legend, (yeah) we can go legend\nCodeine legend (yeah, yeah), microphone legend\nWe go legend, yeah\n\n\nIn my house, yeah, hear alarms\nRingin' through my house (through my house), got 'em goin'\nClimbing in and out (in and out)\nWhat you knowin'? Never run your mouth (never run your mouth)\n \n\nLook, bitch, this not a drill, this the real thing (whoa)\nI do what the f**k I feel, f**k your feelings, yeah\nMade my blueprints, so my life got no ceilings (I don't see 'em)\nI create the energy that they keep stealing, yeah\n...\n\n******* This Lyrics is NOT for Commercial use *******\n(1409617537910)" ] self.assertEqual([track_name, lyrics], cor_song_res)
def get_tracks_musixmatch(): try: musixmatch = Musixmatch(MM_API_KEY) con = mdb.connect(ADDRESS, USERNAME, PASSWORD, SCHEMA) for i in range(1, 10): chart = musixmatch.chart_tracks_get(i, 100, 0, country='il') list_of_tracks = chart.get('message').get('body').get('track_list') for j in range(100): track = list_of_tracks[j].get('track') song_id = track.get('track_id') title = track.get('track_name') lyrics_id = track.get('lyrics_id') album_id = track.get('album_id') album_name = track.get('album_name') artist_id = track.get('artist_id') artist_name = track.get('artist_name') album_cover = track.get('album_coverart_100x100') rating = track.get('track_rating') insert_new_artist_mm(con, artist_name, artist_id) insert_new_album_mm(con, album_id, album_name, artist_id, album_cover) insert_new_song_mm(con, song_id, title, lyrics_id, album_id, artist_id, rating) except: pass
def search_track_by_query(musixmatch_api: Musixmatch, q_track: str, q_artist: str, page_size: int = 10, page: int = 1): response: dict = {} try: response: dict = musixmatch_api.track_search(q_track=q_track, q_artist=q_artist, page_size=page_size, page=page, s_track_rating="desc") response = response.get("message") except Exception as e: logger.error(e) return response
def analyze_artist(artist_name): total_lyrics = dict() long_lyrics = dict() musixmatch = Musixmatch('1d5d5c029c5f15411a43e55e7efe4517') print(musixmatch) search_term = artist_name result = (musixmatch.artist_search(search_term, 1, 5, '', '')) # print(result) artist = result['message']['body']['artist_list'][0]['artist'] #print(artist['artist_name']) artist_id = artist['artist_id'] artist_name = artist['artist_name'] albums = musixmatch.artist_albums_get( artist_id, '', 1, 10, 'desc')['message']['body']['album_list'] try: genre = albums[0]['album']['primary_genres']['music_genre_list'][0][ 'music_genre']['music_genre_name_extended'] except IndexError: genre = 'N/A' for album in albums: album_id = album['album']['album_id'] # try: # print('\t' + album['album']['album_name']) # except: # pass track_list = musixmatch.album_tracks_get( album_id, 1, 25, '')['message']['body']['track_list'] for track in track_list: track_id = track['track']['track_id'] # try: # print('\t\t' + track['track']['track_name']) # except: # pass track_lyrics = musixmatch.track_lyrics_get( track_id)['message']['body']['lyrics']['lyrics_body'] total_lyrics, long_lyrics = tokenize_song( "\n".join(track_lyrics.split("\n")[:-2]), total_lyrics, long_lyrics) ego_rating = rateEgo(total_lyrics) unique_word_count = len(total_lyrics.keys()) top_fifteen = sorted(long_lyrics.items(), key=lambda t: (-t[1], t[0]))[0:10] return (artist_name, unique_word_count, genre, top_fifteen, ego_rating, total_lyrics) '''print('Unique words in vocabulary:' + str(unique_word_count))
def get_lyrics_api(artist_name): musixmatch_key = config.MUSIXMATCH_KEY musixmatch = Musixmatch(musixmatch_key) lyrics_list = [] final_verse_list = [] try: artists_json = musixmatch.artist_search(q_artist=artist_name, page_size=1, page=1, f_artist_id="", f_artist_mbid="") artist_id = artists_json['message']['body']['artist_list'][0][ 'artist']['artist_id'] albums_json = musixmatch.artist_albums_get(artist_id=artist_id, page_size=5, page=1, s_release_date='desc', g_album_name="") albums_list = albums_json['message']['body']['album_list'] for album in albums_list: albums_id = album['album']['album_id'] tracks_json = musixmatch.album_tracks_get(album_id=albums_id, f_has_lyrics=True, page_size=20, page=1, album_mbid='') tracks_list = tracks_json['message']['body']['track_list'] for track in tracks_list: tracks_id = track['track']['track_id'] lyrics_json = musixmatch.track_lyrics_get(tracks_id) lyrics = lyrics_json['message']['body']['lyrics'][ 'lyrics_body'] sep = '*******' lyrics = lyrics.split(sep, 1)[0] lyrics = lyrics.replace('\\', ' ') lyrics = lyrics.replace('\"', ' ') lyrics = lyrics.replace('\\n', ',') lyrics = lyrics.replace('\n', ',') #lyrics = lyrics.replace('...', ',') #lyrics = lyrics.replace('?', ' ') #lyrics = lyrics.replace('!', ' ') final_verse_list.append(lyrics) return final_verse_list except: return None
def setup_class(cls): cls.musixmatch = Musixmatch("test") cls.url = "http://api.musixmatch.com/ws/1.1/"
def setUp(self): self.musixmatch = Musixmatch(os.environ.get('APIKEY')) self.url = 'http://api.musixmatch.com/ws/1.1/'
class TestMusixmatch(unittest.TestCase): def setUp(self): self.musixmatch = Musixmatch(os.environ.get('APIKEY')) self.url = 'http://api.musixmatch.com/ws/1.1/' def test_get_url(self): self.assertEqual( self.musixmatch._get_url('chart.artists.get?' 'page=1&page_size=1&country=us' '&format=json'), self.url + 'chart.artists.get?' 'page=1&page_size=1' '&country=us&format=json&apikey={}'.format( os.environ.get('APIKEY'))) def test_apikey(self): self.assertEqual(self.musixmatch._apikey, os.environ.get('APIKEY')) def test_chart_artists(self): self.assertEqual( self.musixmatch.chart_artists(1, 1)['message']['body'] ['artist_list'][0]['artist']['artist_vanity_id'], 'Ed-Sheeran') self.assertEqual( self.musixmatch.chart_artists(1, 1)['message']['body'] ['artist_list'][0]['artist']['artist_mbid'], 'b8a7c51f-362c-4dcb-a259-bc6e0095f0a6') def test_chart_tracks_get(self): self.assertEqual( self.musixmatch.chart_tracks_get( 1, 1, 1)['message']['body']['track_list'][0]['track']['album_name'], '2U (feat. Justin Bieber)') self.assertEqual( self.musixmatch.chart_tracks_get( 1, 1, 1)['message']['body']['track_list'][0]['track']['track_name'], '2U') def test_track_search(self): self.assertEqual( self.musixmatch.track_search( q_track='Let Me Love You', q_artist='justinbieber', page_size=10, page=1, s_track_rating='desc')['message']['body']['track_list'], []) def test_track_get(self): self.assertEqual( self.musixmatch.track_get(15445219)['message']['body']['track'] ['artist_name'], 'Lady Gaga') self.assertEqual( self.musixmatch.track_get(15445219)['message']['body']['track'] ['album_name'], 'The Fame Monster') def test_track_lyrics_get(self): self.assertEqual( self.musixmatch.track_lyrics_get(15953433)['message']['body'] ['lyrics']['lyrics_language'], 'en') self.assertEqual( self.musixmatch.track_lyrics_get(15953433)['message']['body'] ['lyrics']['lyrics_language_description'], 'English') self.assertEqual( self.musixmatch.track_lyrics_get(15953433)['message']['body'] ['lyrics']['lyrics_id'], 15912802) def test_track_snippet_get(self): self.assertEqual( self.musixmatch.track_snippet_get(16860631)['message']['body'] ['snippet']['snippet_id'], 16229519) self.assertEqual( self.musixmatch.track_snippet_get(16860631)['message']['body'] ['snippet']['snippet_body'], "You shoot me down, but I won't fall") def test_track_subtitle_get(self): self.assertEqual( self.musixmatch.track_subtitle_get(14201829)['message']['body'], '') def test_track_richsync_get(self): self.assertEqual( self.musixmatch.track_richsync_get(114837357)['message']['body'] ['richsync']['richsync_id'], 6) self.assertEqual( self.musixmatch.track_richsync_get(114837357)['message']['body'] ['richsync']['richsync_length'], 230) def test_track_lyrics_post(self): self.assertEqual( self.musixmatch.track_lyrics_post( 1471157, 'test')['message']['header']['status_code'], 200) self.assertEqual( self.musixmatch.track_lyrics_post(1471157, 'test')['message']['body'], '') def test_track_lyrics_feedback_post(self): self.assertEqual( self.musixmatch.track_lyrics_post( 1471157, 4193713, 'wrong_verses')['message']['body'], '') def test_matcher_lyrics_get(self): self.assertEqual( self.musixmatch.matcher_lyrics_get('Sexy and I know it', 'LMFAO')['message']['body'] ['lyrics']['lyrics_language_description'], 'English') self.assertEqual( self.musixmatch.matcher_lyrics_get( 'Sexy and I know it', 'LMFAO')['message']['body']['lyrics']['lyrics_language'], 'en') def test_matcher_track_get(self): self.assertEqual( self.musixmatch.matcher_track_get( 'Lose Yourself (soundtrack)', 'Eminem')['message']['body']['track']['track_name'], 'Lose Yourself - ' 'Soundtrack Version' ' (Explicit)') self.assertEqual( self.musixmatch.matcher_track_get( 'Lose Yourself (soundtrack)', 'Eminem')['message']['body']['track']['album_name'], 'Curtain Call') def test_matcher_subtitle_get(self): self.assertEqual( self.musixmatch.matcher_subtitle_get('Sexy and I know it', 'LMFAO', 200, 3)['message']['body'], '') def test_artist_get(self): self.assertEqual( self.musixmatch.artist_get(118)['message']['body']['artist'] ['artist_name'], 'Queen') self.assertEqual( self.musixmatch.artist_get(118)['message']['body']['artist'] ['artist_mbid'], '5eecaf18-02ec-47af-a4f2-7831db373419') def test_artist_search(self): self.assertEqual( self.musixmatch.artist_search( 'prodigy', 1, 1, 16439, '4a4ee089-93b1-4470-af9a-6ff575d32704')['message']['body'] ['artist_list'][0]['artist']['artist_id'], 16439) self.assertEqual( self.musixmatch.artist_search( 'prodigy', 1, 1, 16439, '4a4ee089-93b1-4470-af9a-6ff575d32704')['message']['body'] ['artist_list'][0]['artist']['artist_name'], 'The Prodigy') def test_artist_albums_get(self): self.assertEqual( self.musixmatch.artist_albums_get(1039, 1, 1, 1, 'desc')['message'] ['body']['album_list'][0]['album']['album_id'], 25660826) self.assertEqual( self.musixmatch.artist_albums_get(1039, 1, 1, 1, 'desc')['message'] ['body']['album_list'][0]['album']['album_name'], 'Kaleidoscope') def test_artist_related_get(self): self.assertEqual( self.musixmatch.artist_related_get( 56, 1, 1)['message']['body']['artist_list'][0]['artist']['artist_id'], 298) self.assertEqual( self.musixmatch.artist_related_get(56, 1, 1)['message']['body'] ['artist_list'][0]['artist']['artist_name'], 'Outkast') def test_album_get(self): self.assertEqual( self.musixmatch.album_get(14250417)['message']['body']['album'] ['album_id'], 14250417) self.assertEqual( self.musixmatch.album_get(14250417)['message']['body']['album'] ['album_name'], 'Party Rock') def test_album_tracks_get(self): self.assertEqual( self.musixmatch.album_tracks_get( 13750844, 1, 1, '')['message']['body']['track_list'][0]['track']['track_id'], 30057052) self.assertEqual( self.musixmatch.album_tracks_get( 13750844, 1, 1, '')['message']['body']['track_list'][0]['track']['track_name'], "Don't Panic") def test_tracking_url_get(self): self.assertEqual( self.musixmatch.tracking_url_get('www.mylyricswebsite.com') ['message']['header']['status_code'], 200) def test_catalogue_dump_get(self): self.assertEqual( self.musixmatch.catalogue_dump_get('test')['message']['body'], '')
# By Carlie Hamilton # 13 March 2019 # https://github.com/BlueCodeThree # Grabs the song spotify is currently playing and shows you the lyrics to it. import spotipy import spotipy.util as util import apikey import sys import webbrowser import os from musixmatch import Musixmatch username = apikey.spotify_username scope = 'user-read-currently-playing' musixmatch = Musixmatch(apikey.musixmatch_api) # getting a token try: token = util.prompt_for_user_token(username, scope, client_id=apikey.spotify_id, client_secret=apikey.spotify_secret, redirect_uri=apikey.spotify_redirect) except: print("Can't get token for", username) os.remove(f".cache-{username}") token = util.prompt_for_user_token(username, scope, client_id=apikey.spotify_id, client_secret=apikey.spotify_secret,
#PhishBot #this bot tweets random lyrics from the legendary rock band from Vermont Phish's extensive catalog #link to the bot is https://twitter.com/Phish_Bot #Created by Sam Kravitz import tweepy import time import random from Phunction import getTweet from musixmatch import Musixmatch from credentials import * musixmatch = Musixmatch(music_key) #values changed for security purposes. #access apps.twitter.com to find the values for your specific project auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_secret) #authorizes the bot and loads in its username api = tweepy.API(auth) user = api.get_user('Phish_Bot') #at the moment the bot also follows follower of my main account, @krav1tz #myFollowers is an array containing each user who follows @krav1tz myFollowers = api.followers_ids('krav1tz') myFollowersLength = len(myFollowers) #artist phish = musixmatch.artist_search('phish', 1, 1, 0, 0) phish_id = phish['message']['body']['artist_list'][0]['artist']['artist_id']
#!/usr/bin/env python3 import json, webbrowser from .config import config from musixmatch import Musixmatch import click from textwrap import fill cfg = config() key = cfg.get_key() musixmatch = Musixmatch(key) class msx: def artists(country): artist_json = musixmatch.chart_artists(country=country, page=1, page_size=20) artist_list = json.loads( json.dumps(artist_json['message']['body']['artist_list'])) for i in range(0, len(artist_list)): wrapped = fill(artist_list[i]['artist']['artist_name'], width=71, subsequent_indent=' ' * 7) print(' ' + wrapped) def songs(country): songs_json = musixmatch.chart_tracks_get(country=country, page=1, page_size=20, f_has_lyrics=1) songs_list = json.loads(
import tkinter as tk from musixmatch import Musixmatch import apikey musixmatch = Musixmatch(apikey.musixmatch_api) # search for the track id def track_id_search(q_track, q_artist): track_id = musixmatch.track_search(q_track, q_artist, page_size=10, page=1, s_track_rating='desc')['message']['body']['track_list'][0]['track']['track_id'] return track_id # get the lyrics of a song def get_lyrics(track_id): lyrics = musixmatch.track_lyrics_get(track_id)['message']['body']['lyrics']['lyrics_body'] return lyrics # lyrics to the label def lyrics_to_label(): print(track_entry) print(artist_entry) print(get_lyrics(track_id_search(track_entry, artist_entry))) HEIGHT = 500 WIDTH = 600 root = tk.Tk()
def initDbCollections(fromApi='Musixmatch'): ''' Initialize MongoDb collection with genres and tracks foreach genre :param fromApi: choose the APIs from which to retrieve the genres (available: MusixMatch) :return: ''' if (fromApi == 'Musixmatch'): client = Musixmatch(__musixmatchAPIKey) # Genres if DbManager.getCollectionGenre().count() == 0: print("Init data genres...\n") count_add = 0 list_genres = client.genres_get( )["message"]["body"]["music_genre_list"] for g in list_genres: count_add += 1 genre = g["music_genre"] genre["localName"] = DbManager.fromServerToLocalGenreName( genre["music_genre_vanity"]) DbManager.getCollectionGenre().insert_one(genre) print("√ Added {0} genre/s".format(count_add)) else: print("- No genres added, {0} on database".format( DbManager.getCollectionGenre().count())) # Music if DbManager.getCollectionMusic().count() == 0: print("Init data music...") count_add = 0 if len(__map_genres_id.items()) == 0: print("You have to a hashmap {genre:id,..}") for keyGen, valGen in __map_genres_id.items(): count_item = 0 for page_count in range(1, 3): ''' list_tracks = client.chart_tracks_get(f_has_lyrics=False, page=page_count, page_size=100, country=country)["message"]["body"][ "track_list"] ''' list_tracks = client.track_by_genre_id( page_size=100, page=page_count, f_music_genre_id=valGen )["message"]["body"]["track_list"] for t in list_tracks: current = t["track"] primary_genres = list() exist = {} exist_genre_locally = False for pg in current["primary_genres"][ "music_genre_list"]: music_genre = pg["music_genre"] music_genre_local = DbManager.fromServerToLocalGenreName( music_genre["music_genre_vanity"]) if DbManager.fromServerToLocalGenreName(music_genre["music_genre_vanity"]) \ and (music_genre_local not in exist): music_genre['localName'] = music_genre_local primary_genres.append(music_genre) exist[music_genre_local] = True exist_genre_locally = True # Add track to mongoDb only if exist if exist_genre_locally: count_add += 1 count_item += 1 DbManager.getCollectionMusic().insert_one({ "artist_name": current["artist_name"], "track_name": current["track_name"], "primary_genres": primary_genres, "instrumental": current["instrumental"], "track_length": current["track_length"] if "track_length" in current else 0 }) print("√ Added {0} track/s for genre {1}".format( count_item, keyGen)) if count_add > 0: print("√ Added {0} track/s".format(count_add)) else: print("- No music added, {0} on database".format( DbManager.getCollectionMusic().count())) else: print("This API is not available\n") return 0
import telebot import lyricsgenius from musixmatch import Musixmatch cfg_file = open('config', 'r', newline='\n') telegram_token, genius_token, musixmatch_token = cfg_file.readlines() cfg_file.close() bot = telebot.TeleBot(telegram_token.split('\n')[0]) genius = lyricsgenius.Genius(genius_token.split('\n')[0]) musixmatch = Musixmatch(musixmatch_token.split('\n')[0]) @bot.message_handler(content_types=['text']) def start(message): if message.text == '/start': bot.send_message( message.from_user.id, 'Введите имя исполнителя и наименование песни в формате {artist_name}-{song_title}' ) else: get_lyrics_from_genius(message) # get_lyrics_from_musixmatch(message) def get_lyrics_from_musixmatch(message): try: args = message.text arg1, arg2 = args.split('-') song_json = musixmatch.matcher_lyrics_get(arg2, arg1)
import random from musixmatch import Musixmatch from credentials import * musixmatch = Musixmatch(music_key) def getTweet(albums): num_albums = len(albums) random_album = albums[random.randint(0, num_albums - 1)] # tracks tracks = musixmatch.album_tracks_get(random_album['album']['album_id'], 1, 100, 0) tracks = tracks['message']['body']['track_list'] num_tracks = len(tracks) rand = int(random.randint(0, num_tracks - 1)) random_track = tracks[rand] # lyrics lyrics = musixmatch.track_lyrics_get(random_track['track']['track_id']) lyrics = lyrics['message']['body']['lyrics']['lyrics_body'] lyricsf = '' for line in lyrics.split('\n'): if '...' in line: pass elif 'Lyrics' in line: pass elif '(' in line: pass
# -*- coding: utf-8 -*- from musixmatch import Musixmatch import json api_key = '' musixmatch = Musixmatch(api_key) # Belgium # Canada # Germany # United Kingdom # Mexico # Norway # Russia # Sweden # United States # Australia # United Arab Emirates # Switzerland # Uganda # New Zealand countries = [ 'BE', 'CA', 'DE', 'GB', 'MX', 'NO', 'RU', 'SE', 'US', 'AU', 'AE', 'CH', 'UG', 'NZ' ] genre_names = {} out = open('canciones.csv', 'w') out.write('lyrics_string,genre_class\n')
# A module for defining currently top songs in a certain country, using python wrapper for Musixmatch API from musixmatch import Musixmatch musixmatch = Musixmatch('<apikey>') # type your key instead of <apikey> def create_dict(js_data): """ Creates a dictionary with a song name as a key and a list with an album name and an artist name as a value. :param js_data: json data :return: dict """ songs_dict = dict() track_list = js_data['message']['body']['track_list'] for song in track_list: track = song['track'] key = track['track_name'] value = [track['album_name'], track['artist_name']] songs_dict[key] = value return songs_dict def top_songs(songs_num, country): """ Returns a dictionary with <songs_num> top sons in a <country> country. :param songs_num: int :param country: str :return: dict """ songs = musixmatch.chart_tracks_get(1, songs_num, f_has_lyrics=True,
def post_facebook_message(fbid, recevied_message): musixmatch = Musixmatch('e66da512f0d41fb64642d7ddc47ab311') track = recevied_message #name of the song answer = "" result = musixmatch.matcher_track_get(track, "") body = result.get('message').get('body') user_details_url = "https://graph.facebook.com/v2.6/%s" % fbid user_details_params = { 'fields': 'first_name,last_name,profile_pic', 'access_token': PAGE_ACCESS_TOKEN } user_details = requests.get(user_details_url, user_details_params).json() objUsr = UsersBot() objUsr.user_id = user_details['id'] objUsr.first_name = user_details['first_name'] objUsr.last_name = user_details['last_name'] users_bot = UsersBot.objects.all() if objUsr in users_bot: objUsr.save() if (body != ''): track_id = body.get('track').get('track_id') res_lyrics = musixmatch.track_lyrics_get(track_id) lyr_body = res_lyrics.get('message').get('body') if (lyr_body != ''): lyrics = lyr_body.get('lyrics').get('lyrics_body') cl_lyrics = lyrics.split("*****") answer = cl_lyrics[0] else: answer = "Lyrics not found!" else: answer = "Lyrics not found!" objConv = Conversations() objConv.user_id = user_details['id'] objConv.message_in = recevied_message objConv.message_out = answer objConv.save() #cursor.execute('INSERT INTO words VALUES (?)', [recevied_message]) post_message_url = 'https://graph.facebook.com/v2.6/me/messages?access_token=%s' % PAGE_ACCESS_TOKEN response_msg = json.dumps({ "recipient": { "id": fbid }, "message": { "text": answer } }) status = requests.post(post_message_url, headers={"Content-Type": "application/json"}, data=response_msg)