audiogen_randomdir.py 1.4 KB

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