Delete Duplicates In MPD Playlist

This is a quick hack in python3 to prune duplicates in the active mpd playlist.
It looks for duplicates by filename. Requires mpc to be installed and respects MPD_HOST and MPD_PORT environment variables.

Sidenote: This is one of my very first python scripts. I am pretty sure this can be done much smarter in python but i am not that skilled yet in that language. So please feel free to improve it. Feedback of any kind is highly appreciated.

#!/usr/bin/python
 
import subprocess
 
data = dict()
delpos = list()
 
p = subprocess.Popen(["/usr/bin/mpc", "-f", "%position% %file%", "playlist"], shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in p.stdout:
 line = line.decode("utf-8")
 line = line.rstrip('\n');
 position, filename = line.split(" ", 1);
 data.setdefault(filename,[]).append(position)
 
for key in data:
 poslen = len(data[key])
 if poslen <= 1: continue
 print("Will delete:", poslen-1, "time(s)", key)
 iterpos = iter(data[key])
 next(iterpos)
 for pos in iterpos:
  delpos.append(pos)
 
delpos = list(map(int, delpos))
delpos.sort(reverse=True)
 
for item in delpos:
 p = subprocess.Popen(["/usr/bin/mpc", "del", str(item)], shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

Usage

Copy and paste the code to some file: e.g: /usr/local/bin/mpddeldup.py
Run it like that:

MPD_HOST="yourpass@yourhost" MPD_PORT="6600" /usr/local/bin/mpddeldups.py

Leave a Reply

Your email address will not be published / Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.