DeaD_EyE

random_video_thumbnail.py

Dec 21st, 2019
82
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/env python3
  2.  
  3. """
  4. Searches for video files and generate a random picture from video.
  5.  
  6. ffmpeg is required
  7. """
  8.  
  9. import random
  10. from pathlib import Path
  11. from subprocess import Popen, DEVNULL, PIPE
  12.  
  13.  
  14. def thumbnail(video):
  15.     picture = video.with_suffix('.jpg')
  16.     picture.unlink(missing_ok=True)
  17.     duration = Popen(
  18.         [
  19.             'ffprobe', '-show_entries', 'format=duration',
  20.             '-of', 'default=noprint_wrappers=1:nokey=1',
  21.             '-i', video
  22.         ],
  23.         encoding='utf8',
  24.         stderr=DEVNULL,
  25.         stdout=PIPE).communicate()[0]
  26.     rnd_duration = random.random() * float(duration)
  27.     mm, ss = divmod(rnd_duration, 60)
  28.     hh, mm = divmod(mm, 60)
  29.     seek = f'{hh:.0f}:{mm:.0f}:{ss:.3f}'
  30.     Popen(
  31.         [
  32.            'ffmpeg', '-ss', seek, '-i', video,
  33.            '-frames:v', '1',
  34.            str(picture),
  35.         ],
  36.         stderr=DEVNULL,
  37.         stdout=DEVNULL).wait()
  38.     return picture
  39.  
  40.  
  41. def make_thumbnails(root, extensions, recursive=False):
  42.     if recursive:
  43.         ext_gen = (root.rglob(f'*.{ext}') for ext in set(extensions))
  44.     else:
  45.         ext_gen = (root.glob(f'*.{ext}') for ext in set(extensions))
  46.     for ext in ext_gen:
  47.         for video in ext:
  48.             picture = thumbnail(video)
  49.             if picture.exists():
  50.                 yield picture
  51.  
  52.  
  53. if __name__ == '__main__':
  54.     import shutil
  55.     from argparse import ArgumentParser
  56.     from argparse import ArgumentDefaultsHelpFormatter
  57.     if not shutil.which('ffmpeg'):
  58.         raise SystemExit('ffmpeg not found on your system')
  59.     default_ext = 'mkv'
  60.     available_exts = ('mkv', 'avi', 'mp4', 'ogg', 'mpg')
  61.     parser = ArgumentParser(description=__doc__, formatter_class=ArgumentDefaultsHelpFormatter)
  62.     parser.add_argument('root', type=Path, help='Root directory to search')
  63.     parser.add_argument('-r', '--recursive', action='store_true', help='Recursive')
  64.     parser.add_argument(
  65.         '--extensions', nargs='+',
  66.         choices=available_exts,
  67.         default=[default_ext],
  68.         help='File extensions of videos')
  69.     args = parser.parse_args()
  70.     for picture in make_thumbnails(**vars(args)):
  71.         print(picture)
RAW Paste Data