Пример #1
0
  def get_video_parts(self, video_filename=None, start_time=0, end_time=0, steps_num=1):
    if not video_filename:
      video_filename = self.config['VideoSection']['sample_video']
      output_video_location = self.config['VideoSection']['video_output']
    if not video_filename:
      print("Error getting video")
      return False
    
    base_name_ext = os.path.basename(video_filename)
    base_name = base_name_ext.split('.')[0]

    if not output_video_location:
      print("Error finding output location")
      output_video_location = 'test_video_'
    
    output_video_name = f'{output_video_location}{base_name}'
      
    with VideoFileClip(video_filename) as video:
      audio = video.audio
      max_duration = video.duration if video.duration < audio.duration else audio.duration
      if start_time >= max_duration:
        print('Video Editor: start_time exceeds max video duration')
        return
      end_time = max_duration if max_duration <= end_time else end_time
      targetname = f'{output_video_name}{start_time}_to_{end_time}.mp4'
      ffmpeg_extract_subclip(video_filename, start_time, end_time, targetname=targetname)
Пример #2
0
	def install_insta(self):
		'''Скачивание видео из инстаграма''' 
		link_to_video = self.request.GET['link']
		response = requests.get(link_to_video)
		text_for_parser = response.content
		text_for_parser = str(text_for_parser)
		regxp =  '(http[^"]+mp4)'
		result = []
		result = re.findall(regxp, text_for_parser)
		try:
			url = result[0]
		except:
			return 'link_error'
		timeof = self.request.GET['timeof'].split(':')
		timeto = self.request.GET['timeto'].split(':')
		timeof_seconds = int(timeof[0]) * 60 + int(timeof[1])
		timeto_seconds = int(timeto[0]) * 60 + int(timeto[1])
		if timeto_seconds - timeof_seconds > 30 and timeto_seconds - timeof_seconds < 1:
			return 'time_error'
		link = link_to_video.split('?')[0] + '?__a=1'
		response = requests.get(link_to_video).text
		soup = BeautifulSoup(response, 'lxml')
		for heading in soup.find_all(re.compile("^script")):
			if heading.text.strip()[0:18] == 'window._sharedData':
				arr_link = heading.text.strip('window._sharedData = ').split('video_url')[1].split('"')[2].strip().split('\\u0026')
				url = ''
				for i in arr_link:
					url += i + '&'
		ffmpeg_extract_subclip(url, timeof_seconds, timeto_seconds, targetname="audio/{}.mp4".format(self.name))
		return 'ok'
Пример #3
0
def test_ffmpeg_extract_subclip(util):
    extract_subclip_tempdir = os.path.join(
        util.TMP_DIR, "moviepy_ffmpeg_extract_subclip"
    )
    if os.path.isdir(extract_subclip_tempdir):
        shutil.rmtree(extract_subclip_tempdir)
    os.mkdir(extract_subclip_tempdir)

    inputfile = os.path.join(extract_subclip_tempdir, "fire2.mp4")
    shutil.copyfile("media/fire2.mp4", inputfile)

    # default name
    expected_outputfile = os.path.join(extract_subclip_tempdir, "fire2SUB300_500.mp4")
    ffmpeg_extract_subclip(inputfile, 0.3, "00:00:00,5", logger=None)
    assert os.path.isfile(expected_outputfile)

    # custom name
    expected_outputfile = os.path.join(extract_subclip_tempdir, "foo.mp4")
    ffmpeg_extract_subclip(
        inputfile, 0.3, "00:00:00,5", outputfile=expected_outputfile, logger=None
    )
    assert os.path.isfile(expected_outputfile)

    # assert subclip duration
    clip = VideoFileClip(expected_outputfile)
    assert 0.18 <= clip.duration <= 0.22  # not accurate

    if os.path.isdir(extract_subclip_tempdir):
        try:
            shutil.rmtree(extract_subclip_tempdir)
        except PermissionError:
            pass
