Beispiel #1
0
def abridge_clip(
    path: str,
    out_dir: str = "processed",
    diff_threshold: float = 20,
    repetition_threshold: int = 5,
) -> None:
    """
    Splice and render out the given clip with the given processing attributes
    """

    clip = VideoFileClip(path)
    clipname = ntpath.basename(path)

    cuts: List[Tuple[float, float]] = _find_voids(
        clip, diff_threshold, repetition_threshold
    )

    print(f"{clipname} - Removing empty sections")

    before_time = clip.duration

    clip = _apply_cuts(clip, cuts)

    after_time = clip.duration
    print(
        f"{clipname} - Removed {before_time - after_time}s from footage. (before: {before_time}s, after: {after_time}s)"
    )

    with ui.ProgressBar(f"{clipname} - Rendering", 1) as progress:
        clip.write_videofile(os.path.join(out_dir, clipname), logger=progress)

    clip.close()
Beispiel #2
0
 def configure_video(self, upload_id, video, thumbnail, caption=''):
     clip = VideoFileClip(video)
     self.upload_photo(photo=thumbnail,
                       caption=caption,
                       upload_id=upload_id)
     data = json.dumps({
         'upload_id': upload_id,
         'source_type': 3,
         'poster_frame_index': 0,
         'length': 0.00,
         'audio_muted': False,
         'filter_type': 0,
         'video_result': 'deprecated',
         'clips': {
             'length': clip.duration,
             'source_type': '3',
             'camera_position': 'back',
         },
         'extra': {
             'source_width': clip.size[0],
             'source_height': clip.size[1],
         },
         'device': DEVICE_SETTINTS,
         '_csrftoken': self.token,
         '_uuid': self.uuid,
         '_uid': self.username_id,
         'caption': caption,
     })
     clip.close()
     return self.send_request('media/configure/?video=1',
                              self.generate_signature(data))
def main():
    while True:
        start_time = datetime.now()
        folder_location = input("Enter Folder Location: ")
        output_location = input("Enter Output Location: ")
        trim_start = input("Enter Seconds to Trim From Start: ")
        trim_end = input("Enter Seconds to Trim From End: ")
        folder = os.listdir(folder_location)
        print(f'{start_time}: Processing {len(folder)} files...')
        for file in folder:
            if file.endswith('.mp4'):
                file_name = f"{folder_location}\\{file}"
                video_file = VideoFileClip(file_name).cutout(
                    0, float(trim_start))
                new_file_duration = float(
                    video_file.duration) - float(trim_end)
                video_file.duration = new_file_duration

                name_array = file.split('-')
                new_file_name = f"{name_array[0].strip()} - {name_array[1].strip()}.mp4"
                video_file.write_videofile(
                    f"{output_location}\\{new_file_name}")
                video_file.close()
        end_time = datetime.now()
        print(f'Ended in {end_time - start_time} seconds')
        continue_input = input("Should I update another folder? (y or n): ")
        if continue_input.lower() == "n":
            return False
Beispiel #4
0
def segment_video(video_file):
    try:
        clip = VideoFileClip(str(video_file))
        video_length = int(clip.duration * 1000)
        step_length = int(constants.SEGMENT_LENGTH * 1000)
        clip.close()
        scene_index = 0
        segments = []
        for scene in range(0, video_length, step_length):
            start = time_handler.timestamp_to_str(scene)
            end = time_handler.timestamp_to_str(scene + step_length)
            segments.append({
                'scene': scene_index,
                'start': start,
                'end':  end
            })
            scene_index += 1

        if SAVE_TO_FILE:
            file_handler.save_to_video_file(video_file, SCENES_KEY, segments)
    
        return segments

    except Exception as e:
        logging.exception(e)
