-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodule.py
More file actions
379 lines (326 loc) · 12.6 KB
/
Copy pathmodule.py
File metadata and controls
379 lines (326 loc) · 12.6 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
"""Deezer lyrics module implementation.
Fetches lyrics from Deezer's GraphQL API using ARL cookie.
"""
from __future__ import annotations
import logging
import re
from typing import ClassVar
import requests
from librelyrics.exceptions import (ConfigurationError, LyricsNotFound,
ProviderError)
from librelyrics.models import LyricsLine, LyricsResponse, LyricsWord
from librelyrics.modules.base import (LyricsModule, LyricsType,
ModuleCapability, ModuleMeta)
logger = logging.getLogger('librelyrics.modules.deezer')
# URL pattern for Deezer
DEEZER_PATTERN = re.compile(r"https://www\.deezer\.com/(track|album)/(\d+)")
# GraphQL query for synchronized lyrics with word-by-word support
LYRICS_QUERY = '''query GetLyrics($trackId: String!) {
track(trackId: $trackId) {
id
lyrics {
id
text
...SynchronizedWordByWordLines
...SynchronizedLines
licence
copyright
writers
__typename
}
__typename
}
}
fragment SynchronizedWordByWordLines on Lyrics {
id
synchronizedWordByWordLines {
start
end
words {
start
end
word
__typename
}
__typename
}
__typename
}
fragment SynchronizedLines on Lyrics {
id
synchronizedLines {
lrcTimestamp
line
lineTranslated
milliseconds
duration
__typename
}
__typename
}'''
class DeezerModule(LyricsModule):
"""Deezer lyrics provider module.
Fetches lyrics from Deezer's GraphQL API.
Supports track and album URLs.
"""
META: ClassVar[ModuleMeta] = ModuleMeta(
name="Deezer",
regex=DEEZER_PATTERN,
requires_auth=True,
description="Fetch lyrics from Deezer",
lyrics_types=frozenset({LyricsType.PLAIN, LyricsType.SYNCED, LyricsType.RICH_SYNCED}),
capabilities=frozenset({
ModuleCapability.SINGLE_TRACK,
ModuleCapability.ALBUM,
}),
config_schema={
'arl': 'Deezer ARL cookie (see README)',
},
)
LIBRELYRICS_API_VERSION: ClassVar[int] = 1
def __init__(self, url: str, config: dict) -> None:
super().__init__(url, config)
self._session: requests.Session | None = None
self._jwt_token: str | None = None
def _ensure_session(self) -> None:
"""Ensure session is initialized with auth."""
arl = self.config.get('arl')
if not arl:
raise ConfigurationError(
"Deezer requires 'arl' cookie in configuration. "
"Run 'librelyrics config edit' to set it up."
)
if self._session is None:
self._session = requests.Session()
self._session.cookies.set('arl', arl)
self._update_bearer()
logger.debug("Initialized Deezer session")
def _update_bearer(self) -> None:
"""Get JWT token from Deezer."""
params = {
'jo': 'p',
'rto': 'c',
'i': 'c',
}
try:
resp = self.session.post(
'https://auth.deezer.com/login/arl',
params=params,
timeout=10,
)
resp.raise_for_status()
data = resp.json()
self._jwt_token = data.get('jwt')
if self._jwt_token:
self.session.headers.update({
'authorization': f'Bearer {self._jwt_token}'
})
except Exception as e:
raise ProviderError(f"Failed to authenticate with Deezer: {e}") from e
@property
def session(self) -> requests.Session:
"""Get the Deezer session."""
if self._session is None:
self._ensure_session()
return self._session # type: ignore
@staticmethod
def default_config() -> dict:
"""Return default Deezer configuration."""
return {
'arl': '',
}
@staticmethod
def validate_config(config: dict) -> None:
"""Validate Deezer configuration."""
if not config.get('arl'):
raise ConfigurationError(
"Deezer requires 'arl' cookie. "
"See README for instructions on finding it."
)
def _parse_url(self) -> tuple[str, str]:
"""Parse the Deezer URL and extract kind and ID."""
match = DEEZER_PATTERN.search(self.url)
if not match:
raise LyricsNotFound(f"Invalid Deezer URL: {self.url}")
return match.groups() # (kind, id)
def fetch(self) -> LyricsResponse:
"""Fetch lyrics for the configured URL."""
kind, item_id = self._parse_url()
if kind == 'track':
return self._fetch_track_lyrics(item_id)
else:
# Album - fetch first track
tracks = self._get_album_tracks(item_id)
if not tracks:
raise LyricsNotFound("No tracks found in album")
return self._fetch_track_lyrics(tracks[0]['id'], tracks[0])
def fetch_album(self) -> list[LyricsResponse]:
"""Fetch lyrics for all tracks in an album."""
kind, item_id = self._parse_url()
if kind == 'track':
return [self._fetch_track_lyrics(item_id)]
tracks = self._get_album_tracks(item_id)
results = []
for i, track in enumerate(tracks, 1):
track['track_number'] = i
try:
response = self._fetch_track_lyrics(track['id'], track)
results.append(response)
except LyricsNotFound:
logger.warning(f"No lyrics found for track: {track['id']}")
except Exception as e:
logger.warning(f"Failed to fetch lyrics for track {track['id']}: {e}")
return results
def _get_album_tracks(self, album_id: str) -> list[dict]:
"""Get track info from an album."""
try:
# Use requests directly - public API doesn't need auth
resp = requests.get(
f"https://api.deezer.com/album/{album_id}",
timeout=10,
)
resp.raise_for_status()
data = resp.json()
album_name = data.get('title', '')
artist_name = data.get('artist', {}).get('name', '')
release_date = data.get('release_date', '')
tracks = []
for track in data.get('tracks', {}).get('data', []):
tracks.append({
'id': str(track['id']),
'title': track['title'],
'artist': artist_name,
'album': album_name,
'release_date': release_date,
})
return tracks
except Exception as e:
raise ProviderError(f"Failed to get album tracks: {e}") from e
def get_album_info(self) -> dict:
"""Get album metadata."""
kind, item_id = self._parse_url()
try:
# Use requests directly - public API doesn't need auth
resp = requests.get(
f"https://api.deezer.com/album/{item_id}",
timeout=10,
)
resp.raise_for_status()
data = resp.json()
return {
'name': data.get('title', 'Unknown Album'),
'artists': [{'name': data.get('artist', {}).get('name', 'Unknown Artist')}],
'total_tracks': data.get('nb_tracks', 0),
'release_date': data.get('release_date', ''),
}
except Exception as e:
raise ProviderError(f"Failed to get album info: {e}") from e
def _fetch_track_lyrics(self, track_id: str, track_info: dict | None = None) -> LyricsResponse:
"""Fetch lyrics for a single track."""
# Get track metadata if not provided
if not track_info:
try:
# Use requests directly - public API doesn't need auth
resp = requests.get(
f"https://api.deezer.com/track/{track_id}",
timeout=10,
)
resp.raise_for_status()
track_data = resp.json()
track_info = {
'title': track_data['title'],
'artist': track_data.get('artist', {}).get('name', ''),
'album': track_data.get('album', {}).get('title', ''),
'release_date': track_data.get('release_date', ''),
'track_number': track_data.get('track_position', 0),
}
except Exception as e:
raise ProviderError(f"Failed to get track metadata: {e}") from e
title = track_info.get('title', 'Unknown')
artist = track_info.get('artist', 'Unknown')
album = track_info.get('album', '')
track_number = track_info.get('track_number', 0)
# Get lyrics via GraphQL
json_data = {
'operationName': 'GetLyrics',
'variables': {'trackId': str(track_id)},
'query': LYRICS_QUERY,
}
try:
resp = self.session.post(
'https://pipe.deezer.com/api',
json=json_data,
timeout=10,
)
resp.raise_for_status()
lyrics_data = resp.json()
except Exception as e:
raise ProviderError(f"Failed to get lyrics: {e}") from e
# Parse lyrics
lines: list[LyricsLine] = []
is_synced = False
is_rich_synced = False
try:
lyrics = lyrics_data.get('data', {}).get('track', {}).get('lyrics', {})
if not lyrics:
raise LyricsNotFound(f"No lyrics found for {title} by {artist}")
# Try word-by-word synced lines first (rich lyrics)
word_by_word = lyrics.get('synchronizedWordByWordLines', [])
sync_lines = lyrics.get('synchronizedLines', [])
if word_by_word:
is_synced = True
is_rich_synced = True
for line_data in word_by_word:
start_ms = line_data.get('start', 0)
end_ms = line_data.get('end', 0)
# Parse words
words_data = line_data.get('words', [])
words = tuple(
LyricsWord(
word=w.get('word', ''),
start_ms=w.get('start', 0),
end_ms=w.get('end', 0),
)
for w in words_data
)
# Construct line text from words
text = ' '.join(w.word for w in words)
lines.append(LyricsLine(
text=text,
start_ms=start_ms,
end_ms=end_ms,
words=words,
))
elif sync_lines:
# Fall back to line-synced lyrics
is_synced = True
for line in sync_lines:
start_ms = line.get('milliseconds', 0)
text = line.get('line', '')
duration = line.get('duration', 0)
end_ms = start_ms + duration if duration else None
lines.append(LyricsLine(text=text, start_ms=start_ms, end_ms=end_ms))
else:
# Fall back to plain text
plain_text = lyrics.get('text', '')
if plain_text:
for line in plain_text.split('\n'):
lines.append(LyricsLine(text=line.strip()))
except (KeyError, TypeError):
raise LyricsNotFound(f"No lyrics found for {title} by {artist}")
if not lines:
raise LyricsNotFound(f"No lyrics found for {title} by {artist}")
logger.debug(f"Fetched {'rich synced' if is_rich_synced else 'synced' if is_synced else 'plain'} lyrics for: {title} - {artist}")
return LyricsResponse(
title=title,
artist=artist,
album=album,
lyrics=lines,
source=self.META.name,
synced=is_synced,
rich_synced=is_rich_synced,
metadata={
'track_id': track_id,
'track_number': track_number,
},
)