Пример #1
0
    def _feature_extractor_component(self):
        """
        Method that creates all feature extraction UI components and their logical
        dependencies.
        """
        # creates a title UI component
        st.sidebar.title("Pick a feature extractor")

        # gets all available extraction strategies
        available_extraction_strategies = ExtractorFactory.values_list()

        # creates a selection box UI component with the available_extraction_strategies
        # and stores the selected in a variable
        self.selected_extractor = st.sidebar.selectbox(
            'Select an extraction strategy', available_extraction_strategies)

        # gets the feature extractor object from the ExtractorFactory
        self.feature_extractor = ExtractorFactory.get(
            self.selected_extractor)()

        # creates the video object with its path and selected extractor name
        self.video = Video(self.video_path, self.selected_extractor)

        # if the video doesn't have features extracted with this extractor
        # it extracts the features
        if self.video.features.has_features is False:
            with st.spinner("Extracting..."):
                self.feature_extractor.extract(self.video)
Пример #2
0
def generate_data(data_dir, detector, transform, device, pose_model, out):
    '''
    Generate series of poses from a folder of videos and then normalize them.
    '''
    data = []
    mask = []
    for filename in tqdm(os.listdir(data_dir)):
        video = Video(os.path.join(data_dir, filename), detector, transform,
                      device, pose_model)
        video.extract_poses()
        generator = PoseSeriesGenerator(video, 10, 7)
        series, mask_ = generator.generate()
        data.extend(series)
        mask.extend(mask_)
    data = np.asarray(data)
    mask = np.asarray(mask)

    # get the head by taking the average of five key points on the head (nose, left_eye, right_eye, left_ear, right_ear)
    data[:, :, 4][mask] = np.mean(data[:, :, :5][mask], axis=1)
    data = data[:, :, 4:]

    # min-max normalization
    min = np.min(data[:, :, :, :2][mask], axis=1, keepdims=True)
    max = np.max(data[:, :, :, :2][mask], axis=1, keepdims=True)
    data[:, :, :, :2][mask] = (data[:, :, :, :2][mask] - min) / (max - min)

    # get the origin by taking the average of four key points on the body (left_shoulder, right_shoulder, left_hip, right_hip)
    origin = (np.sum(data[:, :, 1:3, :2][mask], axis=1, keepdims=True) +
              np.sum(data[:, :, 7:9, :2][mask], axis=1, keepdims=True)) / 4

    # shift the origin
    data[:, :, :, :2][mask] = data[:, :, :, :2][mask] - origin

    # save into file
    np.save(out, data)