def clip_movie(movie_file_path, periods, chara_crop_dir,
               movie_encoded_file_name):
    video = VideoFileClip(movie_file_path, fps_source="fps")
    for period in periods:
        [start_frame, end_frame] = list(map(int, period.split('-')))
        start_time = calc_elapsed_time(start_frame, video.fps)
        end_time = calc_elapsed_time(end_frame, video.fps)
        clip = video.subclip(start_time, end_time)

        [filename, ext] = os.path.splitext(os.path.basename(movie_file_path))
        norm_filename = re.sub(r'[\\|/|:|?|.|"|<|>|\|]', '-',
                               f"{start_time}_{end_frame}")
        output_dir = os.path.join(chara_crop_dir, filename)
        dst = os.path.join(output_dir, f"{norm_filename}{ext}")
        if os.path.exists(dst):
            continue
        if not os.path.exists(output_dir):
            os.makedirs(output_dir, exist_ok=True)

        final = concatenate_videoclips([clip])
        final.write_videofile(
            dst,
            fps=video.fps,
            codec=config["video_codec"],
            audio_codec=config["audio_codec"],
        )
    video.close()
    def export(self):
        if self.clip is not None:

            print("Saving frame_ini = {}, frame_end = {}".format(
                self.selected_frame_ini, self.selected_frame_end))

            _video = VideoFileClip(self.path_video)
            _fpms = _video.fps / 1000
            sub_video = _video.subclip(self.selected_frame_ini * _fpms,
                                       self.selected_frame_end * _fpms)

            export_base_path = os.path.splitext(self.path_video)[0]
            sub_video_path = export_base_path + "_edited.mp4"
            sub_video.write_videofile(filename=sub_video_path,
                                      codec="mpeg4",
                                      audio_codec='aac')
            _video.close()

            self.export_data = {
                "video_path": self.path_video,
                "video_fps": _video.fps,
                "sub_video_path": sub_video_path,
                "exported_date": datetime.now(),
                "selected_frame_ini": self.selected_frame_ini,
                "selected_frame_end": self.selected_frame_end
            }

            with open(export_base_path + "_edited_data.json",
                      'w') as json_file:
                json.dump(self.export_data, json_file, default=str)
Beispiel #7
0
def mp3(URL):
    video = YouTube(URL)
    stream = video.streams.get_lowest_resolution()

    stream.download(os.getcwd()+"/tmp",filename="video")

    audio = VideoFileClip(os.getcwd()+"/tmp/"+"video.mp4")
    audio.audio.write_audiofile(os.getcwd()+"/tmp/"+"audio.mp3")
    audio.close()

    os.rename(os.getcwd()+"/tmp/"+"audio.mp3",os.getcwd()+"/tmp/"+ stream.default_filename[:-4] +".mp3")
    
    audio = eyed3.load("tmp/"+ stream.default_filename[:-4] +".mp3")
    if (audio.tag == None):
        audio.initTag()

    thumb = video.thumbnail_url
    thumb = requests.get(thumb)
    with open("tmp/cover.jpg", "wb") as f:
        f.write(thumb.content)

    print("writting Data...")
    audio.tag.images.set(3, open('./tmp/cover.jpg','rb').read(), 'image/jpeg')
    audio.tag.artist=video.author
    audio.tag.title=video.title

    audio.tag.save()

    
    os.rename(os.getcwd()+"/tmp/"+ stream.default_filename[:-4] +".mp3",os.getcwd()+"/mp3/"+ stream.default_filename[:-4] +".mp3")
Beispiel #8
0
def test_builds_correctly():
    '''
    This test ensures that a valid .mp4 video is created using images from the testing
    directory.
    '''
    src_dir = os.path.join(TLD, 'testing', 'Killer Croc video')
    dest_dir = "/tmp/"
    filename = "test_KROC.mp4"

    fps = random.randrange(MIN_FPS, MAX_FPS + 1)
    ctx = StopMotionCTX(src=src_dir, dst=dest_dir, fps=fps, name=filename)
    yellow_print(
        f"Creating a {ctx.movie_len:.2f} second movie at {ctx.fps} fps: "
        f"{os.path.join(dest_dir, filename)}...")
    ctx.generate_clip()
    green_print("Created.")

    yellow_print(
        f"Verifying created video has correct duration ({ctx.movie_len:.2f}s)..."
    )
    clip = VideoFileClip(ctx.full_name)
    duration = clip.duration
    clip.close()
    assert abs(duration - ctx.movie_len) < LENGTH_MIN_ACCURACY
    green_print("File is correct duration.")

    yellow_print("Removing created video...")
    assert os.remove(ctx.full_name) is None
    green_print("Video file removed.")
