Spaces:
Running
Running
"""Util functions to download videos from youtube.""" | |
from glob import glob | |
import os | |
def download_youtube_video_pytube(video_id, save_path="."): | |
from pytube import YouTube | |
url = f"https://www.youtube.com/watch?v={video_id}" | |
try: | |
# Create a YouTube object | |
yt = YouTube(url) | |
# Select the highest resolution stream | |
stream = yt.streams.get_highest_resolution() | |
# Download the video | |
stream.download(output_path=save_path) | |
print(f"Downloaded: {yt.title}") | |
except Exception as e: | |
print(f"An error occurred: {e}") | |
def download_youtube_video_ytdlp(video_id, save_dir="/tmp/"): | |
import yt_dlp | |
try: | |
# Construct the URL using the video ID | |
url = f"https://www.youtube.com/watch?v={video_id}" | |
# yt-dlp options | |
ydl_opts = { | |
'format': 'best', # Download the best video quality | |
'outtmpl': f'{save_dir}/{video_id}.%(ext)s', # Save using video ID as the filename | |
'noprogress': True, # Suppress progress bar | |
} | |
# Download the video | |
with yt_dlp.YoutubeDL(ydl_opts) as ydl: | |
ydl.download([url]) | |
print(f"Downloaded video with ID: {video_id} to {save_dir}") | |
saved_path = glob(f"{save_dir}/{video_id}.*")[0] | |
assert os.path.exists(saved_path), f"File not found: {saved_path}" | |
return saved_path | |
except Exception as e: | |
print(f"An error occurred for video ID {video_id}: {e}") | |
if __name__ == "__main__": | |
# Example usage | |
# video_id = "FwZfVEuCnI4" | |
video_id = "PCHIWN-Wi3M" | |
# download_youtube_video(video_id) | |
download_youtube_video_ytdlp(video_id) | |