Beispiel #1
0
def search(dirname):
    try:
        filenames = os.listdir(dirname)
        for filename in filenames:
            if dirname[-1] == "/":
                pass
            else:
                dirname = dirname + "/"
            full_path = os.path.join(dirname, filename)
            if os.path.isdir(full_path):
                search(full_path)
            else:

                ext = os.path.splitext(full_path)[-1]
                thum = "%s_" % (datetime.today().strftime('%Y%m%d')) + str(
                    uuid.uuid4())[:8] + ".jpg"
                small_thum_path = "/DATA/reference_library/thumnail/small_thum/%s" % thum

                if ext.lower() == ".mp4" or ext.lower() == ".mov" or ext.lower(
                ) == ".mkv" or ext.lower() == ".avi" or ext.lower() == ".webm":

                    try:
                        duration = int(VideoStream(full_path).duration / 2)
                        thumbnail = VideoStream(full_path).get_frame_at_sec(
                            duration).image()
                        thumbnail.save(small_thum_path)
                    except Exception, e:
                        print e

                    select_query = 'select * from img where full_path = "%s"' % full_path

                    cur.execute("set names utf8")
                    cur.execute(select_query)

                    if cur.rowcount == 0:
                        try:
                            codec = VideoStream(full_path).codec_name
                            if codec == "h264" or codec == "aac":
                                full_path = full_path[5:]
                                query_o = 'insert into img(img_path,img_name,full_path,thumnail,type) values("%s","%s","%s","%s","%s")' % (
                                    dirname, filename, full_path, thum,
                                    'video')
                                cur.execute("set names utf8")
                                cur.execute(query_o)
                                db.commit()

                            else:
                                full_path = full_path[5:]
                                query = 'insert into img(img_path,img_name,full_path,thumnail,type) values("%s","%s","%s","%s","%s")' % (
                                    dirname, filename, full_path, 'codec.png',
                                    'video')
                                cur.execute("set names utf8")
                                cur.execute(query)
                                db.commit()

                        except Exception, e:
                            pass
                    else:
                        pass
                else:
Beispiel #2
0
def test_videoinfo():
    from ffvideo import VideoStream

    vs = VideoStream(v0)
    assert vs.duration == 15.987
    assert vs.width == vs.frame_width
    assert vs.height == vs.frame_height
    assert vs.width == 320
    assert vs.height == 240
    assert vs.codec_name == 'flv'
    assert vs.frame_mode == 'RGB'

    vs = VideoStream(v0, frame_size=(128, 128), frame_mode='L')
    assert vs.width != vs.frame_width
    assert vs.frame_width == 128
    assert vs.frame_height == 128
    assert vs.frame_mode == 'L'

    vs = VideoStream(v0, frame_size=(129, None), frame_mode='L')
    #    raise AssertionError, "(%d, %d)" % (vs.frame_width, vs.frame_height)
    assert vs.width != vs.frame_width
    assert vs.height != vs.frame_height

    assert vs.frame_width == 130
    assert vs.frame_height == 96
Beispiel #3
0
def verify_file(orig_filename, filename):
    name, ext = os.path.splitext(orig_filename)
    ext = ext.lower()
    if ext in ('.jpg', '.jpeg'):
        im = Image.open(filename)
        w, h = im.size
        if w > 1920 or h > 1080:
            raise AssetError("image too big: %dx%d" % (w, h))
        if w < 128 or h < 128:
            raise AssetError("image too small: %dx%d" % (w, h))
        if im.mode != 'RGB':
            raise AssetError("invalid image mode: %s" % im.mode)
        return Asset.TYPE_IMAGE, make_thumb(im)
    elif ext in ('.mp4', ):
        vs = VideoStream(filename)
        if vs.codec_name != 'h264':
            raise AssetError("invalid codec %s" % (vs.codec_name, ))
        w, h = vs.frame_width, vs.frame_height
        duration = vs.duration
        log.info("video info: %dx%d (%fs)" % (w, h, duration))
        if w > 1920 or h > 1080:
            raise AssetError("video too big: %dx%d" % (w, h))
        if w < 128 or h < 128:
            raise AssetError("video too small: %dx%d" % (w, h))
        if duration < 1:
            raise AssetError("video too short: %fs" % (duration, ))
        if duration > 10.5:
            raise AssetError("video too long: %fs" % (duration, ))
        frame = vs.get_frame_no(3)
        im = frame.image()
        return Asset.TYPE_VIDEO, make_thumb(im)
    else:
        raise AssetError("invalid asset file extension")
    def create(file):
        video_name = file.filename
        ext = video_name.rsplit('.', 1)[1].lower()
        if '.' in video_name and ext in VIDEO_EXTS:
            gene_name = str(uuid.uuid4())
            new_video_name = gene_name + '.' + ext
            address = os.path.join('video', new_video_name)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], address))

            screenshot_name = gene_name + '.jpeg'
            screenshot_address = os.path.join('video', 'screenshot',
                                              screenshot_name)
            screenshot = VideoStream(
                os.path.join(app.config['UPLOAD_FOLDER'],
                             address)).get_frame_at_sec(2).image()
            screenshot.save(
                os.path.join(app.config['UPLOAD_FOLDER'], screenshot_address))

            db = mysql.get_db()
            cursor = db.cursor()
            cursor.execute(
                "insert into video (name, address, screenshot) "
                "values (%s, %s, %s)",
                (video_name, address, screenshot_address))
            db.commit()
            if cursor.rowcount != 1:
                return False, 'insert into db failed'

            return True, cursor.lastrowid
        else:
            return False, 'invalid extension'
