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