示例#1
0
def radarr():
    data = json.loads(request.data)
    if data["eventType"] == "Download":
        log("\nDownload received from Radarr at {}".format(
            datetime.datetime.now()))
        id = data["movie"]["id"]
        data = requests.get("http://192.168.0.10:7878/api/movie/{}".format(id),
                            params={
                                "apikey": "26c68f7dfb6d4ad481a33e32a4bf1579"
                            }).json()
        if not data["downloaded"]:
            log("\tAPI Error: Movie not labelled 'downloaded'.")
            return "OK"
        path = data["path"] + "/" + data["movieFile"]["relativePath"]
        path = path.replace("/data/media/", "M:/")
        log("\tFile: " + path)
        vid = Video(path, "movie")
        log("\tCodec: {}\n\tWidth: {}\n\tBitrate: {}".format(
            vid.codec, vid.width, vid.rate))
        if vid.needs_transcoding:
            log("\tParams: {}".format(vid.params))
            if vid.transcode():
                log("\tSuccessfully Transcoded")
            else:
                log("\tTranscode Failed")
            log("\tTranscode ended at {}".format(datetime.datetime.now()))
        else:
            log("\tNo Transcode Required")
    elif data["eventType"] == "Test":
        print("This is a test")
    return "OK"
示例#2
0
def sonarr():
    data = json.loads(request.data)
    if data["eventType"] == "Download":
        log("\nDownload received from Sonarr at {}".format(
            datetime.datetime.now()))
        folder = data["series"]["path"]
        file = data["episodeFile"]["relativePath"]
        path = folder + "/" + file
        path = path.replace("/data/media/", "M:/")
        if path.startswith("M:/Animated TV Shows/"):
            type = "animation"
        else:
            type = "tv"
        log("\tFile: " + path)
        vid = Video(path, type)
        log("\tCodec: {}\n\tWidth: {}\n\tBitrate: {}".format(
            vid.codec, vid.width, vid.rate))
        if vid.needs_transcoding:
            log("\tParams: {}".format(vid.params))
            if vid.transcode():
                log("\tSuccessfully Transcoded")
            else:
                log("\tTranscode Failed")
            log("\tTranscode ended at {}".format(datetime.datetime.now()))
        else:
            log("\tNo Transcode Required")
    return "OK"
示例#3
0
 def pad(self, video, length):
     pad_length = max(length - video.length, 0)
     video_length = min(length, video.length)
     mouth_padding = np.zeros((pad_length, video.mouth.shape[1],
                               video.mouth.shape[2], video.mouth.shape[3]),
                              dtype=np.uint8)
     new_video = Video(video.face_predictor_path)
     new_video.mouth = np.concatenate(
         (video.mouth[0:video_length], mouth_padding), 0)
     new_video.set_data(new_video.mouth)
     return new_video
示例#4
0
 def enumerate_videos(self, path):
     video_list = []
     for video_path in glob.glob(path):
         try:
             if os.path.isfile(video_path):
                 video = Video(self.vtype, self.face_predictor_path).from_video(video_path)
             else:
                 video = Video(self.vtype, self.face_predictor_path).from_frames(video_path)
         except:
             print "Error loading video: "+video_path
         video_list.append(video_path)
     return video_list
示例#5
0
文件: main.py 项目: MG1105/yonder-gae
	def post(self, video_id):
		self.response.headers["Content-Type"] = "application/json"
		try:
			user_id = self.request.POST["user"]
			report = Video()
			report.add_flag(video_id, user_id)
		except Exception:
			logging.exception("Failed to report video %s" % video_id)
			out = {"success": 0}
			self.response.write(json.dumps(out))
		else:
			logging.info("Video reported successfully")
			out = {"success": 1}
			self.response.write(json.dumps(out))