Beispiel #9
0
def clip_duration(invideoF):
    from moviepy.editor import VideoFileClip
    clip = VideoFileClip(invideoF)
    clip_duration = clip.duration
    clip.close()
    clip.close()
    return clip_duration
Beispiel #10
0
def build_sample_slices(feed_dir, speaker_key):
    filename = '{}/{}.mp4'.format(feed_dir, speaker_key)

    video = VideoFileClip(filename)
    duration = video.duration
    video.close()

    sample_video_slices = []
    sample_audio_slices = []

    end = 3.0
    while end < duration:
        start = end - 3.0
        video = VideoFileClip(filename)
        sub_video = video.subclip(start, end)

        frames = [
            frame for frame in sub_video.iter_frames(with_times=False, fps=25)
        ]
        sample_video_slices.append(frames)

        # For debugging only
        # sub_video.write_videofile('test{}.mp4'.format(int(start)), codec="libx264", audio_codec="aac")

        waveform = sub_video.audio.to_soundarray(
            fps=16000)[:, 0]  # We only care about the left channel
        sample_audio_slices.append(waveform)

        sub_video.close()
        video.close()
        end += 2.0

    os.remove(filename)

    return sample_video_slices, sample_audio_slices
Beispiel #11
0
    def generate(self, avatars, text, usernames, kwargs):
        name = uuid.uuid4().hex + '.mp4'
        if len(text) >= 400:
            text = text[:400] + '...'

        @after_this_request
        def remove(response):  # pylint: disable=W0612
            try:
                os.remove(name)
            except (FileNotFoundError, OSError, PermissionError):
                pass

            return response

        clip = VideoFileClip("assets/letmein/letmein.mp4")



        textclip = TextClip(txt=text, bg_color='White', fontsize=32, font='Verdana', method='caption', align='west', size=(clip.size[0], None)).set_duration(clip.duration)

        color = ColorClip((clip.size[0], textclip.size[1]), color=(255, 255, 255), ismask=False).set_duration(clip.duration)

        video = CompositeVideoClip([clip.set_position(("center", textclip.size[1])), color, textclip],
                                   size=(clip.size[0], textclip.size[1] + clip.size[1]))

        video.write_videofile(name, threads=4, preset='superfast', verbose=False)
        clip.close()
        video.close()
        return send_file(name, mimetype='video/mp4')
Beispiel #12
0
def mp4_to_wav(file_path, input_directory, output_directory, name):
    from moviepy.editor import VideoFileClip
    import os

    if (not os.path.exists(output_directory)):
        os.mkdir(output_directory)

    file = VideoFileClip(os.path.join(file_path))
    times = int((file.duration) / 30)
    is_multiple_of_thirty = isinstance((file.duration / 30), int)

    for i in range(times):
        path = input_directory + name + '-' + str(i) + '.mp4'
        output_path = output_directory + name + '-' + str(i) + '.wav'

        video = VideoFileClip(os.path.join(path))
        video.audio.write_audiofile(os.path.join(output_path))
        video.close()

    if (not is_multiple_of_thirty):
        path = input_directory + name + '-' + str(times) + '.mp4'
        output_path = output_directory + name + '-' + str(times) + '.wav'
        video = VideoFileClip(os.path.join(path))
        video.audio.write_audiofile(os.path.join(output_path))
        video.close()
def video_properties(filename):

    my_clip = VideoFileClip(filename)
    print("Duration of video : ", my_clip.duration)
    print("FPS : ", my_clip.fps)
    my_clip.close()
    return my_clip.duration
Beispiel #14
0
def createPartition(index, videoData):
    os.chdir("videos/" + str(index))
    #Get the start and end second from the YAML Config and edit all of the videos into clips that can be concatinated.
    start = videoData['startFrame']
    end = videoData['endFrame']
    print(start, end)
    mp4 = findmp4()
    print(mp4)
    os.chdir(cwd)
    fileLoc = 'videos' + '\\' + str(index) + '\\' + mp4
    video = VideoFileClip(fileLoc).subclip(start - 4, end + 2).fx(
        vfx.fadeout, duration=1).fx(vfx.fadein, duration=5)
    # Make the text. Many more options are available.
    txt_clip = (TextClip(videoData['date'],
                         fontsize=35,
                         color='white',
                         font='Hans Kendrick').set_position(
                             ("center", 80)).set_duration(5).fx(
                                 vfx.fadeout, duration=1.5).fx(vfx.fadein,
                                                               duration=3))

    result = CompositeVideoClip([video, txt_clip])  # Overlay text on video

    result.write_videofile(
        "partitions\\" + str(index) +
        ".mp4")  # Write the partition into a new partition folder
    os.chdir(cwd)
    video.close()
    txt_clip.close()
    result.close()
