Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- """
- Searches for video files and generate a random picture from video.
- ffmpeg is required
- """
- import random
- from pathlib import Path
- from subprocess import Popen, DEVNULL, PIPE
- def thumbnail(video):
- picture = video.with_suffix('.jpg')
- picture.unlink(missing_ok=True)
- duration = Popen(
- [
- 'ffprobe', '-show_entries', 'format=duration',
- '-of', 'default=noprint_wrappers=1:nokey=1',
- '-i', video
- ],
- encoding='utf8',
- stderr=DEVNULL,
- stdout=PIPE).communicate()[0]
- rnd_duration = random.random() * float(duration)
- mm, ss = divmod(rnd_duration, 60)
- hh, mm = divmod(mm, 60)
- seek = f'{hh:.0f}:{mm:.0f}:{ss:.3f}'
- Popen(
- [
- 'ffmpeg', '-ss', seek, '-i', video,
- '-frames:v', '1',
- str(picture),
- ],
- stderr=DEVNULL,
- stdout=DEVNULL).wait()
- return picture
- def make_thumbnails(root, extensions, recursive=False):
- if recursive:
- ext_gen = (root.rglob(f'*.{ext}') for ext in set(extensions))
- else:
- ext_gen = (root.glob(f'*.{ext}') for ext in set(extensions))
- for ext in ext_gen:
- for video in ext:
- picture = thumbnail(video)
- if picture.exists():
- yield picture
- if __name__ == '__main__':
- import shutil
- from argparse import ArgumentParser
- from argparse import ArgumentDefaultsHelpFormatter
- if not shutil.which('ffmpeg'):
- raise SystemExit('ffmpeg not found on your system')
- default_ext = 'mkv'
- available_exts = ('mkv', 'avi', 'mp4', 'ogg', 'mpg')
- parser = ArgumentParser(description=__doc__, formatter_class=ArgumentDefaultsHelpFormatter)
- parser.add_argument('root', type=Path, help='Root directory to search')
- parser.add_argument('-r', '--recursive', action='store_true', help='Recursive')
- parser.add_argument(
- '--extensions', nargs='+',
- choices=available_exts,
- default=[default_ext],
- help='File extensions of videos')
- args = parser.parse_args()
- for picture in make_thumbnails(**vars(args)):
- print(picture)
Add Comment
Please, Sign In to add comment