示例#6
0
文件: main.py 项目: MG1105/yonder-gae
	def post(self, video_id):
		self.response.headers["Content-Type"] = "application/json"
		try:
			rating = self.request.POST["rating"]
			user_id = self.request.POST["user"]
			video = Video()
			video.add_rating(video_id, rating, user_id)
		except Exception:
			logging.exception("Failed to add video rating")
			out = {"success": 0}
			self.response.write(json.dumps(out))
		else:
			logging.info("Video rating added successfully")
			out = {"success": 1}
			self.response.write(json.dumps(out))
示例#7
0
    def random_channel(nb_keywords: int = 1,
                       nb_videos: int = 1,
                       kv_ratio: int = 1,
                       channel_id: int = 0):
        """ Returns a channel of random videos, all similar to a base random video
        :param nb_keywords: int or tuple of ints, specifying the length of the keywords parameter
        :param nb_videos: int, specifying the number of videos on the channel
        :param kv_ratio: int, number of keywords per video
        :param channel_id: int, unique identifier amongst all channels
        """

        # Type-checking
        if not isinstance(nb_keywords, int):
            raise TypeError
        if not isinstance(nb_videos, int):
            raise TypeError
        if not isinstance(kv_ratio, int):
            raise TypeError
        if not isinstance(channel_id, int):
            raise TypeError

        videos = []

        if nb_videos > 0:

            video_id = channel_id * 10**3
            base_video = Video.random_video(nb_keywords, kv_ratio, video_id,
                                            channel_id)
            videos.append(base_video)
            base_keywords = base_video.keywords

            for i in range(nb_videos - 1):
                switch_proba = 0.1
                switch = np.random.uniform(0, 1, size=nb_keywords)
                switch = np.asarray(
                    switch < switch_proba,
                    dtype=np.float)  # bernoulli sampling, p << 0.5
                keywords = np.logical_xor(base_keywords, switch)
                keywords = np.asarray(keywords, dtype=np.float)
                video = Video(keywords, video_id + i + 1, channel_id)
                videos.append(video)

        return Channel(videos, channel_id)
示例#8
0
 def enumerate_videos(self, path):
     video_list = []
     for video_path in glob.glob(path):
         try:
             if os.path.isfile(video_path):
                 video = Video(self.vtype, self.face_predictor_path).from_video(video_path)
             else:
                 video = Video(self.vtype, self.face_predictor_path).from_frames(video_path)
         except AttributeError as err:
             raise err
         except:
             print("Error loading video: "+video_path)
             continue
         if K.image_data_format() == 'channels_first' and video.data.shape != (self.img_c,self.frames_n,self.img_w,self.img_h):
             print("Video "+video_path+" has incorrect shape "+str(video.data.shape)+", must be "+str((self.img_c,self.frames_n,self.img_w,self.img_h))+"")
             continue
         if K.image_data_format() != 'channels_first' and video.data.shape != (self.frames_n,self.img_w,self.img_h,self.img_c):
             print("Video "+video_path+" has incorrect shape "+str(video.data.shape)+", must be "+str((self.frames_n,self.img_w,self.img_h,self.img_c))+"")
             continue
         video_list.append(video_path)
     return video_list
示例#9
0
    def get_batch(self, index, size, train):
        if train:
            video_list = self.train_list
        else:
            video_list = self.val_list

        X_data_path = get_list(video_list, index, size)
        X_data = []
        Y_data = []
        label_length = []
        input_length = []
        source_str = []
        for path in X_data_path:
            video = Video().from_frames(path)
            align = self.align_dict[path.split('/')[-1]]
            if train == True:
                video= self.keyframe.extract(video)
                to_be_augmented = random.choice([True, False, False])]
                if to_be_augmented:
                    video.data = select_augmentation(video.data)

            X_data.append(video.data)
            Y_data.append(align.padded_label)
            label_length.append(align.label_length) 
            input_length.append(video.length) 
            source_str.append(align.sentence)

        source_str = np.array(source_str)
        label_length = np.array(label_length)
        input_length = np.array(input_length)
        Y_data = np.array(Y_data)
        X_data = np.array(X_data).astype(np.float32) / 255 
        X_data, Y_data, input_length, label_length, source_str = shuffle(X_data, Y_data, input_length, label_length, source_str, random_state=random_seed)

        inputs = {'the_input': X_data,
                  'the_labels': Y_data,
                  'input_length': input_length,
                  'label_length': label_length,
                  'source_str': source_str 
                  }
