Debian Codegraph @

beetsplug/chroma.py

raw
1 """Adds Chromaprint/Acoustid acoustic fingerprinting support to the
2 autotagger. Requires the pyacoustid library.
3 """
4
5 from __future__ import annotations
6
7 import heapq
8 import re
9 from collections import defaultdict
10 from functools import cached_property, partial
11 from typing import TYPE_CHECKING, Any, Protocol
12
13 import acoustid
14 import confuse
15
16 from beets import config, ui, util
17 from beets.autotag import Distance
18 from beets.exceptions import UserError
19 from beets.metadata_plugins import MetadataSourcePlugin, get_metadata_source
20 from beets.util.color import colorize
21
22 if TYPE_CHECKING:
23 import optparse
24 from collections.abc import Iterable, Iterator, Sequence
25
26 from beets.autotag import AlbumInfo, TrackInfo
27 from beets.importer import ImportSession, ImportTask
28 from beets.library import Item, Library
29 from beets.logging import BeetsLogger as Logger
30 from beetsplug.musicbrainz import MusicBrainzPlugin
31
32 from ._typing import JSONDict
33
34
35 class ChromaSearchCLIOpts(Protocol):
36 count: int
37 full: bool | None
38 search: str | None
39 write: bool | None
40
41
42 API_KEY = "1vOwZtEn"
43 SCORE_THRESH = 0.5
44 TRACK_ID_WEIGHT = 10.0
45 COMMON_REL_THRESH = 0.6 # How many tracks must have an album in common?
46 MAX_RECORDINGS = 5
47 MAX_RELEASES = 5
48
49 # Stores the Acoustid match information for each track. This is
50 # populated when an import task begins and then used when searching for
51 # candidates. It maps audio file paths to (recording_ids, release_ids)
52 # pairs. If a given path is not present in the mapping, then no match
53 # was found.
54 _matches: dict[bytes, tuple[list[str], list[str]]] = {}
55
56 # Stores the fingerprint and Acoustid ID for each track. This is stored
57 # as metadata for each track for later use but is not relevant for
58 # autotagging.
59 _fingerprints: dict[bytes, str] = {}
60 _acoustids: dict[bytes, str] = {}
61
62
63 def prefix(it: Iterable[Any], count: int) -> Iterator[Any]:
64 """Truncate an iterable to at most `count` items."""
65 for i, v in enumerate(it):
66 if i >= count:
67 break
68 yield v
69
70
71 def releases_key(
72 release: JSONDict, countries: Sequence[re.Pattern[str]], original_year: bool
73 ) -> tuple[int, int, int, int]:
74 """Used as a key to sort releases by date then preferred country"""
75 date = release.get("date")
76 if date and original_year:
77 year = date.get("year", 9999)
78 month = date.get("month", 99)
79 day = date.get("day", 99)
80 else:
81 year = 9999
82 month = 99
83 day = 99
84
85 # Uses index of preferred countries to sort
86 country_key = 99
87 if release.get("country"):
88 for i, country in enumerate(countries):
89 if country.match(release["country"]):
90 country_key = i
91 break
92
93 return (year, month, day, country_key)
94
95
96 def acoustid_match(log: Logger, path: bytes) -> None:
97 """Gets metadata for a file from Acoustid and populates the
98 _matches, _fingerprints, and _acoustids dictionaries accordingly.
99 """
100 try:
101 duration, fp = acoustid.fingerprint_file(util.syspath(path))
102 except acoustid.FingerprintGenerationError as exc:
103 log.error(
104 "fingerprinting of {} failed: {}",
105 util.displayable_path(repr(path)),
106 exc,
107 )
108 return
109 fp = fp.decode()
110 _fingerprints[path] = fp
111 try:
112 res = acoustid.lookup(
113 API_KEY, fp, duration, meta="recordings releases", timeout=10
114 )
115 except acoustid.AcoustidError as exc:
116 log.debug(
117 "fingerprint matching {} failed: {}",
118 util.displayable_path(repr(path)),
119 exc,
120 )
121 return
122 log.debug("chroma: fingerprinted {}", util.displayable_path(repr(path)))
123
124 # Ensure the response is usable and parse it.
125 if res["status"] != "ok" or not res.get("results"):
126 log.debug("no match found")
127 return
128 result = res["results"][0] # Best match.
129 if result["score"] < SCORE_THRESH:
130 log.debug("no results above threshold")
131 return
132 _acoustids[path] = result["id"]
133
134 # Get recording and releases from the result
135 if not result.get("recordings"):
136 log.debug("no recordings found")
137 return
138 recording_ids = []
139 releases = []
140 for recording in result["recordings"]:
141 recording_ids.append(recording["id"])
142 if "releases" in recording:
143 releases.extend(recording["releases"])
144
145 # The releases list is essentially in random order from the Acoustid lookup
146 # so we optionally sort it using the match.preferred configuration options.
147 # 'original_year' to sort the earliest first and
148 # 'countries' to then sort preferred countries first.
149 country_patterns = config["match"]["preferred"]["countries"].as_str_seq()
150 countries = [re.compile(pat, re.I) for pat in country_patterns]
151 original_year = config["match"]["preferred"]["original_year"].get(bool)
152 releases.sort(
153 key=partial(
154 releases_key, countries=countries, original_year=original_year
155 )
156 )
157 release_ids = [rel["id"] for rel in releases]
158
159 log.debug(
160 "matched recordings {} on releases {}", recording_ids, release_ids
161 )
162 _matches[path] = recording_ids, release_ids
163
164
165 # Plugin structure and autotagging logic.
166
167
168 def _all_releases(items: Sequence[Item]) -> Iterator[str]:
169 """Given an iterable of Items, determines (according to Acoustid)
170 which releases the items have in common. Generates release IDs.
171 """
172 # Count the number of "hits" for each release.
173 relcounts = defaultdict[str, int](int)
174 for item in items:
175 if item.path not in _matches:
176 continue
177
178 _, release_ids = _matches[item.path]
179 for release_id in release_ids:
180 relcounts[release_id] += 1
181
182 for release_id, count in relcounts.items():
183 if float(count) / len(items) > COMMON_REL_THRESH:
184 yield release_id
185
186
187 class AcoustidPlugin(MetadataSourcePlugin):
188 def __init__(self) -> None:
189 super().__init__()
190 self.config.add({"auto": True})
191 config["acoustid"]["apikey"].redact = True
192
193 if self.config["auto"]:
194 self.register_listener("import_task_start", self.fingerprint_task)
195 self.register_listener("import_task_apply", apply_acoustid_metadata)
196
197 @cached_property
198 def mb(self) -> MusicBrainzPlugin | None:
199 """The loaded MusicBrainz plugin, or ``None``.
200
201 Acoustid lookups return MusicBrainz IDs, so chroma needs the
202 ``musicbrainz`` plugin to resolve them into album/track
203 candidates. When the user has not enabled ``musicbrainz``,
204 chroma must not produce any candidates.
205
206 Uses the plugin registry so that any plugin that swaps the
207 musicbrainz instance at runtime (e.g. :doc:`plugins/mbpseudo`)
208 is respected.
209 """
210 plugin = get_metadata_source("musicbrainz")
211 if plugin is None:
212 self._log.debug(
213 "musicbrainz plugin not enabled; "
214 "acoustid matches will not produce candidates"
215 )
216 return plugin # type: ignore[return-value]
217
218 def fingerprint_task(
219 self, task: ImportTask, session: ImportSession
220 ) -> None:
221 return fingerprint_task(self._log, task, session)
222
223 def track_distance(self, item: Item, info: TrackInfo) -> Distance:
224 dist = Distance()
225 if item.path not in _matches or not info.track_id:
226 # Match failed or no track ID.
227 return dist
228
229 recording_ids, _ = _matches[item.path]
230 dist.add_expr("track_id", info.track_id not in recording_ids)
231 return dist
232
233 def candidates(
234 self, items: Sequence[Item], artist: str, album: str, va_likely: bool
235 ) -> list[AlbumInfo]:
236 if self.mb is None:
237 return []
238
239 albums = [
240 a
241 for relid in prefix(_all_releases(items), MAX_RELEASES)
242 if (a := self.mb.album_for_id(relid))
243 ]
244
245 self._log.debug("acoustid album candidates: {}", len(albums))
246 return albums
247
248 def item_candidates(
249 self, item: Item, artist: str, title: str
250 ) -> Iterable[TrackInfo]:
251 if item.path not in _matches:
252 return []
253
254 if self.mb is None:
255 return []
256
257 recording_ids, _ = _matches[item.path]
258 tracks = []
259 for recording_id in prefix(recording_ids, MAX_RECORDINGS):
260 track = self.mb.track_for_id(recording_id)
261 if track:
262 tracks.append(track)
263 self._log.debug("acoustid item candidates: {}", len(tracks))
264 return tracks
265
266 def album_for_id(self, *args, **kwargs) -> None:
267 # Lookup by fingerprint ID does not make too much sense.
268 return None
269
270 def track_for_id(self, *args, **kwargs) -> None:
271 # Lookup by fingerprint ID does not make too much sense.
272 return None
273
274 def commands(self) -> list[ui.Subcommand]:
275 submit_cmd = ui.Subcommand(
276 "submit", help="submit Acoustid fingerprints"
277 )
278
279 def submit_cmd_func(
280 lib: Library, opts: optparse.Values, args: list[str]
281 ) -> None:
282 try:
283 apikey = config["acoustid"]["apikey"].as_str()
284 except confuse.NotFoundError:
285 raise UserError("no Acoustid user API key provided")
286 submit_items(self._log, apikey, lib.items(args))
287
288 submit_cmd.func = submit_cmd_func
289
290 fingerprint_cmd = ui.Subcommand(
291 "fingerprint", help="generate fingerprints for items without them"
292 )
293
294 def fingerprint_cmd_func(
295 lib: Library, opts: optparse.Values, args: list[str]
296 ) -> None:
297 for item in lib.items(args):
298 fingerprint_item(self._log, item, write=ui.should_write())
299
300 fingerprint_cmd.func = fingerprint_cmd_func
301
302 return [submit_cmd, fingerprint_cmd, self.chromasearch_cmd()]
303
304 def chromasearch_cmd(self) -> ui.Subcommand:
305 cmd = ui.Subcommand(
306 "chromasearch", help="search local database by chroma fingerprint"
307 )
308 cmd.parser.add_path_option()
309 cmd.parser.add_format_option()
310 cmd.parser.add_option(
311 "-s",
312 "--search",
313 dest="search",
314 action="store",
315 help="Fingerprint to search for (from the output of fpcalc -plain)",
316 )
317 cmd.parser.add_option(
318 "-c",
319 "--count",
320 dest="count",
321 action="store",
322 default=5,
323 type=int,
324 help="Number of items in result",
325 )
326 cmd.parser.add_option(
327 "--full",
328 dest="full",
329 action="store_true",
330 help="Don't stop searching once we found an exact match",
331 )
332 cmd.parser.add_option(
333 "-w",
334 "--write",
335 dest="write",
336 action="store_true",
337 help="Write computed fingerprints to files",
338 )
339
340 def search_cmd_func(
341 lib: Library, opts: ChromaSearchCLIOpts, args: list[str]
342 ) -> None:
343 if not opts.search:
344 raise UserError("no --search provided")
345 if opts.count <= 0:
346 raise UserError("--count must be > 0")
347
348 target = (0, opts.search.encode("utf-8"))
349 top = TopN(opts.count)
350
351 for item in lib.items(args):
352 fp = fingerprint_item(
353 self._log,
354 item,
355 write=ui.should_write(opts.write),
356 quiet=True,
357 )
358 if fp is None:
359 self._log.warning(f"{item}: could not compute fingerprint")
360 continue
361
362 score = acoustid.compare_fingerprints(
363 target, (0, fp.encode("utf-8"))
364 )
365
366 if score == 1 and not opts.full:
367 ui.print_(
368 f"{colorize('text_success', 'Found exact match')}: {item}"
369 )
370 return
371
372 if score > 0:
373 top.add(ScoredItem(item, score))
374
375 for scored_item in top:
376 ui.print_(str(scored_item))
377
378 cmd.func = search_cmd_func
379
380 return cmd
381
382
383 # Hooks into import process.
384
385
386 def fingerprint_task(
387 log: Logger, task: ImportTask, session: ImportSession
388 ) -> None:
389 """Fingerprint each item in the task for later use during the
390 autotagging candidate search.
391 """
392 for item in task.items:
393 acoustid_match(log, item.path)
394
395
396 def apply_acoustid_metadata(task: ImportTask, session: ImportSession) -> None:
397 """Apply Acoustid metadata (fingerprint and ID) to the task's items."""
398 for item in task.imported_items():
399 if item.path in _fingerprints:
400 item.acoustid_fingerprint = _fingerprints[item.path]
401 if item.path in _acoustids:
402 item.acoustid_id = _acoustids[item.path]
403
404
405 # UI commands.
406
407
408 def submit_items(
409 log: Logger, userkey: str, items: Sequence[Item], chunksize: int = 64
410 ) -> None:
411 """Submit fingerprints for the items to the Acoustid server."""
412 # The running list of dictionaries to submit.
413 data: list[JSONDict] = []
414
415 def submit_chunk() -> None:
416 """Submit the current accumulated fingerprint data."""
417 log.info("submitting {} fingerprints", len(data))
418 try:
419 acoustid.submit(API_KEY, userkey, data, timeout=10)
420 except acoustid.AcoustidError as exc:
421 log.warning("acoustid submission error: {}", exc)
422 del data[:]
423
424 for item in items:
425 fp = fingerprint_item(log, item, write=ui.should_write())
426
427 # Construct a submission dictionary for this item.
428 item_data = {"duration": int(item.length), "fingerprint": fp}
429 if item.mb_trackid:
430 item_data["mbid"] = item.mb_trackid
431 log.debug("submitting MBID")
432 else:
433 item_data.update(
434 {
435 "track": item.title,
436 "artist": item.artist,
437 "album": item.album,
438 "albumartist": item.albumartist,
439 "year": item.year,
440 "trackno": item.track,
441 "discno": item.disc,
442 }
443 )
444 log.debug("submitting textual metadata")
445 data.append(item_data)
446
447 # If we have enough data, submit a chunk.
448 if len(data) >= chunksize:
449 submit_chunk()
450
451 # Submit remaining data in a final chunk.
452 if data:
453 submit_chunk()
454
455
456 def fingerprint_item(
457 log: Logger, item: Item, write: bool = False, quiet: bool = False
458 ) -> str | None:
459 """Get the fingerprint for an Item. If the item already has a
460 fingerprint, it is not regenerated. If fingerprint generation fails,
461 return None. If the items are associated with a library, they are
462 saved to the database. If `write` is set, then the new fingerprints
463 are also written to files' metadata.
464 """
465 # Get a fingerprint and length for this track.
466 if not item.length:
467 log.info("{.filepath}: no duration available", item)
468 elif item.acoustid_fingerprint:
469 if not quiet:
470 if write:
471 log.info("{.filepath}: fingerprint exists, skipping", item)
472 else:
473 log.info("{.filepath}: using existing fingerprint", item)
474 return item.acoustid_fingerprint
475 else:
476 log.info("{.filepath}: fingerprinting", item)
477 try:
478 _, fp = acoustid.fingerprint_file(util.syspath(item.path))
479 item.acoustid_fingerprint = fp.decode()
480 if write:
481 log.info("{.filepath}: writing fingerprint", item)
482 item.try_write()
483 if item._db:
484 item.store()
485 return item.acoustid_fingerprint
486 except acoustid.FingerprintGenerationError as exc:
487 log.info("fingerprint generation failed: {}", exc)
488 return None
489
490
491 # Classes for search.
492
493
494 class ScoredItem:
495 def __init__(self, item: Item, score: float) -> None:
496 self.item = item
497 self.score = score
498
499 def __lt__(self, other: object) -> bool:
500 return type(self) is type(other) and self.score < other.score
501
502 def __gt__(self, other: object) -> bool:
503 return type(self) is type(other) and self.score > other.score
504
505 def __str__(self) -> str:
506 percent = f"{round(self.score * 100, 2)}%".rjust(6)
507 if self.score >= 0.95:
508 percent = colorize("text_success", percent)
509 elif self.score >= 0.85:
510 percent = colorize("text_warning", percent)
511 else:
512 percent = colorize("text_error", percent)
513
514 return f"[{percent}] {self.item}"
515
516
517 class TopN:
518 def __init__(self, n: int) -> None:
519 self.n = n
520 self.heap: list[ScoredItem] = []
521
522 def add(self, value: ScoredItem) -> None:
523 if len(self.heap) < self.n:
524 heapq.heappush(self.heap, value)
525 else:
526 if value > self.heap[0]:
527 heapq.heapreplace(self.heap, value)
528
529 def __iter__(self) -> Iterator[ScoredItem]:
530 return iter(sorted(self.heap, reverse=True))