Skip to content

Instantly share code, notes, and snippets.

@noaione
Last active August 4, 2021 06:48
Show Gist options
  • Select an option

  • Save noaione/10564ec6d74e59a99c629f9ff454dc2f to your computer and use it in GitHub Desktop.

Select an option

Save noaione/10564ec6d74e59a99c629f9ff454dc2f to your computer and use it in GitHub Desktop.
Download youtube clip with its desired timestamp
"""
Download a Youtube clip, this script will only download the desired timestamp.
Use ffmpeg to download the video and youtube-dl to extract the video url.
Requirements:
- Python 3.6+
- requests
- beautifulsoup4
- ffmpeg
- youtube-dl
To download just do: `python3 ytclip.py` then enter the
https://youtube.com/clip/xxxxxxxxxxxxxxxxxxx url when asked.
---------------------------------------------------------------------------------
MIT License
Copyright (c) 2021 noaione
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import json
import re
import subprocess
from datetime import timedelta
import requests
import youtube_dl
from bs4 import BeautifulSoup
url = input("Please enter Youtube clip link: ")
print(f"Requesting: {url}")
# Request the clip page
requested = requests.get(url)
html_data = requested.text
print("Parsing HTML...")
# Parse the HTML
soup = BeautifulSoup(html_data, 'html.parser')
print("Extracting ytInitialPlayerResponse...")
# Extract ytInitialPlayerResponse and parse it as json
player_response_js = soup.find(
"script", string=re.compile("ytInitialPlayerResponse"))
player_resp_txt = player_response_js.contents[0]
extracted_data = re.match(r"var ytInitialPlayerResponse = (.+?)}\;", player_resp_txt)
clean_response = extracted_data.group(0).replace("var ytInitialPlayerResponse = ", "").rstrip(";")
player_response = json.loads(clean_response)
# Select the video and audio streams
print("Selecting best video format...")
stream_data = player_response["streamingData"]
adaptive_format = stream_data["adaptiveFormats"]
video_itag = adaptive_format[0]["itag"]
best_format = (adaptive_format[0]["height"], adaptive_format[0]["fps"])
for format in adaptive_format:
if not format["mimeType"].startswith("video/mp4"):
continue
if format["height"] > best_format[0]:
video_itag = format["itag"]
best_format[0] = format["height"]
elif format["height"] == best_format[0]:
if format["fps"] > best_format[1]:
video_itag = format["itag"]
best_format[1] = format["fps"]
print("Selecting best audio format...")
audio_itag = -1
audio_bits = -1
for format in adaptive_format:
if not format["mimeType"].startswith("audio/mp4"):
continue
if format["bitrate"] > audio_bits:
audio_bits = format["bitrate"]
audio_itag = format["itag"]
print(
f"Selected format: {best_format[0]}p{best_format[1]} + {round(audio_bits / 1000, 2)}kb/s"
)
# Extract the timestamped part
print("Extracting timestamp...")
clip_config = player_response["clipConfig"]
start_time_ms = int(clip_config["startTimeMs"])
end_time_ms = int(clip_config["endTimeMs"])
start_ts = timedelta(milliseconds=start_time_ms)
end_ts = timedelta(milliseconds=end_time_ms)
print(f"Will download: {start_ts} to {end_ts}")
def safe_title(save_title: str):
forbidden = ["/", "\\", ":", "*", "?", '"', "<", ">", "|"]
for char in forbidden:
save_title = save_title.replace(char, "_")
return save_title
# Get clip title
clip_id = clip_config["postId"]
# Strip out the "✂️" from title
video_title = player_response["videoDetails"]["title"].replace("✂️ ", "")
save_title = safe_title(f"{video_title}-{clip_id}.mp4".replace(" ", "_"))
print("Extracting video URL...")
video_id = player_response["videoDetails"]["videoId"]
original_video = "https://youtube.com/watch?v=" + video_id
ytdl = youtube_dl.YoutubeDL({"format": f"{video_itag}+{audio_itag}"})
with ytdl:
result = ytdl.extract_info(original_video, download=False)
video_fmt, audio_fmt = result["requested_formats"]
video_url = video_fmt["url"]
audio_url = audio_fmt["url"]
print(f"Downloading to: {save_title}")
# Start downloading
# The magic part is that if we provide `-ss` before the input
# ffmpeg will seek to that timestamp and will start downloading from there.
ffmpeg_cmd = "ffmpeg -ss {st} -to {et} -i {vurl} -ss {st} -to {et} -i {aurl} -map 0:v -map 1:a -c copy {save}"
subprocess.call(
ffmpeg_cmd.format(
st=str(start_ts),
et=str(end_ts),
vurl=video_url,
aurl=audio_url,
save=save_title
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment