audiogen_randomdir.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import os
  2. import logging
  3. import shutil
  4. import random
  5. from tempfile import mkstemp
  6. from larigira.fsutils import scan_dir
  7. def generate(spec):
  8. '''
  9. resolves audiospec-randomdir
  10. Recognized arguments:
  11. - paths [mandatory] list of source paths
  12. - howmany [default=1] number of audio files to pick
  13. '''
  14. spec.setdefault('howmany', 1)
  15. for attr in ('paths', ):
  16. if attr not in spec:
  17. raise ValueError("Malformed audiospec: missing '%s'" % attr)
  18. found_files = set()
  19. for path in spec['paths']:
  20. if not os.path.exists(path):
  21. logging.warning("Can't find requested path: %s", path)
  22. continue
  23. if os.path.isfile(path):
  24. found_files.add(path)
  25. elif os.path.isdir(path):
  26. found_files.update(scan_dir(path))
  27. picked = random.sample(found_files, int(spec['howmany']))
  28. for path in picked:
  29. tmp = mkstemp(suffix=os.path.splitext(path)[-1],
  30. prefix='audiogen-randomdir-')
  31. os.close(tmp[0])
  32. shutil.copy(path, tmp[1])
  33. yield 'file://{}'.format(tmp[1])
  34. generate.description = 'Picks random files from a specified directory'