audiogen_mpdrandom.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  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. how else could we achieve the same result?
  16. artists = list(
  17. {r["artist"] for r in c.listallinfo(prefix) if "artist" in r}
  18. )
  19. else:
  20. artists = c.list("artist")
  21. if not artists:
  22. raise ValueError("no artists in your mpd database")
  23. for _ in range(spec["howmany"]):
  24. artist = random.choice(artists) # pick one artist
  25. # pick one song from that artist
  26. artist_songs = (res["file"] for res in c.find("artist", artist))
  27. if prefix:
  28. artist_songs = [
  29. fname
  30. for fname in artist_songs
  31. if fname.startswith(prefix + "/")
  32. ]
  33. yield random.choice(list(artist_songs))