示例#10
0
    def listSubtitles(self, entries, auto=True):
        """
        Search subtitles within the plugins and return all found subtitles in a list of Subtitle object.

        Attributes:
            entries -- filepath or folderpath of video file or a list of that
            auto    -- automaticaly manage workers"""
        if auto:
            if self.state != IDLE:
                raise BadStateError(self.state, IDLE)
            self.startWorkers()
        if isinstance(entries, basestring):
            entries = [entries]
        scan_result = []
        for e in entries:
            if not isinstance(e, unicode):
                logger.warning(u'Entry %r is not unicode' % e)
            if not os.path.exists(e):
                scan_result.append((e, set(), False))
                continue
            scan_result.extend(scan(e))
        task_count = 0
        for filepath, languages, has_single in scan_result:
            wanted_languages = set(self._languages)
            if not wanted_languages:
                wanted_languages = LANGUAGES
            if not self.force and self.multi:
                wanted_languages = set(wanted_languages) - languages
                if not wanted_languages:
                    logger.debug(
                        u'No need to list multi subtitles %r for %r because %r subtitles detected'
                        % (self._languages, filepath, languages))
                    continue
            if not self.force and not self.multi and has_single:
                logger.debug(
                    u'No need to list single subtitles %r for %r because one detected'
                    % (self._languages, filepath))
                continue
            logger.debug(u'Listing subtitles %r for %r with %r' %
                         (wanted_languages, filepath, self._plugins))
            for plugin in self._plugins:
                self.taskQueue.put((5,
                                    ListTask(Video.factory(filepath),
                                             wanted_languages, plugin,
                                             self.getConfigDict())))
                task_count += 1
        subtitles = []
        for _ in range(task_count):
            subtitles.extend(self.listResultQueue.get())
        if auto:
            self.stopWorkers()
        return subtitles
示例#11
0
    def retain_keyframes(self, video):
        first = video.mouth[0]
        threshold = 300
        res = None
        org_index = 0
        new_mouth = []
        new_mouth.append(first)
        for index in range(len(video.mouth) - 1):
            second = video.mouth[index + 1]
            filename = index + 1
            res = self.find_diff(first, second)
            diff = np.count_nonzero(res)
            if diff > threshold:
                new_mouth.append(second)
            org_index += 1
            first = second
        new_mouth = np.array(new_mouth)

        new_video = Video(video.face_predictor_path)
        new_video.mouth = new_mouth
        new_video.set_data(new_video.mouth)
        return new_video
示例#12
0
文件: core.py 项目: bonega/subliminal
    def listSubtitles(self, entries, auto=True):
        """
        Search subtitles within the plugins and return all found subtitles in a list of Subtitle object.

        Attributes:
            entries -- filepath or folderpath of video file or a list of that
            auto    -- automaticaly manage workers"""
        if auto:
            if self.state != IDLE:
                raise BadStateError(self.state, IDLE)
            self.startWorkers()
        if isinstance(entries, basestring):
            entries = [entries]
        scan_result = []
        for e in entries:
            if not isinstance(e, unicode):
                logger.warning(u"Entry %r is not unicode" % e)
            if not os.path.exists(e):
                scan_result.append((e, set(), False))
                continue
            scan_result.extend(scan(e))
        task_count = 0
        for filepath, languages, has_single in scan_result:
            wanted_languages = set(self._languages)
            if not wanted_languages:
                wanted_languages = LANGUAGES
            if not self.force and self.multi:
                wanted_languages = set(wanted_languages) - languages
                if not wanted_languages:
                    logger.debug(
                        u"No need to list multi subtitles %r for %r because %r subtitles detected"
                        % (self._languages, filepath, languages)
                    )
                    continue
            if not self.force and not self.multi and has_single:
                logger.debug(
                    u"No need to list single subtitles %r for %r because one detected" % (self._languages, filepath)
                )
                continue
            logger.debug(u"Listing subtitles %r for %r with %r" % (wanted_languages, filepath, self._plugins))
            for plugin in self._plugins:
                self.taskQueue.put(
                    (5, ListTask(Video.factory(filepath), wanted_languages, plugin, self.getConfigDict()))
                )
                task_count += 1
        subtitles = []
        for _ in range(task_count):
            subtitles.extend(self.listResultQueue.get())
        if auto:
            self.stopWorkers()
        return subtitles
