Beispiel #1
0
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)
Beispiel #2
0
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)
Beispiel #3
0
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)
Beispiel #4
0
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)
Beispiel #5
0
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
Beispiel #7
0
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)
Beispiel #8
0
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',
    }
Beispiel #9
0
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
Beispiel #10
0
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)
Beispiel #11
0
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)
Beispiel #12
0
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)
Beispiel #13
0
    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)
Beispiel #14
0
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
Beispiel #15
0
#!/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(
Beispiel #16
0
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
Beispiel #17
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)
Beispiel #18
0
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)
Beispiel #19
0
 def setUp(self):
     self.musixmatch = Musixmatch(os.environ.get('APIKEY'))
     self.url = 'http://api.musixmatch.com/ws/1.1/'
Beispiel #20
0
track_info = dataset.iloc[137:200, 1:].values

writer = csv.writer(open('song_features_musix_temp.csv', 'w',
                         encoding='utf-8'))
track_ids = []

song_names = []
all_features = []
all_harmonies = []

labels = []
all_lyric_object = []
all_lyric_tones = []

# MusixMatch API
musixmatch = Musixmatch('3dbbf7d593f0f05ab045dac7b015c430')

# Tone Analyzer API
authenticator = IAMAuthenticator(
    'R7Ja2rP0jp6LucFzOl5-4xbMSVSX5Fci8wc63J0O5-l3')
tone_analyzer = ToneAnalyzerV3(version='2017-09-21',
                               authenticator=authenticator)

tone_analyzer.set_service_url(
    'https://api.us-south.tone-analyzer.watson.cloud.ibm.com/instances/b8f00a45-63d1-4bb9-b1a0-1c2e6bc3e4ca'
)

if token:
    for obs in track_info:
        try:
            labels.append(obs[2])
# coding: utf-8

# In[69]:

import pandas as pd
import numpy as np
import csv
import re
import urllib, json
from musixmatch import Musixmatch
musixmatch = Musixmatch(
    'e5e7719b47f96c02f10ecc01d2025414')  #Musixmatch authentication

# In[70]:

df = pd.read_csv('SongCSV.csv')  #DataFrame
df.head()
songNameList = df['Title'].values.tolist(
)  #Creating a list of the songName column
artistNameList = df['ArtistName'].values.tolist(
)  #Creating a list of the artistName column
albumNameList = df['AlbumName'].values.tolist(
)  #Creating a list of the albumName column

# In[49]:

songNameList[0] = re.sub(
    r'\([^)]*\)', '', songNameList[0]
)  #Removes anything that's in the parenthesis of song name. for example Mr. Brightside (Remix). The bracket part gets removed.
songNameList[0]
Beispiel #22
0
# -*- 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')
Beispiel #23
0
import csv
from musixmatch import Musixmatch
musixmatch = Musixmatch('d9f4b70591c4995eaa6ae7a0c508d465')


def check_language(mmID):
    try:
        lyrics = musixmatch.track_lyrics_get(mmID)
        language = lyrics['message']['body']['lyrics']['lyrics_language_description']
    except:
        language = 'haha'

    return language


all_lan_dataset = open("Country_Rap_12000_2.csv").readlines()
#print len(all_lan_dataset)
en_song_list = []
for i in range(0, len(all_lan_dataset)):
    #print i
    ID_list = []
    song = all_lan_dataset[i]
    info = song.strip().split(",")
    #print info
    mmID = info[3]
    ID_list.append(mmID)
    
    if check_language(mmID) == 'English' or check_language(mmID) =='en':
        en_song_list.append(ID_list)
    
Beispiel #24
0
#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']
Beispiel #25
0
# 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,
#!/usr/bin/env python
from __future__ import absolute_import, division, print_function, unicode_literals
from django.db.models import Q
from django.views.generic import TemplateView, ListView
from rest_framework.views import APIView
from rest_framework.response import Response
from django.http import HttpResponse

from musixmatch import Musixmatch
musixmatch = Musixmatch(env.musixmatch_token)

from .models import Song

import numpy as np

import tensorflow as tf

# !pip install -q tensorflow-hub
# !pip install -q tensorflow-datasets
import tensorflow_hub as hub
import tensorflow_datasets as tfds
import csv
import pandas as pd
pd.options.mode.chained_assignment = None  # default='warn'

from tensorflow.python.keras.preprocessing.text import Tokenizer
from tensorflow.python.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Embedding, LSTM, GRU

# Imports the Google Cloud client library
Beispiel #27
0
 def setup_class(cls):
     cls.musixmatch = Musixmatch("test")
     cls.url = "http://api.musixmatch.com/ws/1.1/"
Beispiel #28
0
import os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "client-secret1.json"

import dialogflow_v2 as dialogflow
dialogflow_session_client = dialogflow.SessionsClient()
PROJECT_ID = "music-neiedm"

from musixmatch import Musixmatch
musixmatch = Musixmatch("668ca0e26add2355dafb6fded1744099")

from gnewsclient import gnewsclient

client = gnewsclient.NewsClient(max_results=3)

from pymongo import MongoClient

cl = MongoClient(
    "mongodb+srv://test:[email protected]/test?retryWrites=true&w=majority"
)
db = cl.get_database('user_db')
records = db.user_info


def update_records(id, topic, language, location):
    if (topic != " "):
        records.update_one({'session_id': id}, {"$set": {
            "news_type": topic
        }},
                           upsert=True)
    if (language != " "):
        records.update_one({'session_id': id},
#  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,
Beispiel #30
0
class CopyrightError(Exception):
    pass


class APILimitError(Exception):
    pass


# Grab the API key from a local 'client_secret.json' file
CLIENT_API_KEY = ''
with open('client_secret.json') as CONFIGS:
    CLIENT_API_KEY = json.load(CONFIGS)['musixmatch_api_key']

# Construct an object of the Musixmatch class with the given API key
musixmatch = Musixmatch(CLIENT_API_KEY)


def get_lyrics_by_search(song_title, artist_name):
    """ Returns an array containing the lyrics of a single song given the song title and artist. """
    lyric_response = musixmatch.matcher_lyrics_get(song_title, artist_name)

    return get_lyrics_from_response(lyric_response)


def get_lyrics_by_id(song_id):
    """ Returns an array containing the lyrics of a single song given the musixmatch song id """
    lyric_response = musixmatch.track_lyrics_get(song_id)

    return get_lyrics_from_response(lyric_response)