-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
1767 lines (1425 loc) · 86.9 KB
/
app.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
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
_____ _ _ _____
/ ____| | | |/ ____|
| | | |__ ___ _ __ __| | (___ _ _ _ __ ___
| | | '_ \ / _ \| '__/ _` |\___ \| | | | '_ \ / __|
| |____| | | | (_) | | | (_| |____) | |_| | | | | (__
\_____|_| |_|\___/|_| \__,_|_____/ \__, |_| |_|\___|
__/ |
|___/
by Simon Roedig (Mediainformatics @LMU Munich)
Bachelor's Thesis (WS 2023/2024)
"""
######## IMPORTS ########
import atexit
import datetime
import html
import json
import math
import os
import re
import requests
from bs4 import BeautifulSoup
from dotenv import load_dotenv
from flask import Flask, redirect, render_template, request, send_from_directory, session, g
from fuzzywuzzy import fuzz
from icecream import ic
from flask_socketio import SocketIO, emit
from flask_cors import CORS
from spotipy import SpotifyOAuth
from spotipy.exceptions import SpotifyException
import spotipy
import sqlite3
######## FLASK ########
app = Flask(__name__)
app.secret_key = os.getenv("FLASK_SECRET_KEY")
#CORS(app, resources={r"/*": {"origins": ["https://chordsync.io", "https://chordsync.onrender.com", "http://192.168.2.100:5000/"]}})
# https://stackoverflow.com/questions/20035101/why-does-my-javascript-code-receive-a-no-access-control-allow-origin-header-i
######## DATABASE ########
DATABASE_LYRICS = 'lyrics_data.db'
DATABASE_UE = 'ue_data.db'
def get_database(db_name):
db = getattr(g, '_database_' + db_name, None)
if db is None:
db = g._database = sqlite3.connect(db_name)
db.row_factory = sqlite3.Row
return db
def close_database(db_name, exception):
db = getattr(g, '_database_' + db_name, None)
if db is not None:
db.close()
def init_database(db_name, table_name, columns):
with app.app_context():
db = get_database(db_name)
cursor = db.cursor()
cursor.execute(f'''
CREATE TABLE IF NOT EXISTS {table_name} (
{', '.join(columns)}
)
''')
db.commit()
@app.teardown_appcontext
def teardown_db(exception):
close_database('lyrics', exception)
close_database('ue', exception)
# Initialization
init_database(DATABASE_LYRICS, 'lyrics_db', [
'track_id TEXT PRIMARY KEY',
'artist_name TEXT',
'track_name TEXT',
'save_timestamp TEXT',
'original_json TEXT'
])
init_database(DATABASE_UE, 'ue_db', [
'track_id TEXT PRIMARY KEY',
'artist_name TEXT',
'track_name TEXT',
'save_timestamp TEXT',
'complete_source_code TEXT',
'complete_source_code_link TEXT',
'complete_source_code_found INTEGER',
'result_index INTEGER'
])
######## .env ########
load_dotenv()
dev_or_prod = os.getenv("DEV_OR_PROD") # either "DEVELOPMENT" or "PRODUCTION"
lyrics_api_source = os.getenv("LYRICS_API_SOURCE") # either "REST" or "SELFMADE"
log_on_off = os.getenv("LOG_ON_OFF") # either "ON" or "OFF"
print(f"dev_or_prod: {dev_or_prod}")
print(f"lyrics_api_source: {lyrics_api_source}")
print(f"log_on_off: {log_on_off}")
######## LOGGING ########
timestamp = datetime.datetime.now().strftime("%d_%m_%Y__%H_%M_%S")
log_file_path = f'logs/log__{timestamp}.txt'
song_in_log = 248
wrote_block_1 = ""
wrote_block_2 = ""
wrote_block_3 = ""
wrote_block_4 = ""
if (dev_or_prod == "DEVELOPMENT" and log_on_off == "ON"):
with open(log_file_path, 'a') as file:
file.write(f"Playlist Name: Easy Songs to Learn on Guitar\n")
file.write(f"Playlist Created by: GuitarCatMatt\n")
file.write(f"Playlist Likes: 1.353\n")
file.write(f"Playlist Timestamp: {timestamp}\n")
file.write(f"-> Link: https://open.spotify.com/playlist/5hrQcqeuQCVu3tWbl8T8Y9?si=f80e9e2d6cea41e4\n")
######## SELFMADE SPOTIFY LYRICS ########
if (lyrics_api_source == "SELFMADE"):
from spotify_lyrics import SpotifyLyrics
sp_dc_cookie = os.getenv("SP_DC_COOKIE")
selfmade_spotify_lyrics = SpotifyLyrics(sp_dc_cookie)
######## WEB SOCKET ########
#socketio = SocketIO(app, cors_allowed_origins=["https://chordsync.io", "https://chordsync.onrender.com", 'http://192.168.2.100:5000/'])
socketio = SocketIO(app, cors_allowed_origins="*")
######## SPOTIFY API ########
if (dev_or_prod == "PRODUCTION"):
print("In Production")
spotify_client_id = os.getenv("SPOTIFY_CLIENT_ID")
spotify_client_secret = os.getenv("SPOTIFY_CLIENT_SECRET")
spotify_redirect_uri = os.getenv("SPOTIFY_REDIRECT_URI")
elif (dev_or_prod == "DEVELOPMENT"):
print("In Development")
spotify_client_id = os.getenv("SPOTIFY_CLIENT_ID_LOCAL")
spotify_client_secret = os.getenv("SPOTIFY_CLIENT_SECRET_LOCAL")
spotify_redirect_uri = os.getenv("SPOTIFY_REDIRECT_URI_LOCAL")
spotify_scope = 'user-modify-playback-state,user-read-playback-state'
sp_oauth = SpotifyOAuth(client_id=spotify_client_id, client_secret=spotify_client_secret, redirect_uri=spotify_redirect_uri, scope=spotify_scope, show_dialog=True, cache_path=None)
######## GOOGLE API ########
google_api_key = os.getenv("GOOGLE_API_KEY")
google_search_engine_id = os.getenv("GOOGLE_SEARCH_ENGINE_ID")
######## GLOBAL VARIABLES ########
complete_source_code = ""
complete_source_code_link = ""
complete_source_code_found = 0
guitar_tuning = 0
guitar_capo = 0
synced_lyrics_json = 0
synced_lyrics_tupel_array = []
main_chords_body = ""
found_musixmatch_lyrics = 0
musixmatch_lyrics_is_linesynced = 0
spotify_error = 0
is_logged_in = False
spotify_user_name = ""
track_bpm = 0
track_key = 0
sync_ratio_percentage = "0%"
previous_spotify_volume = 0
######## HTTP ROUTES ########
@app.route('/favicon.ico')
def favicon():
return send_from_directory(app.root_path, 'static/favicon.png', mimetype='image/vnd.microsoft.icon')
@app.route('/')
def index():
global is_logged_in
token_info = session.get('token_info', {})
if token_info == {}:
is_logged_in = False
else:
is_logged_in = True
token_info = refresh_token()
if token_info != 0:
spotify = spotipy.Spotify(auth=token_info['access_token'])
spotify_user_name = spotify.current_user()['display_name']
image = spotify.current_user()['images']
spotify_user_image = image[0]['url'] if image else ""
else:
spotify_user_name = ""
spotify_user_image = ""
return render_template('index.html', album_cover_url="", track_name="Track", artist_name="Artist", minutes=0, seconds=00,
guitar_tuning="E A D G B E", guitar_capo="0", main_chords_body="", complete_source_code_link='javascript:void(0)',
is_logged_in=is_logged_in, spotify_user_name=spotify_user_name, spotify_user_image=spotify_user_image, dev_or_prod=dev_or_prod, log_on_off=log_on_off)
@app.route('/login')
def login():
auth_url = sp_oauth.get_authorize_url()
return redirect(auth_url)
@app.route('/logout')
def logout():
global is_logged_in
# Clearing the session data
session.clear()
# Delete the Spotipy cache file
cache_file = '.cache'
if os.path.exists(cache_file):
os.remove(cache_file)
is_logged_in = False
return redirect('/')
@app.route('/callback')
def callback():
logout()
global is_logged_in
error = request.args.get('error')
code = request.args.get('code')
if error:
# User declined the authorization
is_logged_in = False
elif code:
# User accepted the authorization, proceed to get the token
is_logged_in = True
session['token_info'] = sp_oauth.get_access_token(code)
else:
# No code and no error, handle according to your application's logic
is_logged_in = False
return redirect('/')
def refresh_token():
global is_logged_in
token_info = session.get('token_info', {})
if token_info == {}:
is_logged_in = False
return 0
if sp_oauth.is_token_expired(token_info):
is_logged_in = True
token_info = sp_oauth.refresh_access_token(token_info['refresh_token'])
session['token_info'] = token_info
return token_info
######## WEBSOCKET ROUTES ########
@socketio.on('connect')
def handleConnect():
print('WebSocket: Client (JavaScript) connected to Server (Python)')
@socketio.on('trackDynamicDataRequest')
def handleDynamicDataRequest():
emit('trackDynamicDataResponse', getTrackDynamicData())
@socketio.on('trackStaticDataRequest')
def handleStaticDataRequest(align="left"):
emit('trackStaticDataResponse', getTrackStaticData(align))
@socketio.on('nextSpotifyTrack')
def nextSpotifyTrack():
try:
token_info = refresh_token()
if token_info == 0:
return redirect('/')
spotify = spotipy.Spotify(auth=token_info['access_token'])
spotify.next_track()
return redirect('/')
except SpotifyException as e:
if e.http_status == 403 and "PREMIUM_REQUIRED" in str(e):
emit('error_message', {'message': 'Error: Spotify Premium required for this action.'})
else:
print(f'Error: {e}')
except Exception as e:
print(f'Error: {e}')
return redirect('/')
@socketio.on('previousSpotifyTrack')
def previousSpotifyTrack():
try:
token_info = refresh_token()
if token_info == 0:
return redirect('/')
spotify = spotipy.Spotify(auth=token_info['access_token'])
spotify.previous_track()
return redirect('/')
except SpotifyException as e:
if e.http_status == 403 and "PREMIUM_REQUIRED" in str(e):
emit('error_message', {'message': 'Error: Spotify Premium required for this action.'})
else:
print(f'Error: {e}')
except Exception as e:
print(f'Error: {e}')
return redirect('/')
@socketio.on('playPauseSpotifyTrack')
def playPauseSpotifyTrack():
try:
token_info = refresh_token()
if token_info == 0:
return redirect('/')
spotify = spotipy.Spotify(auth=token_info['access_token'])
current_track = spotify.current_playback()
is_playing = current_track['is_playing']
if is_playing:
spotify.pause_playback()
else:
spotify.start_playback()
return redirect('/')
except SpotifyException as e:
if e.http_status == 403 and "PREMIUM_REQUIRED" in str(e):
emit('error_message', {'message': 'Error: Spotify Premium required for this action.'})
else:
print(f'Error: {e}')
except Exception as e:
print(f'Error: {e}')
return redirect('/')
@socketio.on('increaseVolumeSpotify')
def increaseVolumeSpotify():
try:
token_info = refresh_token()
if token_info == 0:
return redirect('/')
spotify = spotipy.Spotify(auth=token_info['access_token'])
current_track = spotify.current_playback()
current_volume = current_track['device']['volume_percent']
# Increase the volume by 10% (you can adjust this value)
new_volume = min(current_volume + 10, 100)
spotify.volume(volume_percent=new_volume)
return redirect('/')
except SpotifyException as e:
if e.http_status == 403 and "PREMIUM_REQUIRED" in str(e):
emit('error_message', {'message': 'Error: Spotify Premium required for this action.'})
else:
print(f'Error: {e}')
except Exception as e:
print(f'Error: {e}')
return redirect('/')
@socketio.on('decreaseVolumeSpotify')
def decreaseVolumeSpotify():
try:
token_info = refresh_token()
if token_info == 0:
return redirect('/')
spotify = spotipy.Spotify(auth=token_info['access_token'])
current_track = spotify.current_playback()
current_volume = current_track['device']['volume_percent']
# Decrease the volume by 10% (you can adjust this value)
new_volume = max(current_volume - 10, 0)
spotify.volume(volume_percent=new_volume)
return redirect('/')
except SpotifyException as e:
if e.http_status == 403 and "PREMIUM_REQUIRED" in str(e):
emit('error_message', {'message': 'Error: Spotify Premium required for this action.'})
else:
print(f'Error: {e}')
except Exception as e:
print(f'Error: {e}')
return redirect('/')
@socketio.on('muteSpotifyTrack')
def muteSpotifyTrack():
global previous_spotify_volume
try:
token_info = refresh_token()
if token_info == 0:
return redirect('/')
spotify = spotipy.Spotify(auth=token_info['access_token'])
current_track = spotify.current_playback()
current_volume = current_track['device']['volume_percent']
if (current_volume != 0):
previous_spotify_volume = current_volume
elif (current_volume == 0):
spotify.volume(volume_percent=previous_spotify_volume)
return redirect('/')
# Decrease the volume by 10% (you can adjust this value)
new_volume = max(current_volume - current_volume, 0)
spotify.volume(volume_percent=new_volume)
return redirect('/')
except SpotifyException as e:
if e.http_status == 403 and "PREMIUM_REQUIRED" in str(e):
emit('error_message', {'message': 'Error: Spotify Premium required for this action.'})
else:
print(f'Error: {e}')
except Exception as e:
print(f'Error: {e}')
return redirect('/')
@socketio.on('toggleShuffleState')
def toggleShuffleState():
try:
token_info = refresh_token()
if token_info == 0:
return redirect('/')
spotify = spotipy.Spotify(auth=token_info['access_token'])
current_playback = spotify.current_playback()
current_shuffle_state = current_playback['shuffle_state']
# Toggle the shuffle state
new_shuffle_state = not current_shuffle_state
spotify.shuffle(state=new_shuffle_state)
return redirect('/')
except SpotifyException as e:
if e.http_status == 403 and "PREMIUM_REQUIRED" in str(e):
emit('error_message', {'message': 'Error: Spotify Premium required for this action.'})
else:
print(f'Error: {e}')
except Exception as e:
print(f'Error: {e}')
return redirect('/')
@socketio.on('toggleRepeatState')
def toggleRepeatState():
try:
token_info = refresh_token()
if token_info == 0:
return redirect('/')
spotify = spotipy.Spotify(auth=token_info['access_token'])
current_playback = spotify.current_playback()
current_repeat_state = current_playback['repeat_state']
# Toggle the repeat state
if current_repeat_state == 'off':
new_repeat_state = 'track' # Repeat current track
elif current_repeat_state == 'track':
new_repeat_state = 'context' # Repeat current context (playlist or album)
else:
new_repeat_state = 'off' # Turn off repeat
spotify.repeat(state=new_repeat_state)
return redirect('/')
except SpotifyException as e:
if e.http_status == 403 and "PREMIUM_REQUIRED" in str(e):
emit('error_message', {'message': 'Error: Spotify Premium required for this action.'})
else:
print(f'Error: {e}')
except Exception as e:
print(f'Error: {e}')
return redirect('/')
@socketio.on('jumpInsideTrack')
def jumpInsideTrack(ms):
try:
token_info = refresh_token()
if token_info == 0:
return redirect('/')
spotify = spotipy.Spotify(auth=token_info['access_token'])
spotify.seek_track(ms)
return redirect('/')
except SpotifyException as e:
if e.http_status == 403 and "PREMIUM_REQUIRED" in str(e):
emit('error_message', {'message': 'Error: Spotify Premium required for this action.'})
else:
print(f'Error: {e}')
except Exception as e:
print(f'Error: {e}')
return redirect('/')
@socketio.on('/songBackwards')
def seek(progress_ms, wind_lenght_ms):
try:
token_info = refresh_token()
if token_info == 0:
return redirect('/')
print("SONG BACKWARDS")
new_progress_ms = int(progress_ms) - int(wind_lenght_ms)
if new_progress_ms < 0:
new_progress_ms = 0
spotify = spotipy.Spotify(auth=token_info['access_token'])
spotify.seek_track(new_progress_ms)
return redirect('/')
except SpotifyException as e:
if e.http_status == 403 and "PREMIUM_REQUIRED" in str(e):
emit('error_message', {'message': 'Error: Spotify Premium required for this action.'})
else:
print(f'Error: {e}')
except Exception as e:
print(f'Error: {e}')
return redirect('/')
@socketio.on('/songForwards')
def seek(progress_ms, track_duration_ms, wind_lenght_ms):
try:
token_info = refresh_token()
if token_info == 0:
return redirect('/')
new_progress_ms = int(progress_ms) + int(wind_lenght_ms)
if new_progress_ms > track_duration_ms:
new_progress_ms = progress_ms
spotify = spotipy.Spotify(auth=token_info['access_token'])
spotify.seek_track(new_progress_ms)
return redirect('/')
except SpotifyException as e:
if e.http_status == 403 and "PREMIUM_REQUIRED" in str(e):
emit('error_message', {'message': 'Error: Spotify Premium required for this action.'})
else:
print(f'Error: {e}')
except Exception as e:
print(f'Error: {e}')
return redirect('/')
# Called by WebSocket - returns object with parameters that change during the song
def getTrackDynamicData():
token_info = refresh_token()
if token_info == 0:
return {
'track_id': "0",
'progress_ms': 0,
'current_time': "0:00",
'play_or_pause': "False",
'current_volume': 0,
'current_shuffle_state': "False",
'current_repeat_state': 'off'
}
spotify = spotipy.Spotify(auth=token_info['access_token'])
try:
current_track = spotify.current_playback()
except SpotifyException as e:
current_track = None
ic(f'Error: {e}')
if current_track is None:
return {
'track_id': "0",
'progress_ms': 0,
'current_time': "0:00",
'play_or_pause': "False",
'current_volume': 0,
'current_shuffle_state': "False",
'current_repeat_state': 'off'
}
track_id = current_track['item']['id']
progress_ms = current_track['progress_ms']
minutes, seconds = divmod(progress_ms / 1000, 60)
is_playing = str(current_track['is_playing'])
current_volume = current_track['device']['volume_percent']
current_shuffle_state = current_track['shuffle_state']
current_repeat_state = current_track['repeat_state']
return {
'track_id': track_id,
'progress_ms': progress_ms,
'current_time': f"{int(minutes)}:{int(seconds):02d}",
'play_or_pause': is_playing,
'current_volume': current_volume,
'current_shuffle_state': current_shuffle_state,
'current_repeat_state': current_repeat_state
}
# Called by Websocket - returns object with parameters that DON'T change during the song
def getTrackStaticData(align):
global complete_source_code
global complete_source_code_link
global complete_source_code_found
global guitar_tuning
global guitar_capo
global synced_lyrics_json
global synced_lyrics_tupel_array
global main_chords_body
global spotify_error
global track_bpm
global track_key
global sync_ratio_percentage
global song_in_log
global wrote_block_1
global wrote_block_2
global wrote_block_3
token_info = refresh_token()
if token_info == 0:
complete_source_code_link = ""
complete_source_code_found = 0
guitar_tuning = "E A D G B E"
guitar_capo = "0"
main_chords_body = "Welcome to ChordSync. <br> Login to start."
found_musixmatch_lyrics = 0
musixmatch_lyrics_is_linesynced = 0
track_bpm = 0
track_key = 0
sync_ratio_percentage = "0%"
spotify_error = 1
return {
'track_name': "Track",
'artist_name': "Artist",
'track_duration_ms': "",
'track_duration_m_and_s': "0:00",
'album_cover_url': "",
'guitar_tuning': guitar_tuning,
'guitar_capo': guitar_capo,
'main_chords_body': main_chords_body,
'complete_source_code_link': "javascript:void(0)",
'complete_source_code_found': complete_source_code_found,
'musixmatch_lyrics_is_linesynced': musixmatch_lyrics_is_linesynced,
'found_musixmatch_lyrics': found_musixmatch_lyrics,
'spotify_error': spotify_error,
'track_bpm': track_bpm,
'sync_ratio_percentage': sync_ratio_percentage,
'track_key': track_key
}
spotify = spotipy.Spotify(auth=token_info['access_token'])
try:
current_track = spotify.current_playback()
except SpotifyException as e:
current_track = None
ic(f'Error: {e}')
if current_track is not None:
track_id = current_track['item']['id']
track_name = current_track['item']['name']
artist_name = current_track['item']['artists'][0]['name']
track_duration_ms = current_track["item"]["duration_ms"]
minutes, seconds = divmod(track_duration_ms / 1000, 60)
album_cover_url = current_track['item']['album']['images'][0]['url']
####
# Get audio features for the current track
try:
audio_features = spotify.audio_features([track_id])
if audio_features:
track_bpm = round(audio_features[0]['tempo'])
track_key_value = audio_features[0]['key'] # Range: -1 - 11: https://en.wikipedia.org/wiki/Pitch_class
key_number_array = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
key_tonal_array = ["0", "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
key_tonal = key_tonal_array[key_number_array.index(track_key_value)]
track_key_major_or_minor_value = audio_features[0]['mode'] # Major is represented by 1 and minor is 0
track_key_major_or_minor = "" if track_key_major_or_minor_value == 1 else "m"
track_key = f"{key_tonal}{track_key_major_or_minor}"
else:
ic('Audio features not available for this track.')
except SpotifyException as e:
ic(f'Error fetching audio features: {e}')
###
if (dev_or_prod == "DEVELOPMENT" and log_on_off == "ON" and wrote_block_1 != track_id):
with open(log_file_path, 'a') as file:
wrote_block_1 = track_id
file.write(f"\n")
file.write(f"-------------------------\n")
file.write(f"SONG: {song_in_log}\n")
file.write(f"TRACK ID: {track_id}\n")
file.write(f"TRACK NAME: {track_name}\n")
file.write(f"ARTIST NAME: {artist_name}\n")
file.write(f"-----\n")
song_in_log += 1
spotify_error = 0
complete_source_code, complete_source_code_link, complete_source_code_found, result_index = googleChordsForDB(track_name, artist_name, track_id)
main_chords_body = complete_source_code;
if (dev_or_prod == "DEVELOPMENT" and log_on_off == "ON" and wrote_block_2 != track_id):
with open(log_file_path, 'a') as file:
wrote_block_2 = track_id
file.write(f"FOUND ULTIMATE GUITAR CHORDS: {'YES' if complete_source_code_found else 'NO'}\n")
file.write(f"ULTIMATE GUITAR URL: {complete_source_code_link}\n")
file.write(f"GOOGLE RESULT INDEX: {result_index}\n")
file.write(f"-----\n")
if complete_source_code_found == 1:
guitar_tuning = extractTuning(complete_source_code)
guitar_capo = extractCapo(complete_source_code)
main_chords_body = extractMainChordsBody(complete_source_code, align)
synced_lyrics_json, found_musixmatch_lyrics, musixmatch_lyrics_is_linesynced = getSyncedLyricsJson(track_id, artist_name, track_name)
if (dev_or_prod == "DEVELOPMENT" and log_on_off == "ON" and wrote_block_3 != track_id):
with open(log_file_path, 'a') as file:
wrote_block_3 = track_id
file.write(f"FOUND LYRICS: {'YES' if found_musixmatch_lyrics else 'NO'}\n")
file.write(f"LYRICS ARE LINE SYNCED: {'YES' if musixmatch_lyrics_is_linesynced else 'NO'}\n")
file.write(f"-----\n")
# Happy Path: Chords and synced lyrics found
if (found_musixmatch_lyrics == 1 and musixmatch_lyrics_is_linesynced == 1):
synced_lyrics_tupel_array = parseSyncedLyricsJsonToTupelArray(synced_lyrics_json)
### Main Algorithm
main_chords_body, error_syncing = insertTimestampsToMainChordsBody(synced_lyrics_tupel_array, main_chords_body, track_duration_ms, track_id)
# If sync below treshold, regard as unsyncable (like no lyrics found)
if error_syncing:
print(error_syncing)
sync_ratio_percentage = "0"
found_musixmatch_lyrics = 0
musixmatch_lyrics_is_linesynced = 0
return {
'track_name': track_name,
'artist_name': artist_name,
'track_duration_ms': track_duration_ms,
'track_duration_m_and_s': f"{int(minutes)}:{int(seconds):02d}",
'album_cover_url': album_cover_url,
'guitar_tuning': guitar_tuning,
'guitar_capo': guitar_capo,
'main_chords_body': main_chords_body,
'complete_source_code_link': complete_source_code_link,
'complete_source_code_found': complete_source_code_found,
'musixmatch_lyrics_is_linesynced': musixmatch_lyrics_is_linesynced,
'found_musixmatch_lyrics': found_musixmatch_lyrics,
'spotify_error': spotify_error,
'track_bpm': track_bpm,
'sync_ratio_percentage': sync_ratio_percentage,
'track_key': track_key
}
return {
'track_name': track_name,
'artist_name': artist_name,
'track_duration_ms': track_duration_ms,
'track_duration_m_and_s': f"{int(minutes)}:{int(seconds):02d}",
'album_cover_url': album_cover_url,
'guitar_tuning': guitar_tuning,
'guitar_capo': guitar_capo,
'main_chords_body': main_chords_body,
'complete_source_code_link': complete_source_code_link,
'complete_source_code_found': complete_source_code_found,
'musixmatch_lyrics_is_linesynced': musixmatch_lyrics_is_linesynced,
'found_musixmatch_lyrics': found_musixmatch_lyrics,
'spotify_error': spotify_error,
'track_bpm': track_bpm,
'sync_ratio_percentage': sync_ratio_percentage,
'track_key': track_key
}
# Found chords but no synced lyrics
else:
sync_ratio_percentage = "0"
return {
'track_name': track_name,
'artist_name': artist_name,
'track_duration_ms': track_duration_ms,
'track_duration_m_and_s': f"{int(minutes)}:{int(seconds):02d}",
'album_cover_url': album_cover_url,
'guitar_tuning': guitar_tuning,
'guitar_capo': guitar_capo,
'main_chords_body': main_chords_body,
'complete_source_code_link': complete_source_code_link,
'complete_source_code_found': complete_source_code_found,
'musixmatch_lyrics_is_linesynced': musixmatch_lyrics_is_linesynced,
'found_musixmatch_lyrics': found_musixmatch_lyrics,
'spotify_error': spotify_error,
'track_bpm': track_bpm,
'sync_ratio_percentage': sync_ratio_percentage,
'track_key': track_key
}
# No chords found, also regard as no synced lyrics found
else:
synced_lyrics_json, found_musixmatch_lyrics, musixmatch_lyrics_is_linesynced = getSyncedLyricsJson(track_id, artist_name, track_name)
if (dev_or_prod == "DEVELOPMENT" and log_on_off == "ON" and wrote_block_3 != track_id):
with open(log_file_path, 'a') as file:
wrote_block_3 = track_id
file.write(f"FOUND LYRICS: {'YES' if found_musixmatch_lyrics else 'NO'}\n")
file.write(f"LYRICS ARE LINE SYNCED: {'YES' if musixmatch_lyrics_is_linesynced else 'NO'}\n")
file.write(f"-----\n")
####################################
guitar_tuning = "E A D G B E"
guitar_capo = "0"
spotify_error = 1
found_musixmatch_lyrics = 0
musixmatch_lyrics_is_linesynced = 0
sync_ratio_percentage = "0%"
return {
'track_name': track_name,
'artist_name': artist_name,
'track_duration_ms': track_duration_ms,
'track_duration_m_and_s': f"{int(minutes)}:{int(seconds):02d}",
'album_cover_url': album_cover_url,
'guitar_tuning': guitar_tuning,
'guitar_capo': guitar_capo,
'main_chords_body': main_chords_body,
'complete_source_code_link': complete_source_code_link,
'complete_source_code_found': complete_source_code_found,
'musixmatch_lyrics_is_linesynced': musixmatch_lyrics_is_linesynced,
'found_musixmatch_lyrics': found_musixmatch_lyrics,
'spotify_error': spotify_error,
'track_bpm': track_bpm,
'sync_ratio_percentage': sync_ratio_percentage,
'track_key': track_key
}
# Can't request Spotify (user might need to start Spotify and select song first)
else:
complete_source_code_link = ""
complete_source_code_found = 0
guitar_tuning = "E A D G B E"
guitar_capo = "0"
main_chords_body = "Open Spotify somewhere and select a song."
found_musixmatch_lyrics = 0
musixmatch_lyrics_is_linesynced = 0
track_bpm = 0
track_key = 0
sync_ratio_percentage = "0%"
spotify_error = 1
return {
'track_name': "Track",
'artist_name': "Artist",
'track_duration_ms': "",
'track_duration_m_and_s': "0:00",
'album_cover_url': "",
'guitar_tuning': guitar_tuning,
'guitar_capo': guitar_capo,
'main_chords_body': main_chords_body,
'complete_source_code_link': "javascript:void(0)",
'complete_source_code_found': complete_source_code_found,
'musixmatch_lyrics_is_linesynced': musixmatch_lyrics_is_linesynced,
'found_musixmatch_lyrics': found_musixmatch_lyrics,
'spotify_error': spotify_error,
'track_bpm': track_bpm,
'sync_ratio_percentage': sync_ratio_percentage,
'track_key': track_key
}
######## ULTIMATE GUITAR SCRAPING ########
# Returns the source code, the link to the source, and 0 or 1 if the source code was found or not
def googleChordsForDB(track_name, artist_name, track_id):
db = get_database(DATABASE_UE)
cursor = db.cursor()
cursor.execute('SELECT artist_name, track_name, save_timestamp, complete_source_code, complete_source_code_link, complete_source_code_found, result_index FROM ue_db WHERE track_id = ?', (track_id,))
cached_data = cursor.fetchone()
if cached_data:
artist_name = cached_data[0]
track_name = cached_data[1]
save_timestamp_str = cached_data[2]
save_timestamp = datetime.datetime.strptime(save_timestamp_str, '%Y-%m-%d %H:%M:%S.%f')
complete_source_code = cached_data[3]
complete_source_code_link = cached_data[4]
complete_source_code_found = cached_data[5]
result_index = cached_data[6]
print(f'Found ue in database')
# renew ue in database if older than X days
days_to_renew = 30
current_date = datetime.datetime.now()
if (current_date - save_timestamp).days > days_to_renew:
try:
complete_source_code, complete_source_code_link, complete_source_code_found, result_index = googleChords(track_name, artist_name)
if (complete_source_code_found == 0):
cursor.close()
return complete_source_code, complete_source_code_link, complete_source_code_found, result_index
cursor.execute('INSERT OR REPLACE INTO ue_db (track_id, artist_name, track_name, save_timestamp, complete_source_code, complete_source_code_link, complete_source_code_found, result_index) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', (track_id, artist_name, track_name, datetime.datetime.now(), complete_source_code, complete_source_code_link, complete_source_code_found, result_index))
db.commit()
print(f'UE found in database but outdated, now in ue database')
cursor.close()
return complete_source_code, complete_source_code_link, complete_source_code_found, result_index
except Exception as e:
ic(f'Requested ue to renew in database, as it is older than {days_to_renew} days, failed, used old one: {e}')
artist_name = cached_data[0]
track_name = cached_data[1]
save_timestamp = cached_data[2]
complete_source_code = json.loads(cached_data[3])
complete_source_code_link = cached_data[4]
complete_source_code_found = cached_data[5]
result_index = cached_data[6]
cursor.close()
return complete_source_code, complete_source_code_link, complete_source_code_found, result_index
else:
cursor.close()
return complete_source_code, complete_source_code_link, complete_source_code_found, result_index
else:
complete_source_code, complete_source_code_link, complete_source_code_found, result_index = googleChords(track_name, artist_name)
# do not save if no source code found
if (complete_source_code_found == 0):
cursor.close()
return complete_source_code, complete_source_code_link, complete_source_code_found, result_index
cursor.execute('INSERT OR REPLACE INTO ue_db (track_id, artist_name, track_name, save_timestamp, complete_source_code, complete_source_code_link, complete_source_code_found, result_index) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', (track_id, artist_name, track_name, datetime.datetime.now(), complete_source_code, complete_source_code_link, complete_source_code_found, result_index))
db.commit()
print(f'ue not found in database, but now in ue database')
cursor.close()
return complete_source_code, complete_source_code_link, complete_source_code_found, result_index
cursor.close()
def googleChords(track_name, artist_name):
global spotify_error
print("googled for chords, and used API")
### Example Response to prevent daily free Google API quota from being exceeded
"""
url = 'https://tabs.ultimate-guitar.com/tab/dekker/maybe-october-chords-4033981'
try:
response = requests.get(url)
if response.status_code == 200:
html_content = response.text
return html_content, url, 1
else:
return "EXAMPLE SOURCE CODE FAILED", url, 0
except Exception as e:
print(f"An error occurred: {str(e)}")
"""
###
# remove keywords for remastered version songs as they might hinder the search
query = f'{artist_name} {track_name.lower().replace("remastered", "").replace("remaster", "").replace("version", "")} chords Ultimate Guitar'
search_url = f"https://www.googleapis.com/customsearch/v1?key={google_api_key}&cx={google_search_engine_id}&q={query}"
desired_url_substring = 'tabs.ultimate-guitar.com/tab'