get_artist_art/api_calls.py
20xd6 26dfe543a1 Reimpliment delay to only trigger on 503 response
The code has been refactored to only trigger a one second delay when one of the APIs have returned a 503. This will allow the script to finish faster.
2024-10-15 08:52:22 -04:00

71 lines
2.7 KiB
Python

import requests
import os
from time import sleep
def get_mb_id(artist_name, mb_confidence):
artist_name = artist_name.strip('_')
mb_url = f'https://musicbrainz.org/ws/2/artist?query=artist:"{artist_name}"&fmt=json'
header = {'User-Agent': 'get_artist_art.py/1.0'}
response = requests.get(mb_url, headers=header)
if response.status_code == 200:
mb_data = response.json()
if mb_data['count'] > 0:
if mb_data['artists'][0]['score'] > mb_confidence:
return True, mb_data['artists'][0]['id'], True
else:
print("No artist found of hight enough confidance.")
return False, "", True
else:
print("No artist found.")
return False, "", True
elif (response.status_code == 503):
sleep(1)
return False, "", False
else:
print(f"MB Error: {response.status_code}")
return False, "", True
def get_image(mb_id, ftv_api_key, artist_path):
ftv_api_url = f'https://webservice.fanart.tv/v3/music/{mb_id}?api_key={ftv_api_key}'
response = requests.get(ftv_api_url)
ftv_data =response.json()
if not ('status' in ftv_data):
if ('artistthumb' in ftv_data):
art_url = ftv_data['artistthumb'][0]['url']
print(art_url)
response = requests.get(art_url)
if response.status_code == 200:
with open(os.path.join(artist_path, 'artist.jpg'), 'wb') as f:
f.write(response.content)
return True
elif ('artistbackground' in ftv_data):
art_url = ftv_data['artistbackground'][0]['url']
response = requests.get(art_url)
if (response.status_code == 200):
with open(os.path.join(artist_path, 'artist.jpg'),'wb') as f:
f.write(response.content)
return True
elif ('hdmusiclogo' in ftv_data):
art_url = ftv_data['hdmusiclogo'][0]['url']
response = requests.get(art_url)
if response.status_code == 200:
with open(os.path.join(artist_path, 'artist.png'), 'wb') as f:
f.write(response.content)
return True
else:
print("Error downloading: ", response.status_code)
return True
else:
print("Thumb not found.")
return True
elif (response.status_code == 503):
sleep(1)
return False
else:
error_msg = ftv_data['error message']
if (error_msg == "503"):
sleep(1)
return False
else:
print(f"FTV Error: {error_msg}")
return True