This is a request to create a Python script that:
- Downloads YouTube videos using yt-dlp
- Implements a progress hook/callback
- Displays a custom CLI progress bar using tqdm
- Updates the progress bar based on download bytes ratio
Let me create a comprehensive solution with multiple examples, from basic to advanced.
Key points to cover:
- Basic yt-dlp download with progress hook
- Using tqdm to create a custom progress bar
- Extracting relevant information from yt-dlp callback dictionary
- Handling different download states
- Calculating progress percentage from bytes
- Error handling
- Additional features like multiple videos, concurrent downloads, etc.
Let me write this step by step:
import yt_dlp
from tqdm import tqdm
import os
from pathlib import Path
# Basic example
def download_video_basic(url):
pbar = None
def progress_hook(d):
nonlocal pbar
if d['status'] == 'downloading':
if pbar is None:
# Get total bytes if available
total_bytes = d.get('total_bytes', d.get('total_bytes_estimate', 0))
pbar = tqdm(total=total_bytes, unit='B', unit_scale=True, desc=d.get('_filename', 'Downloading'))
# Current bytes downloaded
downloaded_bytes = d.get('downloaded_bytes', 0)
pbar.update(downloaded_bytes - pbar.n)
elif d['status'] == 'finished':
if pbar is not None:
pbar.close()
print(f"Download finished at {d.get('_filename', '')}")
ydl_opts = {
'progress_hooks': [progress_hook],
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.download([url])
# Run
if __name__ == "__main__":
url = "https://www.youtube.com/watch?v=..."
download_video_basic(url)
I should develop a more advanced and production-ready version with multiple examples that increase in complexity.
YouTube Video Downloader with yt-dlp and tqdm Progress Bar
Here's a comprehensive implementation with multiple examples:
1. Basic Implementation
import yt_dlp
from tqdm import tqdm
import os
def download_with_progress(url, output_path="downloads"):
"""Download YouTube video with tqdm progress bar"""
pbar = None
def progress_hook(d):
nonlocal pbar
if d['status'] == 'downloading':
# Initialize progress bar on first download callback
if pbar is None:
total_bytes = d.get('total_bytes') or d.get('total_bytes_estimate', 0)
filename = d.get('filename', 'video').split('/')[-1]
pbar = tqdm(
total=total_bytes,
unit='B',
unit_scale=True,
desc=filename[:40],
leave=True
)
# Update progress bar
current_bytes = d.get('downloaded_bytes', 0)
pbar.n = current_bytes
pbar.refresh()
elif d['status'] == 'finished':
if pbar is not None:
pbar.close()
print(f"✓ Download complete: {d.get('filename', 'video')}")
# Create output directory
os.makedirs(output_path, exist_ok=True)
ydl_opts = {
'format': 'bestvideo+bestaudio/best',
'postprocessors': [{
'key': 'FFmpegVideoConvertor',
'prefixes': ['ffmpeg', 'ffprobe'],
'args': ['-threads', '4'],
}],
'outtmpl': os.path.join(output_path, '%(title)s.%(ext)s'),
'progress_hooks': [progress_hook],
'quiet': False,
'no_warnings': False,
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.download([url])
if __name__ == "__main__":
url = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
download_with_progress(url)
2. Advanced Implementation with Detailed Metrics
import yt_dlp
from tqdm import tqdm
from datetime import datetime, timedelta
import os
class YouTubeDownloader:
def __init__(self, output_path="downloads"):
self.output_path = output_path
self.pbar = None
self.previous_bytes = 0
def progress_hook(self, d):
"""Enhanced progress hook with speed and ETA"""
if d['status'] == 'downloading':
# Get download info
total_bytes = d.get('total_bytes') or d.get('total_bytes_estimate', 0)
downloaded_bytes = d.get('downloaded_bytes', 0)
speed = d.get('speed', 0)
# Initialize progress bar
if self.pbar is None:
filename = os.path.basename(d.get('filename', 'video'))
self.pbar = tqdm(
total=total_bytes,
unit='B',
unit_scale=True,
unit_divisor=1024,
desc=f"[DL] {filename[:30]}",
bar_format='{desc}: {percentage:3.0f}%|{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}]',
leave=True
)
# Update progress bar
bytes_since_last = downloaded_bytes - self.previous_bytes
self.previous_bytes = downloaded_bytes
self.pbar.update(bytes_since_last)
# Update speed info (optional)
if speed:
self.pbar.set_postfix({'speed': f"{speed/1024/1024:.2f}MB/s"})
elif d['status'] == 'finished':
if self.pbar:
self.pbar.close()
filename = os.path.basename(d.get('filename', 'video'))
print(f"✓ Downloaded: {filename}")
self.pbar = None
self.previous_bytes = 0
elif d['status'] == 'error':
if self.pbar:
self.pbar.close()
print(f"✗ Error: {d.get('info_dict', {})}")
def download(self, url, format_spec='bestvideo+bestaudio/best'):
"""Download video with progress tracking"""
os.makedirs(self.output_path, exist_ok=True)
ydl_opts = {
'format': format_spec,
'outtmpl': os.path.join(self.output_path, '%(title)s.%(ext)s'),
'progress_hooks': [self.progress_hook],
'quiet': False,
'no_warnings': False,
'postprocessor_args': ['-threads', '4'],
}
try:
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
print(f"Starting download: {url}")
ydl.download([url])
print("All downloads completed!")
except Exception as e:
print(f"Error during download: {e}")
# Usage
if __name__ == "__main__":
downloader = YouTubeDownloader(output_path="downloads")
urls = [
"https://www.youtube.com/watch?v=dQw4w9WgXcQ",
]
for url in urls:
downloader.download(url)
3. Multi-video Downloader with Parallel Progress Bars
import yt_dlp
from tqdm import tqdm
from concurrent.futures import ThreadPoolExecutor
import os
from typing import List, Dict
class MultiVideoDownloader:
def __init__(self, output_path="downloads", max_workers=2):
self.output_path = output_path
self.max_workers = max_workers
self.progress_bars: Dict[str, tqdm] = {}
def progress_hook(self, video_id: str):
"""Create progress hook for specific video"""
def hook(d):
if d['status'] == 'downloading':
total = d.get('total_bytes') or d.get('total_bytes_estimate', 0)
downloaded = d.get('downloaded_bytes', 0)
percent = (downloaded / total * 100) if total > 0 else 0
# Create or update progress bar
if video_id not in self.progress_bars:
filename = os.path.basename(d.get('filename', 'video'))[:25]
self.progress_bars[video_id] = tqdm(
total=total,
unit='B',
unit_scale=True,
desc=f"[{video_id}] {filename}",
position=len(self.progress_bars),
leave=True
)
pbar = self.progress_bars[video_id]
pbar.n = downloaded
pbar.refresh()
elif d['status'] == 'finished':
if video_id in self.progress_bars:
self.progress_bars[video_id].close()
del self.progress_bars[video_id]
return hook
def download_single(self, url: str, video_id: str):
"""Download single video"""
ydl_opts = {
'format': 'bestvideo+bestaudio/best',
'outtmpl': os.path.join(self.output_path, '%(title)s.%(ext)s'),
'progress_hooks': [self.progress_hook(video_id)],
'quiet': False,
'no_warnings': False,
}
try:
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.download([url])
return True
except Exception as e:
print(f"Error downloading {video_id}: {e}")
return False
def download_batch(self, urls: List[str]):
"""Download multiple videos in parallel"""
os.makedirs(self.output_path, exist_ok=True)
with ThreadPoolExecutor(max_workers=self.max_workers) as executor:
futures = [
executor.submit(self.download_single, url, f"vid_{i}")
for i, url in enumerate(urls)
]
results = [f.result() for f in futures]
print(f"\nCompleted: {sum(results)}/{len(urls)} downloads successful")
# Usage
if __name__ == "__main__":
downloader = MultiVideoDownloader(max_workers=2)
urls = [
"https://www.youtube.com/watch?v=dQw4w9WgXcQ",
"https://www.youtube.com/watch?v=9bZkp7q19f0",
]
downloader.download_batch(urls)
4. Advanced Custom Progress Bar with Extra Metrics
import yt_dlp
from tqdm import tqdm
import os
from datetime import datetime, timedelta
class EnhancedDownloader:
def __init__(self, output_path="downloads"):
self.output_path = output_path
self.pbar = None
self.start_time = None
self.video_info = {}
def progress_hook(self, d):
"""Advanced progress with ETA, speed, and file info"""
if d['status'] == 'downloading':
if self.pbar is None:
self.start_time = datetime.now()
total = d.get('total_bytes') or d.get('total_bytes_estimate', 0)
filename = os.path.basename(d.get('filename', 'video'))
self.video_info = {
'filename': filename,
'total_bytes': total,
}
self.pbar = tqdm(
total=total,
unit='B',
unit_scale=True,
unit_divisor=1024,
desc=filename[:35],
bar_format=(
'{desc}\n'
'{percentage:3.0f}%|{bar}| {n_fmt}/{total_fmt}\n'
'Speed: {rate_fmt} | ETA: {remaining} | Elapsed: {elapsed}\n'
),
ncols=80,
)
downloaded = d.get('downloaded_bytes', 0)
self.pbar.n = downloaded
self.pbar.refresh()
elif d['status'] == 'finished':
if self.pbar:
elapsed = datetime.now() - self.start_time
file_size = d.get('total_bytes') or d.get('total_bytes_estimate', 0)
avg_speed = file_size / elapsed.total_seconds() if elapsed.total_seconds() > 0 else 0
self.pbar.close()
print("\n" + "="*80)
print(f"Download Statistics:")
print(f" File: {self.video_info.get('filename', 'Unknown')}")
print(f" Size: {file_size / 1024 / 1024:.2f} MB")
print(f" Time: {elapsed}")
print(f" Avg Speed: {avg_speed / 1024 / 1024:.2f} MB/s")
print("="*80 + "\n")
self.pbar = None
def download_playlist(self, playlist_url: str):
"""Download entire playlist with progress"""
os.makedirs(self.output_path, exist_ok=True)
ydl_opts = {
'format': 'bestvideo+bestaudio/best',
'outtmpl': os.path.join(
self.output_path,
'%(playlist_title)s/%(playlist_index)s - %(title)s.%(ext)s'
),
'progress_hooks': [self.progress_hook],
'quiet': False,
'no_warnings': False,
'ignoreerrors': True,
}
try:
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
print(f"Starting playlist download...")
ydl.download([playlist_url])
except Exception as e:
print(f"Error: {e}")
# Usage
if __name__ == "__main__":
downloader = EnhancedDownloader()
# Single video
downloader.download_playlist("https://www.youtube.com/watch?v=dQw4w9WgXcQ")
# Or playlist
# downloader.download_playlist("https://www.youtube.com/playlist?list=...")
5. Complete CLI Application with Click
import yt_dlp
from tqdm import tqdm
import click
import os
from pathlib import Path
from typing import Optional
class YouTubeDownloaderCLI:
def __init__(self, output_path: str = "downloads"):
self.output_path = Path(output_path)
self.pbar = None
self.total_videos = 0
self.completed_videos = 0
def progress_hook(self, d):
"""Progress callback"""
if d['status'] == 'downloading':
total = d.get('total_bytes') or d.get('total_bytes_estimate', 0)
if total == 0:
return
downloaded = d.get('downloaded_bytes', 0)
if self.pbar is None:
filename = Path(d.get('filename', 'video')).name
self.pbar = tqdm(
total=total,
unit='B',
unit_scale=True,
desc=f"{filename[:40]}",
bar_format='{l_bar}{bar}| {n_fmt}/{total_fmt}',
)
self.pbar.n = downloaded
self.pbar.refresh()
elif d['status'] == 'finished':
if self.pbar:
self.pbar.close()
self.pbar = None
self.completed_videos += 1
def download(
self,
url: str,
format_spec: str = 'bestvideo+bestaudio/best',
audio_only: bool = False
):
"""Download video"""
self.output_path.mkdir(parents=True, exist_ok=True)
# Choose format
if audio_only:
format_spec = 'bestaudio/best'
ydl_opts = {
'format': format_spec,
'outtmpl': str(
self.output_path / ('%(title)s.%(ext)s' if audio_only else '%(title)s.%(ext)s')
),
'progress_hooks': [self.progress_hook],
'quiet': False,
'no_warnings': False,
'postprocessor_args': ['-threads', '4'],
}
# Add audio conversion for audio-only
if audio_only:
ydl_opts['postprocessors'] = [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}]
try:
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
click.echo(f"⬇️ Downloading: {url}")
ydl.download([url])
click.echo(f"✅ Download complete!")
except Exception as e:
click.echo(f"❌ Error: {e}", err=True)
@click.group()
def cli():
"""YouTube Downloader with Progress Bar"""
pass
@cli.command()
@click.argument('url')
@click.option(
'--output', '-o',
default='downloads',
help='Output directory'
)
@click.option(
'--audio-only', '-a',
is_flag=True,
help='Download audio only (MP3)'
)
@click.option(
'--format', '-f',
default='bestvideo+bestaudio/best',
help='yt-dlp format specification'
)
def download(url: str, output: str, audio_only: bool, format: str):
"""Download single video"""
downloader = YouTubeDownloaderCLI(output)
downloader.download(url, format, audio_only)
@cli.command()
@click.argument('url')
@click.option(
'--output', '-o',
default='downloads',
help='Output directory'
)
def playlist(url: str, output: str):
"""Download entire playlist"""
downloader = YouTubeDownloaderCLI(output)
ydl_opts = {
'format': 'bestvideo+bestaudio/best',
'outtmpl': os.path.join(output, '%(playlist_title)s/%(playlist_index)s - %(title)s.%(ext)s'),
'progress_hooks': [downloader.progress_hook],
'quiet': False,
'no_warnings': False,
'ignoreerrors': True,
}
try:
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
click.echo(f"⬇️ Downloading playlist: {url}")
ydl.download([url])
click.echo(f"✅ Download complete!")
except Exception as e:
click.echo(f"❌ Error: {e}", err=True)
@cli.command()
@click.argument('url')
@click.option(
'--output', '-o',
default='downloads',
help='Output directory'
)
def info(url: str, output: str):
"""Get video information"""
ydl_opts = {
'quiet': False,
'no_warnings': False,
'extract_flat': 'in_playlist',
}
try:
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(url, download=False)
if 'entries' in info:
click.echo(f"Playlist: {info.get('title', 'Unknown')}")
click.echo(f"Videos: {len(info['entries'])}")
for i, entry in enumerate(info['entries'][:5], 1):
click.echo(f" {i}. {entry.get('title', 'Unknown')}")
else:
click.echo(f"Title: {info.get('title', 'Unknown')}")
click.echo(f"Duration: {info.get('duration', 0) // 60} min")
click.echo(f"Uploader: {info.get('uploader', 'Unknown')}")
except Exception as e:
click.echo(f"❌ Error: {e}", err=True)
if __name__ == "__main__":
cli()
Installation
# Install dependencies
pip install yt-dlp tqdm click
# Optional: FFmpeg for video processing
# Ubuntu/Debian
sudo apt-get install ffmpeg
# macOS
brew install ffmpeg
# Windows
winget install ffmpeg
Usage Examples
# Basic download
python downloader.py download "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
# Download audio only
python downloader.py download "https://www.youtube.com/watch?v=dQw4w9WgXcQ" --audio-only
# Download to custom directory
python downloader.py download "https://www.youtube.com/watch?v=dQw4w9WgXcQ" -o /path/to/dir
# Download playlist
python downloader.py playlist "https://www.youtube.com/playlist?list=..."
# Get video info
python downloader.py info "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
Key Features
✅ Real-time progress tracking with tqdm
✅ Speed and ETA display
✅ Multiple videos with concurrent downloads
✅ Batch processing with callbacks
✅ CLI interface with Click
✅ Error handling and recovery
✅ Playlist support
✅ Audio extraction (MP3 conversion)
✅ Custom formatting options
✅ Detailed download statistics
This implementation provides production-ready YouTube downloading with comprehensive progress tracking!