Ejemplo n.º 1
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")
Ejemplo n.º 2
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")
Ejemplo n.º 3
0
def get_frame(filename, sec=3):
    basename = os.path.basename(filename)
    sans_ext = basename.split('.')[0]
    vs = VideoStream(filename)
    frame = vs.get_frame_at_sec(sec)
    frame_location = os.path.join(config.FRAMES_DIRECTORY, sans_ext + '.png')
    frame.image().save(frame_location)
    return frame_location
Ejemplo n.º 4
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))
Ejemplo n.º 5
0
def get_barcode_image(video_path, barcode_path):
    if os.path.exists(barcode_path):
        return Image.open(barcode_path)
    vs = VideoStream(video_path)
    barcode = Image.new('RGB', BARCODE_SIZE)
    for i, timepoint in enumerate(np.linspace(0, vs.duration, BARCODE_SIZE[0])):
        try:
            frame = vs.get_frame_at_sec(timepoint)
            frame_image = frame.image()
            frame_image = frame_image.resize((1, BARCODE_SIZE[1]), Image.ANTIALIAS)
            barcode.paste(frame_image, (i, 0))
        except Exception, e:
            print e
        finally:
Ejemplo n.º 6
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()
Ejemplo n.º 7
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()
Ejemplo n.º 8
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()
        ''''  
Ejemplo n.º 9
0
def new_video(title, file_name, uploader_ip, file_hash, description):
	#this methods assumes the video is in the temp folder
	try:

		temp_file = os.path.join(tempfile.gettempdir(), file_name)

		vs = VideoStream(temp_file)
		thumb = vs.get_frame_at_sec(int(vs.duration/2)).image()
		thumb.save(os.path.join(app.config["thumbs_dir"], file_name) + '.jpg')

		def_file = os.path.join(app.config["upload_dir"] + file_name)

		shutil.move(temp_file, def_file)

		video = Video(title, file_name, file_hash, uploader_ip, description)

		db.session.add(video)
		db.session.commit()

	except Exception, e:
		logging.error(e)
		abort(500)
Ejemplo n.º 10
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
Ejemplo n.º 11
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
Ejemplo n.º 12
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)
files = []
for ext in ["3gp", "mp4"]:
	files += glob.glob(workingdir + "/*." + ext)

for media in files:
	filename = os.path.basename(media)
	ext = os.path.splitext(filename)
	if ext[1].lower() not in [".mp4", ".3gp"]:
		filename = ext[0] + ".mp4"
		cmd = "avconv -i " + media + " " + imagedir + filename
		subprocess.check_call(cmd) 
	else:
		shutil.copy2(media, imagedir + filename)
	stream = VideoStream(media)
	im = stream.get_frame_at_sec(min(stream.duration / 2, 5)).image()
	thumb_file_name = ext[0] + ".jpeg"
	im.save(imagedir + thumb_file_name)
	im = getThumb(im)
	im.save(thumbdir + thumb_file_name)
	imgs.append({"thumbnail": thumbdir_base + thumb_file_name, 
				"filename": filename,
				"poster": imagedir_base + thumb_file_name, 
				"href": imagedir_base + filename,
				"type": "video/mp4"})

files = []
for ext in ["png", "jpg", "JPG"]:
	files += glob.glob(workingdir + "/*." + ext)

for media in files:
Ejemplo n.º 14
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()
Ejemplo n.º 15
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)
Ejemplo n.º 16
0
class Movie(QtCore.QObject):
    """This class represent the video data stream"""

    frameChanged = QtCore.pyqtSignal()
    endOfVideo = QtCore.pyqtSignal()

    def __init__(self, fileName=None):
        """Initialize the video stream and open the video file if a fileName is provided.
        
        :param filename: a string containing the name of the file to be opened.
        """
        self.rawBuffer = None
        self.source = None
        super(Movie, self).__init__()
        if (fileName is not None):
            self.setMovie(fileName)
        self.timer = None
        self.frame = None
        self.isPlaying = False
        self.frameRate = 0
        self.frameNumber = 0

    def reset(self):
        """Reset the movie object. Remove the source."""
        self.rawBuffer = None
        self.source = None
        self.timer = None
        self.frame = None
        self.isPlaying = False
        self.frameRate = 0
        self.frameNumber = 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)

    def resetMovie(self):
        """Reset the video stream."""
        self.source = VideoStream(self.fileName)

    def play(self):
        """Start to read the video stream."""
        self.isPlaying = True
        self.timer.start()

    def pause(self):
        """Pause the reading of the video stream."""
        self.isPlaying = False
        self.timer.stop()

    def frameMustChange(self):
        """Slot called when it is time to load the next frame.
        
        :raise: Exception: The file cannot be read because the codec is not supported or the video is compressed.
        """
        self.readNextFrame()

    def toggleState(self):
        """Toggle between playing and pausing the video."""
        if (self.isPlaying == True):
            self.pause()
        else:
            self.play()

    def jumpToFrame(self, position):
        """Modify the position in the video.
        
        :param position: a value between 0 and 1 corresponding to the position in the video. 0 is the beginning and 1 is the end.
        """
        if (position > 1.0):
            position = 1.0
        elif (position < 0.001):
            position = 0.001
        frame = self.source.get_frame_at_sec(position *
                                             self.source.duration).ndarray
        return frame

    def readNextFrame(self):
        """Load the next frame.
        :raise: Exception: The file cannot be read because the codec is not supported or the video is compressed.
        """
        try:
            self.rawBuffer = self.source.next().ndarray()
        except ffvideo.NoMoreData:
            self.isPlaying = False
            self.pause()
            self.rawBuffer = None
            self.endOfVideo.emit()
        self.frameChanged.emit()

    def readNCFrame(self, number):
        """Load the next frame.
        :raise: Exception: The file cannot be read because the codec is not supported or the video is compressed.
        """
        position = self.source.current().frameno
        try:
            self.rawBuffer = self.source.get_frame_no(position +
                                                      number).ndarray()
        except ffvideo.NoMoreData:
            self.isPlaying = False
            self.pause()
            self.endOfVideo.emit()
        if (self.source.current().frameno >=
                self.source.duration * self.source.framerate):
            self.isPlaying = False
            self.pause()
            self.endOfVideo.emit()
        self.frameChanged.emit()

    def currentPositionRatio(self):
        """Returns the position in the video.
        
        :return: a value between 0 and 1 representing the position in the video. 0 is the beginning and 1 is the end.
        """
        if (self.source is not None and self.source.current() is not None):
            result = self.source.current().timestamp / self.source.duration
            if (result > 1.0):
                return 1.0
            elif (result < 0.0):
                return 0.0
            else:
                return result
        else:
            return 1.0

    def getFrameNumber(self):
        """Returns the number of frame in the video.
        
        :return: An integer representing the number of frame in the video.
        """
        return int(self.source.duration * self.source.framerate)

    def getFrameSize(self):
        return (self.source.frame_width, self.source.frame_height)

    def getEllapsedTime(self):
        """Returns the number ellapsed time in the video.
        
        :return: An integer representing the number of frame in the video.
        """
        return self.source.current().timestamp
Ejemplo n.º 17
0
def slurp_video(path):
    video = VideoStream(path)
    return video.get_frame_at_sec(2)
Ejemplo n.º 18
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()
Ejemplo n.º 19
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)
Ejemplo n.º 20
0
 def _generate_thumbnail(self, image_filepath, at_second=60):
     vs = VideoStream(self.video_full_path)
     try:
         vs.get_frame_at_sec(int(at_second)).image().save(image_filepath)
     except Exception:
         pass
Ejemplo n.º 21
0
import sys
from ffvideo import VideoStream
from vidextract import bwextract, enc, c64asm

infile = sys.argv[1]
outfile = sys.argv[2]

vs = VideoStream(infile,
                 frame_size=(320, 200),
                 frame_mode='L') # convert to grayscale

frame = vs.get_frame_at_sec(0)
img = bwextract.tobw(frame.ndarray())
bmp = enc.conv_c64_hires(img)
asm = c64asm.asm_byte_frame(bmp)

with open(outfile, 'w') as f:
    f.write(asm)
Ejemplo n.º 22
0
 def _generate_thumbnail(self, image_filepath, at_second=60):
     vs = VideoStream(self.video_full_path)
     try:
         vs.get_frame_at_sec(int(at_second)).image().save(image_filepath)
     except Exception:
         pass
Ejemplo n.º 23
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)
Ejemplo n.º 24
0
class Movie(QtCore.QObject):
    """This class represent the video data stream"""

    frameChanged = QtCore.pyqtSignal()
    endOfVideo = QtCore.pyqtSignal()
    
    def __init__(self, fileName=None):
        """Initialize the video stream and open the video file if a fileName is provided.
        
        :param filename: a string containing the name of the file to be opened.
        """
        self.rawBuffer=None
        self.source=None
        super(Movie, self).__init__()
        if(fileName is not None):
            self.setMovie(fileName)
        self.timer = None
        self.frame = None
        self.isPlaying = False
        self.frameRate = 0
        self.frameNumber = 0
    
    def reset(self):
        """Reset the movie object. Remove the source."""
        self.rawBuffer=None
        self.source=None
        self.timer = None
        self.frame = None
        self.isPlaying = False
        self.frameRate = 0
        self.frameNumber = 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)
    
    def resetMovie(self):
        """Reset the video stream."""
        self.source = VideoStream(self.fileName)
        
    def play(self): 
        """Start to read the video stream."""
        self.isPlaying = True
        self.timer.start()
    
    def pause(self):
        """Pause the reading of the video stream."""
        self.isPlaying = False
        self.timer.stop()
        
    def frameMustChange(self):
        """Slot called when it is time to load the next frame.
        
        :raise: Exception: The file cannot be read because the codec is not supported or the video is compressed.
        """
        self.readNextFrame()
    
    def toggleState(self):
        """Toggle between playing and pausing the video."""
        if(self.isPlaying==True):
            self.pause()
        else:
            self.play()
            
    def jumpToFrame(self, position):
        """Modify the position in the video.
        
        :param position: a value between 0 and 1 corresponding to the position in the video. 0 is the beginning and 1 is the end.
        """
        if(position>1.0):
            position = 1.0
        elif(position<0.001):
            position = 0.001
        frame = self.source.get_frame_at_sec(position*self.source.duration).ndarray
        return frame
    
    def readNextFrame(self):
        """Load the next frame.
        :raise: Exception: The file cannot be read because the codec is not supported or the video is compressed.
        """
        try:
            self.rawBuffer = self.source.next().ndarray()
        except ffvideo.NoMoreData:
            self.isPlaying = False
            self.pause()
            self.rawBuffer = None
            self.endOfVideo.emit()
        self.frameChanged.emit()
        
    def readNCFrame(self, number):
        """Load the next frame.
        :raise: Exception: The file cannot be read because the codec is not supported or the video is compressed.
        """
        position = self.source.current().frameno
        try:
                self.rawBuffer = self.source.get_frame_no(position+number).ndarray()
        except ffvideo.NoMoreData:
            self.isPlaying = False
            self.pause()
            self.endOfVideo.emit()
        if(self.source.current().frameno>=self.source.duration*self.source.framerate):
            self.isPlaying = False
            self.pause()
            self.endOfVideo.emit()
        self.frameChanged.emit()

        
    def currentPositionRatio(self):
        """Returns the position in the video.
        
        :return: a value between 0 and 1 representing the position in the video. 0 is the beginning and 1 is the end.
        """
        if(self.source is not None and self.source.current() is not None):
            result = self.source.current().timestamp/self.source.duration
            if(result>1.0):
                return 1.0
            elif(result<0.0):
                return 0.0
            else:
                return result
        else:
            return 1.0
    
    def getFrameNumber(self):
        """Returns the number of frame in the video.
        
        :return: An integer representing the number of frame in the video.
        """
        return int(self.source.duration*self.source.framerate)
    
    def getFrameSize(self):
        return (self.source.frame_width, self.source.frame_height)
    
    def getEllapsedTime(self):
        """Returns the number ellapsed time in the video.
        
        :return: An integer representing the number of frame in the video.
        """
        return self.source.current().timestamp
Ejemplo n.º 25
0
 def video_thumbnail(temp_file, uploaded_file):
     from ffvideo import VideoStream
     vs = VideoStream(uploaded_file)
     frame = vs.get_frame_at_sec(2)
     frame.image().save(temp_file)