Debian Codegraph @

beetsplug/_utils/art.py

raw
1 """High-level utilities for manipulating image files associated with
2 music and items' embedded album art.
3 """
4
5 from __future__ import annotations
6
7 import os
8 from tempfile import NamedTemporaryFile
9 from typing import TYPE_CHECKING
10
11 import mediafile
12
13 from beets.util import bytestring_path, displayable_path, syspath
14 from beets.util.artresizer import ArtResizer
15
16 if TYPE_CHECKING:
17 from collections.abc import Iterable, Sequence
18
19 from beets.dbcore import Query
20 from beets.library import Album, Item, Library
21 from beets.logging import BeetsLogger as Logger
22 from beets.util import PathLike
23
24
25 def mediafile_image(
26 image_path: bytes, maxwidth: int | None = None
27 ) -> mediafile.Image:
28 """Return a `mediafile.Image` object for the path."""
29
30 with open(syspath(image_path), "rb") as f:
31 data = f.read()
32 return mediafile.Image(data, type=mediafile.ImageType.front)
33
34
35 def get_art(log: Logger, item: Item) -> bytes | None:
36 # Extract the art.
37 try:
38 mf = mediafile.MediaFile(syspath(item.path))
39 except mediafile.UnreadableFileError as exc:
40 log.warning("Could not extract art from {.filepath}: {}", item, exc)
41 return None
42
43 return mf.art
44
45
46 def embed_item(
47 log: Logger,
48 item: Item,
49 imagepath: bytes,
50 maxwidth: int | None = None,
51 itempath: bytes | None = None,
52 compare_threshold: int = 0,
53 ifempty: bool = False,
54 as_album: bool = False,
55 id3v23: bool | None = None,
56 quality: int = 0,
57 ) -> None:
58 """Embed an image into the item's media file."""
59 # Conditions.
60 if compare_threshold:
61 is_similar = check_art_similarity(
62 log, item, imagepath, compare_threshold
63 )
64 if is_similar is None:
65 log.warning("Error while checking art similarity; skipping.")
66 return
67 if not is_similar:
68 log.info("Image not similar; skipping.")
69 return
70
71 if ifempty and get_art(log, item):
72 log.info("media file already contained art")
73 return
74
75 # Filters.
76 if maxwidth and not as_album:
77 imagepath = resize_image(log, imagepath, maxwidth, quality)
78
79 # Get the `Image` object from the file.
80 try:
81 log.debug("embedding {}", displayable_path(imagepath))
82 image = mediafile_image(imagepath, maxwidth)
83 except OSError as exc:
84 log.warning("could not read image file: {}", exc)
85 return
86
87 # Make sure the image kind is safe (some formats only support PNG
88 # and JPEG).
89 if image.mime_type not in ("image/jpeg", "image/png"):
90 log.info("not embedding image of unsupported type: {.mime_type}", image)
91 return
92
93 item.try_write(path=itempath, tags={"images": [image]}, id3v23=id3v23)
94
95
96 def embed_album(
97 log: Logger,
98 album: Album,
99 maxwidth: int | None = None,
100 quiet: bool = False,
101 compare_threshold: int = 0,
102 ifempty: bool = False,
103 quality: int = 0,
104 ) -> None:
105 """Embed album art into all of the album's items."""
106 imagepath = album.artpath
107 if not imagepath:
108 log.info("No album art present for {}", album)
109 return
110 if not os.path.isfile(syspath(imagepath)):
111 log.info(
112 "Album art not found at {} for {}",
113 displayable_path(imagepath),
114 album,
115 )
116 return
117 if maxwidth:
118 imagepath = resize_image(log, imagepath, maxwidth, quality)
119
120 log.info("Embedding album art into {}", album)
121
122 for item in album.items():
123 embed_item(
124 log,
125 item,
126 imagepath,
127 maxwidth,
128 None,
129 compare_threshold,
130 ifempty,
131 as_album=True,
132 quality=quality,
133 )
134
135
136 def resize_image(
137 log: Logger, imagepath: bytes, maxwidth: int, quality: int
138 ) -> bytes:
139 """Returns path to an image resized to maxwidth and encoded with the
140 specified quality level.
141 """
142 log.debug(
143 "Resizing album art to {} pixels wide and encoding at quality level {}",
144 maxwidth,
145 quality,
146 )
147 return ArtResizer.shared.resize(maxwidth, imagepath, quality=quality)
148
149
150 def check_art_similarity(
151 log: Logger,
152 item: Item,
153 imagepath: bytes,
154 compare_threshold: int,
155 artresizer: ArtResizer | None = None,
156 ) -> bool | None:
157 """A boolean indicating if an image is similar to embedded item art.
158
159 If no embedded art exists, always return `True`. If the comparison fails
160 for some reason, the return value is `None`.
161
162 This must only be called if `ArtResizer.shared.can_compare` is `True`.
163 """
164 with NamedTemporaryFile(delete=True) as f:
165 art = extract(log, f.name, item)
166
167 if not art:
168 return True
169
170 if artresizer is None:
171 artresizer = ArtResizer.shared
172
173 return artresizer.compare(art, imagepath, compare_threshold)
174
175
176 def extract(log: Logger, outpath: PathLike, item: Item) -> bytes | None:
177 art = get_art(log, item)
178 outpath = bytestring_path(outpath)
179 if not art:
180 log.info("No album art present in {}, skipping.", item)
181 return None
182
183 # Add an extension to the filename.
184 ext = mediafile.image_extension(art)
185 if not ext:
186 log.warning("Unknown image type in {.filepath}.", item)
187 return None
188 outpath += bytestring_path(f".{ext}")
189
190 log.info(
191 "Extracting album art from: {} to: {}", item, displayable_path(outpath)
192 )
193 with open(syspath(outpath), "wb") as f:
194 f.write(art)
195 return outpath
196
197
198 def extract_first(
199 log: Logger, outpath: bytes, items: Iterable[Item]
200 ) -> bytes | None:
201 for item in items:
202 real_path = extract(log, outpath, item)
203 if real_path:
204 return real_path
205 return None
206
207
208 def clear_item(item: Item, log: Logger) -> None:
209 if mediafile.MediaFile(syspath(item.path)).images:
210 log.debug("Clearing art for {}", item)
211 item.try_write(tags={"images": None})
212
213
214 def clear(
215 log: Logger, lib: Library, query: str | Sequence[str] | Query | None = None
216 ) -> None:
217 items = lib.items(query)
218 log.info("Clearing album art from {} items", len(items))
219 for item in items:
220 clear_item(item, log)