Beispiel #15
0
def merge_audio_and_video(video_input_path, audio_input_path,
                          video_output_path):
    """This function is used to mge voice with a video merged from images.
    Args:
        video_input_path: path of the origin video
        audio_input_path: path of the voice file
        video_output_path: path to the result video
    Returns: int
        on success this function returns 0
        on failure this function returns 1
    """
    if not os.path.isfile(video_input_path):
        print("invalid video path")
        return FAILED
    if not os.path.isfile(audio_input_path):
        print("invalid audio path")
        return FAILED
    my_video_clip = VideoFileClip(video_input_path)
    my_audio_clip = AudioFileClip(audio_input_path)
    video = my_video_clip.set_audio(my_audio_clip)
    video.write_videofile(video_output_path, codec='libvpx')
    if not os.path.isfile(video_output_path):
        print("invalid output path")
        my_audio_clip.close()
        my_video_clip.close()
        return FAILED
    my_audio_clip.close()
    my_video_clip.close()
    return SUCCESS
Beispiel #16
0
class VideoBarrier(object):
    """docstring for VideoBarrier"""
    CLIP_DIR = "clip"

    def __init__(self, input, output, audio_path):
        super(VideoBarrier, self).__init__()
        self.input = input
        self.filename, _ = os.path.splitext(os.path.basename(input))
        self.output = os.path.join(output, VideoBarrier.CLIP_DIR)
        self.audio_path = audio_path

    def __enter__(self):
        self.v_clip = VideoFileClip(self.input, audio=False)
        self.a_clip = AudioFileClip(self.audio_path)
        return self

    def __exit__(self, exception_type, exception_value, traceback):
        self.v_clip.close()
        self.a_clip.close()

    def set_audio(self, t_start=0, t_end=None):
        self.v_clip = self.v_clip.set_audio(self.a_clip.subclip(
            t_start, t_end))

    def save(self, start_time=0, duration=60):
        audio_fname, _ = os.path.splitext(os.path.basename(self.audio_path))
        output_fname = "{}_{}.mp4".format(self.filename, audio_fname)
        output_path = os.path.join(self.output, output_fname)

        self.v_clip.set_duration(duration + 1).subclip(
            t_start=start_time,
            t_end=start_time + duration).write_videofile(output_path)
Beispiel #17
0
    def gif_split(self, target):
        if os.path.getsize(target) <= self.max_size:
            return target
        self.gif_optimize(target)

        logger.info("Media[{}]: Splitting gif".format(target))

        size = os.path.getsize(target)
        path, filename = os.path.split(target)
        filename = os.path.splitext(filename)[0]
        new_filename = 'new_{}.gif'.format(filename)
        new_path = os.path.join(path, new_filename)
        if os.path.exists(new_path):
            os.remove(new_path)

        while size > self.max_size:
            clip = VideoFileClip(target)
            end = clip.duration * self.max_size / size - 1
            clip = clip.subclip(0, end)
            clip.write_gif(new_path, program='ffmpeg')
            clip.close()
            self._force_rename(new_path, target)

            size = os.path.getsize(target)

        return target