Beispiel #5
0
 def getVideoProperties(videoFile):
     if ModuleTools.INSTALLED_FFVIDEO():
         from ffvideo import VideoStream
         s = VideoStream(videoFile)
         return s.width, s.height, s.bitrate, s.duration  #, s.codec_name
     else:
         logger.warn("Python ffvideo library not installed")
Beispiel #6
0
def set_duration_video(sender, instance, **kwargs):
    if instance.file_video:
        video_stream = VideoStream(instance.file_video.path_full)
        seconds = int(video_stream.duration)
        instance.prolongation = datetime.time(hour=seconds / 3600,
                                              minute=seconds / 60,
                                              second=seconds % 60)
    def getRandomFrame(self, pathList, info=False, frameMode='L'):
        """
        returns the first frame from a random video of the list

        Args:
            pathList (List of Strings):
                                paths to video files
            info (bool):
                                return frame and filename
            frameMode (String):
                                Switch of color mode:

                                - 'RGB': color representation
                                - 'L':   gray-scale representation
                                - 'F':   ???

        Returns:
            frame (ndarray):
                                decoded video frame
        """
        file = pathList[random.randint(0, len(pathList) - 1)]
        frameNo = random.randint(0, 1600 - 1)

        if self.verbose:
            print "processing frame {0} of video {1}".format(frameNo, file)

        self.vs = VideoStream(file, frame_mode=frameMode, exact_seek=True)
        self.frameMode = frameMode

        frame = self.vs.next().ndarray()

        if info:
            return [frame, file]
        else:
            return frame
    def setVideoStream(self, file, info=False, frameMode='L'):
        """
        returns the first frame from a random video of the list
        
        Args:
            pathList (List of Strings):
                                paths to video files
            info (bool):
                                return frame and filename
            frameMode (String):
                                Switch of color mode:
                                
                                - 'RGB': color representation
                                - 'L':   gray-scale representation
                                - 'F':   ???
            
        Returns:
            frame (ndarray):
                                decoded video frame
        """
        frameNo = random.randint(0, 1600 - 1)

        if self.verbose:
            print "processing frame {0} of video {1}".format(frameNo, file)

        if not self.frame is None:
            del self.frame

        if not self.vs is None:
            del self.vs

        self.vs = VideoStream(file, frame_mode=frameMode, exact_seek=True)
        self.frameMode = frameMode
Beispiel #9
0
    def __init__(self, input_video_path, output_path, frame_step, resize_factor=2):
        self.input_video_path = input_video_path
        self.output_path = output_path
        self.frame_step = frame_step
        self.resize_factor = resize_factor

        self.vs = VideoStream(input_video_path)
        # self.duration = self.vs.duration
        self.total_frames = int(self.vs.duration * self.vs.framerate)
Beispiel #10
0
def create_thumbmail(filename, imagename):
    vs = VideoStream(filename,
                     # frame_size=(128, None),  # scale to width 128px
                     # frame_mode='L' # convert to grayscale
                     )
    image_name = imagename.split('.')[0]
    frame = vs.get_frame_at_sec(10)
    img = frame.image()
    img = img.resize((300,300))
    img.save('{0}.jpeg'.format(image_name))
