beets-moreart 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,184 @@
1
+ Metadata-Version: 2.4
2
+ Name: beets-moreart
3
+ Version: 0.1.0
4
+ Summary: Fetch additional album artwork for beets
5
+ Author: Jaedon D. Swanson
6
+ Keywords: beets,music,album-art,artwork
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+ Requires-Dist: beets>=2.0.0
10
+
11
+ # beets-moreart
12
+
13
+ A [beets](https://beets.io) plugin that fetches extra album artwork from
14
+ Fanart.tv, MusicBrainz Cover Art Archive, and TheAudioDB.
15
+
16
+ ## Quick Start
17
+
18
+ Install from the MoreArt project directory for local testing:
19
+
20
+ ```bash
21
+ pipx inject beets .
22
+ ```
23
+
24
+ Enable the plugin in your Beets configuration:
25
+
26
+ ```yaml
27
+ plugins:
28
+ - moreart
29
+ ```
30
+
31
+ Fetch artwork for your library:
32
+
33
+ ```bash
34
+ beet moreart
35
+ ```
36
+
37
+ Artwork is saved in each album directory:
38
+
39
+ ```text
40
+ Artist/
41
+ └── Album/
42
+ ├── back.jpg
43
+ ├── discart.png
44
+ └── spine.jpg
45
+ ```
46
+
47
+ ## What does this do?
48
+
49
+ Beets' built-in `fetchart` plugin fetches front-cover artwork. **beets-moreart**
50
+ looks for additional artwork: disc art, spine images, and back covers. It searches Fanart.tv, MusicBrainz Cover Art Archive, and TheAudioDB, then saves the results beside the album's music files.
51
+
52
+ MusicBrainz lookups use the album's release ID. Fanart.tv and TheAudioDB credentials are optional; sources without a configured key are skipped.
53
+
54
+ ## Installation
55
+
56
+ ### With pip
57
+
58
+ After the package has been published to PyPI:
59
+
60
+ ```bash
61
+ pip install beets-moreart
62
+ ```
63
+
64
+ ### With pipx
65
+
66
+ After the package has been published to PyPI:
67
+
68
+ ```bash
69
+ pipx inject beets beets-moreart
70
+ ```
71
+
72
+ ### From this checkout
73
+
74
+ Run these commands from the MoreArt project directory. Use the `pipx` command
75
+ when Beets is installed in a pipx-managed environment; otherwise use pip with
76
+ the same Python environment as Beets.
77
+
78
+ ```bash
79
+ pipx inject beets .
80
+ # Or, when Beets and the plugin share a Python environment:
81
+ python -m pip install .
82
+ ```
83
+
84
+ ## Configuration
85
+
86
+ Add the plugin to your Beets configuration file (`config.yaml`):
87
+
88
+ ```yaml
89
+ plugins:
90
+ - moreart
91
+
92
+ moreart:
93
+ fanarttv_key: YOUR_API_KEY
94
+ theaudiodb_key: YOUR_API_KEY
95
+ sources: [fanarttv, theaudiodb, musicbrainz]
96
+ types: [discart, spine, back]
97
+ run_on_import: yes
98
+ timeout: 15
99
+ cache_results: yes
100
+ recheck_days: 30
101
+ resize:
102
+ enabled: yes
103
+ discart: [1000, 1000]
104
+ back: [750, 750]
105
+ spine: [35, 700]
106
+ fuzz: 15%
107
+ background:
108
+ multi_corner: yes
109
+ ```
110
+
111
+ Adjust options as desired:
112
+
113
+ | Parameter | Default | Description |
114
+ | :--- | :--- | :--- |
115
+ | `fanarttv_key` | `null` | Optional Fanart.tv API key |
116
+ | `theaudiodb_key` | `null` | Optional TheAudioDB API key |
117
+ | `sources` | `[fanarttv, theaudiodb, musicbrainz]` | Sources to try, in order |
118
+ | `types` | `[discart, spine, back]` | Artwork types to fetch |
119
+ | `run_on_import` | `yes` | Fetch artwork after an album is imported |
120
+ | `timeout` | `15` | Seconds to wait for each HTTP request |
121
+ | `cache_results` | `yes` | Remember artwork types that had no usable result |
122
+ | `recheck_days` | `30` | Days to wait before retrying cached no-artwork results |
123
+ | `resize.enabled` | `yes` | Resize fetched images when ImageMagick is available |
124
+ | `resize.discart` | `[1000, 1000]` | Disc art dimensions |
125
+ | `resize.back` | `[750, 750]` | Back-cover dimensions |
126
+ | `resize.spine` | `[35, 700]` | Spine dimensions |
127
+ | `fuzz` | `15%` | ImageMagick color tolerance for disc-art background removal |
128
+ | `background.multi_corner` | `yes` | Remove the background from multiple disc-art edges |
129
+
130
+ ## Usage
131
+
132
+ ### Automatic (during import)
133
+
134
+ When `run_on_import` is enabled, MoreArt checks for artwork after an album is
135
+ imported. Existing artwork is left alone.
136
+
137
+ ### Manual (on demand)
138
+
139
+ | Command | Description |
140
+ | :--- | :--- |
141
+ | `beet moreart` | Fetch configured artwork for all albums |
142
+ | `beet moreart beatles` | Fetch artwork for matching albums |
143
+ | `beet moreart --pretend` | Show planned source/type attempts without downloading or saving |
144
+ | `beet moreart --force` | Ignore cached no-artwork results and search again |
145
+
146
+ Only negative results are cached. Existing artwork is checked on disk each
147
+ time, and changing the configured sources, API keys, or album metadata triggers
148
+ a fresh lookup. `--force` bypasses cached misses; it does not overwrite artwork
149
+ that already exists.
150
+
151
+ After a manual run, MoreArt prints a summary:
152
+
153
+ ```text
154
+ ========================================
155
+ MoreArt summary
156
+ Albums checked: 12
157
+ Artwork saved: 18
158
+ Already present: 14
159
+ Cached no-image: 2
160
+ No image saved: 4
161
+ Would fetch (pretend): 0
162
+ Albums missing path: 0
163
+ ========================================
164
+ ```
165
+
166
+ ## How it Works
167
+
168
+ 1. Checks the album directory and skips artwork that is already present.
169
+ 2. Uses configured sources in order, falling back when no usable image is returned.
170
+ 3. Saves valid images beside the album files.
171
+ 4. Caches missing-artwork searches on the album record and retries after the configured interval.
172
+ 5. Converts back and spine artwork to JPEG when ImageMagick is installed.
173
+ 6. Keeps disc art as PNG when ImageMagick is installed so transparency is preserved.
174
+
175
+ ## Requirements
176
+
177
+ - Beets 2.0.0 or newer
178
+ - Python 3.9 or later
179
+ - Internet access
180
+
181
+ The plugin uses Python's standard library for HTTP requests and adds no
182
+ third-party Python runtime dependency beyond Beets. ImageMagick (`magick` or
183
+ `convert`) is optional; it enables conversion, resizing, and disc-art background
184
+ removal. Without it, images are saved in their original format.
@@ -0,0 +1,7 @@
1
+ beetsplug/moreart/__init__.py,sha256=3f_jUWC1NeoB70w8OQvQerHyesEIio_X1Wp9ijat8uc,122
2
+ beetsplug/moreart/plugin.py,sha256=crZhjW34GsnGFlQc8GUCae4n9RLqR1TXfAFQBR6V1XQ,25177
3
+ beets_moreart-0.1.0.dist-info/METADATA,sha256=KtCWyrqL9tRs4qPjl4pQQD1PmmMrccis_iKRaRJCP3g,5366
4
+ beets_moreart-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
5
+ beets_moreart-0.1.0.dist-info/entry_points.txt,sha256=mr52taHMDlQxvhxQldUd6nLpoqxf2pJblI7rqgQ-1hs,58
6
+ beets_moreart-0.1.0.dist-info/top_level.txt,sha256=za8u6CXAGbgac8cUyn9NlsgXqqq-_4HHZcNmJnfmyWc,10
7
+ beets_moreart-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [beets.plugins]
2
+ moreart = beetsplug.moreart:MoreArtPlugin
@@ -0,0 +1 @@
1
+ beetsplug
@@ -0,0 +1,5 @@
1
+ """Beets plugin for fetching additional album artwork."""
2
+
3
+ from .plugin import MoreArtPlugin
4
+
5
+ __all__ = ["MoreArtPlugin"]
@@ -0,0 +1,670 @@
1
+ """Fetch additional album artwork from Fanart.tv, MusicBrainz, and TheAudioDB."""
2
+
3
+ import hashlib
4
+ import json
5
+ import os
6
+ import re
7
+ import shutil
8
+ import subprocess
9
+ from datetime import datetime, timedelta
10
+ from typing import Any, Dict, List, Optional, Sequence
11
+ from urllib.error import HTTPError, URLError
12
+ from urllib.parse import urlencode, urlsplit
13
+ from urllib.request import Request, urlopen
14
+
15
+ from beets.plugins import BeetsPlugin
16
+ from beets.util import syspath
17
+
18
+
19
+ class ArtworkStats:
20
+ """Counts outcomes from a manual artwork-fetch run."""
21
+
22
+ def __init__(self) -> None:
23
+ self.albums_checked = 0
24
+ self.saved = 0
25
+ self.already_present = 0
26
+ self.no_image = 0
27
+ self.would_fetch = 0
28
+ self.missing_path = 0
29
+ self.cached = 0
30
+
31
+ def print_summary(self) -> None:
32
+ lines = [
33
+ "",
34
+ "=" * 40,
35
+ " MoreArt summary",
36
+ " Albums checked: %d" % self.albums_checked,
37
+ " Artwork saved: %d" % self.saved,
38
+ " Already present: %d" % self.already_present,
39
+ " Cached no-image: %d" % self.cached,
40
+ " No image saved: %d" % self.no_image,
41
+ " Would fetch (pretend): %d" % self.would_fetch,
42
+ " Albums missing path: %d" % self.missing_path,
43
+ "=" * 40,
44
+ ]
45
+ print("\n".join(lines))
46
+
47
+
48
+ class MoreArtPlugin(BeetsPlugin):
49
+ """Fetch disc, spine, and back artwork for albums."""
50
+
51
+ ART_TYPES = ("discart", "spine", "back")
52
+ IMAGE_EXTENSIONS = (".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tif", ".tiff")
53
+
54
+ def __init__(self) -> None:
55
+ super().__init__(name="moreart")
56
+ self.config.add(
57
+ {
58
+ "fanarttv_key": None,
59
+ "theaudiodb_key": None,
60
+ "sources": ["fanarttv", "theaudiodb", "musicbrainz"],
61
+ "types": ["discart", "spine", "back"],
62
+ "run_on_import": True,
63
+ "timeout": 15,
64
+ "cache_results": True,
65
+ "recheck_days": 30,
66
+ "resize": {
67
+ "enabled": True,
68
+ "discart": ["1000", "1000"],
69
+ "back": ["750", "750"],
70
+ "spine": ["35", "700"],
71
+ },
72
+ "fuzz": "15%",
73
+ "background": {"multi_corner": True},
74
+ }
75
+ )
76
+
77
+ self._magick_bin = shutil.which("magick") or shutil.which("convert")
78
+ self._request_failures = 0
79
+ if self.config["run_on_import"].get(bool):
80
+ self.import_stages = [self.import_stage]
81
+
82
+ def import_stage(self, _session: Any, task: Any) -> None:
83
+ album = task.album
84
+ if album:
85
+ self._process_album(album)
86
+
87
+ def commands(self) -> List[Any]:
88
+ from beets.ui import Subcommand
89
+
90
+ cmd = Subcommand(
91
+ "moreart",
92
+ help="fetch extra artworks (discart, spine, back)",
93
+ )
94
+ cmd.parser.add_option(
95
+ "--pretend",
96
+ action="store_true",
97
+ default=False,
98
+ help="show what would be done, but don't download or save",
99
+ )
100
+ cmd.parser.add_option(
101
+ "--force",
102
+ action="store_true",
103
+ default=False,
104
+ help="ignore cached no-artwork results and search again",
105
+ )
106
+
107
+ def func(lib: Any, opts: Any, args: Sequence[str]) -> None:
108
+ albums = list(lib.albums(args))
109
+ if not albums:
110
+ return
111
+
112
+ stats = ArtworkStats()
113
+ for album in albums:
114
+ self._process_album(
115
+ album,
116
+ pretend=opts.pretend,
117
+ force=opts.force,
118
+ stats=stats,
119
+ )
120
+ stats.print_summary()
121
+
122
+ cmd.func = func
123
+ return [cmd]
124
+
125
+ def _process_album(
126
+ self,
127
+ album: Any,
128
+ pretend: bool = False,
129
+ force: bool = False,
130
+ stats: Optional[ArtworkStats] = None,
131
+ ) -> None:
132
+ if stats:
133
+ stats.albums_checked += 1
134
+ if not album.path:
135
+ self._log.warning("Album has no path; skipping extra artwork fetch.")
136
+ if stats:
137
+ stats.missing_path += 1
138
+ return
139
+
140
+ album_dir = syspath(album.path)
141
+ sources = self.config["sources"].as_str_seq()
142
+ art_types = self.config["types"].as_str_seq()
143
+
144
+ for art_type in art_types:
145
+ if art_type not in self.ART_TYPES:
146
+ self._log.warning("Unsupported artwork type %r; skipping.", art_type)
147
+ continue
148
+ if self._art_exists(album_dir, art_type):
149
+ self._log.debug("%s already exists for %s", art_type, album)
150
+ if stats:
151
+ stats.already_present += 1
152
+ continue
153
+
154
+ if pretend:
155
+ if stats:
156
+ stats.would_fetch += 1
157
+ for source in sources:
158
+ self._log.info(
159
+ "[pretend] Would try %s from %s for %s",
160
+ art_type,
161
+ source,
162
+ album,
163
+ )
164
+ continue
165
+
166
+ cache_key = self._cache_key(album, art_type, sources)
167
+ if self._should_skip_cached(album, cache_key, force):
168
+ if stats:
169
+ stats.cached += 1
170
+ self._log.debug("Skipping cached no-artwork lookup for %s (%s)", album, art_type)
171
+ continue
172
+
173
+ failure_count = self._request_failures
174
+ for source in sources:
175
+ images = self._fetch_from_source(source, album, art_type)
176
+ if not images:
177
+ continue
178
+
179
+ saved = 0
180
+ for index, image_bytes in enumerate(images, start=1):
181
+ if art_type == "discart" and len(images) > 1:
182
+ filename = "discart%d.jpg" % index
183
+ else:
184
+ filename = "%s.jpg" % art_type
185
+ path = os.path.join(album_dir, filename)
186
+ saved_path = self._save_image(path, image_bytes, source, art_type)
187
+ if not saved_path:
188
+ continue
189
+
190
+ if art_type == "discart":
191
+ self._fix_discart_background(saved_path)
192
+ if self.config["resize"]["enabled"].get(bool):
193
+ resize_config = self.config["resize"][art_type].as_str_seq()
194
+ if len(resize_config) == 2:
195
+ try:
196
+ width, height = (int(value) for value in resize_config)
197
+ except ValueError:
198
+ self._log.warning(
199
+ "Invalid resize dimensions for %s: %r",
200
+ art_type,
201
+ resize_config,
202
+ )
203
+ else:
204
+ self._resize_image(saved_path, width, height)
205
+
206
+ saved += 1
207
+ self._log.info(
208
+ "%s ready for %s (from %s)",
209
+ os.path.basename(saved_path),
210
+ album,
211
+ source,
212
+ )
213
+
214
+ if saved:
215
+ self._clear_cached_negative(album, cache_key)
216
+ if stats:
217
+ stats.saved += saved
218
+ break
219
+ else:
220
+ if self._request_failures == failure_count:
221
+ self._cache_negative(album, cache_key)
222
+ if stats:
223
+ stats.no_image += 1
224
+ self._log.warning("No valid %s found for %s", art_type, album)
225
+
226
+ def _cache_key(self, album: Any, art_type: str, sources: Sequence[str]) -> str:
227
+ def secret_digest(value: Any) -> str:
228
+ if not value:
229
+ return ""
230
+ return hashlib.sha256(str(value).encode("utf-8")).hexdigest()
231
+
232
+ payload = {
233
+ "art_type": art_type,
234
+ "sources": list(sources),
235
+ "mb_albumid": getattr(album, "mb_albumid", None),
236
+ "albumartist": getattr(album, "albumartist", None),
237
+ "album": getattr(album, "album", None),
238
+ "fanarttv_key": secret_digest(self.config["fanarttv_key"].get()),
239
+ "theaudiodb_key": secret_digest(self.config["theaudiodb_key"].get()),
240
+ }
241
+ serialized = json.dumps(payload, sort_keys=True, separators=(",", ":"))
242
+ return hashlib.sha256(serialized.encode("utf-8")).hexdigest()
243
+
244
+ @staticmethod
245
+ def _read_album_cache(album: Any) -> Dict[str, str]:
246
+ value = album.get("moreart_cache")
247
+ if not isinstance(value, str) or not value:
248
+ return {}
249
+ try:
250
+ cache = json.loads(value)
251
+ except (TypeError, ValueError):
252
+ return {}
253
+ return cache if isinstance(cache, dict) else {}
254
+
255
+ def _should_skip_cached(self, album: Any, cache_key: str, force: bool) -> bool:
256
+ if force or not self.config["cache_results"].get(bool):
257
+ return False
258
+
259
+ checked_at = self._read_album_cache(album).get(cache_key)
260
+ if not isinstance(checked_at, str):
261
+ return False
262
+ try:
263
+ checked = datetime.fromisoformat(checked_at)
264
+ except ValueError:
265
+ return False
266
+
267
+ recheck_days = max(0, self.config["recheck_days"].get(int))
268
+ if datetime.now() - checked < timedelta(days=recheck_days):
269
+ return True
270
+ return False
271
+
272
+ def _write_album_cache(self, album: Any, cache: Dict[str, str]) -> None:
273
+ album["moreart_cache"] = json.dumps(cache, sort_keys=True)
274
+ album.store(inherit=False)
275
+
276
+ def _cache_negative(self, album: Any, cache_key: str) -> None:
277
+ if not self.config["cache_results"].get(bool):
278
+ return
279
+
280
+ cache = self._read_album_cache(album)
281
+ cutoff = datetime.now() - timedelta(
282
+ days=max(0, self.config["recheck_days"].get(int))
283
+ )
284
+ for key, checked_at in list(cache.items()):
285
+ try:
286
+ checked = datetime.fromisoformat(checked_at)
287
+ except (TypeError, ValueError):
288
+ del cache[key]
289
+ continue
290
+ if checked < cutoff:
291
+ del cache[key]
292
+ cache[cache_key] = datetime.now().isoformat()
293
+ self._write_album_cache(album, cache)
294
+
295
+ def _clear_cached_negative(self, album: Any, cache_key: str) -> None:
296
+ if not self.config["cache_results"].get(bool):
297
+ return
298
+ cache = self._read_album_cache(album)
299
+ if cache_key in cache:
300
+ del cache[cache_key]
301
+ self._write_album_cache(album, cache)
302
+
303
+ def _fetch_from_source(
304
+ self, source: str, album: Any, art_type: str
305
+ ) -> Optional[List[bytes]]:
306
+ fetchers = {
307
+ "fanarttv": self._fetch_from_fanarttv,
308
+ "musicbrainz": self._fetch_from_musicbrainz,
309
+ "theaudiodb": self._fetch_from_theaudiodb,
310
+ }
311
+ fetcher = fetchers.get(source)
312
+ if fetcher is None:
313
+ self._log.warning("Unknown artwork source %r; skipping.", source)
314
+ return None
315
+ return fetcher(album, art_type)
316
+
317
+ def _art_exists(self, album_dir: str, art_type: str) -> bool:
318
+ try:
319
+ filenames = os.listdir(album_dir)
320
+ except FileNotFoundError:
321
+ return False
322
+
323
+ stem_pattern = re.compile(
324
+ r"^%s(?:\d+)?$" % re.escape(art_type),
325
+ flags=re.IGNORECASE,
326
+ )
327
+ return any(
328
+ stem_pattern.fullmatch(os.path.splitext(filename)[0])
329
+ and os.path.splitext(filename)[1].lower() in self.IMAGE_EXTENSIONS
330
+ for filename in filenames
331
+ )
332
+
333
+ @staticmethod
334
+ def _image_format(image_bytes: bytes) -> Optional[str]:
335
+ if image_bytes.startswith(b"\x89PNG\r\n\x1a\n"):
336
+ return "png"
337
+ if image_bytes.startswith(b"\xff\xd8\xff"):
338
+ return "jpg"
339
+ if image_bytes.startswith((b"GIF87a", b"GIF89a")):
340
+ return "gif"
341
+ if (
342
+ len(image_bytes) >= 12
343
+ and image_bytes[:4] == b"RIFF"
344
+ and image_bytes[8:12] == b"WEBP"
345
+ ):
346
+ return "webp"
347
+ if image_bytes.startswith(b"BM"):
348
+ return "bmp"
349
+ if image_bytes.startswith((b"II*\x00", b"MM\x00*")):
350
+ return "tif"
351
+ return None
352
+
353
+ @staticmethod
354
+ def _file_checksum(path: str) -> str:
355
+ digest = hashlib.sha256()
356
+ with open(path, "rb") as image_file:
357
+ for chunk in iter(lambda: image_file.read(8192), b""):
358
+ digest.update(chunk)
359
+ return digest.hexdigest()
360
+
361
+ def _save_image(
362
+ self, path: str, image_bytes: bytes, source: str, art_type: str
363
+ ) -> Optional[str]:
364
+ image_format = self._image_format(image_bytes)
365
+ if image_format is None:
366
+ self._request_failures += 1
367
+ self._log.warning(
368
+ "%s did not return a valid %s image.", source, art_type
369
+ )
370
+ return None
371
+
372
+ base, _ = os.path.splitext(path)
373
+ if self._magick_bin:
374
+ output_format = "png" if art_type == "discart" else "jpg"
375
+ else:
376
+ output_format = image_format
377
+ output_path = "%s.%s" % (base, output_format)
378
+ if os.path.exists(output_path):
379
+ if self._file_checksum(output_path) == hashlib.sha256(image_bytes).hexdigest():
380
+ self._log.debug("Skipping identical %s image: %s", art_type, output_path)
381
+ return None
382
+
383
+ download_path = "%s.download.%s" % (base, image_format)
384
+ converted_path = "%s.tmp.%s" % (base, output_format)
385
+ temporary_path = "%s.tmp.%s" % (base, image_format)
386
+ try:
387
+ with open(download_path, "wb") as image_file:
388
+ image_file.write(image_bytes)
389
+
390
+ if self._magick_bin:
391
+ try:
392
+ self._run_magick([download_path, converted_path])
393
+ if not os.path.isfile(converted_path) or os.path.getsize(converted_path) == 0:
394
+ raise OSError("ImageMagick produced no output")
395
+ os.replace(converted_path, output_path)
396
+ return output_path
397
+ except (OSError, subprocess.CalledProcessError) as error:
398
+ self._log.warning(
399
+ "Could not convert %s image with ImageMagick: %s; saving original.",
400
+ art_type,
401
+ error,
402
+ )
403
+ output_path = "%s.%s" % (base, image_format)
404
+
405
+ with open(temporary_path, "wb") as image_file:
406
+ image_file.write(image_bytes)
407
+ os.replace(temporary_path, output_path)
408
+ return output_path
409
+ finally:
410
+ for path_to_clean in (download_path, converted_path, temporary_path):
411
+ if os.path.exists(path_to_clean):
412
+ os.remove(path_to_clean)
413
+
414
+ def _run_magick(self, args: Sequence[str]) -> None:
415
+ if not self._magick_bin:
416
+ raise FileNotFoundError("ImageMagick (magick or convert) is not installed")
417
+ subprocess.run(
418
+ [self._magick_bin, *args],
419
+ check=True,
420
+ stdout=subprocess.DEVNULL,
421
+ stderr=subprocess.PIPE,
422
+ text=True,
423
+ )
424
+
425
+ def _edit_image(self, path: str, options: Sequence[str]) -> None:
426
+ if not self._magick_bin:
427
+ self._log.warning(
428
+ "ImageMagick is not installed; leaving artwork unchanged: %s", path
429
+ )
430
+ return
431
+
432
+ base, extension = os.path.splitext(path)
433
+ temporary_path = "%s.processing%s" % (base, extension)
434
+ try:
435
+ self._run_magick([path, *options, temporary_path])
436
+ if not os.path.isfile(temporary_path) or os.path.getsize(temporary_path) == 0:
437
+ raise OSError("ImageMagick produced no output")
438
+ os.replace(temporary_path, path)
439
+ except (OSError, subprocess.CalledProcessError) as error:
440
+ self._log.warning("Image processing failed for %s: %s", path, error)
441
+ finally:
442
+ if os.path.exists(temporary_path):
443
+ os.remove(temporary_path)
444
+
445
+ def _fix_discart_background(self, path: str) -> None:
446
+ fuzz = self.config["fuzz"].get(str) or "15%"
447
+ options = ["-alpha", "set", "-fuzz", fuzz, "-fill", "none"]
448
+ if self.config["background"]["multi_corner"].get(bool):
449
+ options.extend(
450
+ [
451
+ "-draw",
452
+ "alpha 0,0 floodfill",
453
+ "-draw",
454
+ "alpha 0,%[fx:h-1] floodfill",
455
+ "-draw",
456
+ "alpha %[fx:w-1],0 floodfill",
457
+ "-draw",
458
+ "alpha %[fx:w-1],%[fx:h-1] floodfill",
459
+ "-draw",
460
+ "alpha %[fx:w/2],%[fx:h/2] floodfill",
461
+ ]
462
+ )
463
+ else:
464
+ options.extend(["-draw", "alpha 0,0 floodfill"])
465
+ self._edit_image(path, options)
466
+
467
+ def _resize_image(self, path: str, width: int, height: int) -> None:
468
+ self._edit_image(path, ["-resize", "%dx%d!" % (width, height)])
469
+
470
+ def _request_bytes(
471
+ self, url: str, params: Optional[Dict[str, str]] = None
472
+ ) -> bytes:
473
+ if params:
474
+ separator = "&" if "?" in url else "?"
475
+ url = "%s%s%s" % (url, separator, urlencode(params))
476
+ request = Request(url, headers={"User-Agent": "beets-moreart"})
477
+ try:
478
+ with urlopen(request, timeout=self.config["timeout"].get(int)) as response:
479
+ return response.read()
480
+ except HTTPError as error:
481
+ if error.code != 404:
482
+ self._request_failures += 1
483
+ raise
484
+ except OSError:
485
+ self._request_failures += 1
486
+ raise
487
+
488
+ def _request_json(
489
+ self, url: str, params: Optional[Dict[str, str]] = None
490
+ ) -> Any:
491
+ try:
492
+ return json.loads(self._request_bytes(url, params))
493
+ except ValueError:
494
+ self._request_failures += 1
495
+ raise
496
+
497
+ def _response_mapping(
498
+ self, data: Any, source: str
499
+ ) -> Optional[Dict[str, Any]]:
500
+ if isinstance(data, dict):
501
+ return data
502
+ self._request_failures += 1
503
+ self._log.warning("%s returned an unexpected response format.", source)
504
+ return None
505
+
506
+ def _invalid_response(self, source: str, detail: str) -> None:
507
+ self._request_failures += 1
508
+ self._log.warning("%s returned an invalid %s response.", source, detail)
509
+
510
+ def _response_url(self, value: Any, source: str) -> Optional[str]:
511
+ if value is None or value == "":
512
+ return None
513
+ if not isinstance(value, str):
514
+ self._invalid_response(source, "image URL")
515
+ return None
516
+ try:
517
+ parsed_url = urlsplit(value)
518
+ except ValueError:
519
+ self._invalid_response(source, "image URL")
520
+ return None
521
+ if parsed_url.scheme not in ("http", "https") or not parsed_url.netloc:
522
+ self._invalid_response(source, "image URL")
523
+ return None
524
+ return value
525
+
526
+ def _download_image(self, url: str) -> Optional[bytes]:
527
+ return self._request_bytes(url)
528
+
529
+ def _fetch_from_fanarttv(
530
+ self, album: Any, art_type: str
531
+ ) -> Optional[List[bytes]]:
532
+ api_key = self.config["fanarttv_key"].get()
533
+ mbid = album.mb_albumid
534
+ if not api_key or not mbid:
535
+ return None
536
+
537
+ fields = {
538
+ "discart": "cdart",
539
+ "spine": "albumspine",
540
+ "back": "albumcoverback",
541
+ }
542
+ try:
543
+ data = self._request_json(
544
+ "https://webservice.fanart.tv/v3/music/%s" % mbid,
545
+ params={"api_key": api_key},
546
+ )
547
+ data = self._response_mapping(data, "Fanart.tv")
548
+ if data is None:
549
+ return None
550
+ assets = data.get(fields[art_type], [])
551
+ if not isinstance(assets, list):
552
+ self._invalid_response("Fanart.tv", "artwork list")
553
+ return None
554
+ if art_type != "discart":
555
+ assets = assets[:1]
556
+ images = []
557
+ for asset in assets:
558
+ if not isinstance(asset, dict):
559
+ self._invalid_response("Fanart.tv", "artwork entry")
560
+ continue
561
+ image_url = self._response_url(asset.get("url"), "Fanart.tv")
562
+ if image_url:
563
+ try:
564
+ image = self._download_image(image_url)
565
+ except (OSError, URLError) as error:
566
+ self._log.warning("Fanart.tv image request failed: %s", error)
567
+ continue
568
+ if image:
569
+ images.append(image)
570
+ return images or None
571
+ except (OSError, ValueError) as error:
572
+ self._log.warning("Fanart.tv request failed for %s: %s", mbid, error)
573
+ return None
574
+
575
+ def _fetch_from_musicbrainz(
576
+ self, album: Any, art_type: str
577
+ ) -> Optional[List[bytes]]:
578
+ mbid = album.mb_albumid
579
+ if not mbid or art_type == "spine":
580
+ return None
581
+
582
+ try:
583
+ data = self._request_json(
584
+ "https://coverartarchive.org/release/%s" % mbid
585
+ )
586
+ data = self._response_mapping(data, "MusicBrainz")
587
+ if data is None:
588
+ return None
589
+ entries = data.get("images", [])
590
+ if not isinstance(entries, list):
591
+ self._invalid_response("MusicBrainz", "image list")
592
+ return None
593
+ images = []
594
+ for entry in entries:
595
+ if not isinstance(entry, dict):
596
+ self._invalid_response("MusicBrainz", "image entry")
597
+ continue
598
+ image_types = entry.get("types", [])
599
+ if not isinstance(image_types, list):
600
+ self._invalid_response("MusicBrainz", "image types")
601
+ continue
602
+ if (
603
+ art_type == "back"
604
+ and "Back" in image_types
605
+ or art_type == "discart"
606
+ and "Medium" in image_types
607
+ ):
608
+ image_url = self._response_url(
609
+ entry.get("image"), "MusicBrainz"
610
+ )
611
+ if image_url:
612
+ try:
613
+ image = self._download_image(image_url)
614
+ except (OSError, URLError) as error:
615
+ self._log.warning(
616
+ "MusicBrainz image request failed: %s", error
617
+ )
618
+ continue
619
+ if image:
620
+ images.append(image)
621
+ if art_type != "discart":
622
+ images = images[:1]
623
+ return images or None
624
+ except (OSError, ValueError) as error:
625
+ self._log.warning("MusicBrainz request failed for %s: %s", mbid, error)
626
+ return None
627
+
628
+ def _fetch_from_theaudiodb(
629
+ self, album: Any, art_type: str
630
+ ) -> Optional[List[bytes]]:
631
+ api_key = self.config["theaudiodb_key"].get()
632
+ artist = album.albumartist
633
+ title = album.album
634
+ if not api_key or not artist or not title:
635
+ return None
636
+
637
+ fields = {
638
+ "discart": "strAlbumCDart",
639
+ "spine": "strAlbumSpine",
640
+ "back": "strAlbumThumbBack",
641
+ }
642
+ try:
643
+ data = self._request_json(
644
+ "https://www.theaudiodb.com/api/v1/json/%s/searchalbum.php" % api_key,
645
+ params={"s": artist, "a": title},
646
+ )
647
+ data = self._response_mapping(data, "TheAudioDB")
648
+ if data is None:
649
+ return None
650
+ albums = data.get("album")
651
+ if albums is None:
652
+ return None
653
+ if not isinstance(albums, list):
654
+ self._invalid_response("TheAudioDB", "album list")
655
+ return None
656
+ if not albums:
657
+ return None
658
+ if not isinstance(albums[0], dict):
659
+ self._invalid_response("TheAudioDB", "album entry")
660
+ return None
661
+ image_url = self._response_url(
662
+ albums[0].get(fields[art_type]), "TheAudioDB"
663
+ )
664
+ if not image_url:
665
+ return None
666
+ image = self._download_image(image_url)
667
+ return [image] if image else None
668
+ except (OSError, ValueError) as error:
669
+ self._log.warning("TheAudioDB request failed for %s - %s: %s", artist, title, error)
670
+ return None