-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
263 lines (197 loc) · 6.91 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
import os
import hmac
import hashlib
import requests
import subprocess
import httpx
from bs4 import BeautifulSoup
from flask import Flask, jsonify, request, render_template
from dotenv import load_dotenv
from werkzeug.middleware.proxy_fix import ProxyFix
load_dotenv()
app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1)
client = httpx.Client(http2=True)
APP_SECRET_TOKEN = os.environ.get("APP_SECRET_TOKEN")
API_SCRAPER_URL = os.environ.get("API_SCRAPER_URL")
USER_AGENT = "Mozilla/5.0 (Linux; Android 15; SM-G960U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.7049.38 Mobile Safari/537.36"
class ScrapeError(Exception):
"""
custom exception to raise when scrapping
"""
pass
class TimeoutError(Exception):
"""
error to raise when timeout
"""
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(self, link):
lyrics = []
try:
req = requests.get(f"{API_SCRAPER_URL}?url={link}", timeout=15)
req_data = req.json()
soup = BeautifulSoup(req_data["html"], "html.parser")
for lyricheader in soup.select("div[class*=LyricsHeader__Container]"):
lyricheader.decompose()
for lyrics_data in soup.select("div[class*=Lyrics__Container]"):
for tag in lyrics_data.select("a, span"):
tag.unwrap()
for br in lyrics_data.find_all("br"):
br.replace_with("\n")
text = lyrics_data.get_text()
text = text.replace("\\n", "\n").strip()
lyrics.append(text + "\n")
if lyrics:
lyrics = "".join(lyrics)
lyrics = (
lyrics.replace("\n[", "\n\n[")
.replace("\n(\n", "(")
.replace("\n)", ")")
.replace("(\n", "(")
.replace("& \n", "& ")
.replace("\n]", "]")
)
return lyrics
raise ScrapeError(
f"Could not scrape data. 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 as exc:
raise RequestConnectionError(
f"Could not connect to {self.api_url}. Is it down?"
) from exc
except requests.exceptions.Timeout as exc:
raise TimeoutError(
"Could not scrape. Request to scrape API timed out."
) 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"]
header_image_url = result["response"]["hits"][0]["result"][
"header_image_url"
]
return (artists, title, genius_url, header_image_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"],
)
def verify_signature(secret_token, signature_header, payload_body):
if not signature_header:
return False
hash_object = hmac.new(
secret_token.encode("utf-8"), msg=payload_body, digestmod=hashlib.sha256
)
expected_signature = "sha256=" + hash_object.hexdigest()
if hmac.compare_digest(expected_signature, signature_header):
return True
else:
return False
@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("/autod", methods=["POST"])
def autod():
signature = request.headers.get("X-Hub-Signature-256")
payload = request.get_data()
if verify_signature(APP_SECRET_TOKEN, signature, payload):
subprocess.Popen([os.path.abspath("auto-deploy.sh")])
return "", 200
else:
return "", 403
@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:
scraped_lyrics = genius_api.scrape(data[2])
except ScrapeError as scrape_exc:
return (
jsonify(
{
"status": 500,
"message": str(scrape_exc),
"exception": scrape_exc.__class__.__name__,
}
),
500,
)
return (
jsonify(
{
"status": 200,
"artists": data[0],
"title": data[1],
"source": data[2],
"lyrics": scraped_lyrics,
"cover_image": data[3],
}
),
200,
)
return jsonify({"status": 400, "message": "Missing parameter 'q'."}), 400