Beispiel #11
0
 def generatePreviewFromVideo(videoFile):
     if ModuleTools.INSTALLED_FFVIDEO():
         from ffvideo import VideoStream
         fd, path = tempfile.mkstemp('.jpg')
         stream = VideoStream(videoFile)
         stream.get_frame_at_sec(0).image().save(path)
         preview = ImageTools.generatePreviewFromImage(path)
         os.remove(path)
         return preview
     else:
         logger.warn("Python ffvideo library not installed")
Beispiel #12
0
    def thumbnail(self):
        filename = STATIC_DIR + self.hash + '.png'
        try:
            open(filename)
        except:
            logger.debug("Generating new thumbnail.")

            pil_image = VideoStream(self.full_path)\
                .get_frame_at_sec(60).image()
            pil_image.save(filename)

        return filename
Beispiel #13
0
def video_upload():
    path = '/usr/local/nginx/Videos/vod'
    category = request.forms.get('category')
    upload = request.files.get('upload')

    upload.save(path)  # appends upload.filename automatically
    #create thumbnail
    thumbnail = VideoStream(path + '/' +
                            str(upload.filename)).get_frame_at_sec(3).image()
    thumbnail.save('./index/static/images/thumbnails/' +
                   str(upload.filename).replace('.flv', '') + '.jpeg')
    #run transcode module
    subprocess.call('cd ' + path + ' && ' + './transcode.sh ' +
                    str(upload.filename) + ' ' +
                    str(upload.filename).replace('.flv', ''),
                    shell=True)
    redirect("/home")
Beispiel #14
0
def test_open():
    from ffvideo import VideoStream, DecoderError, FAST_BILINEAR, BILINEAR
    try:
        VideoStream('non-existing-file')
    except DecoderError:
        pass
    else:
        raise AssertionError, "expected IOError"

    try:
        VideoStream('tests/test_ffvideo.py')
    except DecoderError:
        pass
    else:
        raise AssertionError, "expected DecodeError"

    VideoStream(v0)
    VideoStream(v0, frame_size=(128, 128), frame_mode='L')
    VideoStream(v0, frame_size=(None, 128), frame_mode='L')
    VideoStream(v0,
                frame_size=(None, 128),
                frame_mode='L',
                scale_mode=BILINEAR)
    VideoStream(v0, scale_mode=FAST_BILINEAR, frame_size=(None, 128))

    try:
        VideoStream(v0, frame_size=(None, 128, 33), frame_mode='L')
    except ValueError:
        pass
    else:
        raise AssertionErrror, "expected ValueError"

    try:
        VideoStream(v0, frame_size=344, frame_mode='L')
    except ValueError:
        pass
    else:
        raise AssertionErrror, "expected ValueError"
Beispiel #15
0
def search(dirname):
    try:
        filenames = os.listdir(dirname)
        for filename in filenames:
            if dirname[-1] == "/":
                pass
            else:
                dirname = dirname + "/"
            full_path = os.path.join(dirname, filename)
            if os.path.isdir(full_path):
                search(full_path)
            else:
                ext = os.path.splitext(full_path)[-1]
                thum = "%s_" % (datetime.today().strftime('%Y%m%d')) + str(
                    uuid.uuid4())[:8] + ".jpg"
                small_thum_path = "/DATA/reference_library/thumnail/small_thum/%s" % thum

                if ext.lower() == ".mp4" or ext.lower() == ".mov" or ext.lower(
                ) == ".mkv" or ext.lower() == ".avi":

                    try:
                        thumbnail = VideoStream(full_path).get_frame_at_sec(
                            1).image()
                        thumbnail.save(small_thum_path)

                        full_path = full_path[5:]

                        select_query = "select * from img where full_path = '%s'" % full_path
                        cur.execute("set names utf8")
                        cur.execute(select_query)
                        if cur.rowcount == 0:
                            query = "insert into img(img_path,img_name,full_path,thumnail,type) values('%s','%s','%s','%s','%s')" % (
                                dirname, filename, full_path, thum, 'video')
                            cur.execute("set names utf8")
                            cur.execute(query)
                            db.commit()
                        else:
                            pass

                    except Exception, e:
                        print e

                else:
                    pass
Beispiel #16
0
    def setMovie(self, fileName):
        """Open a video file.
        
        :param filename: a string containing the name of the file to be opened.
            
        :raise: TypeError: The fileName is not a string.
        """
        if (isinstance(fileName, basestring)):
            self.fileName = u''.join(fileName).encode('utf-8')
            self.source = VideoStream(self.fileName)
        else:
            raise TypeError('fileName must be a string')

        self.frameRate = self.source.framerate
        self.frameNumber = self.source.duration * 1000 / self.source.framerate
        self.timer = QtCore.QTimer()
        self.timer.setInterval(1000.0 / self.frameRate)
        self.timer.setSingleShot(False)
        self.timer.timeout.connect(self.frameMustChange)