示例#13
0
    def get_batch(self, index, size, train):
        if train:
            video_list = self.train_list
        else:
            video_list = self.val_list

        def get_list_safe(l, index, size):
            ret = l[index:index + size]
            while size - len(ret) > 0:
                ret += l[0:size - len(ret)]
            return ret

        X_data_path = get_list_safe(video_list, index, size)
        #print "X_data_path",X_data_path
        X_data = []
        Y_data = []
        label_length = []
        input_length = []
        source_str = []
        for path in X_data_path:
            #print "path",path
            video = Video().from_frames(path)
            align = self.get_align(path.split('/')[-1])
            video_unpadded_length = video.length
            #print "vavl",video,align,video_unpadded_length
            #print "vavlnext",video.data,align.padded_label,align.label_length,align.sentence
            X_data.append(video.data)
            Y_data.append(align.padded_label)
            label_length.append(align.label_length)
            input_length.append(video.length)
            source_str.append(align.sentence)
        source_str = np.array(source_str)
        label_length = np.array(label_length)
        input_length = np.array(input_length)
        Y_data = np.array(Y_data)
        X_data = np.array(X_data).astype(
            np.float32) / 255  # Normalize image data to [0,1],

        inputs = {
            'the_input': X_data,
            'the_labels': Y_data,
            'input_length': input_length,
            'label_length': label_length,
            'source_str': source_str  # used for visualization only
        }
        outputs = {
            'ctc': np.zeros([size])
        }  # dummy data for dummy loss function

        return (inputs, outputs)
示例#14
0
    def get_batch(self, index, size, train):
        if train:
            video_list = self.train_list
        else:
            video_list = self.val_list
	def get_list_safe(l, index, size):
            ret = l[index:index+size]
            while size - len(ret) > 0:
                ret += l[0:size - len(ret)]
            return ret

        X_data_path = get_list_safe(video_list, index, size)
        X_data = []
        Y_data = []
        label_length = []
        input_length = []
        source_str = []
        for path in X_data_path:
            video = Video().from_frames(path)
            align = self.get_align(path.split('/')[-1])
            video_unpadded_length = video.length
            if self.curriculum is not None:
                video, align, video_unpadded_length = self.curriculum.apply(video, align)
            X_data.append(video.data)
            Y_data.append(align.padded_label)
            label_length.append(align.label_length) # CHANGED [A] -> A, CHECK!
            # input_length.append([video_unpadded_length - 2]) # 2 first frame discarded
            input_length.append(video.length) # Just use the video padded length to avoid CTC No path found error (v_len < a_len)
            source_str.append(align.sentence) # CHANGED [A] -> A, CHECK!

        source_str = np.array(source_str)
        label_length = np.array(label_length)
        input_length = np.array(input_length)
        Y_data = np.array(Y_data)
        X_data = np.array(X_data).astype(np.float32) / 255 # Normalize image data to [0,1], TODO: mean normalization over training data

        inputs = {'the_input': X_data,
                  'the_labels': Y_data,
                  'input_length': input_length,
                  'label_length': label_length,
                  'source_str': source_str  # used for visualization only
                  }
        outputs = {'ctc': np.zeros([size])}  # dummy data for dummy loss function

        return (inputs, outputs)
示例#15
0
    for root, dirs, files in os.walk(
            directory):  # os.walk generates the file names in a directory tree
        for basename in files:
            if fnmatch.fnmatch(
                    basename, pattern
            ):  # Test whether basename matches the pattern string
                filename = os.path.join(root, basename)
                yield filename


