audiogen_mpdrandom.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import logging
  2. import random
  3. from mpd import MPDClient
  4. from .config import get_conf
  5. log = logging.getLogger(__name__)
  6. def generate_by_artist(spec):
  7. """Choose HOWMANY random artists, and for each one choose a random song."""
  8. spec.setdefault("howmany", 1)
  9. prefix = spec.get("prefix", "").rstrip("/")
  10. log.info("generating")
  11. conf = get_conf()
  12. c = MPDClient(use_unicode=True)
  13. c.connect(conf["MPD_HOST"], conf["MPD_PORT"])
  14. if prefix:
  15. # TODO: listallinfo is discouraged.
  16. # how else could we achieve the same result?
  17. artists = list(
  18. {r["artist"] for r in c.listallinfo(prefix) if "artist" in r}
  19. )
  20. else:
  21. artists = c.list("artist")
  22. if not artists:
  23. raise ValueError("no artists in your mpd database")
  24. for _ in range(spec["howmany"]):
  25. artist = random.choice(artists) # pick one artist
  26. if type(artist) is not str:
  27. # different mpd library versions have different behavior
  28. artist = artist['artist']
  29. # pick one song from that artist
  30. artist_songs = (res["file"] for res in c.find("artist", artist))
  31. if prefix:
  32. artist_songs = [
  33. fname
  34. for fname in artist_songs
  35. if fname.startswith(prefix + "/")
  36. ]
  37. yield random.choice(list(artist_songs))