-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_lyrics.py
executable file
·125 lines (105 loc) · 4.22 KB
/
get_lyrics.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
#!/usr/bin/env python3
import subprocess as sp
import os.path
import json
import re
from utils import termux_api_toast as toast
from file_reader import open_file
WORK_DIR = "/data/data/com.termux/files/home/tp-lyrics"
DATA_DIR = WORK_DIR + "/cache"
# reqd config
with open(f"{WORK_DIR}/conf.json", "r") as file:
conf = json.load(file)
def getCurrent():
try:
# current = []
otp = sp.Popen('termux-notification-list', stdout=sp.PIPE)
otp.wait()
# for n in json.loads(
# str().join([str(line.decode('utf-8').replace('\n', ''))
# for line in otp.stdout])):
# if n['packageName'] == 'com.rhapsody.alditalk' and n['id'] != 1:
# current.append((n['content'], n['title']))
current = [(n["content"], n["title"],) for n in
json.loads("".join(
[str(line.decode("utf-8").replace("\n", ""))
for line in otp.stdout]))
if any(all(n[attr] == val for attr, val in provider.items())
for provider in conf["player_signatures"].values())
]
finally:
otp.stdout.close()
if len(current) > 1:
toast("to many players running")
raise IndexError("found multiple music control notifications")
elif len(current) == 0:
toast("nothing is playing, couldn't search for lyrics")
raise IndexError(f"failed to get current song name.\nGot: {current}")
try:
fc = f"{current[0][0]}%{current[0][1]}"
with open(f"{WORK_DIR}/name_sub.conf", 'r') as f:
print("sub file found")
for i, line in enumerate(f):
print(line)
rp = [i.lstrip('"') for i in re.split(r"\", \"", line)]
print(len(rp), ":\t", rp)
fc = re.sub(rp[0], rp[1], fc)
except FileNotFoundError:
print("no sub file found, skipping")
pass
else:
current = [fc.replace("\n", '').split('%')]
print(current)
return (current, "{D}/{artist}%{song}".format(D=DATA_DIR,
artist=current[0][0],
song=current[0][1]))
def fetch_lyrics(current, path):
"""
fetch lytics from genius and store it locally
in the coressponding file that has been given to it
"""
import lyricsgenius
headline = f"[0-9]+ Contributors{current[0][1]} Lyrics"
try:
lapi = lyricsgenius.Genius(
conf["genius_token"],
skip_non_songs=True,
)
song = lapi.search_song(str(current[0][1]), str(current[0][0]))
except ConnectionError as e:
toast("connection to genius timed out")
raise ConnectionError(e)
try:
if not re.match(headline + '.*', song.lyrics.splitlines()[0]):
toast("genius sent back bullshit")
raise RuntimeError("headlines don't match:\n- {exp}\n- {got}"
.format(exp=headline,
got=song.lyrics.splitlines()[0]))
with open(path, 'x') as f:
f.write(song.lyrics.replace(f"{current[0][1]} Lyrics", '', 1))
toast("lyrics fetched from genius")
except AttributeError:
toast("genius didn't send anything back")
raise RuntimeError("genius api didn't open up lyrics attribute")
except FileExistsError:
toast('found local lyrics, cannot overwrite')
raise RuntimeError("lyrics file found, delete it if you want to"
+ " refetch automatically")
def print_lyrics(current):
try:
with open("{D}/{artist}%{song}".format(D=DATA_DIR,
artist=current[0][0],
song=current[0][1]),
'r') as f:
toast("lyrics found")
return f.readlines()
except FileNotFoundError:
return fetch_lyrics(current)
def main():
# add argparse so current can be read from args
crt, path = getCurrent()
if not os.path.exists(path):
fetch_lyrics(crt, path)
open_file(path, full_path_title=False)
if __name__ == "__main__":
main()