audiogen_randomdir.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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', spec.eid)
  34. for path in picked:
  35. tmp = mkstemp(suffix=os.path.splitext(path)[-1],
  36. prefix='randomdir-%s-%s-' % (shortname(nick),
  37. shortname(path)))
  38. os.close(tmp[0])
  39. shutil.copy(path, tmp[1])
  40. log.info("copying %s -> %s", path, os.path.basename(tmp[1]))
  41. yield 'file://{}'.format(tmp[1])
  42. generate.description = 'Picks random files from a specified directory'