use black library for code
This commit is contained in:
parent
b63e1f1536
commit
f6f3a653df
119
lastfm_backup.py
119
lastfm_backup.py
@ -5,118 +5,124 @@ import csv
|
||||
import os.path
|
||||
import requests
|
||||
|
||||
__author__ = 'Alexander Popov'
|
||||
__version__ = '2.1.0'
|
||||
__license__ = 'Unlicense'
|
||||
__author__ = "Alexander Popov"
|
||||
__version__ = "2.1.0"
|
||||
__license__ = "Unlicense"
|
||||
|
||||
|
||||
def get_pages(username, api_key, limit=200):
|
||||
""" Getting the number of pages with scrobbling data """
|
||||
|
||||
response = requests.get(
|
||||
'https://ws.audioscrobbler.com/2.0/'
|
||||
'?method=user.getrecenttracks&user='
|
||||
'{0}&api_key={1}&format=json&limit={2}'
|
||||
.format(username, api_key, limit))
|
||||
"https://ws.audioscrobbler.com/2.0/"
|
||||
"?method=user.getrecenttracks&user="
|
||||
"{0}&api_key={1}&format=json&limit={2}".format(username, api_key, limit)
|
||||
)
|
||||
|
||||
data = json.loads(response.content.decode("utf8"))
|
||||
|
||||
return(int(data['recenttracks']['@attr']['totalPages']))
|
||||
return int(data["recenttracks"]["@attr"]["totalPages"])
|
||||
|
||||
|
||||
def get_page(username, api_key, page, limit=200):
|
||||
""" Getting scrobbling data from a page """
|
||||
|
||||
response = requests.get(
|
||||
'https://ws.audioscrobbler.com/2.0/'
|
||||
'?method=user.getrecenttracks&user={0}&api_key={1}&format=json'
|
||||
'&limit={2}&page={3}'.format(username, api_key, limit, page))
|
||||
"https://ws.audioscrobbler.com/2.0/"
|
||||
"?method=user.getrecenttracks&user={0}&api_key={1}&format=json"
|
||||
"&limit={2}&page={3}".format(username, api_key, limit, page)
|
||||
)
|
||||
|
||||
data = json.loads(response.content.decode("utf8"))
|
||||
|
||||
return(data['recenttracks']['track'])
|
||||
return data["recenttracks"]["track"]
|
||||
|
||||
|
||||
def get_now_scrobbling(username, api_key):
|
||||
""" Getting now scrobbling track """
|
||||
|
||||
response = requests.get(
|
||||
'https://ws.audioscrobbler.com/2.0/'
|
||||
'?method=user.getrecenttracks&user={0}'
|
||||
'&api_key={1}&format=json&limit=1'
|
||||
.format(username, api_key))
|
||||
"https://ws.audioscrobbler.com/2.0/"
|
||||
"?method=user.getrecenttracks&user={0}"
|
||||
"&api_key={1}&format=json&limit=1".format(username, api_key)
|
||||
)
|
||||
|
||||
data = json.loads(response.content.decode('utf-8'))
|
||||
data = json.loads(response.content.decode("utf-8"))
|
||||
|
||||
if '@attr' in data['recenttracks']['track'][0]:
|
||||
return(True)
|
||||
if "@attr" in data["recenttracks"]["track"][0]:
|
||||
return True
|
||||
else:
|
||||
return(False)
|
||||
return False
|
||||
|
||||
|
||||
def scrobbling_export(tracks, username, export_format='dump'):
|
||||
def scrobbling_export(tracks, username, export_format="dump"):
|
||||
""" Save scrobbled track via various format """
|
||||
|
||||
if export_format == 'dump':
|
||||
with open('%s.json' % (username), 'w', encoding='utf-8') as f:
|
||||
data = json.dumps(tracks, indent=4,
|
||||
sort_keys=True, ensure_ascii=False)
|
||||
if export_format == "dump":
|
||||
with open("%s.json" % (username), "w", encoding="utf-8") as f:
|
||||
data = json.dumps(tracks, indent=4, sort_keys=True, ensure_ascii=False)
|
||||
f.write(data)
|
||||
|
||||
elif export_format == 'simple':
|
||||
elif export_format == "simple":
|
||||
_ = []
|
||||
|
||||
for track in tracks:
|
||||
_.append({
|
||||
'artist': track['artist']['#text'],
|
||||
'name': track['name'],
|
||||
'album': track['album']['#text'],
|
||||
'date': int(track['date']['uts'])
|
||||
})
|
||||
_.append(
|
||||
{
|
||||
"artist": track["artist"]["#text"],
|
||||
"name": track["name"],
|
||||
"album": track["album"]["#text"],
|
||||
"date": int(track["date"]["uts"]),
|
||||
}
|
||||
)
|
||||
|
||||
with open('%s.json' % (username), 'w', encoding='utf-8') as f:
|
||||
with open("%s.json" % (username), "w", encoding="utf-8") as f:
|
||||
data = json.dumps(_, indent=4, sort_keys=True, ensure_ascii=False)
|
||||
f.write(data)
|
||||
|
||||
elif export_format == 'csv':
|
||||
elif export_format == "csv":
|
||||
_ = []
|
||||
|
||||
for track in tracks:
|
||||
_.append([
|
||||
track['artist']['#text'],
|
||||
track['name'],
|
||||
track['album']['#text'],
|
||||
int(track['date']['uts'])
|
||||
])
|
||||
_.append(
|
||||
[
|
||||
track["artist"]["#text"],
|
||||
track["name"],
|
||||
track["album"]["#text"],
|
||||
int(track["date"]["uts"]),
|
||||
]
|
||||
)
|
||||
|
||||
with open('%s.csv' % (username), 'w', encoding='utf-8',
|
||||
newline='') as f:
|
||||
data = csv.writer(f, quoting=csv.QUOTE_NONNUMERIC, delimiter=',')
|
||||
data.writerow(['artist', 'track', 'album', 'date'])
|
||||
with open("%s.csv" % (username), "w", encoding="utf-8", newline="") as f:
|
||||
data = csv.writer(f, quoting=csv.QUOTE_NONNUMERIC, delimiter=",")
|
||||
data.writerow(["artist", "track", "album", "date"])
|
||||
data.writerows(_)
|
||||
|
||||
return(1)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if __name__ == "__main__":
|
||||
_ = dict()
|
||||
|
||||
if os.path.exists('./config.json'):
|
||||
with open('./config.json') as f:
|
||||
if os.path.exists("./config.json"):
|
||||
with open("./config.json") as f:
|
||||
_ = json.loads(f.read())
|
||||
else:
|
||||
_['api_key'] = input('API Key: ')
|
||||
_['username'] = input('Username: ')
|
||||
api_key, username = _['api_key'], _['username']
|
||||
_["api_key"] = input("API Key: ")
|
||||
_["username"] = input("Username: ")
|
||||
api_key, username = _["api_key"], _["username"]
|
||||
|
||||
total_pages = get_pages(username, api_key)
|
||||
current_page = 1
|
||||
scrobbled = []
|
||||
|
||||
while current_page <= total_pages:
|
||||
print('\r{0:.2f}% [{1} of {2}]'
|
||||
.format((current_page * 100 / total_pages),
|
||||
current_page, total_pages), end='')
|
||||
print(
|
||||
"\r{0:.2f}% [{1} of {2}]".format(
|
||||
(current_page * 100 / total_pages), current_page, total_pages
|
||||
),
|
||||
end="",
|
||||
)
|
||||
|
||||
response = get_page(username, api_key, current_page)
|
||||
|
||||
@ -128,6 +134,5 @@ if __name__ == '__main__':
|
||||
# if get_now_scrobbling(username, api_key):
|
||||
# scrobbled.pop(0)
|
||||
|
||||
if scrobbling_export(scrobbled, username, _['export_format']):
|
||||
print('\n{0} tracks saved!'.format(
|
||||
len(scrobbled), username))
|
||||
if scrobbling_export(scrobbled, username, _["export_format"]):
|
||||
print("\n{0} tracks saved!".format(len(scrobbled), username))
|
||||
|
1
requirements.txt
Normal file
1
requirements.txt
Normal file
@ -0,0 +1 @@
|
||||
requests==2.24.0
|
@ -2,10 +2,10 @@
|
||||
|
||||
import lastfm_backup as lfm
|
||||
|
||||
API_KEY = '0'
|
||||
USERNAME = 'admin'
|
||||
API_KEY = "0"
|
||||
USERNAME = "admin"
|
||||
|
||||
if __name__ == '__main__':
|
||||
if __name__ == "__main__":
|
||||
pages = lfm.get_pages(USERNAME, API_KEY)
|
||||
count = 0
|
||||
|
||||
@ -13,7 +13,13 @@ if __name__ == '__main__':
|
||||
tracks = lfm.get_scrobbles(USERNAME, API_KEY, page)
|
||||
|
||||
for track in tracks:
|
||||
print('%s - %s' % (track['artist']['#text'], track['name'],))
|
||||
print(
|
||||
"%s - %s"
|
||||
% (
|
||||
track["artist"]["#text"],
|
||||
track["name"],
|
||||
)
|
||||
)
|
||||
count = count + 1
|
||||
|
||||
print('\nTotal scrobbling tracks: %d' % count)
|
||||
print("\nTotal scrobbling tracks: %d" % count)
|
||||
|
26
setup.py
26
setup.py
@ -3,19 +3,21 @@ import setuptools
|
||||
import lastfm_backup
|
||||
|
||||
setuptools.setup(
|
||||
name='lastfm-backup',
|
||||
name="lastfm-backup",
|
||||
version=lastfm_backup.__version__,
|
||||
description='Last.fm scrobbling backup',
|
||||
description="Last.fm scrobbling backup",
|
||||
author=lastfm_backup.__author__,
|
||||
author_email='iiiypuk@fastmail.fm',
|
||||
url='https://github.com/iiiypuk/lastfm-backup',
|
||||
py_modules=['lastfm_backup'],
|
||||
scripts=['lastfm_backup.py'],
|
||||
author_email="iiiypuk@fastmail.fm",
|
||||
url="https://github.com/iiiypuk/lastfm-backup",
|
||||
py_modules=["lastfm_backup"],
|
||||
scripts=["lastfm_backup.py"],
|
||||
license=lastfm_backup.__license__,
|
||||
platforms='any',
|
||||
keywords=['last.fm', 'lastfm', 'backup'],
|
||||
classifiers=['License :: Public Domain',
|
||||
'Programming Language :: Python :: 3',
|
||||
'Operating System :: OS Independent'],
|
||||
python_requires='>=3.2'
|
||||
platforms="any",
|
||||
keywords=["last.fm", "lastfm", "backup"],
|
||||
classifiers=[
|
||||
"License :: Public Domain",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Operating System :: OS Independent",
|
||||
],
|
||||
python_requires=">=3.2",
|
||||
)
|
||||
|
Loading…
Reference in New Issue
Block a user