audiogen_randomdir.py 1.3 KB

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