| 1 |
"""List duplicate tracks or albums.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import os |
| 6 |
import shlex |
| 7 |
from functools import partial |
| 8 |
from typing import TYPE_CHECKING, Any |
| 9 |
|
| 10 |
from beets.library import Album, Item |
| 11 |
from beets.plugins import BeetsPlugin |
| 12 |
from beets.ui import Subcommand, UserError, print_ |
| 13 |
from beets.util import ( |
| 14 |
MoveOperation, |
| 15 |
bytestring_path, |
| 16 |
command_output, |
| 17 |
displayable_path, |
| 18 |
subprocess, |
| 19 |
) |
| 20 |
|
| 21 |
if TYPE_CHECKING: |
| 22 |
import optparse |
| 23 |
from collections.abc import Callable, Iterator, Sequence |
| 24 |
|
| 25 |
from beets.library import AlbumOrItem, LibModel, Library |
| 26 |
|
| 27 |
|
| 28 |
PLUGIN = "duplicates" |
| 29 |
|
| 30 |
|
| 31 |
class DuplicatesPlugin(BeetsPlugin): |
| 32 |
"""List duplicate tracks or albums""" |
| 33 |
|
| 34 |
def __init__(self) -> None: |
| 35 |
super().__init__() |
| 36 |
|
| 37 |
self.config.add( |
| 38 |
{ |
| 39 |
"album": False, |
| 40 |
"checksum": "", |
| 41 |
"copy": "", |
| 42 |
"count": False, |
| 43 |
"delete": False, |
| 44 |
"format": "", |
| 45 |
"full": False, |
| 46 |
"keys": [], |
| 47 |
"merge": False, |
| 48 |
"move": "", |
| 49 |
"path": False, |
| 50 |
"tiebreak": {}, |
| 51 |
"strict": False, |
| 52 |
"tag": "", |
| 53 |
"remove": False, |
| 54 |
} |
| 55 |
) |
| 56 |
|
| 57 |
self._command = Subcommand("duplicates", help=__doc__, aliases=["dup"]) |
| 58 |
self._command.parser.add_option( |
| 59 |
"-c", |
| 60 |
"--count", |
| 61 |
dest="count", |
| 62 |
action="store_true", |
| 63 |
help="show duplicate counts", |
| 64 |
) |
| 65 |
self._command.parser.add_option( |
| 66 |
"-C", |
| 67 |
"--checksum", |
| 68 |
dest="checksum", |
| 69 |
action="store", |
| 70 |
metavar="PROG", |
| 71 |
help="report duplicates based on arbitrary command", |
| 72 |
) |
| 73 |
self._command.parser.add_option( |
| 74 |
"-d", |
| 75 |
"--delete", |
| 76 |
dest="delete", |
| 77 |
action="store_true", |
| 78 |
help="delete items from library and disk", |
| 79 |
) |
| 80 |
self._command.parser.add_option( |
| 81 |
"-F", |
| 82 |
"--full", |
| 83 |
dest="full", |
| 84 |
action="store_true", |
| 85 |
help="show all versions of duplicate tracks or albums", |
| 86 |
) |
| 87 |
self._command.parser.add_option( |
| 88 |
"-s", |
| 89 |
"--strict", |
| 90 |
dest="strict", |
| 91 |
action="store_true", |
| 92 |
help="report duplicates only if all attributes are set", |
| 93 |
) |
| 94 |
self._command.parser.add_option( |
| 95 |
"-k", |
| 96 |
"--key", |
| 97 |
dest="keys", |
| 98 |
action="append", |
| 99 |
metavar="KEY", |
| 100 |
help="report duplicates based on keys (use multiple times)", |
| 101 |
) |
| 102 |
self._command.parser.add_option( |
| 103 |
"-M", |
| 104 |
"--merge", |
| 105 |
dest="merge", |
| 106 |
action="store_true", |
| 107 |
help="merge duplicate items", |
| 108 |
) |
| 109 |
self._command.parser.add_option( |
| 110 |
"-m", |
| 111 |
"--move", |
| 112 |
dest="move", |
| 113 |
action="store", |
| 114 |
metavar="DEST", |
| 115 |
help="move items to dest", |
| 116 |
) |
| 117 |
self._command.parser.add_option( |
| 118 |
"-o", |
| 119 |
"--copy", |
| 120 |
dest="copy", |
| 121 |
action="store", |
| 122 |
metavar="DEST", |
| 123 |
help="copy items to dest", |
| 124 |
) |
| 125 |
self._command.parser.add_option( |
| 126 |
"-t", |
| 127 |
"--tag", |
| 128 |
dest="tag", |
| 129 |
action="store", |
| 130 |
help="tag matched items with 'k=v' attribute", |
| 131 |
) |
| 132 |
self._command.parser.add_option( |
| 133 |
"-r", |
| 134 |
"--remove", |
| 135 |
dest="remove", |
| 136 |
action="store_true", |
| 137 |
help="remove items from library", |
| 138 |
) |
| 139 |
self._command.parser.add_all_common_options() |
| 140 |
|
| 141 |
def commands(self) -> list[Subcommand]: |
| 142 |
def _dup(lib: Library, opts: optparse.Values, args: list[str]) -> None: |
| 143 |
self.config.set_args(opts) |
| 144 |
keys = self.config["keys"].as_str_seq() |
| 145 |
|
| 146 |
if self.config["album"].get(bool): |
| 147 |
self._run_command( |
| 148 |
lib.albums(args), |
| 149 |
keys or ["mb_albumid"], |
| 150 |
"$albumartist - $album", |
| 151 |
merge_func=self._merge_albums, |
| 152 |
) |
| 153 |
else: |
| 154 |
self._run_command( |
| 155 |
lib.items(args), |
| 156 |
keys or ["mb_trackid", "mb_albumid"], |
| 157 |
"$albumartist - $album - $title", |
| 158 |
merge_func=self._merge_items, |
| 159 |
) |
| 160 |
|
| 161 |
self._command.func = _dup |
| 162 |
return [self._command] |
| 163 |
|
| 164 |
def _run_command( |
| 165 |
self, |
| 166 |
items: Sequence[AlbumOrItem], |
| 167 |
keys: list[str], |
| 168 |
fmt_tmpl_fallback: str, |
| 169 |
*, |
| 170 |
merge_func: Callable[[list[AlbumOrItem]], list[AlbumOrItem]], |
| 171 |
) -> None: |
| 172 |
"""Process one homogeneous set of duplicate candidates.""" |
| 173 |
checksum = self.config["checksum"].get(str) |
| 174 |
copy = bytestring_path(self.config["copy"].as_str()) |
| 175 |
count = self.config["count"].get(bool) |
| 176 |
delete = self.config["delete"].get(bool) |
| 177 |
remove = self.config["remove"].get(bool) |
| 178 |
fmt_tmpl = self.config["format"].get(str) |
| 179 |
full = self.config["full"].get(bool) |
| 180 |
merge = self.config["merge"].get(bool) |
| 181 |
move = bytestring_path(self.config["move"].as_str()) |
| 182 |
path = self.config["path"].get(bool) |
| 183 |
tiebreak = self.config["tiebreak"].get(dict) |
| 184 |
strict = self.config["strict"].get(bool) |
| 185 |
tag = self.config["tag"].get(str) |
| 186 |
|
| 187 |
# If there's nothing to do, return early. The code below assumes |
| 188 |
# `items` to be non-empty. |
| 189 |
if not items: |
| 190 |
return |
| 191 |
|
| 192 |
if path: |
| 193 |
fmt_tmpl = "$path" |
| 194 |
elif not fmt_tmpl: |
| 195 |
fmt_tmpl = fmt_tmpl_fallback |
| 196 |
|
| 197 |
if checksum: |
| 198 |
for i in items: |
| 199 |
k, _ = self._checksum(i, checksum) |
| 200 |
keys = [k] |
| 201 |
|
| 202 |
for obj_id, obj_count, objs in self._duplicates( |
| 203 |
items, |
| 204 |
keys=keys, |
| 205 |
full=full, |
| 206 |
strict=strict, |
| 207 |
tiebreak=tiebreak, |
| 208 |
merge_func=merge_func if merge else None, |
| 209 |
): |
| 210 |
if obj_id: # Skip empty IDs. |
| 211 |
for o in objs: |
| 212 |
self._process_item( |
| 213 |
o, |
| 214 |
copy=copy, |
| 215 |
move=move, |
| 216 |
delete=delete, |
| 217 |
remove=remove, |
| 218 |
tag=tag, |
| 219 |
fmt=( |
| 220 |
fmt_tmpl |
| 221 |
if not count |
| 222 |
else f"{fmt_tmpl}: {obj_count}" |
| 223 |
), |
| 224 |
) |
| 225 |
|
| 226 |
def _process_item( |
| 227 |
self, |
| 228 |
model: LibModel, |
| 229 |
*, |
| 230 |
copy: bytes, |
| 231 |
move: bytes, |
| 232 |
delete: bool, |
| 233 |
tag: str, |
| 234 |
fmt: str, |
| 235 |
remove: bool, |
| 236 |
) -> None: |
| 237 |
"""Process one library model.""" |
| 238 |
print_(format(model, fmt)) |
| 239 |
if copy: |
| 240 |
model.move(basedir=copy, operation=MoveOperation.COPY) |
| 241 |
model.store() |
| 242 |
if move: |
| 243 |
model.move(basedir=move) |
| 244 |
model.store() |
| 245 |
if delete: |
| 246 |
model.remove(delete=True) |
| 247 |
elif remove: |
| 248 |
model.remove(delete=False) |
| 249 |
if tag: |
| 250 |
try: |
| 251 |
k, v = tag.split("=") |
| 252 |
except Exception: |
| 253 |
raise UserError(f"{PLUGIN}: can't parse k=v tag: {tag}") |
| 254 |
setattr(model, k, v) |
| 255 |
model.store() |
| 256 |
|
| 257 |
def _checksum(self, model: LibModel, prog: str) -> tuple[str, Any]: |
| 258 |
"""Run external `prog` on file path associated with `model`, cache |
| 259 |
output as flexattr on a key that is the name of the program, and |
| 260 |
return the key, checksum tuple. |
| 261 |
""" |
| 262 |
args = [ |
| 263 |
p.format(file=os.fsdecode(model.path)) for p in shlex.split(prog) |
| 264 |
] |
| 265 |
key = args[0] |
| 266 |
checksum = getattr(model, key, False) |
| 267 |
if not checksum: |
| 268 |
self._log.debug( |
| 269 |
"key {} on model {.filepath} not cached:computing checksum", |
| 270 |
key, |
| 271 |
model, |
| 272 |
) |
| 273 |
try: |
| 274 |
checksum = command_output(args).stdout |
| 275 |
setattr(model, key, checksum) |
| 276 |
model.store() |
| 277 |
self._log.debug( |
| 278 |
"computed checksum for {.title} using {}", model, key |
| 279 |
) |
| 280 |
except subprocess.CalledProcessError as e: |
| 281 |
self._log.debug("failed to checksum {.filepath}: {}", model, e) |
| 282 |
else: |
| 283 |
self._log.debug( |
| 284 |
"key {} on item {.filepath} cached:not computing checksum", |
| 285 |
key, |
| 286 |
model, |
| 287 |
) |
| 288 |
return key, checksum |
| 289 |
|
| 290 |
def _group_by( |
| 291 |
self, objs: Sequence[AlbumOrItem], keys: Sequence[str], strict: bool |
| 292 |
) -> dict[tuple[Any, ...], list[AlbumOrItem]]: |
| 293 |
"""Return a dictionary with keys arbitrary concatenations of attributes |
| 294 |
and values lists of objects (Albums or Items) with those keys. |
| 295 |
|
| 296 |
If strict, all attributes must be defined for a duplicate match. |
| 297 |
""" |
| 298 |
import collections |
| 299 |
|
| 300 |
counts = collections.defaultdict(list) |
| 301 |
for obj in objs: |
| 302 |
values = [getattr(obj, k, None) for k in keys] |
| 303 |
values = [v for v in values if v not in (None, "")] |
| 304 |
if strict and len(values) < len(keys): |
| 305 |
self._log.debug( |
| 306 |
"some keys {} on item {.filepath} are null or empty: skipping", |
| 307 |
keys, |
| 308 |
obj, |
| 309 |
) |
| 310 |
elif not strict and not len(values): |
| 311 |
self._log.debug( |
| 312 |
"all keys {} on item {.filepath} are null or empty: skipping", |
| 313 |
keys, |
| 314 |
obj, |
| 315 |
) |
| 316 |
else: |
| 317 |
key = tuple(values) |
| 318 |
counts[key].append(obj) |
| 319 |
|
| 320 |
return counts |
| 321 |
|
| 322 |
def _order( |
| 323 |
self, |
| 324 |
objs: Sequence[AlbumOrItem], |
| 325 |
tiebreak: dict[str, list[str]] | None = None, |
| 326 |
) -> list[AlbumOrItem]: |
| 327 |
"""Return the objects (Items or Albums) sorted by descending |
| 328 |
order of priority. |
| 329 |
|
| 330 |
If provided, the `tiebreak` dict indicates the field to use to |
| 331 |
prioritize the objects. Otherwise, Items are placed in order of |
| 332 |
"completeness" (objects with more non-null fields come first) |
| 333 |
and Albums are ordered by their track count. |
| 334 |
""" |
| 335 |
kind = "items" if all(isinstance(o, Item) for o in objs) else "albums" |
| 336 |
|
| 337 |
sort = partial(sorted, reverse=True) |
| 338 |
if tiebreak and kind in tiebreak.keys(): |
| 339 |
return sort( |
| 340 |
objs, key=lambda x: tuple(getattr(x, k) for k in tiebreak[kind]) |
| 341 |
) |
| 342 |
if kind == "items": |
| 343 |
|
| 344 |
def truthy(v: object) -> bool: |
| 345 |
# Avoid a Unicode warning by avoiding comparison |
| 346 |
# between a bytes object and the empty Unicode |
| 347 |
# string ''. |
| 348 |
return v is not None and ( |
| 349 |
v != "" if isinstance(v, str) else True |
| 350 |
) |
| 351 |
|
| 352 |
fields = Item.all_keys() |
| 353 |
|
| 354 |
return sort( |
| 355 |
objs, |
| 356 |
key=lambda x: sum(1 for f in fields if truthy(getattr(x, f))), |
| 357 |
) |
| 358 |
return sort(objs, key=lambda x: len(x.items())) |
| 359 |
|
| 360 |
def _merge_items(self, objs: list[Item]) -> list[Item]: |
| 361 |
"""Merge Item objs by copying missing fields from items in the tail to |
| 362 |
the head item. |
| 363 |
|
| 364 |
Return same number of items, with the head item modified. |
| 365 |
""" |
| 366 |
fields = Item.all_keys() |
| 367 |
for f in fields: |
| 368 |
for o in objs[1:]: |
| 369 |
if getattr(objs[0], f, None) in (None, ""): |
| 370 |
value = getattr(o, f, None) |
| 371 |
if value: |
| 372 |
self._log.debug( |
| 373 |
"key {} on item {} is null " |
| 374 |
"or empty: setting from item {.filepath}", |
| 375 |
f, |
| 376 |
displayable_path(objs[0].path), |
| 377 |
o, |
| 378 |
) |
| 379 |
setattr(objs[0], f, value) |
| 380 |
objs[0].store() |
| 381 |
break |
| 382 |
return objs |
| 383 |
|
| 384 |
def _merge_albums(self, objs: list[Album]) -> list[Album]: |
| 385 |
"""Merge Album objs by copying missing items from albums in the tail |
| 386 |
to the head album. |
| 387 |
|
| 388 |
Return same number of albums, with the head album modified.""" |
| 389 |
ids = [i.mb_trackid for i in objs[0].items()] |
| 390 |
for o in objs[1:]: |
| 391 |
for i in o.items(): |
| 392 |
if i.mb_trackid not in ids: |
| 393 |
missing = Item.from_path(i.path) |
| 394 |
missing.album_id = objs[0].id |
| 395 |
missing.add(i._db) |
| 396 |
self._log.debug( |
| 397 |
"item {} missing from album {}:" |
| 398 |
" merging from {.filepath} into {}", |
| 399 |
missing, |
| 400 |
objs[0], |
| 401 |
o, |
| 402 |
displayable_path(missing.destination()), |
| 403 |
) |
| 404 |
missing.move(operation=MoveOperation.COPY) |
| 405 |
return objs |
| 406 |
|
| 407 |
def _duplicates( |
| 408 |
self, |
| 409 |
objs: Sequence[AlbumOrItem], |
| 410 |
keys: Sequence[str], |
| 411 |
full: bool, |
| 412 |
strict: bool, |
| 413 |
tiebreak: dict[str, list[str]] | None, |
| 414 |
merge_func: Callable[[list[AlbumOrItem]], list[AlbumOrItem]] | None, |
| 415 |
) -> Iterator[tuple[tuple[Any, ...], int, Sequence[AlbumOrItem]]]: |
| 416 |
"""Generate triples of keys, duplicate counts, and constituent objects.""" |
| 417 |
offset = 0 if full else 1 |
| 418 |
for k, objs in self._group_by(objs, keys, strict).items(): |
| 419 |
if len(objs) > 1: |
| 420 |
objs = self._order(objs, tiebreak) |
| 421 |
if merge_func: |
| 422 |
objs = merge_func(objs) |
| 423 |
yield (k, len(objs) - offset, objs[offset:]) |