Пример #4
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()
Пример #5
0
def split_videos(labels_path, videos_path, target_path):
    """
    This function splits the given videos into small chunks of videos
    corresponding to each delivery. It takes the csv files in the label path
    which has a separate file for each video and corresponding video file
    from videos_path and does the splitting according to the csv data"""

    no_videos = len(glob.glob(labels_path + "/*.csv"))

    for i in range(1, no_videos + 1):
        file1 = labels_path + "/" + str(
            i) + ".csv"  #csv file must be named like "1.csv", 2.csv
        file2 = videos_path + "/" + str(
            i) + ".mp4"  #video file must be named like "1.mp4", "2.mp4"
        obj = pd.read_csv(file1)
        for j in range(len(obj)):
            target = target_path + "/" + str(count) + ".mp4"
            ffmpeg_extract_subclip(file2,
                                   obj['s'][j],
                                   obj['e'][j],
                                   targetname=target)
            csv.append([
                "video" + str(count) + ".mp4", obj['ba'][j], obj['bo'][j],
                obj['ty'][j], i, j + 1, obj['e'][j] - obj['s'][j]
            ])
            count = count + 1
    csv = pd.DataFrame(csv,
                       columns=[
                           'File', 'Batsman', 'Bowler', 'Delivery', 'Video',
                           'index', 'Time'
                       ])
    csv.to_csv(targets_path + "/processed_file.csv", index=False)
