wibe/wibe.py

70 lines
2.7 KiB
Python
Raw Permalink 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
2021-12-16 11:57:27 +01:00
import math
2021-12-16 11:31:41 +01:00
from pprint import pprint
2021-12-16 16:09:10 +01:00
import colorsys
2021-12-16 11:31:41 +01:00
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)
2021-12-16 12:27:30 +01:00
speed = min(int((feat['tempo']/30*feat['energy'])**2.0)*10,255)
power = min(8 + int(((feat['energy']*10)**2.0)*0.5),255)
2021-12-16 16:09:10 +01:00
pprint(requests.post(url, json={"seg": [{"col": palette, "pal": wledPalettes['colorGradient'], 'sx': speed, 'ix': power}]}).json())
2021-12-16 11:31:41 +01:00
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")
2021-12-16 16:09:10 +01:00
palette = [normalizeColor([col.rgb[c] for c in range(3)]+[0]) for col in sorted(colorgram.extract(imgFile, numColors), key=lambda c: c.proportion*0 + c.hsl.h)]
2021-12-16 11:31:41 +01:00
return palette
2021-12-16 16:09:10 +01:00
def normalizeColorByLength(rgbw):
2021-12-16 11:57:27 +01:00
s = max(max(rgbw),1)
2021-12-16 11:31:41 +01:00
fac = (1 + 255/s)/2
return [min(int(c*fac),255) for c in rgbw]
2021-12-16 16:09:10 +01:00
def normalizeColorByHue(rgbw, strength=1.0):
x = strength
y = 1-x
r, g, b, w = rgbw
h, l, s = colorsys.rgb_to_hls(r/255, g/255, b/255)
r, g, b = colorsys.hls_to_rgb(h, 0.5*x+l*y, 1*x+s*y)
return [r*255, g*255, b*255]
def normalizeColor(rgbw):
return normalizeColorByHue(rgbw, strength=0.5)
2021-12-16 11:31:41 +01:00
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')