Beispiel #17
0
    def update_thumbnail(self, commit=False):
        """Generates the thumbnail for video and image resources

		:param commit: States whether to perform self.save() at the end of this method
		:type commit: bool
		"""
        if not self.mime_type:
            self.update_mimetype()

        if self.mime_type.startswith('video'):
            # FIXME: There's a problem with seeking in ogg files
            s = VideoStream(self.file.path)
            i = s.get_frame_at_sec(1).image()
            self._set_thumbnail(i)
        elif self.mime_type.startswith('image'):
            i = Image.open(self.file.path)
            self._set_thumbnail(i)
        # TODO/FEATUE: possibly create a soundwave thumbnail out of the audio files

        if commit:
            self.save()
Beispiel #18
0
def convert():
    from videolearn.models import Vlesson
    from subprocess import call
    import subprocess
    from ffvideo import VideoStream
    from django.core.files import File
    from co.settings import BASE_DIR
    for v in Vlesson.objects.filter(is_converted=False):
        ex = 'avconv -i %s -ar 22050 -crf 28 %s.flv' % (v.video.path,
                                                        v.video.path)
        print ex
        return_code = call(ex, shell=True)
        print return_code
        if (return_code == 1):
            p = subprocess.Popen(ex,
                                 shell=True,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.STDOUT)
            v.is_error = True
            v.error_desc = str(p.stdout.read())
            v.save()
        else:
            v.is_converted = True

            with open(v.video.path):
                vs = VideoStream(v.video.path + '.flv', frame_size=(800, None))
                token = 'screen_%s' % v.id
                thumb = BASE_DIR + '/media/vcourse_images/' + token + '.jpg'
                print 'Time:::: %s' % vs.duration
                #duration = int(vs.duration)
                duration = 2
                frame = vs.get_frame_at_sec(duration)
                frame.image().save(thumb)
                f = File(open(thumb))
                v.image.save(thumb, f)
            dur = int(vs.duration / 60)
            durs = ' %s sec (%s min)' % (vs.duration, str(dur))
            v.duration = durs
            v.save()
        ''''  
    def getFrame(self, file, frameNo=0, info=False, frameMode='L'):
        """
        returns the given frame from a given video

        Args:
            file (String):
                                path to video file
            frameNo (int):
                                frame number to be returned
            info (bool):
                                return frame and filename
            frameMode (String):
                                Switch of color mode:

                                - 'RGB': color representation
                                - 'L':   gray-scale representation
                                - 'F':   ???


        Returns:
            frame (ndarray):
                                decoded video frame
        """

        if self.verbose:
            print "processing frame {0} of video {1}".format(frameNo, file)

        if not self.vs \
        or self.frameMode != frameMode \
        or self.vs.filename != file:
            self.vs = VideoStream(file, frame_mode=frameMode, exact_seek=True)

            self.frameMode = frameMode

        frame = self.vs.get_frame_no(frameNo).ndarray()

        if info:
            return [frame, file]
        else:
            return frame
Beispiel #20
0
def test_frames_getting():
    from ffvideo import VideoStream

    vs = VideoStream(v0)

    f1 = vs.current()  # first frame
    f2 = vs.next()
    assert f2.timestamp > f1.timestamp

    f = vs[0]  # first frame
    assert f.frameno == 0
    f = vs.get_frame_no(100)
    #    f = vs[100]
    #    assert f.frameno == 100

    f = vs.get_frame_no(100)
    f = vs.get_frame_at_sec(1)
    assert f.timestamp - 1 < 0.1
    f = vs.get_frame_at_pts(133000)

    assert f.width == vs.frame_width
    assert f.height == vs.frame_height
    assert f.mode == vs.frame_mode
Beispiel #21
0
def make_thumb(user):
    from ffvideo import VideoStream
    from co.settings import FLV_PATH
    from co.settings import BASE_DIR
    from shutil import copyfile
    from django.core.files import File
    token = 'my_%s' % user.id
    filename = FLV_PATH+'/'+token+'.flv'
    print filename
    #filenametmp = MEDIA_ROOT+'/video/'+token+'_tmp.flv'
    thumb = BASE_DIR+'/media/profile_images/'+token+'.jpg'
    #try:
    with open(filename):
        print ('converting:'+filename+' to '+thumb)
        #copyfile(filename,filenametmp)
        vs = VideoStream(filename,frame_size=(800, None))
        duration = int(vs.duration)
        duration = 1
        print('get frame number'+str(duration))
        #try:
        frame = vs.get_frame_at_sec(duration)
        frame.image().save(thumb)
        f = File(open(thumb))
        user.image.save(thumb,f)
Beispiel #22
0
 def getVideoProperties(videoFile):
     if ModuleTools.INSTALLED_FFVIDEO():
         from ffvideo import VideoStream
         s = VideoStream(videoFile)
         return s.width, s.height, s.bitrate, s.duration  #, s.codec_name
     elif ModuleTools.INSTALLED_EXIFTOOL():
         try:
             result = json.loads(
                 check_output(["exiftool", "-j", "-n", videoFile]))[0]
         except CalledProcessError:
             logger.warn("exiftool returned non-zero status for video %s",
                         videoFile)
         except (IndexError, ValueError):
             logger.warn("Failed reading exiftool result for video %s",
                         videoFile)
         else:
             try:
                 return result["ImageWidth"], result["ImageHeight"], \
                         result["AvgBitrate"], result["Duration"]
             except KeyError:
                 logger.warn(
                     "Failed reading video properties from exiftool JSON")
     else:
         logger.warn("None of [Python ffvideo library, exiftool] installed")
Beispiel #23
0
def prep_sql_shows(Shows_mnt, conn):
    cur = conn.cursor()
    while 1:
        ii = 0
        for (dirpath, dirnames,
             filenames) in os.walk(os.path.normpath(Shows_mnt)):
            if filenames:
                for file in filenames:
                    if ".DS_Store" in file:
                        continue
                    file_parts = file.split(".")
                    ext = file_parts[-1].lower()
                    del file_parts[-1]
                    if ext == "nfo" or ext == "jpg" or ext == "jpeg" or ext == "srt" or ext == "ifo" or ext == "bup" or ext == "nzb" or ext == "idx" or ext == "sfv" or ext == "txt" or ext == "db" or ext == "part":
                        continue
                    paths = []
                    parse = ""
                    i = 0
                    while Shows_mnt != parse:
                        if i == 0:
                            paths.append(file)
                            parse = os.path.dirname(
                                os.path.normpath(dirpath + "/" + file))
                        else:
                            if parse in paths:
                                parse = os.path.dirname(parse)
                        i += 1
                        paths.append(parse)

                    #print paths
                    path_string = ''.join(paths)
                    path_hash = hashlib.sha256(path_string).hexdigest()
                    #print path_hash
                    cur.execute(
                        "SELECT `id` FROM `tongue`.`video_files` WHERE `path_hash` = %s LIMIT 1",
                        str(path_hash))
                    row = cur.fetchone()
                    #print row
                    if not row:
                        if ext != "rm":
                            filepath = dirpath + "/" + file
                            print filepath
                            file_parts = file.split(".")
                            ext = file_parts[-1].lower()
                            del file_parts[-1]
                            file_name_no_ext = "-".join(file_parts)
                            try:
                                vs = VideoStream(filepath)
                            except DecoderError:
                                #pass
                                codec = "unknown"
                                length = 0
                                dimensions = "0x0"
                                print "Decoder Error :("
                            except NoMoreData:
                                codec = "unknown"
                                length = 0
                                dimensions = "0x0"
                                print "File corrupt??"
                            else:
                                if vs.duration < 20:
                                    frame = vs.get_frame_at_sec(vs.duration /
                                                                2)
                                else:
                                    frame = vs.get_frame_at_sec(20)
                                codec = vs.codec_name
                                hours = vs.duration / 3600
                                minuets = (vs.duration / 60) - (int(hours) *
                                                                60)
                                rg = re.compile('.*?\\d+.*?(\\d+)',
                                                re.IGNORECASE | re.DOTALL)
                                m = rg.search(str(minuets))
                                seconds = int(float("0." + m.group(1)) * 60)

                                # print vs.duration, minuets, hours
                                length = "%dh:%02d:%02d" % (hours, minuets,
                                                            seconds)
                                dimensions = "%dx%d" % (vs.frame_width,
                                                        vs.frame_height)
                        if paths:
                            plen = len(paths)
                            if plen == 3:
                                video = str(paths[0])

                                show_folder = str(
                                    os.path.basename(paths[plen - 2]))
                                show_id = select_show_id(
                                    show_folder.replace("'", "\\'").replace(
                                        " ", "\\ ").replace("-", "\-").replace(
                                            "&",
                                            "\&").replace(")", "\)").replace(
                                                "(", "\("), conn)
                                if show_id == 0:
                                    show_id = insert_show(
                                        show_folder.replace(
                                            "'",
                                            "\\'").replace(" ", "\\ ").replace(
                                                "-", "\-").replace(
                                                    "&", "\&").replace(
                                                        ")", "\)").replace(
                                                            "(", "\("), conn)

                                season_folder = str(
                                    os.path.basename(paths[plen - 2]))
                                season_id = select_season_id(
                                    season_folder.replace("'", "\\'").replace(
                                        " ", "\\ ").replace("-", "\-").replace(
                                            "&",
                                            "\&").replace(")", "\)").replace(
                                                "(", "\("), conn)
                                if season_id == 0:
                                    season_id = insert_season(
                                        season_folder.replace(
                                            "'",
                                            "\\'").replace(" ", "\\ ").replace(
                                                "-", "\-").replace(
                                                    "&", "\&").replace(
                                                        ")", "\)").replace(
                                                            "(", "\("),
                                        show_id, conn)

                                try:
                                    cur.execute(
                                        "INSERT INTO `tongue`.`video_files` (`id`, `video`, `season_id`, `show_id`, `path_hash`, `runtime`, `dimensions`) VALUES (NULL, %s, %s, %s, %s, %s, %s )",
                                        (video.replace("'", "\\'").replace(
                                            " ",
                                            "\\ ").replace("-", "\-").replace(
                                                "&", "\&").replace(
                                                    ")", "\)").replace(
                                                        "(", "\("), season_id,
                                         show_id, str(path_hash), length,
                                         dimensions))
                                except cymysql.MySQLError, e:
                                    print e
                                else:
                                    #print paths[0]+"|=|"+os.path.basename(paths[plen-2])+"|=|"+os.path.basename(paths[plen-2])
                                    #print show_id, season_id
                                    if ii == 100:
                                        sys.stdout.write("\n")
                                        ii = 0
                                    ii += 1
                                    sys.stdout.write(".")
                                    sys.stdout.flush()
                            else:
                                video = str(paths[0])

                                show_folder = str(
                                    os.path.basename(paths[plen - 2]))
                                show_id = select_show_id(
                                    show_folder.replace("'", "\\'").replace(
                                        " ", "\\ ").replace("-", "\-").replace(
                                            "&",
                                            "\&").replace(")", "\)").replace(
                                                "(", "\("), conn)
                                if show_id == 0:
                                    show_id = insert_show(
                                        show_folder.replace(
                                            "'",
                                            "\\'").replace(" ", "\\ ").replace(
                                                "-", "\-").replace(
                                                    "&", "\&").replace(
                                                        ")", "\)").replace(
                                                            "(", "\("), conn)

                                season_folder = str(paths[plen -
                                                          3].strip(Shows_mnt))
                                season_id = select_season_id(
                                    season_folder.replace("'", "\\'").replace(
                                        " ", "\\ ").replace("-", "\-").replace(
                                            "&",
                                            "\&").replace(")", "\)").replace(
                                                "(", "\("), conn)
                                if season_id == 0:
                                    season_id = insert_season(
                                        season_folder.replace(
                                            "'",
                                            "\\'").replace(" ", "\\ ").replace(
                                                "-", "\-").replace(
                                                    "&", "\&").replace(
                                                        ")", "\)").replace(
                                                            "(", "\("),
                                        show_id, conn)
                                try:
                                    cur.execute(
                                        "INSERT INTO `tongue`.`video_files` (`id`, `video`, `season_id`, `show_id`, `path_hash`) VALUES (NULL, %s, %s, %s, %s )",
                                        (video.replace("'", "\\'").replace(
                                            " ",
                                            "\\ ").replace("-", "\-").replace(
                                                "&", "\&").replace(
                                                    ")", "\)").replace(
                                                        "(", "\("), season_id,
                                         show_id, str(path_hash)))
                                except cymysql.MySQLError, e:
                                    print e
                                sys.stdout.write(".")
                                sys.stdout.flush()
                            conn.commit()
Beispiel #24
0
def get_video_dimensions(path):
    from ffvideo import VideoStream

    vs = VideoStream(path)
    return (vs.window_width, vs.window_height)
Beispiel #25
0
def prep_sql_movies(Movies_mnt, conn):
    cur = conn.cursor()
    #print [name for name in os.listdir(Movies_mnt) if os.path.isdir(Movies_mnt)]
    mnt_path = Movies_mnt.split('/')
    mnt_num = (len(mnt_path) - 1)
    while 1:
        dvd_flag = 0
        grouped = 0
        group = 1
        prev_folder = ""
        for root, dirs, files in os.walk(Movies_mnt):
            path = root.split('/')
            #print path
            root_num = (len(path) - 1)
            sub = os.path.basename(root)
            if prev_folder != sub:
                grouped = 0
            for file in files:
                filepath = root + "/" + file
                #print filepath
                path_hash = hashlib.sha256(filepath).hexdigest()
                file_parts = file.split(".")
                ext = file_parts[-1].lower()
                if ext == "nfo" or ext == "jpg" or ext == "jpeg" or ext == "srt" or ext == "ifo" or ext == "bup" or ext == "nzb" or ext == "idx" or ext == "sfv" or ext == "txt" or ext == "db" or ext == "DS_Store":
                    continue
                cur.execute(
                    "SELECT `id` FROM `tongue`.`movie_files` WHERE `path_hash` = %s LIMIT 1",
                    str(path_hash))
                row = cur.fetchone()
                #print filepath
                #print row
                if not row:
                    del file_parts[-1]
                    file_name_no_ext = "-".join(file_parts)
                else:
                    continue
                #print len(path)*'---'
                if mnt_num == root_num - 1:
                    #print "In root: " + root
                    ii = 0
                else:
                    #print "Sub of root: " + sub + " : " + file
                    if sub.upper() == "VIDEO_TS":
                        #print "Is DVD Video: " + file
                        if dvd_flag == 1:
                            print "flag already set"
                            #continue
                        else:
                            dvd_flag = 1
                        file = sub
                    else:
                        dvd_flag = 0
                    lower_file = file.lower()

                    if "cd1" in lower_file or "cd2" in lower_file:
                        #print lower_file
                        if prev_folder != sub:
                            prev_folder = sub
                            grouped = 1
                            group += 1
                            #print
                    else:
                        grouped = 0
                if not dvd_flag:
                    try:
                        vs = VideoStream(filepath)
                    except DecoderError:
                        #pass
                        codec = "unknown"
                        length = 0
                        dimensions = "0x0"
                        print "Decoder Error :("
                    except NoMoreData:
                        codec = "unknown"
                        length = 0
                        dimensions = "0x0"
                        print "File corrupt??"
                    else:
                        frame = vs.get_frame_at_sec(200)
                        codec = vs.codec_name
                        hours = vs.duration / 3600
                        minuets = (vs.duration / 60) - (int(hours) * 60)
                        rg = re.compile('.*?\\d+.*?(\\d+)',
                                        re.IGNORECASE | re.DOTALL)
                        m = rg.search(str(minuets))
                        seconds = int(float("0." + m.group(1)) * 60)

                        # print vs.duration, minuets, hours
                        length = "%dh:%02d:%02d" % (hours, minuets, seconds)
                        dimensions = "%dx%d" % (vs.frame_width,
                                                vs.frame_height)
                else:
                    codec = "RAWDVD"
                    length = 0
                    dimensions = "0x0"

                fullpath = filepath.replace("'", "\\'").replace(
                    " ", "\\ ").replace("-", "\-").replace("&", "\&").replace(
                        ")", "\)").replace("(", "\(")
                file_ = file.replace("'", "\\'").replace(" ", "\\ ").replace(
                    "-", "\-").replace("&",
                                       "\&").replace(")",
                                                     "\)").replace("(", "\(")
                #print "DVD Flag: " + str(dvd_flag)
                if dvd_flag == 1:
                    file_ = path[-2]
                if grouped == 0:
                    group_ins = 0
                else:
                    group_ins = group
                #print grouped, group_ins
                try:
                    cur.execute(
                        "INSERT INTO `tongue`.`movie_files` (`id`, `fullpath`, `filename`, `path_hash`, `grouped`, `group`, `dvd_raw`, `runtime`, `dimensions`, `codec`) VALUES (NULL, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
                        (fullpath.replace(os.path.dirname(root),
                                          ""), file_, str(path_hash), grouped,
                         group_ins, dvd_flag, length, dimensions, codec))
                except cymysql.MySQLError, e:
                    print e
                sys.stdout.write("`")
                sys.stdout.flush()
                conn.commit()
                #print len(path)*'---', file
        time.sleep(900)
Beispiel #26
0

def scale_to_range(image):  # skalira elemente slike na opseg od 0 do 1
    ''' Elementi matrice image su vrednosti 0 ili 255.
        Potrebno je skalirati sve elemente matrica na opseg od 0 do 1
    '''
    return image / 255


def matrix_to_vector(image):
    '''Sliku koja je zapravo matrica 28x28 transformisati u vektor sa 784 elementa'''
    return image.flatten()

i = 0

for frame in VideoStream('videos/video-9.avi'):

    i = i + 1
    if not i % 40 == 0:
        continue

    frame.image().save('temp.png')
    image_color = load_image('temp.png')
    img = invert(image_bin(image_gray(image_color)))
    img_bin = erode(dilate(img))
    selected_regions, numbers = select_roi(image_color.copy(), img)
    new = cv2.addWeighted(image_color, 1, selected_regions, 1, 0)
    new = cv2.cvtColor(new, cv2.COLOR_BGR2RGB)
    if i % 40 == 0:
#        cv2.imwrite('i2v/'+str(i)+'.png', new)
        plt.imshow(new)
Beispiel #27
0
def insert(dirname):
    select_query = 'select * from img where img_path="%s"'%path
    cur.execute("set names utf8")
    cur.execute(select_query)

    results = cur.fetchall()
    db_path_arr = []

    for i in results:
        db_path_arr.append(i[3])
    diff_arr = []

    for a in path_arr:
        if a not in db_path_arr:
            diff_arr.append(a)

    for full_path in diff_arr:

        ext = os.path.splitext(full_path)[-1]
        thum = "%s_" % (datetime.today().strftime('%Y%m%d')) + str(uuid.uuid4())[:8] + ".jpg"
        small_thum_path = "/DATA/reference_library/thumnail/small_thum/%s"%thum
        filename = os.path.split(full_path)[-1]

        if ext.lower() == ".mp4" or ext.lower() == ".mov" or ext.lower() == ".mkv" or ext.lower() == ".avi" or ext.lower() == ".webm":

            try:
                duration = int(VideoStream(full_path).duration/2)
                thumbnail = VideoStream(full_path).get_frame_at_sec(duration).image()
                thumbnail.save(small_thum_path)

            except Exception, e:
                print e

            select_query = 'select * from img where full_path = "%s"' % full_path[5:]
            cur.execute("set names utf8")
            cur.execute(select_query)

            if cur.rowcount == 0:
                try:
                    codec = VideoStream(full_path).codec_name
                    print codec
                    if codec == "h264" or codec =="aac":
                        full_path = full_path[5:]
                        query_o = 'insert into img(img_path,img_name,full_path,thumnail,type) values("%s","%s","%s","%s","%s")' % (path,filename,full_path,thum,'video')
                        # print query_o
                        cur.execute("set names utf8")
                        cur.execute(query_o)
                        db.commit()

                    else:
                        full_path = full_path[5:]
                        query = 'insert into img(img_path,img_name,full_path,thumnail,type) values("%s","%s","%s","%s","%s")'%(path,filename,full_path,'codec.png','video')
                        # print query
                        cur.execute("set names utf8")
                        cur.execute(query)
                        db.commit()

                except Exception,e:
                    pass
            else:
                pass
Beispiel #28
0
 def resetMovie(self):
     """Reset the video stream."""
     self.source = VideoStream(self.fileName)
Beispiel #29
0
import PIL

from ffvideo import VideoStream


VIDEO_FILE = '/Users/drautb/Desktop/haystack-samples/moto-x/VID_20151207_081126527.mp4'
THUMBNAIL = '/Users/drautb/Desktop/haystack-samples/moto-x/test-thumbnail.jpg'

vs = VideoStream(VIDEO_FILE,
                 frame_size=(128, None),  # scale to width 128px
                 frame_mode='RGB')  # convert to grayscale

# vs = VideoStream(VIDEO_FILE)

print "frame size: %dx%d" % (vs.frame_width, vs.frame_height)
print "Width: %d" % (vs.width)
print "Height: %d" % (vs.height)

frame = vs.get_frame_at_sec(0)
frame.image().transpose(PIL.Image.ROTATE_270).save(THUMBNAIL)
Beispiel #30
0
def slurp_video(path):
    video = VideoStream(path)
    return video.get_frame_at_sec(2)