audiogen_mostrecent.py 2.0 KB

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