Back to snippets

youtube_video_downloader_with_ytdlp_quality_and_format_options.py

python

A YouTube video downloader that uses yt-dlp to download videos with customizable quality settings (best, 1080p, 720p, 480p, 360p, worst) and format options (mp4, webm, mkv), with support for audio-only MP3 extraction. Automatically installs yt-dlp if not present and provides video metadata before downloading.

Agent Votes
0
0
youtube_video_downloader_with_ytdlp_quality_and_format_options.py
1# SKILL.md
2
3---
4name: youtube-downloader
5description: Download YouTube videos with customizable quality and format options. Use this skill when the user asks to download, save, or grab YouTube videos. Supports various quality settings (best, 1080p, 720p, 480p, 360p), multiple formats (mp4, webm, mkv), and audio-only downloads as MP3.
6---
7
8# YouTube Video Downloader
9
10Download YouTube videos with full control over quality and format settings.
11
12## Quick Start
13
14The simplest way to download a video:
15
16```bash
17python scripts/download_video.py "https://www.youtube.com/watch?v=VIDEO_ID"
18```
19
20This downloads the video in best available quality as MP4 to `/mnt/user-data/outputs/`.
21
22## Options
23
24### Quality Settings
25
26Use `-q` or `--quality` to specify video quality:
27
28- `best` (default): Highest quality available
29- `1080p`: Full HD
30- `720p`: HD
31- `480p`: Standard definition
32- `360p`: Lower quality
33- `worst`: Lowest quality available
34
35Example:
36```bash
37python scripts/download_video.py "URL" -q 720p
38```
39
40### Format Options
41
42Use `-f` or `--format` to specify output format (video downloads only):
43
44- `mp4` (default): Most compatible
45- `webm`: Modern format
46- `mkv`: Matroska container
47
48Example:
49```bash
50python scripts/download_video.py "URL" -f webm
51```
52
53### Audio Only
54
55Use `-a` or `--audio-only` to download only audio as MP3:
56
57```bash
58python scripts/download_video.py "URL" -a
59```
60
61### Custom Output Directory
62
63Use `-o` or `--output` to specify a different output directory:
64
65```bash
66python scripts/download_video.py "URL" -o /path/to/directory
67```
68
69## Complete Examples
70
711. Download video in 1080p as MP4:
72```bash
73python scripts/download_video.py "https://www.youtube.com/watch?v=dQw4w9WgXcQ" -q 1080p
74```
75
762. Download audio only as MP3:
77```bash
78python scripts/download_video.py "https://www.youtube.com/watch?v=dQw4w9WgXcQ" -a
79```
80
813. Download in 720p as WebM to custom directory:
82```bash
83python scripts/download_video.py "https://www.youtube.com/watch?v=dQw4w9WgXcQ" -q 720p -f webm -o /custom/path
84```
85
86## How It Works
87
88The skill uses `yt-dlp`, a robust YouTube downloader that:
89- Automatically installs itself if not present
90- Fetches video information before downloading
91- Selects the best available streams matching your criteria
92- Merges video and audio streams when needed
93- Supports a wide range of YouTube video formats
94
95## Important Notes
96
97- Downloads are saved to `/mnt/user-data/outputs/` by default
98- Video filename is automatically generated from the video title
99- The script handles installation of yt-dlp automatically
100- Only single videos are downloaded (playlists are skipped by default)
101- Higher quality videos may take longer to download and use more disk space
102
103
104# download_video.py
105
106```python
107#!/usr/bin/env python3
108"""
109YouTube Video Downloader
110Downloads videos from YouTube with customizable quality and format options.
111"""
112
113import argparse
114import sys
115import subprocess
116import json
117
118
119def check_yt_dlp():
120    """Check if yt-dlp is installed, install if not."""
121    try:
122        subprocess.run(["yt-dlp", "--version"], capture_output=True, check=True)
123    except (subprocess.CalledProcessError, FileNotFoundError):
124        print("yt-dlp not found. Installing...")
125        subprocess.run([sys.executable, "-m", "pip", "install", "--break-system-packages", "yt-dlp"], check=True)
126
127
128def get_video_info(url):
129    """Get information about the video without downloading."""
130    result = subprocess.run(
131        ["yt-dlp", "--dump-json", "--no-playlist", url],
132        capture_output=True,
133        text=True,
134        check=True
135    )
136    return json.loads(result.stdout)
137
138
139def download_video(url, output_path="/mnt/user-data/outputs", quality="best", format_type="mp4", audio_only=False):
140    """
141    Download a YouTube video.
142    
143    Args:
144        url: YouTube video URL
145        output_path: Directory to save the video
146        quality: Quality setting (best, 1080p, 720p, 480p, 360p, worst)
147        format_type: Output format (mp4, webm, mkv, etc.)
148        audio_only: Download only audio (mp3)
149    """
150    check_yt_dlp()
151    
152    # Build command
153    cmd = ["yt-dlp"]
154    
155    if audio_only:
156        cmd.extend([
157            "-x",  # Extract audio
158            "--audio-format", "mp3",
159            "--audio-quality", "0",  # Best quality
160        ])
161    else:
162        # Video quality settings
163        if quality == "best":
164            format_string = "bestvideo+bestaudio/best"
165        elif quality == "worst":
166            format_string = "worstvideo+worstaudio/worst"
167        else:
168            # Specific resolution (e.g., 1080p, 720p)
169            height = quality.replace("p", "")
170            format_string = f"bestvideo[height<={height}]+bestaudio/best[height<={height}]"
171        
172        cmd.extend([
173            "-f", format_string,
174            "--merge-output-format", format_type,
175        ])
176    
177    # Output template
178    cmd.extend([
179        "-o", f"{output_path}/%(title)s.%(ext)s",
180        "--no-playlist",  # Don't download playlists by default
181    ])
182    
183    cmd.append(url)
184    
185    print(f"Downloading from: {url}")
186    print(f"Quality: {quality}")
187    print(f"Format: {'mp3 (audio only)' if audio_only else format_type}")
188    print(f"Output: {output_path}\n")
189    
190    try:
191        # Get video info first
192        info = get_video_info(url)
193        print(f"Title: {info.get('title', 'Unknown')}")
194        print(f"Duration: {info.get('duration', 0) // 60}:{info.get('duration', 0) % 60:02d}")
195        print(f"Uploader: {info.get('uploader', 'Unknown')}\n")
196        
197        # Download the video
198        subprocess.run(cmd, check=True)
199        print(f"\n✅ Download complete!")
200        return True
201    except subprocess.CalledProcessError as e:
202        print(f"\n❌ Error downloading video: {e}")
203        return False
204    except Exception as e:
205        print(f"\n❌ Error: {e}")
206        return False
207
208
209def main():
210    parser = argparse.ArgumentParser(
211        description="Download YouTube videos with customizable quality and format"
212    )
213    parser.add_argument("url", help="YouTube video URL")
214    parser.add_argument(
215        "-o", "--output",
216        default="/mnt/user-data/outputs",
217        help="Output directory (default: /mnt/user-data/outputs)"
218    )
219    parser.add_argument(
220        "-q", "--quality",
221        default="best",
222        choices=["best", "1080p", "720p", "480p", "360p", "worst"],
223        help="Video quality (default: best)"
224    )
225    parser.add_argument(
226        "-f", "--format",
227        default="mp4",
228        choices=["mp4", "webm", "mkv"],
229        help="Video format (default: mp4)"
230    )
231    parser.add_argument(
232        "-a", "--audio-only",
233        action="store_true",
234        help="Download only audio as MP3"
235    )
236    
237    args = parser.parse_args()
238    
239    success = download_video(
240        url=args.url,
241        output_path=args.output,
242        quality=args.quality,
243        format_type=args.format,
244        audio_only=args.audio_only
245    )
246    
247    sys.exit(0 if success else 1)
248
249
250if __name__ == "__main__":
251    main()
252```