Created
October 28, 2023 17:35
-
-
Save pakkinlau/7acda5a495a76863826cb32562e7aa95 to your computer and use it in GitHub Desktop.
A python script that download a video with chopping. Only videoID and time periods are needed to be provided to run the script.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pytube.cli import on_progress | |
from pytube import YouTube | |
import os | |
from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip | |
def download_with_cut(link, target_folder=None, time_ranges=None): | |
yt = YouTube( | |
link, on_progress_callback=on_progress, use_oauth=True, allow_oauth_cache=True | |
) | |
video_stream = ( | |
yt.streams.filter(progressive=True, file_extension="mp4") | |
.order_by("resolution") | |
.desc() | |
.first() | |
) | |
video_path = video_stream.download(output_path=target_folder) | |
video_filename = os.path.basename(video_path) | |
if time_ranges is not None: | |
index = 1 | |
for start_time, end_time in time_ranges: | |
start_time = parse_time(start_time) | |
end_time = parse_time(end_time) | |
clip_filename = f"{os.path.splitext(video_filename)[0]}_clip{index}.mp4" | |
clip_path = os.path.join(target_folder, clip_filename) | |
ffmpeg_extract_subclip( | |
video_path, start_time, end_time, targetname=clip_path | |
) | |
print(f"Video clip saved: {clip_path}") | |
index += 1 | |
os.remove(video_path) | |
else: | |
print( | |
"Please provide time_ranges to specify the start_time and end_time for cutting the video clip." | |
) | |
def parse_time(time_str): | |
h, m, s = time_str.split(":") | |
return int(h) * 3600 + int(m) * 60 + int(s) | |
links = ["https://www.youtube.com/watch?v=EQXPm_WQzcU"] | |
time_ranges = [("00:09:44", "00:36:32")] | |
target_folder = r"F:\Downloads\YT extracts" # Replace with the desired target folder path | |
if __name__ == "__main__": | |
for link in links: | |
download_with_cut(link, target_folder, time_ranges=time_ranges) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment