Esempio n. 1
0
def last_fm_init():
    network = pylast.LastFMNetwork(api_key=API_KEY,
                                   api_secret=API_SECRET,
                                   username=USERNAME,
                                   password_hash=pylast.md5(PASSWORD))

    return pylast.User("", network)
Esempio n. 2
0
def User(username, password=None):
    password = pylast.md5(password) if password else None
    return pylast.User(
        username,
        LastFMNetwork(api_key=API_KEY,
                      api_secret=API_SEC,
                      password_hash=password))
def getFriends(friend):
    network = pylast.LastFMNetwork(api_key=API_KEY,
                                   api_secret=API_SECRET,
                                   username=friend,
                                   password_hash=None)
    user = pylast.User(friend, network)
    friends = user.get_friends(10, True)
    return friends
def recent_tracks():
    user = pylast.User(lastfm_username, network)
    track_list = []
    print('{0} tracks found.'.format(len(user.get_recent_tracks(limit=2))))
    for played_track in user.get_recent_tracks(limit=2):
        track_list.append('{0} | {1}'.format(played_track.track.artist,
                                             played_track.track.title))

    return '<br/>'.join(track_list)
Esempio n. 5
0
 def __init__(self, jockey):
     self.jockey = jockey
     self.network = pylast.LastFMNetwork(
         api_key=config.LASTFM_API_KEY,
         api_secret=config.LASTFM_API_SECRET,
         username=config.LASTFM_USERNAME,
         password_hash=pylast.md5(config.LASTFM_PASSWORD)
     )
     self.user_details = pylast.User("rehab_belfast", self.network)
def update_now_playing():
    username = request.args.get('username', '', type=str)
    try:
        playing = pylast.User(username, network).get_now_playing()
        print('{0} {1}'.format(playing.artist, playing.title))
        image = get_cover_art(playing)
        return jsonify(track=playing.title,
                       artist=playing.artist.get_name(),
                       image=image,
                       track_url=playing.get_url())
    except AttributeError:
        print('No data to update')
        return jsonify(track='playing',
                       artist='nothing',
                       image=DEFAULT_ALBUM_ART,
                       track_url='#')
def currently_playing(username=None):
    username = username or 'wisdomwolf'
    playing = pylast.User(username, network).get_now_playing()
    try:
        image = get_cover_art(playing)
        print('{0} {1}'.format(playing.artist, playing.title))
        return render_template('currently-playing.html',
                               artist=playing.artist,
                               track=playing.title,
                               image=image)
    except AttributeError:
        print('Nothing playing')
        return render_template('currently-playing.html',
                               artist='nothing',
                               track='playing',
                               image=DEFAULT_ALBUM_ART)
Esempio n. 8
0
def cli_main():
    args = _parse_args()
    logging.basicConfig(
        format="%(asctime)s|%(levelname)s|%(message)s",
        level=logging.DEBUG if args.debug else logging.INFO,
    )
    target_file = os.path.abspath(os.path.expanduser(args.file))

    if os.path.isfile(target_file):
        logging.warning(f"Given output file {target_file} already exists!")
        sys.exit(1)

    timestamp_from = _parse_dt_into_timestamp(
        args.time_from) if args.time_from else None
    timestamp_to = _parse_dt_into_timestamp(
        args.time_to) if args.time_to else None

    network = pylast.LastFMNetwork(
        api_key=args.api_key or EnvVar.get(EnvVar.API_KEY),
        username=args.user or EnvVar.get(EnvVar.USER),
    )

    recent_tracks_gen = pylast.User(
        network.username, network).get_recent_tracks(stream=True,
                                                     limit=None,
                                                     time_from=timestamp_from,
                                                     time_to=timestamp_to)
    logging.info(
        f"Backing up scrobbles for user {network.username} with "
        f"time range {args.time_from} ({timestamp_from}) - {args.time_to} ({timestamp_to}) "
        f"into {target_file}...")
    for played_tracks_chunk in _chunks(n=50, iterable=recent_tracks_gen):
        with open(target_file, "a") as csv_:
            writer = csv.writer(csv_,
                                delimiter=",",
                                quotechar='"',
                                quoting=csv.QUOTE_MINIMAL)
            for played_track in played_tracks_chunk:
                logging.debug(
                    f"Writing track played at {played_track.timestamp}: {played_track.track}"
                )
                row = _to_csv_row(played_track)
                if row:
                    writer.writerow(row)
        logging.info(
            f"Written {len(played_tracks_chunk)} tracks into {target_file} file"
        )
Esempio n. 9
0
def getData():
	"""
	gets any lastfm listening statistics for the last ten minutes.
	
	and then judges you. wait, no -- that's in a future version of hu.
	"""
	try:
		apiKey = "fd4197bb1bfc8521ced2ba81d70fd812"
		network = lastfm.get_lastfm_network(api_key = apiKey, username = lastfm_username)
		user = lastfm.User(lastfm_username, network)
		recentTracks = user.get_recent_tracks(20)
		tracksFromLastTenMinutes = []
		# get rid of any tracks with a play-time earlier than fifteen minutes ago.
	
		for track in recentTracks:
			now = time.time()
			if int(track[2]) + 600 > now:	# track was played < 10 minutes (600 seconds) ago.
				tracksFromLastTenMinutes.append(track)
		return xmlify(tracksFromLastTenMinutes)
	except:
		return ""
Esempio n. 10
0
    def writeUserPlaylist(self, songlistlimit):
        count = 0
        for user in self.userlist:
            network = self.networkdeclaration(user)
            username = pylast.User(user, network)
            try:
                tracks = username.get_recent_tracks(limit=songlistlimit)
            except:
                print "Exception", user
                self.writeToCSV()
                continue
            for trackname in tracks:
                # try:
                #     thistrack = network.get_track(trackname.track.artist, trackname.track.title)
                # except:
                #     continue
                # try:
                #     tags = thistrack.get_top_tags(limit=200)
                # except:
                #     tags=[]
                # temptags = []
                # if tags==[]:
                #     self.tagslist.append(temptags)
                # else:
                #     for temp in tags:
                #         temptags.append(temp.item.get_name())
                #     self.tagslist.append(temptags)

                self.musictitle.append((trackname.track.title).encode("utf-8"))
                self.artist.append((trackname.track.artist))
                self.playingtime.append(
                    (trackname.playback_date).encode("utf-8"))
                albumtemp = trackname.album
                self.usernames.append(user)
                if albumtemp == None:
                    self.album.append(albumtemp)
                else:
                    self.album.append(albumtemp.encode("utf-8"))
                count = count + 1
        self.writeToCSV()
Esempio n. 11
0
    def from_account(cls, account):
        """Initialize a new song or update an existing song without saving."""
        log.debug(f"Adding songs from '{account.username}'...")

        time.sleep(settings.LASTFM_API_DELAY)  # rate limit API calls

        network = pylast.LastFMNetwork(
            api_key=settings.LASTFM_API_KEY,
            api_secret=settings.LASTFM_API_SECRET,
        )

        user = pylast.User(account.username, network)
        try:
            username = user.get_name(properly_capitalized=True)
        except pylast.WSError as exc:
            log.debug(exc)
            return None

        track = user.get_now_playing()
        if track:
            song, new = cls._get_or_init(track, account)
            if new:
                log.info(f"Added now playing from {username}: {song}")
            else:
                log.debug(f"Updated now playing from {username}: {song}")
            song.date = timezone.now()
            return song

        played_tracks = user.get_recent_tracks()
        if played_tracks:
            song, new = cls._get_or_init(played_tracks[0].track, account)
            if new:
                log.info(f"Added last track from {username}: {song}")
            else:
                log.debug(f"Updated last track from {username}: {song}")
            song.date = cls._timestamp_to_datetime(played_tracks[0].timestamp)
            return song

        return None
Esempio n. 12
0
    def get_track_list(self):
        """
            Returns a list of your scrobbles given your inputted date range and tag.

        """
        API_KEY = 'paste your API key here'
        API_SECRET = 'paste your API secret here'
        username = '******'
        password_hash = pylast.md5('enter your password')
        n = pylast.LastFMNetwork(api_key=API_KEY, api_secret=API_SECRET, username=username, password_hash=password_hash)
        u = pylast.User(user_name=username,network=n)
        time_input = input("input initial time [yr][mon][day] i.e. 190101, 191230 --   ")
        init_time = int(time.mktime(time.strptime(time_input+"", "%y%m%d")))
        time_input = input("input final time [yr][mon][day] i.e. 190101, 191230 --   ")
        final_time = int(time.mktime(time.strptime(time_input+"", "%y%m%d")))
        tag_input = input("input a tag: ")
        recent_tracks = u.get_recent_tracks(limit=1000,time_from=init_time, time_to=final_time)
        track_list = []

        for track in recent_tracks:
            title = track.track.title
            album = track.album
            artist = track.track.artist
            o = pylast._Opus(artist=artist,title=album,network=n,ws_prefix='album',username=username)
            tags = artist.get_top_tags(limit=10)
            tag_list = []
            for tag in tags:
                tag = tag.item
                tag_name = tag.get_name()
                tag_list.append(tag_name)
            for tag_item in tag_list: 
                if tag_input.lower() in tag_item.lower():
                    track_item = str(artist)+" "+str(title)
                    track_list.append(track_item)
                    print(track.playback_date+" -- "+track_item) #print scrobble
        track_list = list(dict.fromkeys(track_list)) #eliminate duplicates
        self.track_list = track_list
        return track_list