Пример #6
0
def video_to_frames(video_url, res, video_name, length):
    """
    video_url: url of youtube video
    res: resolution; eg '144p'
    video_name: name of video
    length: trim length
    """
    # grab YouTube object from url and download it to data/
    yt = get_yt(video_url)
    if yt is None:
        return
    download_video(yt, res, video_name)

    # trim to first length seconds
    ffmpeg_extract_subclip('data' + res + '/' + video_name + '.mp4',
                           0,
                           length,
                           targetname='data' + res + '/' + video_name +
                           '_trimmed.mp4')

    # loads video and extracts frame by frame
    vid_cap = cv2.VideoCapture('data' + res + '/' + video_name + '.mp4')
    success, image = vid_cap.read()
    count = 0
    while success:
        if not os.path.exists("video_frames" + res):
            os.makedirs("video_frames" + res)
        cv2.imwrite("video_frames" + res + "/frame%d.jpg" % count,
                    image)  # save frame as JPEG file
        success, image = vid_cap.read()
        print('Read a new frame: ', success)
        count += 1
    def upload_video(self, item, filename):
        full_path = str(Path("./videos/{f}.mp4".format(f=filename)))
        video = requests.get(item["url"])
        open(full_path, "wb").write(video.content)
        if item["cut"] == True:
            new_path = str(Path("./videos/{f}_cut.mp4".format(f=filename)))
            ffmpeg_extract_subclip(full_path, 0, 59, targetname=new_path)
            os.remove(full_path)
            full_path = new_path
        xd = self.api.prepare_direct_video(item["userid"], full_path)
        try:
            self.api.send_direct_video(xd)
        except Exception as e:
            rnd = random.randint(1, 5)
            time.sleep(rnd)
            self.api.send_direct_video(xd)

        user = self.cfg.get_user(item["userid"])
        cfg.user_add_download(item["userid"], item["username"],
                              item["download_from"])
        cfg.day_add_download()
        logging.info("{d} successfully downloaded a video from {u}".format(
            d=item["username"], u=item["download_from"]))

        logging.info("Timespan since sent video: {0}ms".format(
            str((time.time() * 1000 // 1) - item["sent"] // 1000)))
        self.cfg.capture_delay(int(time.time() - item["sent"] // 1000000),
                               item["priority"])
        if os.path.exists(full_path):
            os.remove(full_path)
Пример #8
0
def cut_clips(data):
    for line in data:
        videoName = line[0]
        if videoName + '.mp4' not in videoNames:
            continue
        actionId = int(line[-1].strip())
        # I only want fall-down action
        if actionId != 5:
            continue

        if videoName != prename:
            count = 0
        else:
            count += 1

        middleTimeStamp = int(line[1])
        startTime = middleTimeStamp - 2.0
        endTime = middleTimeStamp + 1.5

        targetVideo = os.path.join(videoFolder,
                                   videoName + '-' + str(count) + '-cut.mp4')

        ffmpeg_extract_subclip(os.path.join(videoFolder, videoName + '.mp4'),
                               startTime,
                               endTime,
                               targetname=targetVideo)
Пример #9
0
def cutAndScaleVideo(file, start, end, width, height):
    fileName = file.replace('.mp4', '')
    ffmpeg_extract_subclip(file,
                           start,
                           end,
                           targetname=fileName + "_cutted.mp4")
    escape = 27

    #fourcc = cv2.VideoWriter_fourcc(*'MPEG')
    fourcc = cv2.VideoWriter_fourcc(*'FMP4')
    out = cv2.VideoWriter(fileName + '_cutted_scaled.mp4', fourcc, 20,
                          (width, height))
    capture = cv2.VideoCapture(fileName + '_cutted.mp4')
    while capture.isOpened():
        ret, frame = capture.read()
        if ret:
            sky = frame[300:1300, 200:900]
            resized_frame = cv2.resize(sky, (width, height),
                                       fx=0,
                                       fy=0,
                                       interpolation=cv2.INTER_CUBIC)
            out.write(resized_frame)
            cv2.imshow('', resized_frame)
        else:
            break
        key = cv2.waitKey(1)
        if key == escape:
            break
    capture.release()
    out.release()
Пример #10
0
def check_save_video(item, url, settings):
    # First: Check if the video is new (is not in the video backup directory)
    # Second: If new trims the video, saves the video and finally returns the path of the video, if not new return False

    destination_dir = f"{settings['vid_backup_dir']}".format(
        arrow.utcnow().format("DD-MM-YYYY"))
    destination_path_beforetrimming = os.path.join(destination_dir,
                                                   f"trim_me.mp4")
    destination_path_final = os.path.join(destination_dir, f"{item['id']}.mp4")

    if os.path.isfile(destination_path_final):
        print(f"Video {destination_path_final} already exists.")
        return False

    elif not os.path.isfile(destination_path_final):
        os.makedirs(destination_dir, exist_ok=True)
        ydl_opts = {
            "format": "mp4",
            "outtmpl": destination_path_beforetrimming,
        }

        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            ydl.download([url])

        # trim video to 10 seconds
        print("Triming video...")
        ffmpeg_extract_subclip(destination_path_beforetrimming,
                               0,
                               9,
                               targetname=destination_path_final)
        os.remove(destination_path_beforetrimming)

        return destination_path_final
Пример #11
0
def sync_videos(videofile, visualise=False, output='output.mov'):

    clip = mp.VideoFileClip(videofile)
    waveform = clip.audio.to_soundarray()  
    fs = waveform.shape[0] // clip.duration
    audio = AudioProcessing(waveform, fs, clip.fps)
    bandpass = audio.filter((3700, 4000), btype='bandpass', order=7)

    # plot onsets from bandpass 
    mono = 

    peaks = bandpass.detect_onsets()
    n1 = parse_input('Select start peak: ')
    n2 = parse_input('Select end peak (-1 for EOF): ')
    
    if n1 >= len(peaks):
        print(f'error - peak {n1} does not exists')
        err = True

    if n2 >= len(peaks) or (n2 < -1):
        print(f'error - peak {n2} does not exists or invalid')
        err = True

    if n2 != -1 and n1 >= n2:
        print(f'error - peak2 must be greater than peak1')
        err = True
    
    if err:
        print('fatal error has occured')
        exit(0)


    if output:
        ffmpeg_extract_subclip(videofile, peaks[n], clip.duration, output)
def cut_lecture_mp4(video_path, save_path, lecture_trim_path):
    print("\n[lec mp4 CUT 시작] 원본 강의의 mp4 파일 CUT을 시작합니다")

    time_csv = pd.read_csv(save_path)

    # 디렉토리 유무 검사 및 디렉토리 생성
    try:
        if not os.path.exists(lecture_trim_path):  # 디렉토리 없을 시 생성
            os.makedirs(lecture_trim_path)
    except OSError:
        print('Error: Creating directory. ' + lecture_trim_path)  # 디렉토리 생성 오류

    for i in range(len(time_csv["time"])):

        fileName = "lec_" + set_Filenum_of_Name(i + 1) + ".mp4"
        fileName = lecture_trim_path + fileName

        if i == (len(time_csv["time"]) - 1):  # 마지막 클립
            cut_point_start = int(time_csv["time"][i])
            clip = VideoFileClip(video_path)
            ffmpeg_extract_subclip(video_path,
                                   cut_point_start,
                                   clip.duration,
                                   targetname=fileName)
        else:  # 처음, 중간 클립
            cut_point_start = int(time_csv["time"][i])
            cut_point_end = int(time_csv["time"][i + 1])
            ffmpeg_extract_subclip(video_path,
                                   cut_point_start,
                                   cut_point_end,
                                   targetname=fileName)

        print(">>> >>>", i + 1, "번째 클립 mp4 파일 생성 완료")

    print("\n[lec mp4 CUT 시작] 원본 강의의 mp4 파일 CUT을 종료합니다")
Пример #13
0
def process(video_path: str, credentials):
    from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip

    ffmpeg_extract_subclip(video_path,
                           0,
                           30,
                           targetname=video_path.replace('.mp4', '_cuted.mp4'))
    video_path = video_path.replace('.mp4', '_cuted.mp4')
    video_path = decrease_fps(video_path)

    video = cv2.VideoCapture(video_path)
    video_seconds = int(
        video.get(cv2.CAP_PROP_FRAME_COUNT) / video.get(cv2.CAP_PROP_FPS))
    extracted_labels = extract_labels(video_path, credentials)

    results = pd.DataFrame(data={'second': list(range(1, video_seconds))})
    results[EXPECTED_LABELS] = 0

    for _, row in extracted_labels.iterrows():
        label = row['label']
        assigned_labels = get_similar_label(label, 0.55) if label else None

        for assigned_label in assigned_labels:
            results.loc[(row['start_time'] < results['second']) &
                        (results['second'] <= row['end_time']),
                        assigned_label] = 1

    return results
Пример #14
0
def splitter(day, streamtime, i):
    offset = datetime.datetime.utcnow() - datetime.datetime.now()
    matchtimestamp = i.actual_time + offset
    starttime = matchtimestamp - streamtime
    endtime = starttime + 180
    ffmpeg_extract_subclip('{}.mp4'.format(day), starttime, endtime,
                           '{}.mp4'.format(i.key))
Пример #15
0
def trim_video(video_path, start_time, end_time):
    file_name = video_path.split('/')[-1]
    ffmpeg_extract_subclip(video_path,
                           start_time,
                           end_time,
                           targetname=os.path.join('python_files', 'instance',
                                                   'videos', file_name))
Пример #16
0
def download_file(filename, prefix, num_videos=None):
    try:
        os.mkdir('{}_videos'.format(prefix))
    except Exception as e:
        print(e)

    try:
        os.mkdir('{}_audio'.format(prefix))
    except Exception as e:
        print(e)

    num_downloaded = 0

    with open(filename) as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        for row in csv_reader:
            video_id = row[0]
            end_time = string_to_int(row[1])
            start_time = end_time - 1

            url = 'http://youtube.com/watch?v={}'.format(video_id)

            try:
                yt = YouTube(url)
            except:
                print('Error when trying to fetch video')
                continue

            if int(yt.length) > 500:
                continue

            filtered = yt.streams.filter(res='360p', mime_type='video/mp4', fps=30, progressive=True)

            if not filtered.all():
                continue

            num_downloaded += 1

            itag = filtered.first().itag
            filename = '{}.mp4'.format(video_id)
            filename_mp4 = '{}.mp4'.format(video_id)
            original_video_location = f'videos/{filename}'
            keyframe_video_location = f'videos/key-{filename}'
            download_video(url, itag, filename=original_video_location)

            start_min = start_time//60
            start_sec = start_time%60
            subprocess.call(f'ffmpeg -i {original_video_location} -force_key_frames 00:{start_min}:{start_sec} {keyframe_video_location}', shell=True)
            ffmpeg_extract_subclip(keyframe_video_location,
                    start_time,
                    end_time,
                    targetname='{}_videos/{}'.format(prefix, filename_mp4))

            extract_audio(prefix, video_id)

            os.remove(original_video_location)
            os.remove(keyframe_video_location)

            if num_videos and num_downloaded == num_videos:
                break
Пример #17
0
    def extractVideoClip(self, file, startTime, endTime, filename='subclip'):
        ffmpeg_extract_subclip(f'{file}.mp4',
                               startTime,
                               endTime,
                               targetname=f'{filename}.mp4')

        return True
Пример #18
0
def extract_videos_from_annotations_colab(video_name, eaf_file_name, gloss_list):
    """
    Function to extract videos from eaf annotations.
    Additionally it creates folders with the extracted frames for each video.
    """

    def check_folders(gl_name):
        directory1 = "openpose/" + gl_name + "/"
        if not os.path.exists(directory1):
            os.makedirs(directory1)

    file = pympi.Eaf(file_path=eaf_file_name)
    tier_names = file.get_tier_names()

    for tier_name in tier_names:
        annotations = file.get_annotation_data_for_tier(tier_name)
        count = 0
        for annotation in annotations:
            for gloss in gloss_list:
                if annotation[2] == gloss:
                    start = annotation[0]
                    end = annotation[1]
                    print(start / 1000, end / 1000)
                    check_folders(gloss)
                    ffmpeg_extract_subclip(video_name, start / 1000, end / 1000,
                                           targetname="openpose/" + str(gloss) + "/" + "%#05d.mp4" % (count + 1))
                    # Comment next line if you don't want to extract the frames for each video
                    # video_to_frames("Data/"+str(gloss)+"/Videos/"+"%#05d.mp4" % (count+1), "Data/"+str(gloss)+"/"+"%#05d" % (count+1) )
                    count = count + 1
        if count == 0:
            print("No annotation found with this name")
Пример #19
0
 def status_maker(self):
     self.disable_button()
     file = self.op.text
     reading_directory = os.path.dirname(file)
     basename = os.path.basename(file)
     basename_root = os.path.splitext(basename)[0]
     ext = os.path.splitext(basename)[1]
     if ext == ".mp4":
         os.chdir(reading_directory)  #changing file directory
         writing_directory = os.path.join(reading_directory,
                                          basename_root + "_WA_Status")
         if not os.path.exists(writing_directory):
             os.mkdir(writing_directory)
         os.chdir(writing_directory)
         size = VideoFileClip(file).duration
         i = 0
         ii = 1
         while i < size:
             try:
                 ffmpeg_extract_subclip(file, i, i + 25, str(ii) + ext)
             except:
                 self.status.text = "Error: File Could not be manipulated."
             i += 25
             ii += 1
         self.status.text = f"Your o/p saved in {writing_directory}"
     else:
         self.status.text = f"Extension Error. Choose .mp4 extension."
     self.enable_button()
Пример #20
0
 def cut_video_by_scenes(self):
     try:
         scenes = find_scenes(
             video_path=f"{self.path_to_videos}/{self.last_video_id}.mp4",
             threshold=50.0)
         self.number_of_scenes = len(scenes[5:-5])
         for index, scene in enumerate(scenes[5:-5]):
             start_scene_seconds = to_secondes(time=str(scene[0]),
                                               time_format="%H:%M:%S.%f")
             end_scene_seconds = to_secondes(time=str(scene[1]),
                                             time_format="%H:%M:%S.%f")
             if int(end_scene_seconds) - int(start_scene_seconds) < 15:
                 continue
             # Enlever les deux premières secondes pour corriger les erreurs de cuts
             start_scene_seconds = start_scene_seconds + 2
             ffmpeg_extract_subclip(
                 filename=f"{self.path_to_videos}/{self.last_video_id}.mp4",
                 t1=start_scene_seconds,
                 t2=end_scene_seconds,
                 targetname=
                 f"{self.path_to_cutted_videos}/{self.last_video_id}_{index}.mp4"
             )
             self.cutted_videos.append(f"{self.last_video_id}_{index}")
         print('cut_video_by_scenes: DONE')
     except Exception as e:
         logging.error(e)
Пример #21
0
def split_movie(inputfile, number):
    clip = VideoFileClip(inputfile)
    start = 0.0

    total = math.floor(clip.duration)
    segment = total // number

    filename, extension = os.path.splitext(inputfile)

    print(filename)
    endpoints = []
    for i in range(number):
        if i == number - 1:
            endpoints.append(clip.duration)
        else:
            endpoints.append(segment * (i + 1))

    pieces = []
    for point in endpoints:
        pieces.append((start, point))
        start = point

    for i, piece in enumerate(pieces):
        name = filename + "_" + str(i + 1) + extension
        ffmpeg_extract_subclip(inputfile, piece[0], piece[1], name)
        print("Splitting %s into file %s..." % (inputfile, name))
Пример #22
0
def frames_to_videos(original_videos_path, frame_indices_dict, results_clips_path):
    """
    :param original_videos_path: path to the videos
    :param frame_indices_dict: indices of the frames as a result of the search
    :param results_clips_path: path to the directory where the resulting videos are saved
    :return:
    """
    print('Constricting video clips ...')
    t = time.time()

    for video in frame_indices_dict.keys():
        if frame_indices_dict[video] == []:
            continue
        else:
            count = 0
            if not os.path.exists(os.path.join(results_clips_path, video)):
                os.mkdir(os.path.join(results_clips_path, video))
                for i, item in enumerate(frame_indices_dict[video]):
                    target_path = os.path.join(results_clips_path, video, "subvideo_{}.mp4".format(count))
                    start_time = item[0]
                    end_time = item[-1]
                    ffmpeg_extract_subclip(os.path.join(original_videos_path, "{}".format(video)),
                                           start_time - 1,
                                           end_time + 1,
                                           targetname=target_path)
                    count += 1
            elif os.path.exists(os.path.join(results_clips_path, video)) and len(
                    os.listdir(os.path.join(results_clips_path, video))) > 0:
                print("{} directory exists and is not empty".format(os.path.join(results_clips_path, video)))
        print('Done constructing video clips ... {} seconds'.format(time.time() - t))
Пример #23
0
def cut_movie(file_dir):
    for root, dirs, files in os.walk(file_dir):
        # print(root)  # 当前目录路径
        # print(dirs)  # 当前路径下所有子目录
        # print(files)  # 当前路径下所有非目录子文件
        if len(files) >= 1 and "out_to" not in dirs:
            # print(len(files))
            print("发现需处理的文件")
            for file_info in files:
                # print(file_info[-3:])
                if file_info[-3:] == "mp4":
                    # 新建输出文件夹
                    if not os.path.exists(root + "\\out_to\\"):
                        os.makedirs(root + "\\out_to\\")
                    # print(file_info)
                    # 获取视频时间
                    file_dirs = root + "\\" + file_info
                    # print(file_dirs)
                    clip = VideoFileClip(file_dirs)
                    # print(clip.end)
                    # 分割
                    print(root + "\\out_to\\" + file_info)
                    ffmpeg_extract_subclip(
                        file_dirs,
                        3.4,
                        clip.end - 9.8,
                        targetname=root + "\\out_to\\" +
                        file_info.replace(" ", "").replace("000", ""))
                    time.sleep(1.5)
                    clean_ffmpeg()
Пример #24
0
def split_video(videofile):
    """
	Given a path to a video file, load the video and split the videos into 30 second segments. The last segment would be
	the rest of the video, even if it's less than 30 seconds. The video segments are saved with the original name followed
	by their number, in the same folder as the original video. 

	Example: input file = "example.mp4" -> "example1.mp4" "example2.mp4" "example3.mp4"
	"""
    clip = VideoFileClip(videofile)
    start = 0
    end = clip.duration
    i = 1
    filename = videofile.split('.')
    extension = filename[1]
    filename = filename[0]

    while start + 30 <= end:
        target_name = filename + str(i) + '.' + extension
        ffmpeg_extract_subclip(videofile,
                               start,
                               start + 30,
                               targetname=target_name)
        start += 30
        i += 1

    target_name = filename + str(i) + '.' + extension
    ffmpeg_extract_subclip(videofile, start, end, targetname=target_name)
Пример #25
0
	def install_vk(self):
		'''Скачивание видео из вк'''
		videos = self.request.GET['link'].strip('https://vk.com/video')
		videos = videos.split('?')[0]
		token = 'ae1f79f5b6f3ff797737b9462904dc1c0b531fb8a95e3cff8d8ea45d2dab94fb223ba4a814879dfc7c829'
		vk = vk_api.VkApi(token=token)
		vk._auth_token()
		video_url = vk.method("video.get", 
		{
		'videos' : videos,
		'extended': True,
		})	
		if len(video_url['items']) > 0:
			url = video_url['items'][0]['files']['mp4_240']
		else:
			return 'link_error'
		timeof = self.request.GET['timeof'].split(':')
		timeto = self.request.GET['timeto'].split(':')
		timeof_seconds = int(timeof[0]) * 60 + int(timeof[1])
		timeto_seconds = int(timeto[0]) * 60 + int(timeto[1])
		if timeto_seconds - timeof_seconds > 30 and timeto_seconds - timeof_seconds < 1:
			return 'time_error'
		ffmpeg_extract_subclip(url, timeof_seconds, timeto_seconds, targetname="audio/{}.mp4".format(self.name))# + '000'
		# ffmpeg_extract_audio("audio/{}.mp4".format(self.name + '000'), "audio/{}.mp4".format(self.name), bitrate=3000, fps=44100)
		# path = os.path.join(os.path.abspath(os.getcwd()), 'audio/{}.mp4'.format(self.name + '000'))
		# os.remove(path)
		return 'ok'
def extract_subclips(annots, counter, output_folder):
    csv = []
    for i in range(len(annots)):
        video_name, start_time, end_time, label = annots[i]

        if "test" in video_name:
            ffmpeg_extract_subclip(
                "./videos/test/{}.mp4".format(video_name),
                float(start_time),
                float(end_time),
                targetname="./new_videos/{}/{:05d}.mp4".format(
                    output_folder, counter))
        elif "validation" in video_name:
            ffmpeg_extract_subclip(
                "./videos/val/{}.mp4".format(video_name),
                float(start_time),
                float(end_time),
                targetname="./new_videos/{}/{:05d}.mp4".format(
                    output_folder, counter))

        csv.append("{};{}".format(counter, label))
        counter += 1

        if i % 50 == 0:
            print("-- \t{} / {} ({}%)".format(
                i, len(annots), round(i / len(annots) * 100.0, 2)))
    return csv, counter
Пример #27
0
 def cut_patches(clip_config, temp_dir):
     Utils.log(" [Tailor] Cutting patch from (%s)" % (clip_config["name"]))
     ffmpeg_extract_subclip(clip_config["name"],
                            clip_config["start_at"],
                            clip_config["end_at"],
                            targetname=temp_dir + "/" + Tailor.CLIP_PREFIX +
                            clip_config["name"])
Пример #28
0
 def makevideofromvideos(video_filenames, video_length):
     print("Making the video...")
     path = DIRECTORY
     directory = sorted(os.listdir(path))
     video_list = video_filenames
     print("VIDEO PRESENT: ", video_list)
     os.chdir("..")
     os.chdir(path)
     name_list = []
     vidcount = 1
     print("VIDEO LENGTH: ", video_length)
     for vid in video_list:
         print("VID:", vid)
         vidname = "video" + str(vidcount) + ".mp4"
         print("vidname:", vidname)
         my_clip = mp.VideoFileClip(vid)
         if my_clip.duration > video_length:
             start_time = 0
             end_time = video_length
             ffmpeg_extract_subclip(vid,
                                    start_time,
                                    end_time,
                                    targetname=vidname)
         else:
             start_time = 0
             end_time = my_clip.duration
             ffmpeg_extract_subclip(vid,
                                    start_time,
                                    end_time,
                                    targetname=vidname)
         name_list.append(vidname)
         vidcount += 1
     return name_list
     os.chdir("..")
Пример #29
0
def Splitter(spl_file):
    video = VideoFileClip(spl_file)
    vtime = video.duration
    vsize = os.stat(spl_file).st_size / (1024 * 1024)  #size in MB

    time_per_clip = int(50 * vtime / vsize)

    if vsize <= 50:
        return

    start = 0
    end = time_per_clip
    i = 1
    while end <= vtime:
        ffmpeg_extract_subclip(spl_file,
                               start,
                               end,
                               targetname=str(i) + "_" + spl_file)
        start += time_per_clip
        end += time_per_clip

        i += 1
    if end > vtime and start < vtime:
        ffmpeg_extract_subclip(spl_file,
                               start,
                               vtime,
                               targetname=str(i) + "_" + spl_file)
Пример #30
0
def main(file_name: str):
    uploadable_size = 900000000
    duration, size = get_duration(file_name), get_size(file_name)
    divide = size // uploadable_size
    time, time_table = 0, [0]
    chunks = duration // divide

    while time < duration:
        time += chunks
        time_table.append(round(time))

    time_table.pop()
    if time_table[-1] < duration:
        time_table.pop()
        time_table.append(round(duration))

    total_split = []

    for t in range(1, len(time_table)):
        new_name = file_name[:-4] + f'{t:02}' + file_name[-4:]
        total_split.append(new_name)
        ffmpeg_extract_subclip(file_name,
                               time_table[t - 1],
                               time_table[t],
                               targetname=new_name)

    print("Completed Split!")