if __name__ == '__main__':
    for filepath in find_files(SOURCE_PATH, SOURCE_EXTS):
        print(("Processing: {}".format(filepath)))
        # vtype = face indicates input is a video
        video = Video(
            vtype='face',
            face_predictor_path=FACE_PREDICTOR_PATH).from_video(filepath)

        mkdir_p(TARGET_PATH)
        filepath_wo_ext = os.path.splitext(filepath)[
            0]  # Remove extension from video file name
        target_dir = os.path.join(
            TARGET_PATH,
            filepath_wo_ext)  # Name directory to save each processed video
        mkdir_p(target_dir)

        index = 0
        for frame in video.mouth:
            io.imsave(
                os.path.join(target_dir, "mouth_{0:03d}.png".format(index)),
                frame)
示例#16
0
        path = open(utility_path, 'w')
        print(
            'You have changed the path of Credentials or the file is not exist, please specify it again (open the program again!)'
        )
        path.close()
        exit()

    os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
    credential_dict = {
        'client_secret_file': CLIENT_SECRETS_FILE,
        'scopes': SCOPES,
        'api_name': API_SERVICE_NAME,
        'api_version': API_VERSION,
        'api_key': API_KEY
    }
    video = Video(**credential_dict)
    while True:
        # print choice menu
        print_choice()
        # check if the choice correct
        try:
            choice = int(input("enter choice: "))
        except ValueError:
            choice = -1
        # Getting the video/playlist url and rate if choice is 1 or 2, exit if the choice 3
        data_info = choice_switcher(choice)
        print(
            '\n********************************* The Result *********************************'
        )
        # Extract id and rate
        id_rate_dict = extract_id_rate(data_info)
    log_file = "logs/{} Log.txt".format(datetime.date.today())
    print(line)
    with open(log_file, "a", encoding="utf8") as f:
        f.write(line + "\n")


log("Converter Started at {}".format(datetime.datetime.now()))
media_libraries = {
    "tv": "M:/TV Shows/",
    "movie": "M:/Movies/",
    "animation": "M:/Animated TV Shows/",
}
types = ["**/*." + x for x in Video.FILE_EXTENSIONS]
for type in types:
    for media_type, media_dir in media_libraries.items():
        for file in glob.glob(media_dir + type, recursive=True):
            file = os.path.abspath(file)
            log(file)
            vid = Video(file, media_type)
            log("\tCodec: {}\n\tWidth: {}\n\tBitrate: {}".format(
                vid.codec, vid.width, vid.rate))
            if vid.needs_transcoding:
                log("\tParams: {}".format(vid.params))
                if vid.transcode():
                    log("\tSuccessfully Transcoded")
                else:
                    log("\tTranscode Failed")
            else:
                log("\tNo Transcode Required")
            log("\n")
示例#18
0
         opcion=int(input("¿Donde desea interactuar?\n1)Empleados\n2)Curso\n3)Temas\n4)Videos\n5)Temas Asignados\n6)VideosAsignados\n7)Salir\n >>Seleccione opcion: "))
         break
     except ValueError:
         limpiar_pantalla()
         input("Error, introducir unicamente numero, vuelva a intentar")
 if opcion<1:
         input("Error, introduzca un numero valido ")
 
 elif opcion==1:
     valor=Empleado(0,None,None)
     valor.menu()   
 elif opcion==2:
     valor=Cursos(0,None,None)
     valor.minimenu()
 elif opcion==3:
     valor=Tema(0,0)
     valor.menu()
 elif opcion==4:
     valor=Video(0,0,0,0)
     valor.Minimenu()
 elif opcion==5:
     valor=Curso_Tema(0,0,0)
     valor.Minimenu()
 elif opcion==6:
     valor=Curso_tema_video(0,0,0)
     valor.minimenu()
 elif opcion==7:
     limpiar_pantalla()
     break
 elif opcion>7:
     input("Error, introduzca un numero valido")