Пример #3
0
    def __iter__(self):
        for idx in range(len(self.df)):
            video_id = self.df.video_id.loc[idx]
            start = self.df.middle_frame_timestamp.loc[idx]
            path = glob(os.path.join(self.root, video_id + "*"))[0]

            vid = Video(path, debug=False)
            video_frames = []  # video frame buffer

            if self.fp != "beginning":
                # FIXME: this is approximate situation
                fps = vid.metadata[vid.current_stream]['fps']
                start = max(0, start - float((self.clip_len // 2) * fps))

            vid.seek(start, stream="video", any_frame=True)
            while len(video_frames) < self.clip_len:
                frame, current_pts = vid.next("video")
                video_frames.append(self.frame_transform(frame))

            # stack it into a tensor
            video = torch.stack(video_frames, 0)
            if self.video_transform:
                video = self.video_transform(video)
            output = {
                'path': path,
                'video': video,
                # These are a pain lenghts of these is not constant,
                'person_id': self.df.person_id.loc[idx],
            }
            yield output
Пример #4
0
    def __init__(self, title, description, rating, poster_image_url,
                 trailer_youtube_url, duration):

        Video.__init__(self, title, description, rating, poster_image_url,
                       trailer_youtube_url)

        self.duration = duration
Пример #5
0
def video_files_cleaner():
    while True:
        app.logger.debug('Deleting paid videos older than %d hours',
                         Settings.PAID_VIDEO_TIMEOUT)
        ttl = datetime.now() - timedelta(hours=Settings.PAID_VIDEO_TIMEOUT)
        for video in Video.select().where(Video.paid == True,
                                          Video.date_time < ttl):
            try:
                app.logger.debug('Deleting video %s', video.uuid)
                os.remove(video.original_file_path)
                os.remove(video.converted_file_path)
                # Remove record from DB
                # video.delete_instance()
            except:
                app.logger.error('Failed to delete %s', video.uuid)
                continue

        app.logger.debug('Deleting unpaid videos older than %d hours',
                         Settings.UNPAID_VIDEO_TIMEOUT)
        ttl = datetime.now() - timedelta(hours=Settings.UNPAID_VIDEO_TIMEOUT)
        for video in Video.select().where(Video.paid == False,
                                          Video.date_time < ttl):
            try:
                app.logger.debug('Deleting video %s', video.uuid)
                os.remove(video.original_file_path)
                os.remove(video.converted_file_path)
                # Remove record from DB
                # video.delete_instance()
            except:
                app.logger.error('Failed to delete %s', video.uuid)
                continue

        # Make a check once an hour
        sleep(1 * 60 * 60)  # 1 hour
Пример #6
0
 def __init__(self, details):
     """Creates a new instance of a TvShow. Should be provided with media
         details in a given object, including some values specific to TV."""
     Video.__init__(self, details)
     self.seasons = details['seasons']
     self.network_url = details['network_url']
     self.rating = Video.get_rating(self, TvShow.VALID_RATINGS, details['rating'])
Пример #7
0
	def autoAd(self, dir):
		# Find all files in the dir
		files = listFiles(os.path.join(settings.MEDIA_DIR, dir))
		
		# Now sort the files alphabetically
		files.sort()
		
		# Get rid of files that don't have a media extension
		temp = []
		for file in files:
			found = False
			for extension in settings.SERIES_AUTOFIND_EXTENSIONS:
				if file.endswith("." + extension):
					found = True
			if found:
				temp.append(file)
		files = temp
		
		# Now make video objects for remaining files
		self.videos = []
		for file in files:
			newVideo = Video()
			newVideo.path = os.path.join(dir, file)
			newVideo.number = files.index(file)
			self.ads.append(newVideo)
Пример #8
0
def video_processor():
    while True:
        try:
            not_processesed_videos = Video.select().where(
                Video.converted_file_size == -1).order_by(
                    Video.date_time.asc())
        except Video.DoesNotExist:
            sleep(15)  # if no video to process then sleep 15 sec
            continue

        if not not_processesed_videos:
            sleep(15)  # if no video to process then sleep 15 sec
            continue

        with concurrent.futures.ProcessPoolExecutor(
                max_workers=Settings.PROCESSINGS_THREADS_NUM) as executor:
            # for video in not_processesed_videos:
            futures = {
                executor.submit(convert_fisheye_video,
                                video.original_file_path,
                                video.converted_file_path, video.angle,
                                video.rotation): video
                for video in not_processesed_videos
            }

            app.logger.info('Started video processing')
            concurrent.futures.wait(futures)
            not_processesed_videos = Video.select().where(
                Video.converted_file_size == -1).order_by(
                    Video.date_time.asc())
            app.logger.info('Currently %d videos in processing queue',
                            not_processesed_videos.count())
Пример #9
0
def get_info_list(path):
    workspace_path = path + "/workspace"
    pic_info = []
    pic_info.append(PIC_SHEET_TITLE)
    vid_info = []
    vid_info.append((VID_SHEET_TITLE))
    target_files = []

    for root, dirs, files in os.walk(workspace_path):
        for file in files:
            tmp_file = root + "/" + file
            target_files.append(tmp_file)

    for file in sort_by_creation_time(target_files):
        _, file_suffix = file.split(".")
        if file_suffix in PIC_FORMAT:
            pic = Picture(file)
            pic_item = pic.get_info()
            pic_info.append(pic_item)  #二维列表
        elif file_suffix in VID_FORMAT:
            vid = Video(file)
            vid_item = vid.get_info()
            vid_info.append(vid_item)
        else:
            continue
    return pic_info, vid_info
Пример #10
0
    def startVideo(self, vidName, vidPath):
        # create the video object
        self.currVideo = Video(vidName, vidPath)

        # start recording the video
        self.picam.start_recording(self.currVideo.getFullPath())
        return
 def displayVideo(self, file_path, width=None, height=None):
     if width == None:
         width = self.width
     if height == None:
         height = self.height
     video = Video(self.disp, width, height, file_path)
     video.play()
    def __create_bags(self, video_collection, total_bags=1):
        # Create an empty bag collection
        bags = []
        count = 0

        # Load and collect a number of bags from the given video collection
        for current_bag in range(total_bags):
            count += 1
            video = None

            # Continually load videos until it finds a video that contains a valid number of frames
            while True:
                # Randomly choose video from video collection
                row = random.choice(video_collection)

                # Load the given video
                print("Loading video: %s..." % (row[0]))
                video = Video(row[0],row[1])
                video.resize(self.img_width, self.img_height)
                instances = video.getSegments()
                print("FINISHED!!!")
                print("Loaded video shape: %s" % (str(instances.shape)))

                # Exit out of the loop if the video is valid
                if instances.shape[0] > 0:
                    break

            # Add bag to collection
            bags.append(instances)

        # Create Numpy array
        bags = np.vstack(bags)
        print("Loaded video of shape: %s" % (str(bags.shape)))
        return bags
Пример #13
0
def admin():
    if "loggedin" in session:
        print("buzz")
        if request.method == "GET":
            videos = Video.objects()
            return render_template('admin.html', videos=videos)
        elif request.method == "POST":
            form = request.form
            link = form['link']
            ydl = YoutubeDL()

            data = ydl.extract_info(link, download=False)
            title = data['title']
            thumbnail = data['thumbnail']
            views = data['view_count']
            youtube_id = data['id']
            video = Video(title=title,
                          thumbnail=thumbnail,
                          views=views,
                          youtube_id=youtube_id,
                          link=link)
            video.save()
            return link
    else:
        return redirect(url_for("login"))
    def __init__(self, title, description, rating, poster_image_url,
                 trailer_youtube_url, seasons):

        Video.__init__(self, title, description, rating, poster_image_url,
                       trailer_youtube_url)

        self.seasons = seasons
Пример #15
0
    def __init__(self, verbose=False):
        self.verbose = verbose
        self.status_counter = 0
        self.state = self.STATE_WAITING
        self.currenttime = 0
        self.flex_fish_limit = self.FLEX_FISH_LIMIT
        self.player = Player(self, verbose)
        self.adc_sensors = AdcSensors(self, verbose)
        self.motors = Motors(self, verbose)
        self.web_connection = WebConnection(self, verbose)
        self.gps_tracker = GpsTracker(self, verbose)
        self.video = Video(self, verbose)

        # Initial valus for settings
        # Speed: (0-1). 1 = Full speed ahead
        # Turn = -1 - +1  = +1 Only left motor on (turn to right)
        #                    0 Both motors same speed
        #                   -1 Only right motor on (turn to left)
        self.speed = 0.0
        self.turn = 0.0
        # speed style examples:
        #   - Constant speed = (low_speed_percent = 100)
        #   - Stop and go jigging with 6 sec motor on and 4 sec stop. low_speed_percent = 0,speed_change_cycle = 10, speed_motors_full_percent = 60
        #   - Trolling with 10 sec half speed and 5 sec full speed. low_speed_percent = 50, speed_change_cycle = 15, speed_motors_full_percent = 66.66
        self.speed_change_cycle = 0
        self.speed_motors_full_percent = 100
        self.low_speed_percent = 0

        # Play music or not
        self.play_music = False
 def do_POST(self):
     if not self.path.startswith("/video"):
         self.send_error(404, "Page Not Found")
         return        
     
     header = self.headers.getheader('content-type')              
     content_len = int(self.headers.getheader('content-length', 0))
     post_body = self.rfile.read(content_len)            
     
     if header == "application/json":            
         dict = json.loads(post_body)
     else:
         self.send_error(400, "This server only accepts application/json POST data")         
     
     v = Video()
     try:                
         v.fromJson(dict)
         videoRepository.addVideo(v)
         
         self.send_response(200)
         self.send_header("Content-type", "application/json")
         self.end_headers() 
         self.wfile.write('{"status": "OK", "description": "Video added"}')
     except(KeyError):    
         self.send_error(400, "Missing ['name','duration','url'].")            
Пример #17
0
    def __iter__(self):
        for i in range(len(self.samples)):
            # get random sample
            path, target = self.samples[i]
            # get video object
            vid = Video(path, debug=False)
            video_frames = []  # video frame buffer
            # seek and return frames

            max_seek = vid.metadata[vid.current_stream]['duration'] - (
                self.clip_len / vid.metadata[vid.current_stream]['fps'] +
                self.alpha)
            step = max(max_seek // self.num_steps, 1)
            tss = [
                i.item() for i in list(
                    torch.linspace(0, max_seek, steps=self.num_steps))
            ]
            for start in tss:
                vid.seek(start, stream="video", any_frame=True)
                while len(video_frames) < self.clip_len:
                    frame, current_pts = vid.next("video")
                    video_frames.append(self.frame_transform(frame))
                # stack it into a tensor
                video = torch.stack(video_frames, 0)
                if self.video_transform:
                    video = self.video_transform(video)
                output = {
                    'path': path,
                    'video': video,
                    'target': target,
                    'start': start,
                    'end': current_pts
                }
                yield output
Пример #18
0
 def reset(cls):
   """Reset to default state."""
   Box.reset()
   Note.reset()
   Figure.reset()
   Table.reset()
   Video.reset()
Пример #19
0
 def __iter__(self):
     for i in range(self.epoch_size):
         # get random sample
         path, target = random.choice(self.samples)
         # get video object
         vid = Video(path, debug=False)
         video_frames = [] # video frame buffer 
         # seek and return frames
         max_seek = vid.metadata[vid.current_stream]['duration'] - (self.clip_len / vid.metadata[vid.current_stream]['fps'] + self.alpha)
         start = random.uniform(0., max_seek)
         vid.seek(start, stream="video", any_frame=self.from_keyframes)
         while len(video_frames) < self.clip_len:
             frame, current_pts = vid.next("video")
             video_frames.append(self.frame_transform(frame))
         # stack it into a tensor
         video = torch.stack(video_frames, 0)
         if self.video_transform:
             video = self.video_transform(video)
         output = {
             'path': path,
             'video': video,
             'target': target,
             'start': start,
             'end': current_pts}
         yield output
Пример #20
0
 def __init__(self,movie_title, duration,movie_storyline, poster_image_url,trailer_youtube_url):
     Video.__init__(self,movie_title,duration)
     #self.title=movie_title
     #self.duration = duration
     self.storyline = movie_storyline
     self.poster_image_url = poster_image_url
     self.trailer_youtube_url = trailer_youtube_url
Пример #21
0
 def download(self, download_path: str = "downloads"):
     # TODO: Add creating folders if not exist
     videos = [
         "https://www.cda.pl/video/2486267d4",
         "https://www.cda.pl/video/248630943",
         "https://www.cda.pl/video/250105452",
         "https://www.cda.pl/video/2518128a9",
         "https://www.cda.pl/video/2531640cb",
         "https://www.cda.pl/video/2546847e8",
         "https://www.cda.pl/video/256809044",
         "https://www.cda.pl/video/2583666bd",
         "https://www.cda.pl/video/25999076f",
         "https://www.cda.pl/video/261542952",
         "https://www.cda.pl/video/2652516eb",
         "https://www.cda.pl/video/2671470a4",
         "https://www.cda.pl/video/3424375c3",
         "https://www.cda.pl/video/3443971c3",
         "https://www.cda.pl/video/3463282e8",
         "https://www.cda.pl/video/3485605e6",
         "https://www.cda.pl/video/351312746",
         "https://www.cda.pl/video/35377301f",
         "https://www.cda.pl/video/35612772a",
         "https://www.cda.pl/video/358452193",
         "https://www.cda.pl/video/360697930",
         "https://www.cda.pl/video/362523795"
     ]
     for url in videos:
         video = Video(url)
         print(url)
         video.download(download_path)
Пример #22
0
 def reset(cls):
     """Reset to default state."""
     Box.reset()
     Note.reset()
     Figure.reset()
     Table.reset()
     Video.reset()
Пример #23
0
def videos_list():
    if request.method == 'POST':
        # We are only expecting the URL and Directory
        data = request.json
        vid_url = data["data"]["attributes"]["url"]
        vid_dir = data["data"]["attributes"]["directory"]
        if vid_url == None:
            return mod_response({'error': 'URL not specified'}, 400)
        if vid_dir == None:
            vid_dir = ""

        # Create the Video row & object
        rowId = create_row(vid_url, "", "Pending", "Placed in Queue", vid_dir,
                           "")
        newVid = Video(rowId, vid_url, "", "Pending", "Placed in Queue",
                       vid_dir, "")

        # Pass this video object to the Queue
        q.put(newVid)

        return mod_response({'data': newVid.toJson()}, 201)

    else:
        data = {
            'data': [
                Video(row[0], row[1], row[2], row[3], row[4], row[5],
                      row[6]).toJson() for row in get_all_rows()
            ]
        }

        return mod_response(data, 200)
Пример #24
0
def table_dump():
    try:
        with open(location) as f:
            table = f.read().splitlines()
    except FileNotFoundError:
        f2 = open(location, "w+")
        f2.close()
        table_dump()
    # Change rows to amount of "queued" videos
    video_list = []
    times = []
    videos = []
    flags = []

    for row in table:
        print(row, "row")
        try:
            h, m, s, name, args = row.split(',')  # to be safe(and readable), always put the ' '
            print("Phase 1")
            h, m, s = map(int, (h, m, s))  # convert these to int
            print(name, "name")
            length = getLength(name)
            print(length, "length")
            times.append(":".join([str(h), str(m), str(s)]))
            videos.append(name)
            flags.append(args)
            print("Phase 2")
            # make sure video uses os-specific directory separator
            print("Not removed", name)
            name = name.replace("C:/", "")
            print("Removed", name)
            name_split = name.split("/")
            print("System: ", platform.system())
            if platform.system() == "Windows":
                print("Windows!")
                name_split.insert(0, "C:\\")
                print(name_split, "splitname")
                name = os.path.join(*name_split)
            else:
                print(name_split, "splitname")
                name = "/" + os.path.join(*name_split)

            print("Name:", name)
            if h != -1:
                video_list.append(Video(h, m, s, name, ["--fullscreen"], length, True))
            else:
                video_list.append(Video(h, m, s, name, ["--fullscreen"], length, False))
            # print("Video list:", video_list)

            # Enqueue videos for playing. If the video is set to play manually, do not enqueue.
                # we need a list to keep track of these threads, so they can be stopped later if the video is deleted
            print(times, videos, flags, "total")
        except (IndexError, ValueError):
            print(row, "row-except")
            print("excepted")
            continue

    print("Video list:", video_list)
    model = VideoTableModel(None, video_list, ["Video File Name", "Play Time", "Duration"])
    ui.table_videos.setModel(model)
Пример #25
0
 def validation_video_ids(self):
     # return ids that belong to validation videos, regardless if the labels are valid or not
     print('val ids...')
     val_indices = np.nonzero(self.val_ids == 1)[0]
     val_video_id = []
     for i in val_indices:
         val_video_id.append(self.video_id[i])
     self.unique_val_videos = sorted(list(
         set(val_video_id)))  # val should be 145 videos
     assert len(self.unique_val_videos) == 145
     self.val_video_indices = []
     self.val_video_real_names = []
     self.val_video_types = []
     for vid in self.unique_val_videos:
         tmp = [
             i for i in range(len(self.video_id))
             if self.video_id[i] == vid and self.val_ids[i] == 1
         ]
         self.val_video_indices.append(tmp)
         # append the "real name
         position = get_position(vid)
         vid_path = os.path.join(self.video_dir, vid + '.mp4')
         vid_path2 = os.path.join(self.video_dir, vid + '.avi')
         if os.path.isfile(vid_path):
             real_name = Video(vid_path).meta['original_video']
         elif os.path.isfile(vid_path2):
             real_name = Video(vid_path2).meta['original_video']
         else:
             print(vid_path)
             print(vid_path2)
             raise NameError('video not found')
         self.val_video_real_names.append(real_name + position)
         # check what types should be processed for this video
         self.val_video_types.append(
             self.get_types_from_name_split(vid, 'val'))
Пример #26
0
 def testCheckVideoInput(self):
     self.hyperlapse.checkVideoInput()
     self.hyperlapse.video = Video('')
     self.assertRaises(InputError, self.hyperlapse.checkVideoInput)
     self.hyperlapse.video = Video(
         '/home/victorhugomoura/Documents/example.csv')
     self.assertRaises(InputError, self.hyperlapse.checkVideoInput)
    def __init__(self, movie_title, movie_description, movie_poster_image_url,
                 movie_trailer_youtube_url):
        """Initiate the movie instance.

        Args:
            movie_title: A string representing the movie title.
            movie_description: A string representing the movie description.
            movie_poster_image_url: A string representing the movie poster image url.
            movie_trailer_youtube_url: A string representing the movie trailer youtube url.

        Returns:
            Nothing.
        """
        Video.__init__(self, movie_title, movie_description,
                       movie_poster_image_url, movie_trailer_youtube_url)
        self.storyline = "movie_storyline"
        self.director = "Unknown"
        self.writers = "writers"
        self.stars = "stars"
        self.taglines = "taglines"
        self.genres = "genres"
        self.country = "country"
        self.language = "language"
        self.release_date = "release_date"
        self.runtime = "runtime"
Пример #28
0
    def __init__(self, verbose, scale):
        #
        self._verbose = verbose
        # CPU properties
        # 16 general purpose 8-bit registers
        self._reg = array.array(
            'B', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
        # 16-bit register
        self._I = array.array('H', [0])
        # Timers delay = 0 / sound = 1
        self._timer = array.array('B', [0, 0])
        # Stack
        self._stack = array.array(
            'H', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
        # Program Counter
        self._PC = array.array('H', [0x0200])
        # Memory
        self.memory = Memory()
        # Video
        self.video = Video(verbose, scale)
        # Key states
        self._keystate = array.array(
            'B', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

        # private properties
        self.__ips = 60
        self.clock = pygame.time.Clock()
Пример #29
0
 def __init__(self, parent=None, max_buf_size=500):
     super(VideoWidget, self).__init__(parent)
     self.video = Video(max_buf_size=max_buf_size)
     self.max_buf_size = max_buf_size
     self.init_ui()
     self.slider.sliderReleased.connect(self.on_slider_released)
     self.installEventFilter(self)
def main():
    print('Initializing camera')
    with picamera.PiCamera() as camera:
        camera.resolution = (WIDTH, HEIGHT)
        camera.framerate = FRAMERATE
        camera.vflip = VFLIP  # flips image rightside up, as needed
        camera.hflip = HFLIP  # flips image left-right, as needed
        sleep(1)  # camera warm-up time
        print('Initializing websockets server on port %d' % WS_PORT)
        WebSocketWSGIHandler.http_version = '1.1'
        websocket_server = make_server(
            '',
            WS_PORT,
            server_class=WSGIServer,
            handler_class=WebSocketWSGIRequestHandler,
            app=WebSocketWSGIApplication(handler_cls=StreamingWebSocket))
        websocket_server.initialize_websockets_manager()
        websocket_thread = Thread(target=websocket_server.serve_forever)
        print('Initializing HTTP server on port %d' % HTTP_PORT)
        http_server = StreamingHttpServer()
        http_thread = Thread(target=http_server.serve_forever)
        print('Initializing broadcast thread')
        output = BroadcastOutput(camera)
        broadcast_thread = BroadcastThread(output.converter, websocket_server)
        print("Initialize video object")

        # Initialize the face detection with the camera object
        # that is being used by the live streaming thread.
        video = Video(camera, cascPath="./cascade.xml")
        print('Starting recording')
        camera.start_recording(output, 'yuv')
        try:
            print('Starting websockets thread')
            websocket_thread.start()
            print('Starting HTTP server thread')
            http_thread.start()
            print('Starting broadcast thread')
            broadcast_thread.start()

            # Start the video thread.
            print("Start video")
            video.start()
            while True:
                camera.wait_recording(1)
        except KeyboardInterrupt:
            pass
        finally:
            print('Stopping recording')
            camera.stop_recording()
            print('Waiting for broadcast thread to finish')
            broadcast_thread.join()
            print('Shutting down HTTP server')
            http_server.shutdown()
            print('Shutting down websockets server')
            websocket_server.shutdown()
            print('Waiting for HTTP server thread to finish')
            http_thread.join()
            print('Waiting for websockets thread to finish')
            websocket_thread.join()
Пример #31
0
 def __init__(self, title, poster_img, dur, trailer, series_start, series_end,
              number_of_seasons, number_of_episodes, plot_summary):
     Video.__init__(self, title, poster_img, Tvseries.__name__, dur, trailer)
     self.start_date = series_start
     self.end_date = series_end
     self.seasons = number_of_seasons
     self.episodes = number_of_episodes
     self.plot = plot_summary
Пример #32
0
 def __init__(self, dirPath):
     Video.__init__(self, dirPath)                   # Call parent contructor
     self.curTrailerName = self._getTrailerFile()    # Current Trailer FileName
     self.imdbUrl        = None                      # URL to IMDB Info
     self.imdbInfo       = None                      # IMDB information
     self.imdbUpdate     = None                      # Date we last searched IMDB
     self.trailerUrl     = None                      # New TrailerAddict URL
     self._newInfoFound  = False                     # Set True when New Info is Found
Пример #33
0
def main(a):
    srt = pysrt.open('tmp/sub.srt')
    for i in range(0, 10):
        text = random.choice(srt).text
        path = 'F:\Filmid\[ www.CpasBien.cm ] Zootopia.2016.MULTi.1080p.BluRay.x264-VENUE.mkv'
        video = Video(text, path, a)
        video.start()
        print i
Пример #34
0
    def __init__(self, video_path, options):
        self.options = options

        self.detector = Detector()
        self.video = Video(video_path)
        self.video_writer = VideoWriter(self.options["outputfile"], self.video)
        self.summary = {}
        self.current_frame_category = ""
Пример #35
0
    def __init__(self, device='udp:192.168.2.1:14550', baudrate=115200):
        """ BlueRov ROS Bridge

        Args:
            device (str, optional): mavproxy device description
            baudrate (int, optional): Serial baudrate
        """
        super(BlueRov, self).__init__(device, baudrate)
        self.pub = Pubs()
        self.sub = Subs()
        self.ROV_name = 'BlueRov2'
        self.model_base_link = '/base_link'

        self.video = Video()
        self.video_bridge = CvBridge()

        self.pub_topics = [
            [self._create_battery_msg, '/battery', BatteryState, 1],
            [self._create_camera_msg, '/camera/image_raw', Image, 1],
            [self._create_ROV_state, '/state', State, 1],
            [self._create_imu_msg, '/imu/data', Imu, 1],
            [self._create_odometry_msg, '/odometry', Odometry, 1],
            [self._create_bar30_msg, '/bar30', Bar30, 1],
            [self._create_imu_euler_msg, '/imu/attitude', Attitude, 1]
        ]

        self.sub_topics = [
            [
                self._setpoint_velocity_cmd_vel_callback,
                '/setpoint_velocity/cmd_vel', TwistStamped, 1
            ],
            [
                self._set_servo_callback, '/servo{}/set_pwm', UInt16, 1,
                [1, 2, 3, 4, 5, 6, 7, 8]
            ],
            [
                self._set_rc_channel_callback, '/rc_channel{}/set_pwm', UInt16,
                1, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
            ], [self._set_mode_callback, '/mode/set', String, 1],
            [self._arm_callback, '/arm', Bool, 1],
            [self._manual_control_callback, '/manual_control', Joy, 1]
        ]

        self.mavlink_msg_available = {}

        for _, topic, msg, queue in self.pub_topics:
            self.mavlink_msg_available[topic] = 0
            self._pub_subscribe_topic(topic, msg, queue)

        for topic in self.sub_topics:
            if len(topic) <= 4:
                callback, topic_name, msg, queue = topic
                self._sub_subscribe_topic(topic_name, msg, queue, callback)
            else:
                callback, topic_name, msg, queue, arg = topic
                for name in arg:
                    self._sub_subscribe_topic(topic_name.format(name), msg,
                                              queue, callback)
def walk(model, samples_z, out_dir, inv_transform=None):
    print('Outputting walk video')
    model.phase = 'test'
    walk_video = Video(os.path.join(out_dir, 'walk.mp4'))
    for z in random_walk(samples_z, 150, n_dir_steps=10, change_fraction=0.1):
        x = model.decode(z)
        if inv_transform is not None:
            x = inv_transform(x)
        walk_video.append(dp.misc.img_tile(x))
Пример #37
0
	def __init__(self, title, story_line, poster_image_url,
				 trailer_youtube_url, rating, duration, release_year):

		# Call base class init with appropriate init variables
		Video.__init__(self, title, story_line, poster_image_url, trailer_youtube_url)
		
		self.rating = rating
		self.duration = duration
		self.release_year = release_year
Пример #38
0
def _set_monitoring(value):
    global is_monitoring
    if value == video.ON_STRING:
        is_monitoring = True
    else:
        is_monitoring = False
        if video.recording:
            Video.generate_thumbnail(video.stop_recording(), hres=args.horizontal_resolution,
                                     vres=args.vertical_resolution)
Пример #39
0
def main(args):
  """
    Mainline of application
  """
  
  config = config_from_args(args)
  
  if config.single['id'] != '':
    id = int(config.single['id'])
    v = Video(config, id)
    s = SubtitleV4(config, id)
    filename = '%s.srt' % (os.path.basename(v.video_url()))
    s.download(filename)
    v.download()
  elif config.search['query'] == default_config.search['query']:
    print 'Please specify a query. Example: "--search-query=Queen Seon Deok"'
    sys.exit(1)
  else:
    searcher = ChannelSearcher(config)
    channels = searcher.search(config.search['query'], config.search['method'])
    
    for channel in channels:
      sys.stdout.write('Channel: %s\n' %(channel.name))
      for episode in channel.episodes():
        sys.stdout.write('Episode: %s\n' % (episode.episode_num))
        media_id = episode.media_id
        
        video = Video(config, media_id)
        if not config.video['skip']:
          video.download()
        
        video_info = video.video_info()
        
        filename = video.filename()
        
        # remove the extension
        filename = os.path.splitext(filename)[0]
        
        if config.subtitles['check_parts']:
          # videos that have multiple subtitle parts will need
          # to have them downloaded separately and merged
          parts = VideoParts(config, episode.full_url).parts()
          first = True
          start_index = 0
          for part in parts:
            start_time = int(part['part_info']['start_time'])
            subtitle = Subtitle(config, part['media_resource_id'], start_index, start_time)
            if first:
              subtitle.download(filename)
              first = False
            else:
              subtitle.merge(filename)
            start_index = subtitle.end_index
        else:
          media_resource_id = video.media_resource(video_info)
          subtitle = Subtitle(config, media_resource_id)
          subtitle.download(filename)
    def test_i3d(self):
        i3d = I3DStrategy()
        video = Video(self.video_path, ExtractorFactory.I3D.value)

        i3d.extract(video)
        features = video.features()

        self.assertIsInstance(features, np.ndarray)
        assert features.shape == (17, 2048)
def goGetEm():
	minRemovalScore = 0.0001
	timeOut = 10
	cleanThresh = 5
	binNumber = 100
	distanceWeight = 0.5
	sizeWeight = 0.0
	timeWeight = 0.5
	weights = (distanceWeight, timeWeight, sizeWeight)
	writingToFiles = True
	distDev = 200
	timeDev = 0.34
	sizeDev = 0.25
	devs = (distDev, timeDev, sizeDev)
	framesback = 2
	variables = [minRemovalScore, timeOut, cleanThresh, binNumber, weights, writingToFiles, devs, framesback]
	vid = Video(0, variables)
	# vidFile = "outvid.avi"
	# csvFile = "variable.csv"
	# if writingToFiles:
	# 	vid.openVidWrite(vidFile)
	# 	vid.openCSVWrite(csvFile)
	while (True):
		vid.readFrame()
		vid.findFaces()
		vid.display()
		# vid.writeToVideo()
		# exit on escape key
		key = cv2.waitKey(1)
		if key == 27:
			break
	vid.endWindow()
Пример #42
0
 def __init__(self, movie_title, movie_storyline,
              poster_image,
              trailer_youtube,
              duration,
              ratings):
     Video.__init__(self, movie_title, duration)
     self.storyline = movie_storyline
     self.poster_image_url = poster_image
     self.trailer_youtube_url = trailer_youtube
     assert(ratings in self.VALID_RATINGS)
     self.ratings = ratings
Пример #43
0
	def auto(self, dir):
		# Find all files in the dir
		files = listFiles(os.path.join(settings.MEDIA_DIR, dir))
		
		# Now sort the files alphabetically
		files.sort()

		# Check for pickle file
		temp = files
		for file in files:
			# Check if this file is the pickle file.
			if file == ".pickle":
				# Load this file
				self.pickle = pickle.load(open(os.path.join(settings.MEDIA_DIR, dir, ".pickle"), "rb"))
				temp.remove(file)
		files = temp
		
		# Get rid of files that don't have a media extension
		temp = []
		for file in files:
			found = False
			for extension in self.extensions:
				if file.endswith("." + extension):
					found = True
			if found:
				temp.append(file)
		files = temp
		
		
		# Now make video objects for remaining files
		self.videos = []
		for file in files:
			newVideo = Video()
			newVideo.path = os.path.join(dir, file)
			newVideo.number = files.index(file)
			
			# While we are here, we can check if there are any subs for this video
			if "subs" in listDirs(os.path.join(settings.MEDIA_DIR, dir)):
				for sub in listFiles(os.path.join(settings.MEDIA_DIR, dir, "subs")):
					
					# Check if any of these subs match the video
					if sub.split(".")[0] == file.split(".")[0]:
						
						# Cool, this file has some subtitles
						newVideo.sub_path = os.path.join(settings.MEDIA_DIR, dir, "subs", sub)

			self.videos.append(newVideo)
				
			
		# Make this dir our new path
		self.path = os.path.join(settings.MEDIA_DIR, dir)
		
		# Make sure we note how many files there were.
		self.pickle.num = len(self.videos)
Пример #44
0
 def scrapPage(self, page):
     videoDOMs = self.findVideoDOMs(self.requestPage(page))
     for videoDOM in videoDOMs:
         link     = self.formatLinkDOM(self.findLinkDOM(videoDOM))
         title    = self.formatTitleDOM(self.findTitleDOM(videoDOM))
         duration = self.formatDurationDOM(self.findDurationDOM(videoDOM))
         views    = self.formatViewsDOM(self.findViewsDOM(videoDOM))
         rating   = self.formatRatingDOM(self.findRatingDOM(videoDOM))
         
         vid = Video(link, title, duration, views, rating)
         vid.printVid()
         self.vid_list.append(vid)
Пример #45
0
 def parse(self):
     """
     Consume the feed.
     """
     feed = feedparser.parse(self.rss_url)
     for entry in feed.entries:
         entry['published_parsed'] = str(entry.get('published_parsed'))
         entry['thumbnail'] = Image.get_smallest_image(entry.media_thumbnail)
         if len(entry.media_content) > 0:
             entry['duration'] = Video.get_duration(entry.media_content[0])
             entry['video_codec'] = Video.get_codec(entry.media_content[0])
             entry['bitrate'] = Video.get_bitrate(entry.media_content[0])
     return feed.entries
Пример #46
0
 def __init__(self, parent=None, max_buf_size=500):
     super(VideoWidget, self).__init__(parent)
     self.video = Video(max_buf_size=max_buf_size)
     self.max_buf_size = max_buf_size
     self.init_ui()
     self.slider.sliderReleased.connect(self.on_slider_released)
     self.installEventFilter(self)
Пример #47
0
 def get_parent_video(self):
     from video import Video #need to keep this here to avoid circular import...
     vids = Video.get_all(filter_str="WHERE id=%d" % self.vid)
     if len(vids) != 1:
         self.log.error("ERROR: invalid parent video")
         return None
     else:
         return vids[0]
 def run(self, information):
   # On a fini de telecharger la video
   self.parent._status["current_video"] = None
   assert self.transcode_queue
   video = Video(url=information["url"], name=information["title"],
                 description=information.get("description",
                                             "Pas de description"),
                 date=int(time.time()),
                 unique_id=self.unique_id,
                 pipeline_name=self.pipeline_name)
   video.already_downloaded = True
   video.already_transcoded = False
   video.local_filename = information['filepath']
   self.downloaded_files.add(video)
   logging.info("YoutubePostProcessor: %s finished" % video.name)
   self.transcode_queue.put(video)
   return information
Пример #49
0
            def add_hash():
                SqlClass.turn_off_commits()
                videos = Video.get_all()
                tags = [video.get_tags() for video in videos]
                # We need to get all the frame info before
                # we erase the video table!
                for tag_ls in tags:
                    for tag in tag_ls:
                        tag._populate_frame_dict()

                for video in videos:
                    if not video.present():
                        self.log.error("Not all videos are present, cannot upgrade database!")
                        return False

                [video.remove() for video in videos]
                Video.remove_table()
                Video.table_setup()
                for i, video in enumerate(videos):
                    video.video_hash = \
                      hash_video(self.get_absolute_path(video.video_path))
                    Video.add(video)
                    for tag in tags[i]:
                        self.log.info("Adding tag %s in video %s" %(tag, video.video_path))
                        Tag.tag_add(tag)

                SqlClass.turn_on_commits()
                self.conn.commit()
                return True
Пример #50
0
def main():

	gfx = Video()
	inp = Input()
	gui = GUI()

	# Initialize
	try:
		gfx.initialize()
		inp.initialize()
		gui.initialize()
	except InitializationError as error:
		print(error)
		return 1

	# Setup the interface
	gui.setupInterface()

	# Main Loop
	gfx.enterMainLoop()

	# Done
	# - We will never actually get here.
	gfx.shutdown()
	
	return 0
Пример #51
0
    def copy_video(self, vhash, source_db, dest_db, copy_tags=False):
        Video.link_sqlite(source_db)
        v = self.hash_to_vid(vhash)
        self.log.info("Copy video %s" % v)
        video_params = {}
        for k in v.__get_table_keys__():
            if k not in v.ban_keys:
                video_params[k] = getattr(v, k)
        Video.link_sqlite(dest_db)
        new_vid = Video.new(**video_params)

        if copy_tags:
            Tag.link_sqlite(source_db)
            for t in v.get_tags():
                new_tag = self.copy_tag(t, source_db, dest_db, copy_tag_data=True)
                new_tag.set_parent(new_vid)

        return new_vid
Пример #52
0
class Model(GObject.GObject):
    __gsignals__ = { 'audio-ready': (GObject.SIGNAL_RUN_LAST, None, ()) }

    video = None
    audio = None
    subtitles = Subtitles()
    voReference = cVOReference()
    ready = False
    voFilename = ""
    subFilename = ""
    peakFilename = ""
    projectFilename = ""

    def __init__(self):
        super(Model, self).__init__()
        Gst.init(None)
        self.video = Video()
        self.audio = None
        self.subtitles = Subtitles()
        self.voReference = cVOReference()
        self.ready = False
        # File Names
        self.voFilename = ""
        self.subFilename = ""
        self.peakFilename = ""
        self.projectFilename = ""

    def setup_audio(self, buffers):
        self.audio = Audio(*buffers)
        self.ready = True
        self.emit("audio-ready")

    def get_waveform(self):
        if self.peakFilename == "":
            return
        f = open(self.peakFilename.decode('utf-8'), 'rb')
        dataFile = load(f)
        hiAudio = dataFile['arr_0']
        lowAudio = dataFile['arr_1']
        f.close()
        self.audio = Audio(hiAudio, lowAudio)
        self.video.calc_duration()
        self.ready = True
        self.emit("audio-ready")
class Scene(object):
    def __init__(self, scenecfg, basepath='./', length=1):
        self.videofiles = []
        self.video = Video(scenecfg['video'], basepath, length)
        self.audio = Audio(scenecfg['sound'], basepath, self.video)
        self.length = scenecfg['video']['length']

    def __len__(self):
        return len(self.files)

    def get_video_input_list(self, fixedlength=1):
        return self.video.get_input_list(fixedlength)

    def get_audio_input_list(self):
        return self.audio.get_input_list()

    def generate_complex_video(self, scr):
        cofilter = []
        cofilter.append(' -filter_complex ')
        #generate total screen
        cofilter.append('"color=c=black:size={0}x{1} [base]'.format(
            scr.get_total_width(), scr.get_total_height()))

        v, videocount = self.video.get_video_layers(scr)
        cofilter += v
        cofilter += self.audio.get_audio_layers(self.video.files)
        cofilter.append(' " ')
        return cofilter


    def get_finish_lines(self):
        finishlines = []
        finishlines.append(self.audio.get_finish_line())
        if self.length == 'shortest':
            finishlines.append(' -shortest')
        else:
            finishlines.append(' -t ' + str(self.length))

        finishlines.append(self.audio.get_distort_line())
        finishlines.append(self.video.get_distort_line())

        finishlines.append(' -c:v libx264 -threads 4')

        return finishlines
Пример #54
0
    def get_frames(self, vision_enable=True):
        melements = get_registered_elements()
        frame_count = 0

        for vid in Video.get_all():
            tgs = vid.get_tags()
            if len(tgs) > 0:
                self.log.info("Loading video id %d" % vid.id)
                if(self.parent != None):
                    self.parent.video_box.load_video(vid)
                # XXX The below sleep was added to prevent a "Bus Error"
                # XXX when running a test with a lot of disabled tags - Alex S.
                # TODO FIX
                sleep(0.1)

            for tag in filter(lambda t: t.active, tgs):
                frame_list = tag.get_frame_list()[::self.skip]
                if len(frame_list) > 0:
                    #Carry out testing on this tag
                    self.log.info("Testing tag #%d (%d frames)" % (tag.id, len(frame_list)))
                    frame_list.sort()
                    tag.clear_test_results()
                    if vision_enable:
                        if not melements.has_key(tag.mission_element):
                            self.log.warning("Skipping tag %s; not a mission element." % tag.mission_element)
                            continue

                        m_element = melements[tag.mission_element]()
                        m_element.init() #Turn on vision for this mission element

                    for frame in frame_list:
                        #The test of the frame
                        if vision_enable:
                            yield frame, tag, m_element
                        else:
                            yield frame, tag

                        frame_count += 1
                        self.status_callback(frame_count)

                        if self.has_aborted():
                            break

                    if vision_enable:
                        m_element.deinit() #Turn off vision for this mission element

                    self.log.info("Waiting for module shutdown")
                    sleep(1) # We sleep here because vision will reset the enabled flag if vision is stopped and started too qucikly
                             # This happens if we immediately stop and start the same vision module
                             # TODO: Refactor to fix this (or fix this behavior in vision)
                             # Testing could potentially time out if a vision module does not shut down within
                             # this period
                if self.has_aborted():
                    break
            if self.has_aborted():
                break
Пример #55
0
    def populate_info(self):
        self.total_frames = 0
        for vid in Video.get_all():
            tgs = vid.get_tags()
            for tag in tgs:
                if tag.active:
                    frame_list = tag.get_frame_list()[::self.skip_value]
                    self.total_frames += len(frame_list)

        print("Frames to process: %d" % self.total_frames)
Пример #56
0
 def load_db(x):
     self.log.info("Loading %s" % x)
     db = Database(x)
     if db is None or db.error:
         self.log.error("Failed to load database %s" % x)
         return (None, None)
     d = dict()
     for v in Video.get_all():
         d[v] = v.get_tags()
     return (d, db)
Пример #57
0
    def resetToDefault(self):

        self.video = Video()
        self.audio = Audio()

        self.populateVideoComboBox()
        self.populateAudioComboBox()

        self.recordPushButton.setIcon(QtGui.QIcon(os.path.join(scriptDir, 'rec_btn_off.svg')))
        self.recordPushButton.setChecked(False)
        self.recordPushButton.setEnabled(False)
Пример #58
0
	def run(self):
		video = None
		while True:
			# Make sure our printing thread is alive and happy
			if not video or not video.is_alive():
				self.logger.info("Starting video thread")
				video = Video(self.logger, self.videoQueue, self.queue)
				video.setDaemon(True)
				video.start()

			try:
				# Pull the message from the queue
				msg = self.queue.get()
				self.videoQueue.put(msg)
				priority = msg[0]
				line1 = msg[1]
				line2 = msg[2]
				alert = msg[3]
				t0 = time.time()

				if priority == PRIORITY_HIGH:
					self.logger.info(line1 + " " + line2)
				
				# If we should turn the light on, do it
				if (alert):
					if self.pi:
						self.blink()
					else:
						time.sleep(LIGHT_RUN_TIME)

					remaining_time = t0 + ALERT_DISPLAY_TIME - time.time()
					if(remaining_time > 0):
						time.sleep(remaining_time)
				else:
					time.sleep(SLIDE_TIME)

				# All done!
				self.queue.task_done()
				self.logger.debug("Finished queue item. Queue size: %i" % self.queue.qsize())
			except Exception as e:
				self.logger.exception("Exception in printer: " + str(e))
Пример #59
0
 def __init__(self):
     super(Model, self).__init__()
     Gst.init(None)
     self.video = Video()
     self.audio = None
     self.subtitles = Subtitles()
     self.voReference = cVOReference()
     self.ready = False
     # File Names
     self.voFilename = ""
     self.subFilename = ""
     self.peakFilename = ""
     self.projectFilename = ""
Пример #60
0
 def loadVideo(self):
     """Load the video information and setup the GUI"""
     logger.debug("VideoInterface.loadVideo")
     self.video = Video(self.filename)
     self.xml.get_widget("filename").set_text(self.video.videoFile)
     self.xml.get_widget("model").set_text(self.video.camera.encode("UTF-8"))
     self.xml.get_widget("resolution").set_text("%ix%i" % (self.video.width, self.video.height))
     self.xml.get_widget("size").set_text("%.2f %s" % smartSize(os.path.getsize(self.filename)))
     self.xml.get_widget("dateTime").set_text(self.video.timeStamp.strftime("%Y:%m:%d %Hh%Mm%Ss"))
     self.xml.get_widget("duration").set_text("%s s" % self.video.duration)
     self.xml.get_widget("video").set_text("%.1f fps\t%s\t%s" % (self.video.frameRate, self.video.videoCodec, self.video.videoBitRate))
     self.xml.get_widget("audio").set_text("%i ch\t%.1fHz\t%s\t%s" % (self.video.audioChannel, self.video.audioSampleRate, self.video.audioCodec, self.video.audioBitRate))
     if "INAM" in self.video.data:
         self.xml.get_widget("title").set_text(self.video.data["INAM"])
     if "IKEY" in self.video.data:
         self.xml.get_widget("keyword").set_text(" ".join(self.video.data["IKEY"].split(";")))