Beispiel #18
0
    def process(self, data, inputs, utils):
        logger = logging.getLogger(f'mainModule.{__name__}')
        clips = []
        for found in data:
            logger.info(found.time)
            logger.info(found.yt)
            start, end = self.parse_caption_time(found.time)
            try:
                video = VideoFileClip(found.yt.get_video_filepath()).subclip(
                    start, end)
            except OSError:
                logger.warning('no video')
                continue
            # 因為影片太少會出錯找不到路徑 目前先 skip 掉這個步驟
            clips.append(video)
            if len(clips) >= inputs['limit']:
                break
        output_filepath = utils.get_output_filepath(inputs['channel_id'],
                                                    inputs['search_word'])
        final_clip = concatenate_videoclips(clips)
        final_clip.write_videofile(output_filepath)

        # closing VideoFileClips
        for video in clips:
            video.close()

        return output_filepath
    def encoding_videos(self, start_end=None, use_GPU=False, codec='libx264'):
        video_out_path, temp_audio_path, CPU_GPU = self.get_video_out_path(
            start_end, use_GPU, codec)
        duration = dict()
        for i, in_path in enumerate(self.video_in_path):
            out_path = video_out_path[i]

            start_time = time.time()
            clip = VideoFileClip(in_path)
            if start_end is not None:
                clip = clip.subclip(*start_end)
            clip.write_videofile(out_path,
                                 write_logfile=True,
                                 codec=codec,
                                 temp_audiofile=temp_audio_path[i])
            clip.close()
            duration[out_path] = dict()
            duration[out_path]['time'] = str(
                datetime.timedelta(seconds=(time.time() - start_time)))
            duration[out_path]['device'] = CPU_GPU
            duration[out_path]['codec'] = codec
            duration[out_path]['start_end'] = start_end
            print(duration[out_path]['time'])
        print(duration)
        curr_time = datetime.datetime.now()
        curr_time_str = '{}-{}-{}_{}.{}.{}'.format(
            curr_time.year, curr_time.month, curr_time.day, curr_time.hour,
            curr_time.minute, curr_time.second)
        json_path = os.path.join(self.root,
                                 '{}_log.json'.format(curr_time_str))
        json.dump(duration, open(json_path, 'w'), indent=2)
    def preview_video(self, filename, playtime_before, playtime_after,
                      silence):
        videoclip = VideoFileClip(filename)

        start = max(0, silence.start_time - playtime_before)
        stop = min(videoclip.duration, silence.stop_time + playtime_after)
        start_cut = silence.start_cut()
        stop_cut = silence.stop_cut()

        if start_cut < stop_cut:
            cliplist = []

            if start < start_cut:
                cliplist.append(videoclip.subclip(start, start_cut))
            if stop_cut < stop:
                cliplist.append(videoclip.subclip(stop_cut, stop))

            assert len(cliplist) > 0
            tmpclip = concatenate_videoclips(cliplist)
        else:
            tmpclip = videoclip.subclip(start, stop)

        pygame.display.set_caption('Silence cut preview')
        os.environ['SDL_VIDEO_WINDOW_POS'] = '%d,%d' % (0, 30)

        aud = tmpclip.audio.set_fps(44100)
        tmpclip = tmpclip.without_audio().set_audio(aud)
        tmpclip.preview()
        pygame.display.quit()

        videoclip.close()
Beispiel #21
0
    def make_crab(self, t, u_id):
        """Non blocking crab rave video generation from DankMemer bot
        
        https://github.com/DankMemer/meme-server/blob/master/endpoints/crab.py
        """
        fp = str(cog_data_path(self) / f"Verdana.ttf")
        clip = VideoFileClip(str(cog_data_path(self)) + "/template.mp4")
        text = TextClip(t[0], fontsize=48, color="white", font=fp)
        text2 = (
            TextClip("____________________", fontsize=48, color="white", font=fp)
            .set_position(("center", 210))
            .set_duration(15.4)
        )
        text = text.set_position(("center", 200)).set_duration(15.4)
        text3 = (
            TextClip(t[1], fontsize=48, color="white", font=fp)
            .set_position(("center", 270))
            .set_duration(15.4)
        )

        video = CompositeVideoClip(
            [clip, text.crossfadein(1), text2.crossfadein(1), text3.crossfadein(1)]
        ).set_duration(15.4)
        video.write_videofile(
            str(cog_data_path(self)) + f"/{u_id}crabrave.mp4",
            threads=1,
            preset="superfast",
            verbose=False,
            logger=None,
            temp_audiofile=str(cog_data_path(self) / "crabraveaudio.mp3")
        )
        clip.close()
        video.close()
        return True
