-
Notifications
You must be signed in to change notification settings - Fork 0
/
serv.py
219 lines (166 loc) · 5.56 KB
/
serv.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
import os
import requests
from flask import Flask, jsonify, request, render_template
from bs4 import BeautifulSoup
from dotenv import load_dotenv
load_dotenv()
app = Flask(__name__)
class ScrapeError(Exception):
"""
custom exception to raise when scrapping
"""
pass
class RequestConnectionError(Exception):
"""
custom exception to raise when api cannot
send a request/contact genius.com
"""
pass
class NoResults(Exception):
"""
custom exception to raise when no results
for q (query)
"""
pass
class GeniusAPI:
"""
making things a bit easier
"""
def __init__(self, api_url, token):
self.api_url = api_url
self.token = token
def scrape_cover(self, link):
image = None
try:
req = requests.get(link, timeout=5)
req.raise_for_status()
soup = BeautifulSoup(req.text, "html.parser")
for img in soup.find_all("img"):
try:
if "1000x1000x1" in img.get("src"):
image = img.get("src")
except: # TypeError
pass
except (
requests.exceptions.ConnectionError,
requests.exceptions.Timeout,
) as exc:
raise RequestConnectionError(
f"Could not connect to {self.api_url}. Is it down?"
) from exc
return image
def scrape_lyrics(self, link):
song_lyrics = []
try:
req = requests.get(link, timeout=5)
req.raise_for_status()
for lyrics_data in BeautifulSoup(req.text, "html.parser").select(
"div[class*=Lyrics__Container]"
):
data = lyrics_data.get_text("\n")
song_lyrics.append(f"{data}\n")
if len(song_lyrics) != 0:
return str("".join(song_lyrics)).replace("\n[", "\n\n[")
raise ScrapeError(
f"Could not scrape lyrics. Did the HTML change? Please open an issue at https://github.com/devlocalhost/pylyrical_api and paste this: URL: {link}. Data text: ```{req.text}```"
)
except (
requests.exceptions.ConnectionError,
requests.exceptions.Timeout,
) as exc:
raise RequestConnectionError(
f"Could not connect to {self.api_url}. Is it down?"
) from exc
def search(self, query_term):
data = {"q": query_term}
headers = {"Authorization": f"Bearer {self.token}"}
try:
result = requests.get(
self.api_url, params=data, headers=headers, timeout=5
).json()
except (
requests.exceptions.ConnectionError,
requests.exceptions.Timeout,
) as exc:
raise RequestConnectionError(
f"Could not connect to {self.api_url}. Is it down?"
) from exc
if len(result["response"]["hits"]) != 0:
artists = result["response"]["hits"][0]["result"]["artist_names"]
title = result["response"]["hits"][0]["result"]["title"]
genius_url = result["response"]["hits"][0]["result"]["url"]
return (artists, title, genius_url)
raise NoResults(
f"'{query_term}' did not give any results, Please try a different term."
)
genius_api = GeniusAPI(
api_url="https://api.genius.com/search/",
token=os.environ["GENIUS_API_TOKEN"],
)
@app.after_request
def add_cors_headers(response):
# response.headers['Content-Type'] = 'application/json'
# fuck this shit breaks the main page lol
response.headers["Access-Control-Allow-Origin"] = "*"
return response
@app.route("/")
def index():
return render_template("index.html")
@app.route("/lyrics", methods=["GET"])
def get_lyrics():
query = request.args.get("q")
if query:
try:
data = genius_api.search(str(query))
except RequestConnectionError as request_exc:
return (
jsonify(
{
"status": 502,
"message": str(request_exc),
"exception": request_exc.__class__.__name__,
}
),
502,
)
except NoResults as results_exc:
return (
jsonify(
{
"status": 404,
"message": str(results_exc),
"exception": results_exc.__class__.__name__,
}
),
404,
)
try:
lyrics = genius_api.scrape_lyrics(data[2])
except ScrapeError as scrape_exc:
return (
jsonify(
{
"status": 500,
"message": str(scrape_exc),
"exception": scrape_exc.__class__.__name__,
}
),
500,
)
cover_image = genius_api.scrape_cover(data[2])
return (
jsonify(
{
"status": 200,
"artists": data[0],
"title": data[1],
"source": data[2],
"lyrics": lyrics,
"cover_image": cover_image,
}
),
200,
)
return jsonify({"status": 400, "message": "Missing parameter 'q'."}), 400
if __name__ == "__main__":
app.run(host="0.0.0.0")