-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlrc.py
More file actions
526 lines (473 loc) · 21.3 KB
/
lrc.py
File metadata and controls
526 lines (473 loc) · 21.3 KB
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
import requests, json, sys, re, os
from datetime import datetime, timedelta
from pathlib import Path
class Colors:
BLUE = "\033[94m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
RED = "\033[91m"
MAGENTA = "\033[95m"
CYAN = "\033[96m"
BOLD = "\033[1m"
END = "\033[0m"
ICON_SUCCESS = "✔"
ICON_FAIL = "✘"
ICON_INFO = "ℹ"
ICON_MUSIC = "🎵"
def print_banner(platform):
platforms = {
"spotify": (Colors.GREEN, "SPOTIFY"),
"apple": (Colors.MAGENTA, "APPLE MUSIC"),
"amazon": (Colors.CYAN, "AMAZON MUSIC"),
"jiosaavn": (Colors.BLUE, "JIOSAAVN"),
"gaana": (Colors.RED, "GAANA"),
"qobuz": (Colors.YELLOW, "QOBUZ"),
"deezer": (Colors.MAGENTA, "DEEZER"),
"tidal": (Colors.CYAN, "TIDAL")
}
color, name = platforms.get(platform, (Colors.BOLD, "UNKNOWN"))
print(f"\n{color}{Colors.BOLD}═══ {ICON_MUSIC} {name} ═══{Colors.END}")
url = input(f"{Colors.BOLD}{Colors.YELLOW}Enter Link: {Colors.END}").strip()
client = requests.Session()
def jsonToLRC(jsonLRC):
lrc = '[00:00.000]\n'
for item in jsonLRC['lyrics']['lines']:
ms = int(item['startTimeMs'])
td = str(timedelta(milliseconds=ms))
if '.' in td:
lrc += str(f"[{td[2:-3]}]{item['words']}\n")
else:
lrc += str(f"[{td[2:]}]{item['words']}\n")
return lrc
def makeCookiesDict():
try:
with open('Auth/cookie.txt', 'r') as f:
data = json.loads(f.read())
cookies = {}
for el in data:
cookies[el['name']] = el['value']
return cookies
except (FileNotFoundError, json.JSONDecodeError):
return None
def updateToken():
cookies = makeCookiesDict()
if not cookies: return None
try:
r = requests.get("https://open.spotify.com", cookies=cookies).text
token = "Bearer " + re.findall(r'"accessToken":"(.*?)"', r)[0]
with open('Auth/token.json', 'w') as f: f.write(token)
return token
except Exception:
return None
def apiReq(api, Session=requests):
token = None
try:
with open('Auth/token.json', 'r') as f: token = f.read()
except FileNotFoundError:
token = updateToken()
if not token: return None, None
info = Session.get(api, headers={"authorization":token})
if info.status_code in [400, 401]:
token = updateToken()
if token:
info = requests.get(api, headers={"authorization": token})
else:
return None, None
return json.loads(info.text), token
def fetch_track_ids(resource_type, resource_id):
api = f"https://api.spotify.com/v1/{resource_type}s/{resource_id}/tracks?market=us"
info, _ = apiReq(api)
if info:
if resource_type == "playlist":
return list(i["track"].get("id") for i in info["items"] if i.get("track"))
else:
return list(i.get("id") for i in info["items"])
# Fallback: Scrape public page for metadata
url = f"https://open.spotify.com/{resource_type}/{resource_id}"
r = requests.get(url).text
# Find track IDs in the page (embedded in links)
ids = re.findall(r'https://open.spotify.com/track/([a-zA-Z0-9]+)', r)
# Remove duplicates while preserving order
return list(dict.fromkeys(ids))
def format_filename(filename):
return re.sub(r'[\\/*?:"<>|]', "-", filename).replace('"', "'")
def fetch_lrclib(artist, title):
try:
url = f"https://lrclib.net/api/get?artist_name={artist}&track_name={title}"
r = requests.get(url)
if r.status_code == 200:
return r.json().get("syncedLyrics")
# Search if exact GET fails
url = f"https://lrclib.net/api/search?artist_name={artist}&track_name={title}"
r = requests.get(url)
if r.status_code == 200 and r.json():
return r.json()[0].get("syncedLyrics")
# Try with a super clean title (stripped from JioSaavn/Gaana)
clean_title = re.sub(r' \(.*?\)', '', title).strip()
if clean_title != title:
url = f"https://lrclib.net/api/search?artist_name={artist}&track_name={clean_title}"
r = requests.get(url)
if r.status_code == 200 and r.json():
return r.json()[0].get("syncedLyrics")
except Exception:
pass
return None
def download_lyrics(artist_str, title, filename, album_name=None, track_num=None):
lyrics = fetch_lrclib(artist_str, title)
if lyrics:
base_dir = "Lyrics"
if album_name:
base_dir = os.path.join(base_dir, format_filename(album_name))
os.makedirs(base_dir, exist_ok=True)
# Apply numbering
if track_num is not None:
filename = f"{str(track_num).zfill(2)}. {filename}"
filepath = os.path.join(base_dir, filename)
with open(filepath, "w", encoding="utf-8") as x:
x.write(lyrics)
print(f" {Colors.GREEN}{ICON_SUCCESS} {Colors.BOLD}{filename}{Colors.END} {Colors.BLUE}[LRCLIB]{Colors.END}")
return filename
print(f" {Colors.RED}{ICON_FAIL} {artist_str} - {title}{Colors.END} {Colors.YELLOW}[Not Found]{Colors.END}")
return None
def process_spotify_track(id):
api = f"https://api.spotify.com/v1/tracks/{id}"
trackInfo, token = apiReq(api, client)
if trackInfo:
artists = [a.get("name") for a in trackInfo.get("artists", [])]
artist_str = ', '.join(artists)
title = trackInfo.get("name", "Unknown Track")
else:
# Fallback: Use Songlink API for account-free metadata
songlink_url = f"https://api.song.link/v1-alpha.1/links?url=https://open.spotify.com/track/{id}"
r = requests.get(songlink_url).json()
e_id = r.get('entityUniqueId')
data = r.get('entitiesByUniqueId', {}).get(e_id, {})
title = data.get('title', "Unknown")
artist_str = data.get('artistName', "Unknown")
filename = format_filename(f"{artist_str} - {title}.lrc")
# Try Spotify (Account)
if token:
url = f"https://spclient.wg.spotify.com/color-lyrics/v2/track/{id}/image/MadeByRAGA?format=json&vocalRemoval=false&market=from_token"
lyrics = client.get(url, headers={"authorization":token, "User-Agent":"Mozilla/5.0", "app-platform":"WebPlayer"})
if lyrics.status_code == 200 and len(lyrics.text) > 0:
data = lyrics.json()
if data["lyrics"]["syncType"] == "LINE_SYNCED":
filepath = os.path.join("Lyrics", filename)
# Note: Spotify track processor doesn't handle album folders yet for individual tracks
# Todo: Add album folder support #Skillissue
os.makedirs("Lyrics", exist_ok=True)
with open(filepath, "w", encoding="utf-8") as x:
x.write(jsonToLRC(data))
print(f" {Colors.GREEN}{ICON_SUCCESS} {Colors.BOLD}{filename}{Colors.END} {Colors.GREEN}[Spotify]{Colors.END}")
return filename
# Fallback/Free Mode: Try LRCLIB using generic downloader
return download_lyrics(artist_str, title, filename)
def fetch_metadata_songlink(url):
try:
r = requests.get(f"https://api.song.link/v1-alpha.1/links?url={url}").json()
e_id = r.get('entityUniqueId')
data = r.get('entitiesByUniqueId', {}).get(e_id, {})
return data.get('title'), data.get('artistName')
except Exception:
return None, None
def fetch_metadata_html(url, platform):
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}
try:
r = requests.get(url, headers=headers).text
if platform == "gaana":
# Extract from JSON-LD
# Todo: Better extractor or look for API
import json
matches = re.findall(r'<script type="application/ld\+json">(.*?)</script>', r, re.DOTALL)
for block in matches:
try:
data = json.loads(block)
if isinstance(data, dict) and data.get("@type") == "MusicRecording":
artists = ", ".join([a.get('name') for a in data.get('byArtist', [])])
return data.get('name'), artists
except:
continue
else:
# Qobuz, JioSaavn - OpenGraph tags
title = re.findall(r'<meta property="og:title" content="(.*?)"', r)
if title:
# JioSaavn format: "Song Name - Artist - Download..."
# Qobuz format: "SongName, Artist - Qobuz"
full_str = title[0]
if platform == "jiosaavn":
parts = full_str.split(" - ")
if len(parts) >= 2:
return parts[0], parts[1]
elif platform == "qobuz":
parts = full_str.split(" - Qobuz")[0].split(", ")
if len(parts) >= 2:
return parts[0], ", ".join(parts[1:])
except Exception:
pass
return None, None
def process_other_track(url, platform):
print_banner(platform)
title, artist_str = None, None
if platform in ["apple", "deezer", "tidal"]:
title, artist_str = fetch_metadata_songlink(url)
elif platform == "amazon":
# Extract the region
domain_match = re.search(r'music\.amazon\.[a-z.]+', url)
domain = domain_match.group(0) if domain_match else "music.amazon.com"
asin_match = re.search(r'([A-Z0-9]{10})', url)
if asin_match:
asin = asin_match.group(1)
album_link = f"https://{domain}/albums/{asin}?trackAsin={asin}"
title, artist_str = fetch_metadata_songlink(album_link)
else:
title, artist_str = fetch_metadata_html(url, platform)
if title and artist_str:
filename = format_filename(f"{artist_str} - {title}.lrc")
return download_lyrics(artist_str, title, filename)
else:
print(f"Failed to extract metadata from {url}")
return None
def process_qobuz_album(url):
print_banner("qobuz")
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}
try:
r = requests.get(url, headers=headers).text
# Qobuz encodes track info in data-track-v2 attributes
# Todo: Better extractor or look for API
import html
matches = re.findall(r'data-track-v2="(.*?)"', r)
count = 0
album_name_match = re.findall(r'<meta property="og:title" content="(.*?)"', r)
album_name = album_name_match[0].split(", ")[0] if album_name_match else "Unknown Qobuz Album"
for match in matches:
count += 1
try:
# Unescape HTML entities and parse JSON
# Todo: Better parser
track_data = json.loads(html.unescape(match))
title = track_data.get("item_name")
artist = track_data.get("item_brand")
if title and artist:
filename = format_filename(f"{artist} - {title}.lrc")
download_lyrics(artist, title, filename, album_name=album_name, track_num=count)
except:
continue
print(f"Processed {count} tracks from Qobuz.")
except Exception as e:
print(f"Error parsing Qobuz album: {e}")
def extract_json_from_script(html_content, start_marker, end_marker=";"):
start_idx = html_content.find(start_marker)
if start_idx == -1:
return None
# Move to the start of the JSON object
# Todo: Better Approach
json_start = html_content.find("{", start_idx)
if json_start == -1:
return None
count = 0
for i in range(json_start, len(html_content)):
char = html_content[i]
if char == "{":
count += 1
elif char == "}":
count -= 1
if count == 0:
return html_content[json_start:i+1]
return None
def process_jiosaavn_album(url):
print_banner("jiosaavn")
headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"}
try:
r = requests.get(url, headers=headers).text
import html
# Extract all tracks from the entire page and dedupe
# Use re.DOTALL to handle potential newlines and [^"]* for clean matching
# Note: Not including closing braces because there might be other properties (action, role, etc)
# Todo: Better approach or find API Maybe?
import re
tracks_raw = re.findall(r'"type":"song".*?"title":\{"text":"([^"]*)"[^}]*?.*?"subtitle":\[\{"text":"([^"]*)"', r, re.DOTALL)
processed_tracks = set()
count = 0
album_name_match = re.findall(r'"type":"album".*?"title":\{"text":"([^"]*)"', r)
album_name = html.unescape(album_name_match[0]) if album_name_match else "Unknown JioSaavn Album"
for title, artist in tracks_raw:
title = html.unescape(title)
artist = html.unescape(artist)
track_key = (artist.lower(), title.lower())
if track_key not in processed_tracks:
count += 1
filename = format_filename(f"{artist} - {title}.lrc")
download_lyrics(artist, title, filename, album_name=album_name, track_num=count)
processed_tracks.add(track_key)
if count > 0:
print(f"Processed {count} tracks from JioSaavn.")
else:
print("Could not find tracks in JioSaavn data.")
except Exception as e:
print(f"Error parsing JioSaavn album: {e}")
def process_gaana_album(url):
print_banner("gaana")
headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"}
try:
r = requests.get(url, headers=headers).text
import html
# Gaana uses REDUX_DATA
# Todo: Better approach or find API Maybe Skillissue?
redux_str = extract_json_from_script(r, "window.REDUX_DATA")
count = 0
album_name = "Unknown Gaana Album"
if redux_str:
try:
data = json.loads(redux_str)
album_data = data.get("album", {}).get("albumDetail", {})
album_name = album_data.get("album_title", "Unknown Gaana Album")
tracks = album_data.get("tracks", [])
for track in tracks:
count += 1
title = track.get("track_title")
artists = [a.get("name") for a in track.get("artist", [])]
artist = ", ".join(artists)
if title and artist:
title = html.unescape(title)
artist = html.unescape(artist)
filename = format_filename(f"{artist} - {title}.lrc")
download_lyrics(artist, title, filename, album_name=album_name, track_num=count)
except Exception as e:
print(f"Error parsing Gaana REDUX_DATA: {e}")
if count == 0:
# Fallback to MusicRecording in JSON-LD
scripts = re.findall(r'<script type="application/ld\+json">(.*?)</script>', r, re.DOTALL)
for script in scripts:
try:
ld_data = json.loads(script)
items = ld_data if isinstance(ld_data, list) else [ld_data]
for item in items:
if item.get("@type") == "MusicRecording":
title = item.get("name")
artist_data = item.get("byArtist", {})
if isinstance(artist_data, list):
artist = ", ".join([a.get("name") for a in artist_data if a.get("name")])
else:
artist = artist_data.get("name")
if title and artist:
count += 1
title = html.unescape(title)
artist = html.unescape(artist)
filename = format_filename(f"{artist} - {title}.lrc")
download_lyrics(artist, title, filename, album_name=album_name, track_num=count)
except:
continue
print(f"Processed {count} tracks from Gaana.")
except Exception as e:
print(f"Error parsing Gaana album: {e}")
def process_apple_album(url):
print_banner("apple")
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}
try:
r = requests.get(url, headers=headers).text
matches = re.findall(r'<script id=schema:music-album type="application/ld\+json">(.*?)</script>', r, re.DOTALL)
if matches:
data = json.loads(matches[0])
album_artist = data.get('byArtist', [{}])[0].get('name', 'Unknown Artist')
album_name = data.get('name', 'Unknown Apple Music Album')
tracks = data.get('tracks', [])
print(f"Found {len(tracks)} tracks.")
idx = 0
for track in tracks:
idx += 1
title = track.get('name')
filename = format_filename(f"{album_artist} - {title}.lrc")
download_lyrics(album_artist, title, filename, album_name=album_name, track_num=idx)
except Exception as e:
print(f"Error parsing Apple Music album: {e}")
def process_spotify_album_free(album_id):
print_banner("spotify")
url = f"https://open.spotify.com/embed/album/{album_id}"
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}
try:
r = requests.get(url, headers=headers).text
next_data = re.search(r'<script id="__NEXT_DATA__" type="application/json">(.*?)</script>', r)
if next_data:
data = json.loads(next_data.group(1))
entity = data.get("props", {}).get("pageProps", {}).get("state", {}).get("data", {}).get("entity", {})
tracks = entity.get("trackList", [])
album_name = entity.get("title", "Unknown Spotify Album")
album_artist = entity.get("subtitle", "Unknown Artist")
print(f"Found {len(tracks)} tracks.")
idx = 0
for track in tracks:
idx += 1
title = track.get("title")
# Spotify embed subtitle often has multiple artists
artists = track.get("subtitle", album_artist)
filename = format_filename(f"{artists} - {title}.lrc")
download_lyrics(artists, title, filename, album_name=album_name, track_num=idx)
except Exception as e:
print(f"Error parsing Spotify album embed: {e}")
def process_amazon_album(url):
print_banner("amazon")
try:
r = requests.get(f"https://api.song.link/v1-alpha.1/links?url={url}").json()
spotify_url = r.get('linksByPlatform', {}).get('spotify', {}).get('url')
if spotify_url:
print(f"Found Spotify equivalent: {spotify_url}")
album_id = spotify_url.split("album/")[1].split("?")[0]
process_spotify_album_free(album_id)
else:
print("Could not find Spotify equivalent for this Amazon album.")
except Exception as e:
print(f"Error processing Amazon album: {e}")
def process_url(url):
if "spotify.com" in url:
if "track" in url:
id = url.split("track/")[1].split("?")[0]
process_spotify_track(id)
elif "playlist" in url:
playlist_id = url.split("playlist/")[1].split("?")[0]
idList = fetch_track_ids("playlist", playlist_id)
for id in idList:
process_spotify_track(id)
elif "album" in url:
album_id = url.split("album/")[1].split("?")[0]
# Try authenticated first if possible
api = f"https://api.spotify.com/v1/albums/{album_id}/tracks?market=us"
info, _ = apiReq(api)
if info and "items" in info:
for item in info["items"]:
process_spotify_track(item.get("id"))
else:
# Fallback to account-free scraping
process_spotify_album_free(album_id)
elif "apple.com" in url or "music.apple.com" in url:
if "album" in url:
process_apple_album(url)
elif "song" in url:
process_other_track(url, "apple")
elif "deezer.com" in url:
process_other_track(url, "deezer")
elif "tidal.com" in url:
process_other_track(url, "tidal")
elif "amazon." in url:
if "album" in url:
process_amazon_album(url)
else:
process_other_track(url, "amazon")
elif "qobuz.com" in url:
if "album" in url:
process_qobuz_album(url)
else:
process_other_track(url, "qobuz")
elif "jiosaavn.com" in url:
if "album" in url:
process_jiosaavn_album(url)
else:
process_other_track(url, "jiosaavn")
elif "gaana.com" in url:
if "album" in url:
process_gaana_album(url)
else:
process_other_track(url, "gaana")
else:
print(f"{Colors.RED}{ICON_FAIL} This platform is not yet supported.{Colors.END}")
process_url(url)
print(f"\n{Colors.BOLD}{Colors.GREEN}Done!{Colors.END}")