Repository navigation
Expand file tree
/
Copy path__init__.py
More file actions
190 lines (151 loc) · 5.64 KB
/
Copy path__init__.py
File metadata and controls
190 lines (151 loc) · 5.64 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
# Picard Sözler is a plugin that fetches lyrics from a public API.
# Copyright (C) 2024 Deniz Engin <dev@dilbil.im>
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <https://www.gnu.org/licenses/>.
from functools import partial
import itertools
import json
from picard import log
PLUGIN_NAME = "Picard Sözler" # used only for log prefixes now
_api = None # set in enable()
_task_counter = itertools.count()
def log_debug(s):
log.debug(f"{PLUGIN_NAME}: {s}")
def log_err(s):
log.error(f"{PLUGIN_NAME}: {s}")
def _add_album_task(album, task_id, description):
"""Tell Picard the album has a pending background task so it waits
for our lyrics response before finalizing. Returns True on success."""
try:
_api.add_album_task(album, task_id, description)
return True
except Exception as e:
log_err(f"add_album_task failed: {e}")
return False
def _complete_album_task(album, task_id):
"""Mark our background task as done so the album can finalize."""
try:
_api.complete_album_task(album, task_id)
return
except TypeError:
pass
except Exception as e:
log_err(f"complete_album_task failed: {e}")
return
try:
# Some builds may key tasks by id alone
_api.complete_album_task(task_id)
except Exception as e:
log_err(f"complete_album_task fallback failed: {e}")
def _iter_track_files(track):
files = getattr(track, "files", None)
if files:
return list(files)
iterfiles = getattr(track, "iterfiles", None)
if iterfiles:
try:
return list(iterfiles())
except Exception:
pass
return []
def _apply_lyrics(track, metadata, lyrics):
"""Write lyrics to every metadata object that matters: the processor
metadata (snapshot), the live track metadata, and any matched files."""
applied_to = []
metadata["lyrics"] = lyrics
applied_to.append("processor metadata")
track_metadata = getattr(track, "metadata", None)
if track_metadata is not None and track_metadata is not metadata:
track_metadata["lyrics"] = lyrics
applied_to.append("track metadata")
for file in _iter_track_files(track):
try:
file.metadata["lyrics"] = lyrics
file.update()
applied_to.append(f"file {file.base_filename!r}")
except Exception as e:
log_err(f"could not apply lyrics to file: {e}")
try:
track.update()
except Exception:
pass
log_debug(f"lyrics applied to: {', '.join(applied_to)}")
def process_response(album, track, metadata, task_id, data, reply, error):
try:
if error:
log_debug("request errored (likely no match on lrclib)")
return
log_debug("starting to process")
if isinstance(data, (bytes, bytearray, str)):
response_data = json.loads(data)
else:
# Already-parsed JSON (dict), depending on webservice settings
response_data = data
if response_data.get("instrumental"):
log_debug("instrumental track; skipping")
lyrics = None
else:
lyrics = response_data.get("syncedLyrics") or response_data.get("plainLyrics")
if lyrics is not None:
_apply_lyrics(track, metadata, lyrics)
else:
log_debug("no lyrics in response")
except Exception as e:
log_err(f"api malformed response or parse error: {e}")
finally:
if task_id is not None:
_complete_album_task(album, task_id)
def _resolve_album(obj):
"""Picard 3 passes the Track object to track metadata processors;
Picard 2 passed the Album. Find the Album either way."""
album = getattr(obj, "album", None)
if album is not None:
return album
if hasattr(obj, "_requests"):
return obj
return None
def process_track(api, obj, metadata, track, release):
album = _resolve_album(obj)
if album is None:
log_err(f"could not resolve album from {type(obj).__name__}; skipping")
return
try:
(mins, secs) = map(int, metadata["~length"].split(":"))
duration_secs = mins * 60 + secs
except (ValueError, KeyError):
duration_secs = 0
title = metadata["title"]
query = {
"artist_name": metadata["albumartist"] or metadata["artist"],
"album_name": metadata["album"],
"track_name": title,
"duration": duration_secs,
}
log_debug(f"trying to query with: {query}")
task_id = f"sozler-lyrics-{next(_task_counter)}"
if not _add_album_task(album, task_id, f"Fetching lyrics for {title}"):
task_id = None # fetch anyway, just without blocking finalization
album.tagger.webservice.get_url(
url="https://lrclib.net/api/get",
handler=partial(process_response, album, obj, metadata, task_id),
queryargs=query,
)
# ---- Picard 3 plugin entry points ----
def enable(api):
global _api
_api = api
log_debug("plugin enabled")
api.register_track_metadata_processor(process_track)
def disable():
log_debug("plugin disabled")