Beispiel #22
0
def separate(input_path: str, output_directory: str, name: str):
    if (not os.path.exists(output_directory)):
        os.mkdir(output_directory)

    video = VideoFileClip(input_path)
    times = int((video.duration) / 30)
    init_time = 0
    final_time = 30

    is_multiple_of_thirty = isinstance((video.duration / 30), int)

    for i in range(times):
        ffmpeg_extract_subclip(input_path,
                               init_time,
                               final_time,
                               targetname=output_directory + name + "-" +
                               str(i) + ".mp4")
        init_time += 30
        final_time += 30
        video.close()

    if (not is_multiple_of_thirty):
        video = VideoFileClip(input_path)
        rest = int(video.duration - (times * 30))
        init_rest_time = times * 30
        final_rest_time = init_rest_time + rest

        ffmpeg_extract_subclip(input_path,
                               init_rest_time,
                               final_rest_time,
                               targetname=output_directory + name + "-" +
                               str(times) + ".mp4")
        video.close()
Beispiel #23
0
    def make_highlight(self, data_loader, y_pred):
        segment_length = data_loader.get_metadata()['config']['segment_length']
        segment_df = data_loader.test_segment_df.copy()
        segment_df['pred'] = y_pred
        segment_df['start_sec'] = (segment_df['index'] * segment_length)
        segment_df['end_sec'] = ((segment_df['index'] + 1) * segment_length)
        start = np.array(segment_df['start_sec'][segment_df['pred'] == 1])
        end = np.array(segment_df['end_sec'][segment_df['pred'] == 1])
        name = "raw"

        i = 1
        while (i < len(end)):
            if end[i] - 3 == end[i - 1]:
                end[i - 1] = end[i]
                start = np.delete(start, i)
                end = np.delete(end, i)
            else:
                i += 1

        clip = VideoFileClip(os.path.join(self.video_dir, name + ".mp4"))
        subclips = []
        for i in range(len(start)):
            start_lim = start[i]
            end_lim = end[i]
            subclips.append(clip.subclip(start_lim, end_lim))
        final_clip = concatenate_videoclips(subclips)
        final_clip.write_videofile(
            "./Highlights" + name +
            ".mp4")  #Enter the desired output highlights filename.
        for i in subclips:
            i.close()
        clip.close()
Beispiel #24
0
def videoV():
    #Initialize and access video functions
    out = cv2.VideoWriter(clip.filename, clip.fourcc, clip.fps, (1366, 768), True)
    #fps = 14.0 at 1920x1080
    #Begin recording
    while clip.begin == 1:
        img = ImageGrab.grab(bbox=(clip.x0, clip.y0, clip.x1, clip.y1))
        frame = cv2.cvtColor(np.array(img), cv2.COLOR_BGR2RGB)
        reducedframe = cv2.resize(frame, (1366, 768), fx=0, fy=0, interpolation=cv2.INTER_CUBIC)
        out.write(reducedframe)
    #Stop recording and close VideoWriter
    out.release()

    # Get duration of the clip and check difference between audio and clip duration
    check_clip = VideoFileClip(clip.filename)
    sync = clip.timer / check_clip.duration
    check_clip.close()

    # Re-size clip to match audio duration size
    path = os.path.join(clip.curpath, "ffmpeg", "bin", "ffmpeg.exe")
    proc = subprocess.Popen(path + ' -i output.mp4 -vf "setpts='+str(sync)
                            + '*PTS" output2.mp4', cwd=clip.curpath)

    # Wait until process is done and close all windows
    while proc.poll() is None:
        continue
    cv2.destroyAllWindows()
