import os
import shutil
import random
import Image

class extract(object):
    def __init__(self, path, fps = None, size = None):
        self.key = int(random.random() * 1000000000)
        self.key = "pyvision-ffmpeg-{0}".format(self.key)
        self.output = "/tmp/{0}".format(self.key)
        self.path = path
        try:
            os.makedirs(self.output) 
        except:
            pass

        cmd = "ffmpeg -i {0} -b 10000k".format(path)
        if fps:
            cmd = "{0} -r {1}".format(cmd, int(fps))
        if size:
            w, h = size
            cmd = "{0} -s {1}x{2}".format(cmd, int(w), int(h))
        os.system("{0} {1}/%d.jpg".format(cmd, self.output))

    def __del__(self):
        if self.output:
            shutil.rmtree(self.output)

    def __getitem__(self, k):
        return Image.open(self.getframepath(k))

    def getframepath(self, k):
        return "{0}/{1}.jpg".format(self.output, k+1)

    def __len__(self):
        f = 1
        while True:
            if not os.path.exists(self.getframepath(f)):
                return f
            f += 1

    def __iter__(self):
        for i in range(len(self)):
            yield self[i]

import os
import shutil
import random
import Image
import subprocess, re

class extract(object):
    def __init__(self, path, fps = None, size = None):
        self.key = int(random.random() * 1000000000)
        self.key = "pyvision-ffmpeg-{0}".format(self.key)
        self.output = "/tmp/{0}".format(self.key)
        self.path = path
        try:
            os.makedirs(self.output)
        except:
            pass

        cmd = "ffmpeg -i {0} -b 10000k".format(path)
        if fps:
            cmd = "{0} -r {1}".format(cmd, int(fps))
        if size:
            w, h = size
            cmd = "{0} -s {1}x{2}".format(cmd, int(w), int(h))
        os.system("{0} {1}/%d.jpg".format(cmd, self.output))

    def __del__(self):
        if self.output:
            shutil.rmtree(self.output)

    def __getitem__(self, k):
        return Image.open(self.getframepath(k))

    def getframepath(self, k):
        return "{0}/{1}.jpg".format(self.output, k+1)

    def __len__(self):
        f = 1
        while True:
            if not os.path.exists(self.getframepath(f)):
                return f
            f += 1

    def __iter__(self):
        for i in range(len(self)):
            yield self[i]

class info:
    def get_size(self, path):
        pattern = re.compile(r'Stream.*Video.* (\d+)x(\d+)')
        p = subprocess.Popen(['ffmpeg', '-i', path], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        stdout, stderr = p.communicate()
        match = pattern.search(stderr)
        if match:
            # print match.groups()
            x, y = map(int, match.groups()[0:2])
        else:
            x = y = 0
        return x, y

add get_size to ffmpeg, credit @dreamdragon