-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
795 lines (615 loc) · 24.4 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
import spotipy
import spotipy.util as util
import os
import time
import datetime
import requests
import wget
import shutil
import re #for non ASCII detector
import sys
import configparser
import math
import cv2
import numpy as np
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
#my idea section:
"""
✅ Non-Ascii support
❌ Enable or disable image output generation
❌ Add option to enable dominant color (officialy used on older android's by spotify)
"""
#end of user edit section 😁
OpenSans = 'fonts/OpenSans.ttf'
NotoSans = 'fonts/NotoSans.ttf'
non_ascii_font = NotoSans
scope = "user-read-currently-playing"
version = "v4.5 Python"
inf = 1
osn = os.name
def read_config():
if not os.path.exists("spotix_config.ini"):
print(" ")
myClientId = input("Please input your client id: ")
mySecret = input("Please input your secret: ")
print("Make sure you have your redirect-uri set to http://localhost:8888/callback in your spotify application")
username = input("Please input your username: ")
config = configparser.ConfigParser()
config['LOGIN'] = {'client-id': myClientId,
'client-secret': mySecret,
'username': username}
config['REDIRECT'] = {'redc': 'http://localhost:8888/callback'}
config['custom'] = {
'get_average_color': False,
'get_dominant_color': True,
'set_background_color': False,
'background_color': (50, 50, 50),
'delay': 20,
'font': "OpenSans-Regular.ttf",
'font_name_size': 97,
'font_artist_size': 80
}
with open('spotix_config.ini', 'w') as configfile:
config.write(configfile)
time.sleep(5)
else:
config = configparser.ConfigParser()
# Read in the config file
config.read('spotix_config.ini')
# Access values in the config file
myClientId = config.get('LOGIN', 'client-id')
mySecret = config.get('LOGIN', 'client-secret')
myRedirect = config.get('REDIRECT', 'redc')
delay = config.getint('custom', 'delay')
get_average_color = config.getboolean('custom', 'get_average_color')
get_dominant_color = config.getboolean('custom', 'get_dominant_color')
if get_average_color:
if get_dominant_color:
get_average_color = False
print("Using dominant color")
else:
get_dominant_color = False
print("Using average color")
font = config.get('custom', 'font')
font_name_size = config.getint('custom', 'font_name_size')
font_artist_size = config.getint('custom', 'font_artist_size')
username = config.get('LOGIN', 'username')
background_color = eval(config.get('custom', 'background_color'))
def gen_token():
config = configparser.ConfigParser()
# Read in the config file
config.read('spotix_config.ini')
# Access values in the config file
myClientId = config.get('LOGIN', 'client-id')
mySecret = config.get('LOGIN', 'client-secret')
myRedirect = config.get('REDIRECT', 'redc')
username = config.get('LOGIN', 'username')
"""
returns refreshed Spotify API authentication with defined credentials
"""
start_time = time.time()
scope = "user-read-currently-playing"
token = util.prompt_for_user_token(username, scope, myClientId, mySecret, myRedirect)
currenttime = time.ctime()
sp = spotipy.Spotify(auth=token)
print("Refreshing token |", f'{currenttime}')
print("Using generated token for 1000 seconds")
return start_time
def renew_token():
config = configparser.ConfigParser()
# Read in the config file
config.read('spotix_config.ini')
# Access values in the config file
myClientId = config.get('LOGIN', 'client-id')
mySecret = config.get('LOGIN', 'client-secret')
myRedirect = config.get('REDIRECT', 'redc')
username = config.get('LOGIN', 'username')
"""
returns renewed Spotify API authentication with defined credentials
"""
start_time = time.time()
scope = "user-read-currently-playing"
token = util.prompt_for_user_token(username, scope, myClientId, mySecret, myRedirect)
currenttime = time.ctime()
sp = spotipy.Spotify(auth=token)
print("Renewing token |", f'{currenttime}')
print("Using renewed token for 1000 seconds")
return start_time
def check_token():
config = configparser.ConfigParser()
# Read in the config file
config.read('spotix_config.ini')
# Access values in the config file
username = config.get('LOGIN', 'username')
token_valid = False
if os.path.exists(".cache-"f'{username}'):
try:
token = util.prompt_for_user_token(username, scope)
sp = spotipy.Spotify(auth=token)
sp.current_user()
token_valid = True
except spotipy.SpotifyException:
token_valid = False
return token_valid
def findfonts(OpenSans, NotoSans):
fontfiles = [OpenSans, NotoSans]
missingfonts = []
for fontfile in fontfiles:
if not os.path.exists(fontfile):
missingfonts.append(fontfile)
return not missingfonts
def checkfiles(OpenSans, NotoSans):
print("----Folders----")
#folders part
if not os.path.exists('fonts'):
os.mkdir('fonts')
print("Folder fonts not found")
else:
print("Folder fonts already exist 😎")
if not os.path.exists('output'):
os.mkdir('output')
print("Folder output not found")
else:
print("Folder output already exists 😎")
print(" ")
print("----Fonts----")
checkfonts = findfonts(OpenSans, NotoSans)
#define names
OpenSans_file_name = 'OpenSans.ttf'
non_ascii_file_name = 'NotoSans.ttf'
#font part
OpenSans_extract_dir = 'fonts/' + OpenSans_file_name
non_ascii_extract_dir = 'fonts/' + non_ascii_file_name
if not checkfonts:
if not os.path.exists(OpenSans_path):
#download OpenSans
print("Missing " f'{OpenSans_path}' " 💀")
print("Please download OpenSans.ttf")
print("and place it in the fonts folder")
time.sleep(20)
if not os.path.exists(NotoSans_path):
print('')
print("Missing " f'{NotoSans_path}' " 💀")
print("Please download NotoSans.ttf")
print("and place it in the fonts folder")
time.sleep(20)
def cjk_detect(text):
cjk_pattern = re.compile(r'[\u4e00-\u9fff]|[\u3040-\u30ff]|[\u3130-\u318f]|[\uac00-\ud7af]')
return cjk_pattern.search(text)
def clear():
if(osn == 'posix'):
os.system('clear')
else:
os.system('cls')
def checkstring(string):
if string.isdigit():
# The string is a valid integer, so we can safely interpret it as one
integer = int(string)
else:
print(Exception)
return(integer)
def is_color_white(color):
white = (255, 255, 255)
threshold = 55
try:
distance = math.sqrt((white[0]-color[0])**2 + (white[1]-color[1])**2 + (white[2]-color[2])**2)
if distance < threshold:
return True
else:
return False
except:
print("error checking for white")
return True
def averageimg():
config = configparser.ConfigParser()
# Read in the config file
config.read('spotix_config.ini')
# Access values in the config file
myClientId = config.get('LOGIN', 'client-id')
mySecret = config.get('LOGIN', 'client-secret')
myRedirect = config.get('REDIRECT', 'redc')
font = config.get('custom', 'font')
font = "assets/{}".format(font)
font_name_size = config.get('custom', 'font_name_size')
font_artist_size = config.get('custom', 'font_artist_size')
username = config.get('LOGIN', 'username')
token = util.prompt_for_user_token(username, scope, myClientId, mySecret, myRedirect)
sp = spotipy.Spotify(auth=token)
currentsong = sp.currently_playing()
while True:
try:
currentsong = sp.currently_playing()
song_name = currentsong['item']['name']
except spotipy.SpotifyException: #token expired
print("Refreshing token")
gen_token()
break
except TypeError: #checks if something is playing
logo()
print("Nothing is playing at the moment | {}".format(datetime.datetime.now().strftime("%H:%M:%S")))
time.sleep(5)
clear()
else:
break
song_image = currentsong['item']['album']['images'][0]['url']
song_artist = currentsong['item']['artists'][0]['name']
url = song_image
#simple request for cover image
r = requests.get(url, stream=True)
ext = r.headers['content-type'].split('/')[-1] # converts response headers mime type to an extension (may not work with everything)
with open("output/icon.jpeg" , 'wb') as f: # open the file to write as binary - replace 'wb' with 'w' for text files
for chunk in r.iter_content(1024): # iterate on stream using 1KB packets
f.write(chunk) # write the file
# Calculate the average color of the image
src_img = cv2.imread('output/icon.jpeg')
average_color_row = np.average(src_img, axis=0)
average_color = np.average(average_color_row, axis=0)
'''
cv2.imshow('Source image',src_img)
cv2.imshow('Average Color',average_color_row)
cv2.waitKey(1)
'''
#convert to simple brackets
average_color = average_color.astype(np.uint)
average_color_tuple = (*average_color,)
print("Average color (RGB): " + f'{average_color_tuple}')
#building the final image
img = Image.open('output/icon.jpeg', 'r')
background = Image.new('RGB', (1920, 640), average_color_tuple)
offset = (0, 0)
background.paste(img, offset)
draw = ImageDraw.Draw(background)
if cjk_detect(song_name) == True:
non_ascii_font_size = int(font_name_size) - 15
name = ImageFont.truetype(non_ascii_font, non_ascii_font_size)
print("Found non ASCII chars in song's name")
else:
name = ImageFont.truetype(font, int(font_artist_size))
if cjk_detect(song_image) == True:
non_ascii_font_size = int(font_artist_size) - 15
art = ImageFont.truetype(non_ascii_font, non_ascii_font_size)
print("Found non ASCII chars in song's artist")
else:
art = ImageFont.truetype(font, int(font_artist_size))
if is_color_white(average_color_tuple) == True:
draw.text((650, 240),song_name,(0,0,0),font=name)
draw.text((650, 320),song_artist,(0,0,0),font=art)
else:
draw.text((650, 240),song_name,(255,255,255),font=name)
draw.text((650, 320),song_artist,(255,255,255),font=art)
background.save('output/output.jpeg')
def dominantimg():
config = configparser.ConfigParser()
# Read in the config file
config.read('spotix_config.ini')
# Access values in the config file
myClientId = config.get('LOGIN', 'client-id')
mySecret = config.get('LOGIN', 'client-secret')
myRedirect = config.get('REDIRECT', 'redc')
font = config.get('custom', 'font')
font = "assets/{}".format(font)
font_name_size = config.get('custom', 'font_name_size')
font_artist_size = config.get('custom', 'font_artist_size')
username = config.get('LOGIN', 'username')
token = util.prompt_for_user_token(username, scope, myClientId, mySecret, myRedirect)
sp = spotipy.Spotify(auth=token)
currentsong = sp.currently_playing()
while True:
try:
currentsong = sp.currently_playing()
song_name = currentsong['item']['name']
except spotipy.SpotifyException: #token expired
print("Refreshing token")
gen_token()
break
except TypeError: #checks if something is playing
logo()
print("Nothing is playing at the moment | {}".format(datetime.datetime.now().strftime("%H:%M:%S")))
time.sleep(5)
clear()
else:
break
song_image = currentsong['item']['album']['images'][0]['url']
song_artist = currentsong['item']['artists'][0]['name']
url = song_image
#simple request for cover image
r = requests.get(url, stream=True)
ext = r.headers['content-type'].split('/')[-1] # converts response headers mime type to an extension (may not work with everything)
with open("output/icon.jpeg" , 'wb') as f: # open the file to write as binary - replace 'wb' with 'w' for text files
for chunk in r.iter_content(1024): # iterate on stream using 1KB packets
f.write(chunk) # write the file
# Calculate the average color of the image
img = Image.open('output/icon.jpeg', 'r')
colors = img.getcolors(img.size[0] * img.size[1])
# Sort the list of colors by count
sorted_colors = sorted(colors, key=lambda t: t[0])
# Get the most frequent color
dominant_color = sorted_colors[-1][1]
if dominant_color == '255':
dominant_color = (255, 255, 255)
print("Dominant color = {}".format(dominant_color))
background = Image.new('RGB', (1920, 640), dominant_color)
offset = (0, 0)
background.paste(img, offset)
draw = ImageDraw.Draw(background)
if cjk_detect(song_name) == True:
non_ascii_font_size = int(font_name_size) - 15
name = ImageFont.truetype(non_ascii_font, non_ascii_font_size)
print("Found non ASCII chars in song's name")
else:
name = ImageFont.truetype(font, int(font_artist_size))
if cjk_detect(song_image) == True:
non_ascii_font_size = int(font_artist_size) - 15
art = ImageFont.truetype(non_ascii_font, non_ascii_font_size)
print("Found non ASCII chars in song's artist")
else:
art = ImageFont.truetype(font, int(font_artist_size))
if is_color_white(dominant_color) == True:
draw.text((650, 240),song_name,(0,0,0),font=name)
draw.text((650, 320),song_artist,(0,0,0),font=art)
else:
draw.text((650, 240),song_name,(255,255,255),font=name)
draw.text((650, 320),song_artist,(255,255,255),font=art)
background.save('output/output.jpeg')
def setcolor():
config = configparser.ConfigParser()
# Read in the config file
config.read('spotix_config.ini')
# Access values in the config file
myClientId = config.get('LOGIN', 'client-id')
mySecret = config.get('LOGIN', 'client-secret')
myRedirect = config.get('REDIRECT', 'redc')
font = config.get('custom', 'font')
font = "assets/{}".format(font)
font_name_size = config.get('custom', 'font_name_size')
font_artist_size = config.get('custom', 'font_artist_size')
username = config.get('LOGIN', 'username')
background_color = config.get('custom', 'background_color')
token = util.prompt_for_user_token(username, scope, myClientId, mySecret, myRedirect)
sp = spotipy.Spotify(auth=token)
currentsong = sp.currently_playing()
while True:
try:
currentsong = sp.currently_playing()
song_name = currentsong['item']['name']
except spotipy.SpotifyException: #token expired
print("Refreshing token")
gen_token()
break
except TypeError: #checks if something is playing
logo()
print("Nothing is playing at the moment | {}".format(datetime.datetime.now().strftime("%H:%M:%S")))
time.sleep(5)
clear()
else:
break
song_image = currentsong['item']['album']['images'][0]['url']
song_artist = currentsong['item']['artists'][0]['name']
url = song_image
#simple request for cover image
r = requests.get(url, stream=True)
ext = r.headers['content-type'].split('/')[-1] # converts response headers mime type to an extension (may not work with everything)
with open("output/icon.jpeg" , 'wb') as f: # open the file to write as binary - replace 'wb' with 'w' for text files
for chunk in r.iter_content(1024): # iterate on stream using 1KB packets
f.write(chunk) # write the file
print("Using color from config (RGB): {}".format(background_color))
background = Image.new('RGB', (1920, 640), eval(background_color))
img = Image.open('output/icon.jpeg', 'r')
offset = (0, 0)
background.paste(img, offset)
draw = ImageDraw.Draw(background)
if cjk_detect(song_name) == True:
non_ascii_font_size = int(font_name_size) - 15
name = ImageFont.truetype(non_ascii_font, non_ascii_font_size)
print("Found non ASCII chars in song's name")
else:
name = ImageFont.truetype(font, int(font_artist_size))
if cjk_detect(song_image) == True:
non_ascii_font_size = int(font_artist_size) - 15
art = ImageFont.truetype(non_ascii_font, non_ascii_font_size)
print("Found non ASCII chars in song's artist")
else:
art = ImageFont.truetype(font, int(font_artist_size))
if is_color_white(eval(background_color)) == True:
draw.text((650, 240),song_name,(0,0,0),font=name)
draw.text((650, 320),song_artist,(0,0,0),font=art)
else:
draw.text((650, 240),song_name,(255,255,255),font=name)
draw.text((650, 320),song_artist,(255,255,255),font=art)
background.save('output/output.jpeg')
def getname():
config = configparser.ConfigParser()
# Read in the config file
config.read('spotix_config.ini')
# Access values in the config file
myClientId = config.get('LOGIN', 'client-id')
mySecret = config.get('LOGIN', 'client-secret')
myRedirect = config.get('REDIRECT', 'redc')
username = config.get('LOGIN', 'username')
token = util.prompt_for_user_token(username, scope, myClientId, mySecret, myRedirect)
sp = spotipy.Spotify(auth=token)
currentsong = sp.currently_playing()
while True:
try:
currentsong = sp.currently_playing()
song_name = currentsong['item']['name']
except spotipy.SpotifyException: # token expired
print("Refreshing token")
gen_token()
break
except TypeError: # checks if something is playing
logo()
print("Nothing is playing at the moment | {}".format(datetime.datetime.now().strftime("%H:%M:%S")))
time.sleep(5)
clear()
else:
break
song_artist = currentsong['item']['artists'][0]['name']
song_image = currentsong['item']['album']['images'][0]['url']
out = {
"NAME": song_name,
"ARTIST": song_artist
}
print("Now playing: {} by {}".format(song_name, song_artist), "🎧")
txtoutput = song_name + " by " + song_artist
if cjk_detect(txtoutput) == True:
with open("output/song.txt", "w", encoding='utf-8') as f:
f.writelines(txtoutput)
f.close()
else:
f = open("output/song.txt", "w")
f.write(txtoutput)
f.close()
# if the name of the song is the same skip the image generation
url = song_image
last_url = "output/last_url.txt"
if os.path.exists(last_url):
with open(last_url, "r") as f:
previous_url = f.read()
if previous_url == url:
return out, False
with open(last_url, "w") as f:
f.write(url)
return out, True
#ascii art 👑
def art():
osn = os.name
print(r"""
____
/ __/
_\ \/
/___/
""")
time.sleep(.5)
clear()
print(r"""
____
/ __/__
_\ \/ _ \
/___/ .__/
/_/
""")
time.sleep(.5)
clear()
print(r"""
____
/ __/__ ___
_\ \/ _ \/ _ \
/___/ .__/\___/
/_/
""")
time.sleep(.5)
clear()
print(r"""
____ __
/ __/__ ___ / /_
_\ \/ _ \/ _ \/ __/
/___/ .__/\___/\__/
/_/
""")
time.sleep(.5)
clear()
print(r"""
____ __ _
/ __/__ ___ / /_(_)
_\ \/ _ \/ _ \/ __/ /
/___/ .__/\___/\__/_/
/_/
""")
time.sleep(.5)
clear()
print("""
____ __ _
/ __/__ ___ / /_(_)_ __
_\ \/ _ \/ _ \/ __/ /\ \ /
/___/ .__/\___/\__/_//_\_\ {}
/_/
""".format(version))
def updelay():
repeat = 0
config = configparser.ConfigParser()
config.read('spotix_config.ini')
# Access values in the config file
delay = config.get('custom', 'delay')
print("Delay in seconds: "f'{delay}')
while int(delay) > repeat:
repeat = repeat + 1
time.sleep(1)
print("["f'{repeat}'"]", end='', flush=True)
def logo():
print("""
____ __ _
/ __/__ ___ / /_(_)_ __
_\ \/ _ \/ _ \/ __/ /\ \ /
/___/ .__/\___/\__/_//_\_\ {}
/_/
""".format(version))
def main():
# Start
art()
checkfiles(OpenSans, NotoSans) # Checks if folders and fonts are OK
read_config() # Read the configuration
# Check if token is valid, if not, generate a new one
if not check_token():
start_time = gen_token()
else:
start_time = time.time()
start_output = start_time + 1000
time.sleep(5)
#
# Looking at this back, I was really crazy to write this in one file 😂
#
clear()
# ez infinity loop
while inf == 1:
new_time = time.time()
# Renew token if needed
if new_time >= start_time + 1000:
start_time = renew_token()
start_output = start_time + 1000
logo() # hehe
remaining = start_output - new_time
tokenage = np.round(remaining)
# Prints all info!
print("Remaining seconds till token refresh: " f'{tokenage}')
config = configparser.ConfigParser()
# Read in the config file
config.read('spotix_config.ini')
get_average_color = config.getboolean('custom', 'get_average_color')
get_dominant_color = config.getboolean('custom', 'get_dominant_color')
set_background_color = config.getboolean('custom', 'set_background_color')
if get_dominant_color: # Gets dominant color if set in config
if get_average_color or set_background_color:
clear()
print("Only one option please :D")
print("get_average OR get_dominant OR set_background")
time.sleep(10)
exit("Two or more options set in config")
dominantimg()
if get_average_color: # Gets average color if set in config
if get_dominant_color or set_background_color:
clear()
print("Only one option please :D")
print("get_average OR get_dominant OR set_background")
time.sleep(10)
exit("Two or more options set in config")
averageimg()
if set_background_color: # Gets set background color as set in config
if get_dominant_color or get_average_color:
clear()
print("Only one option please :D")
print("get_average OR get_dominant OR set_background")
time.sleep(10)
exit("Two or more options set in config")
setcolor()
out, new_image = getname()
if new_image:
print(" ")
updelay()
else:
print(" ")
updelay()
clear()
main()