wibe/wibe.py

57 lines
2.3 KiB
Python
Raw Normal View History

2021-12-16 11:31:41 +01:00
import spotipy
from spotipy import util as spoUtil
import requests
import io
import colorgram
import json
import time
from pprint import pprint
wledPalettes = {'colorsOnly': 5, 'colorGradient': 4, '2Colors': 3}
def main(token, ip='192.168.3.42', bri=51):
url = 'http://'+ip+'/json/state'
sp = spotipy.Spotify(auth=token)
curTrack = None
requests.post(url, json={"on":True,"bri":bri,"transition":7,"mainseg":0,"seg":[{"id":0,"grp":1,"spc":0,"of":0,"on":True,"bri":255,"cct":127,"col":[[0,0,0,255],[0,0,0,0],[0,0,0,0]],"fx":38,"sx":24,"ix":16,"pal":5,"sel":True,"rev":False,"mi":False}]}).json()
while True:
res = sp.current_user_playing_track()
if res and res["item"] and (curTrack == None or curTrack['uri'] != res["item"]['uri']):
curTrack = res["item"]
del curTrack['available_markets']
del curTrack['album']['available_markets']
print("[*] Now Playing: "+curTrack["name"])
feat = sp.audio_features(curTrack["uri"])[0]
palette = getPalette(curTrack,3)
#pprint(curTrack)
#pprint(feat)
#pprint(palette)
speed = min(int(feat['tempo']/2),255)
power = 16 + int(feat['energy'])*64
pprint(requests.post(url, json={"seg": [{"col": palette, "pal": wledPalettes['colorGradient'], 'sx': speed, 'ix': power}]}).json())
time.sleep(3)
time.sleep(1)
def getPalette(curTrack,numColors):
imgStream = requests.get(curTrack["album"]["images"][-1]["url"]).content #Get the lowest res cover
imgFile = io.BytesIO(imgStream)
print("[i] Generating palette")
palette = [normalizeColor([col.rgb[c] for c in range(3)]+[0]) for col in sorted(colorgram.extract(imgFile, numColors), key=lambda c: c.hsl.h)] #c.proportion
return palette
def normalizeColor(rgbw):
s = max(rgbw)
fac = (1 + 255/s)/2
return [min(int(c*fac),255) for c in rgbw]
def genSpoToken(username, client_id, client_secret):
return spoUtil.prompt_for_user_token(username,"user-read-currently-playing",client_id=client_id,client_secret=client_secret,redirect_uri='http://localhost/')
if __name__=="__main__":
with open('secret.json') as f:
username, client_id, client_secret = json.loads(f.read())
token = genSpoToken(username, client_id, client_secret)
main(token,'192.168.3.42')