def extract_highlights(file_paths):
    """
    :param file_paths: 동영상 경로 리스트
    :return: 추출한 하이라이트 동영상 경로 리스트
    """

    max_highlights = []
    min_highlights = []

    for file_path in file_paths:
        video_clip = VideoFileClip(file_path)
        audio_clip = video_clip.audio
        src_audio_file_name = get_random_name('wav')
        audio_clip.write_audiofile(src_audio_file_name)
        source_wave = wave.read(src_audio_file_name)

        stereo_channel_wave = source_wave[1].T[1]
        normalize_wave = [(ele / 2 ** 8.) * 2 - 1 for ele in stereo_channel_wave]  # this is 8-bit track, now normalized on [-1,1)
        fourier_transform_wave = fft(normalize_wave)  # calculate fourier transform (complex numbers list)

        normalize_time = len(fourier_transform_wave) / video_clip.duration

        argmax_frequency = np.argmax(fourier_transform_wave) / normalize_time + 0.5
        argmin_frequency = np.argmin(abs(fourier_transform_wave)) / normalize_time + 0.5

        max_highlight_path = max_highlights.append(get_random_name('mp4'))
        min_highlight_path = min_highlights.append(get_random_name('mp4'))

        video_clip.subclip(argmax_frequency - (HIGHLIGHT_LENGTH/2), argmax_frequency + (HIGHLIGHT_LENGTH/2)).write_videofile(max_highlight_path, codec='libx264', audio_codec='aac')
        video_clip.subclip(argmin_frequency - (HIGHLIGHT_LENGTH/2), argmin_frequency + (HIGHLIGHT_LENGTH/2)).write_videofile(min_highlight_path, codec='libx264', audio_codec='aac')
        video_clip.close()
    return max_highlights, min_highlights
Beispiel #26
0
    def video(self,
              max_duration: int = 0,
              font: str = 'Arial',
              fontsize: int = 100,
              color: str = 'white',
              link: str = ''):
        """
        Build CompositeVideoClip from source video

        Parameters
        ----------
        max_duration: int, optional
            Duration of the clip if a video clip, default value is 0
        font: str, optional
            Name of font for text clip
        fontsize: int, optional
            Size of font
        color: str, optional
            Color of text

        Returns
        -------
        StoryBuild
            An object of StoryBuild
        """
        clip = VideoFileClip(str(self.path), has_mask=True)
        build = self.build_main(clip, max_duration, font, fontsize, color,
                                link)
        clip.close()
        return build
Beispiel #27
0
    def generate(self, avatars, text, usernames, kwargs):
        name = uuid.uuid4().hex + '.gif'

        @after_this_request
        def remove(response):  # pylint: disable=W0612
            try:
                os.remove(name)
            except (FileNotFoundError, OSError, PermissionError):
                pass

            return response

        clip = VideoFileClip("assets/kowalski/kowalski.gif")
        text = TextClip(text,
                        fontsize=36,
                        method='caption',
                        size=(245, None),
                        align='West',
                        color='black',
                        stroke_color='black',
                        stroke_width=1,
                        font='Verdana').set_duration(clip.duration)
        text = text.set_position((340, 65)).set_duration(clip.duration)
        text = rotate(text, angle=10, resample='bilinear')

        video = CompositeVideoClip([clip, text]).set_duration(clip.duration)

        video.write_gif(name)
        clip.close()
        video.close()
        return send_file(name, mimetype='image/gif')
Beispiel #28
0
def make(csv_dir, mp4_dir):
    # 모든 csv 불러와서 돌아가면서 시간값, 이름 읽기
    all_csv_name_list = sorted(glob.glob(os.path.join(csv_dir, '*.csv')))
    for csv_name in all_csv_name_list:
        df = pd.read_csv(csv_name)
        print(df)
        start = np.array(df['start_sec'][df['pred'] == 1])
        end = np.array(df['end_sec'][df['pred'] == 1])
        name = os.path.split(os.path.splitext(csv_name)[0])[1]

        i = 1
        while (i < len(end)):
            if end[i] - 3 == end[i - 1]:
                end[i - 1] = end[i]
                start = np.delete(start, i)
                end = np.delete(end, i)
            else:
                i += 1

        clip = VideoFileClip(os.path.join(mp4_dir, name + ".mp4"))
        subclips = []
        for i in range(len(start)):
            start_lim = start[i]
            end_lim = end[i]
            subclips.append(clip.subclip(start_lim, end_lim))
        final_clip = concatenate_videoclips(subclips)
        final_clip.write_videofile(
            "./Highlights" + name +
            ".mp4")  #Enter the desired output highlights filename.
        for i in subclips:
            i.close()
        clip.close()
