audiogen_mostrecent.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import os
  2. import logging
  3. import shutil
  4. import time
  5. from tempfile import mkstemp
  6. from pytimeparse.timeparse import timeparse
  7. from larigira.fsutils import scan_dir, shortname
  8. log = logging.getLogger(__name__)
  9. def get_mtime(fname):
  10. return int(os.path.getmtime(fname))
  11. def recent_choose(paths, howmany, minepoch):
  12. found_files = {}
  13. for path in paths:
  14. if not os.path.exists(path):
  15. log.warning("Can't find requested path: %s", path)
  16. continue
  17. if os.path.isfile(path):
  18. found_files[path] = get_mtime(path)
  19. elif os.path.isdir(path):
  20. found_files.update({fname: get_mtime(fname)
  21. for fname in scan_dir(path)})
  22. found_files = [(fname, mtime)
  23. for (fname, mtime) in found_files.items()
  24. if mtime >= minepoch]
  25. return [fname for fname, mtime in
  26. sorted(found_files, key=lambda x: x[1])[:howmany]]
  27. def generate(spec):
  28. '''
  29. resolves audiospec-randomdir
  30. Recognized arguments:
  31. - path [mandatory] source dir
  32. - maxage [default=ignored] max age of audio files to pick
  33. '''
  34. for attr in ('path', 'maxage'):
  35. if attr not in spec:
  36. raise ValueError("Malformed audiospec: missing '%s'" % attr)
  37. if spec['maxage'].strip():
  38. try:
  39. maxage = int(spec['maxage'])
  40. except ValueError:
  41. maxage = timeparse(spec['maxage'])
  42. if maxage is None:
  43. raise ValueError("Unknown format for maxage: '{}'"
  44. .format(spec['maxage']))
  45. assert type(maxage) is int
  46. else:
  47. maxage = None
  48. now = int(time.time())
  49. minepoch = 0 if maxage is None else now - maxage
  50. picked = recent_choose([spec['path']], 1, minepoch)
  51. for path in picked:
  52. tmp = mkstemp(suffix=os.path.splitext(path)[-1],
  53. prefix='randomdir-%s-' % shortname(path))
  54. os.close(tmp[0])
  55. shutil.copy(path, tmp[1])
  56. log.info("copying %s -> %s", path, os.path.basename(tmp[1]))
  57. yield 'file://{}'.format(tmp[1])
  58. generate.description = 'Select most recent file inside a directory'