audiogen_randomdir.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import os
  2. import logging
  3. import shutil
  4. import random
  5. from tempfile import mkstemp
  6. from pathlib import Path
  7. from larigira.fsutils import scan_dir_audio, shortname, is_audio
  8. log = logging.getLogger(__name__)
  9. def candidates(paths):
  10. c = set()
  11. for path in paths:
  12. if not path.exists():
  13. log.warning("Can't find requested path: %s", path)
  14. continue
  15. if path.is_file() and is_audio(str(path)):
  16. c.add(str(path))
  17. elif path.is_dir():
  18. c.update(scan_dir_audio(str(path)))
  19. return c
  20. def generate(spec):
  21. """
  22. resolves audiospec-randomdir
  23. Recognized arguments:
  24. - paths [mandatory] list of source paths
  25. - howmany [default=1] number of audio files to pick
  26. """
  27. spec.setdefault("howmany", 1)
  28. for attr in ("paths",):
  29. if attr not in spec:
  30. raise ValueError("Malformed audiospec: missing '%s'" % attr)
  31. found_files = candidates([Path(p) for p in spec["paths"]])
  32. picked = random.sample(found_files, int(spec["howmany"]))
  33. nick = spec.get("nick", "")
  34. if not nick:
  35. if hasattr(spec, "eid"):
  36. nick = spec.eid
  37. else:
  38. nick = "NONICK"
  39. for path in picked:
  40. tmp = mkstemp(
  41. suffix=os.path.splitext(path)[-1],
  42. prefix="randomdir-%s-%s-" % (shortname(nick), shortname(path)),
  43. )
  44. os.close(tmp[0])
  45. shutil.copy(path, tmp[1])
  46. log.info("copying %s -> %s", path, os.path.basename(tmp[1]))
  47. yield "file://{}".format(tmp[1])
  48. generate.description = "Picks random files from a specified directory"