def convert(name, outname):
    # Buscamos el vídeo en la carpeta
    p = Path("videos")
    files = list(p.glob("*"))
    for f in files:
        fstr = str(f).lower()
        if f.is_file() and f.suffix.lower() in video_formats and name in fstr:
            video_path = str(f)
            break
    print(video_path)

    # Buscamos la carátula
    p = Path("Slides_start_end")
    files = list(p.glob("*"))
    for f in files:
        fstr = str(f).lower()
        if (f.is_file() and "1440" in str(f) and "end_1440" not in str(f)
                and name in fstr):
            cover_path = str(f)
            break
    print(cover_path)

    # Buscamos la imagen de cierre
    p = Path("Slides_start_end", "end_1440.png")
    end_path = str(p)
    print(end_path)

    # Buscamos el ancho y alto del vídeo
    clip = VideoFileClip(video_path)
    clip_part = clip.subclip(0, 5)
    clip_size = clip_part.size

    # Ponemos el cover y final al mismo tamaño que el vídeo
    im = Image.open(cover_path)
    out = im.resize(clip_size)
    arr_in = np.array(out)

    im = Image.open(end_path)
    out = im.resize(clip_size)
    arr_out = np.array(out)

    # Generamos la entradilla
    clip = ImageClip(arr_in).set_duration(5)
    clip.write_videofile('video_start.mp4', fps=24)
    clip.close()

    # Generamos el cierre
    clip = ImageClip(arr_out).set_duration(5)
    clip.write_videofile('video_end.mp4', fps=24)
    clip.close()

    # Generamos vídeo final
    clip1 = VideoFileClip('video_start.mp4')
    clip2 = VideoFileClip(video_path)
    clip3 = VideoFileClip('video_end.mp4')

    final = concatenate_videoclips([clip1, clip2, clip3], method="compose")
    final.write_videofile(f'{outname}_final.mp4')
    final.close()
Beispiel #30
0
def download_data(filename, output_dir, limit=0):
    output_dir = output_dir.rstrip('/')

    clip_dictionary = {}
    with open(filename) as fp:
        reader = csv.reader(fp, delimiter=',')
        for row in reader:
            if row[0] not in clip_dictionary:
                clip_dictionary[row[0]] = []

            clip_dictionary[row[0]].append((float(row[1]), float(row[2]), float(row[3]), float(row[4])))

    meta_data, used_clips = build_meta(output_dir, clip_dictionary)

    if limit:
        limit = max(limit - len(used_clips), 0)
        limited_keys = random.sample(list(set(list(clip_dictionary.keys())) - used_clips), limit)
        clip_dictionary = {key: clip_dictionary[key] for key in limited_keys}

    items_to_download = len(clip_dictionary)
    downloading = 0
    for clip_id, params in clip_dictionary.items():
        downloading += 1
        print(
            '[IMP] Downloading {} of {}'.format(downloading, items_to_download))

        download_opts = {
            'format': 'mp4',
            'outtmpl': 'data/{}.mp4'.format(clip_id),
            'nocheckcertificate': True
        }

        try:
            with youtube_dl.YoutubeDL(download_opts) as ydl:
                ydl.download(['https://www.youtube.com/watch?v={}'.format(clip_id)])

            for idx, param in enumerate(params):
                main_clip = VideoFileClip('data/{}.mp4'.format(clip_id))
                print(
                    '[IMP] {}_{} -> {} to {} from max {}'.format(clip_id, idx, param[0], param[1], main_clip.duration))

                sub_clip = main_clip.subclip(param[0], param[1])

                sub_clip_id = '{}_{}'.format(clip_id, idx)
                sub_clip_file_name = '{}/{}.mp4'.format(output_dir, sub_clip_id)
                sub_clip.write_videofile(sub_clip_file_name, codec="libx264", audio_codec="aac")

                sub_clip.close()
                main_clip.close()

                meta_data[sub_clip_id] = (param[2], param[3])

            os.remove('data/{}.mp4'.format(clip_id))

        except youtube_dl.utils.DownloadError as error:
            print(error)

    with open('{}/meta.json'.format(output_dir), 'w') as fp:
        fp.write(json.dumps(meta_data))
Beispiel #31
0
from py.utils.IO_util import get_all_file
from moviepy.editor import VideoFileClip

filePath = input('mp4 Path:')
files = get_all_file(filePath)
duration = 0
for f in files:
    if f.endswith('.mp4'):
        clip = VideoFileClip(f)
        duration += clip.duration
        print(f, clip.duration)  # seconds
        clip.close()

print(duration / 60)