Esempio n. 13
0
def main():

    # Lastfm init
    network = pylast.LastFMNetwork(api_key=API_KEY,
                                   api_secret=API_SECRET,
                                   username=USERNAME,
                                   password_hash=pylast.md5(PASSWORD))

    lastfm = pylast.User("", network)

    # VK init
    vk_session = vk_api.VkApi(token=VK_USER_TOKEN)
    vk = vk_session.get_api()

    last_track = ''

    while True:
        if lastfm:
            results = lastfm.get_now_playing()
            if not results:
                if last_track:
                    last_track = ''
                    vk.status.set(text="")
                time.sleep(INTERVAL)
                continue
            if results != last_track:
                time_now = time.strftime("%H:%M", time.localtime())
                status_text = f"🎧 Last.fm | {results}"
                print(f"[{time_now}] {status_text}")
                vk.status.set(text=status_text)
                last_track = results
                time.sleep(INTERVAL)
            else:
                time.sleep(INTERVAL)
        else:
            print(f"Can't get user")
            sys.exit()
Esempio n. 14
0
def lastfm_event_recommendations():
    """Fetch a list of event recommendations for today from Last.fm"""
    user = pylast.User('jwheare', LASTFM_KEY, LASTFM_SECRET, LASTFM_SESSION)
    events = user.getRecommendedEvents(limit=6)
    return events
Esempio n. 15
0
query = "CREATE TABLE IF NOT EXISTS similarity(first INTEGER, second INTEGER, UNIQUE(first, second))"
cur.execute(query)

query = "SELECT COUNT(*) FROM artists"
cur.execute(query)
number = cur.fetchone()[0]

query = "SELECT artist FROM artists"
cur.execute(query)
data = cur.fetchall()
current_artists = [elt[0] for elt in data]

network = pylast.get_lastfm_network(keys.api_key, keys.api_secret, keys.user,
                                    keys.password)
user = pylast.User(sys.argv[1], network)
top_artists = user.get_top_artists(limit=50)

query = "INSERT INTO artists VALUES (?,?)"
count = 1
insert = []
for artist in top_artists:
    name = artist.item.get_name()
    if name not in current_artists:
        insert.append((count + number, name))
        count += 1

cur.executemany(query, insert)

query = "SELECT * FROM artists"
cur.execute(query)
Esempio n. 16
0
# Params
N_words = 100
recompute_lda = False
top_songs = 200  # numbers of song to retrieve
username = "******"

API_KEY, API_SECRET = set_api_key("API_INFO.txt")

output_words = username + "_words_list.p"
output_lyrics = username + "_lyrics_list.p"
output_alllyrics = username + "_alllyrics.txt"

print("Setup configurations...")
network = pylast.LastFMNetwork(api_key=API_KEY, api_secret=API_SECRET)

user = pylast.User(username, network)

# Tracks analysis
#tracks = user.get_recent_tracks(limit=None)
library = user.get_library()
tracks = library.get_tracks(limit=top_songs)

# load stopwords file
stopwords = open("stopwords.txt", "r").read().split()
stiowords = [x.strip(punctuation) for x in stopwords if len(x) > 2]

lyrics_list = {}
words_list = {}
if not os.path.exists(output_words) or not os.path.exists(output_alllyrics):
    print("Fetching tracks lyrics...")
    outfile = open(output_alllyrics, "w")
Esempio n. 17
0
def get_artists(plays=20):
    api = pylast.LastFMNetwork(api_key=api_key, api_secret=api_secret, username=username)
    artists = [artist.item.name for artist in pylast.User(username, api).get_library().get_artists(limit=None)
               if artist.playcount >= plays]

    return artists
Esempio n. 18
0
def get_top_tracks(user_name, limit=None):
    network = get_network()
    user = pylast.User(user_name, network)
    return user.get_top_tracks(limit=limit)
Esempio n. 19
0
# Ini
config = configparser.ConfigParser()
config.read('settings.ini')
env_vars = config['Environment Vars']

# PyLast
API_KEY = os.getenv('LASTFM_API_KEY') or env_vars['lastfm_api_key']
API_SECRET = os.getenv('LASTFM_API_SECRET') or env_vars['lastfm_api_secret']
lastfm_username = os.getenv('LASTFM_DEFAULT_USERNAME') or env_vars['lastfm_default_username']
password_hash = os.getenv('LASTFM_DEFAULT_PWHASH') or env_vars['lastfm_default_pwhash']
network = pylast.LastFMNetwork(api_key=API_KEY, api_secret=API_SECRET,
                               username=lastfm_username,
                               password_hash=password_hash)
# sets user to DEFAULT
user = pylast.User(lastfm_username, network)


def get_all_tracks(user, chunk_size=1000, last_timestamp=0):
    playcount = user.get_playcount()
    tracks = set()
    last_timestamp = last_timestamp
    chunks = playcount // chunk_size + 1
    for i in range(chunks):
        print('Getting chunk {} of {}'.format(i + 1, chunks))
        recent_tracks = user.get_recent_tracks(limit=chunk_size, time_to=last_timestamp)
        tracks = tracks.union(recent_tracks)
        last_timestamp = int(recent_tracks[-1].timestamp)
    return sorted(list(tracks), key=lambda x: x.timestamp, reverse=True)

def create_library_set(track_history, user):
Esempio n. 20
0
def now_playing():
    user = pylast.User(lastfm_username, network)
    return '{0} | {1}'.format(user.get_now_playing().artist,
                              user.get_now_playing().title)
Esempio n. 21
0


# defining various list for merging into the final .csv file
usernames = []
musictitle= []
artist  = []
playingtime= []
album = []
tagslist  = []
Userlist = BFS("rj", count1 ,friendlist=[] )

# gettig the user infor and then adding all the individual elements in temporary list in order to be dumped into final list
for user in Userlist:
    network = networkdeclaration(user)
    username = pylast.User(user, network)
    print username
    tracks = username.get_recent_tracks(limit= 200)
    musictemp = []
    artisttemp = []
    playtimetemp = []
    albumtemp = []
    count = 0
    itr = 0
    for trackname in tracks:
        count = count + 1
        musictemp.append(trackname.track.title)
        artisttemp.append(trackname.track.artist)
        playtimetemp.append(trackname.playback_date)
        albumtemp.append(trackname.album)
    for itr in range(count):
Esempio n. 22
0
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 24 18:41:13 2018

@author: Jana
"""

import credentials
import pylast
import math

network = pylast.LastFMNetwork(api_key=credentials.lastfmKey,
                               api_secret=credentials.lastfmSecret,
                               username='******')

me = pylast.User('defektseit94', network)

#    artist1 = network.get_artist(raw_input("Enter first artist: "))
#    artist2 = network.get_artist(raw_input("Enter second artist: "))


def makeTagList(artist, tagArray):
    try:
        for tag in artist.get_top_tags():
            tagArray += [str(tag.item)]
    except pylast.WSError:
        raise


def makeArtistList(artist, artistArray, limit):
    try:
Esempio n. 23
0
# get configuration
configfile = dirname(dirname(abspath(__file__))) + '/config'

import configparser

config = configparser.RawConfigParser()
config.read(configfile)

ApiKey = config['lastfm']['ApiKey']
Username = config['lastfm']['Username']

# init last.fm access
network = pylast.LastFMNetwork(api_key=ApiKey, username=Username)

user = pylast.User(user_name=Username, network=network)

# get recent tracks
tracks = user.get_recent_tracks(limit=11)

# process recent tracks
listened = ''
for track in tracks:
    listened += '* ' + str(track.track)
    if track.album: listened += str(track.album)
    listened += '(' + track.playback_date + ')\n'

# insert recent listening in markdown file
# FIXME: markdown syntax should not be interpreted
with open('_includes/index-content.md', 'r') as f:
    oldcontent = f.read()
Esempio n. 24
0
    client_id=SPOTIFY_APP_ID,
    redirect_uri=redirect_url,
    token_url=
    "https://dk1ytlmiwk.execute-api.us-east-1.amazonaws.com/dev/token",
    auth_func=get_aws_auth)
sp = spotiwise.Spotify(oauth=oauth)

config = configparser.ConfigParser()
config.read('settings.ini')
env_vars = config['Environment Vars']
password_hash = env_vars['lastfm_default_pwhash']
network = pylast.LastFMNetwork(api_key=LASTFM_API_KEY,
                               api_secret=LASTFM_API_SECRET,
                               username='******',
                               password_hash=password_hash)
user = pylast.User('wisdomwolf', network)


def restart_scheduler():
    global scheduler
    try:
        scheduler.shutdown()
    except SchedulerNotRunningError:
        logging.info('Scheduler already shutdown')
        pass
    scheduler = BackgroundScheduler()
    job = scheduler.add_job(my_scrobbler.update_track,
                            'interval',
                            seconds=10,
                            replace_existing=True)
    scheduler.start()