Skip to content
The Chat Archive
deepseek-v3-0324· DeepSeek LMArena Human Preference 140K

Write a full single python code for Google Colab. It features a user friendly yt-dlp…

  1. User

    Write a full single python code for Google Colab. It features a user friendly yt-dlp application. All together, the UI gives you end‑to‑end control over yt-dlp without ever touching the command line.

  2. Assistant

    YouTube Downloader with yt-dlp - Google Colab UI

    Here's a complete Python script for Google Colab that provides a user-friendly interface for yt-dlp with a variety of download options:

    import ipywidgets as widgets
    from IPython.display import display, clear_output, HTML
    import subprocess
    import os
    import re
    import json
    from pathlib import Path
    
    # Initialize variables
    download_path = "/content/downloads"
    os.makedirs(download_path, exist_ok=True)
    
    # Custom CSS for better UI
    css = """
    <style>
    .widget-label { font-weight: bold !important; }
    .download-btn { background-color: #4CAF50 !important; color: white !important; }
    .info-btn { background-color: #2196F3 !important; color: white !important; }
    .warning { color: #FF5722; font-weight: bold; }
    .success { color: #4CAF50; font-weight: bold; }
    .progress-bar { width: 100%; background-color: #e0e0e0; border-radius: 5px; }
    .progress-bar-fill { height: 20px; background-color: #4CAF50; border-radius: 5px; width: 0%; }
    </style>
    """
    display(HTML(css))
    
    # Create widgets
    url_input = widgets.Text(
        placeholder='Enter YouTube URL (or playlist/channel)',
        description='URL:',
        layout=widgets.Layout(width='80%')
    )
    
    format_dropdown = widgets.Dropdown(
        options=[
            ('Best quality (video+audio)', 'best'),
            ('1080p (video+audio)', 'bestvideo[height<=1080]+bestaudio/best[height<=1080]'),
            ('720p (video+audio)', 'bestvideo[height<=720]+bestaudio/best[height<=720]'),
            ('480p (video+audio)', 'bestvideo[height<=480]+bestaudio/best[height<=480]'),
            ('Audio only (MP3)', 'bestaudio[ext=m4a]/bestaudio/best'),
            ('Audio only (OGG)', 'bestaudio[ext=ogg]/bestaudio/best'),
            ('Custom format (advanced)', 'custom')
        ],
        value='best',
        description='Format:',
        layout=widgets.Layout(width='80%')
    )
    
    custom_format = widgets.Text(
        placeholder='e.g. bestvideo[height<=720]+bestaudio/best[height<=720]',
        description='Custom format:',
        layout=widgets.Layout(width='80%'),
        disabled=True
    )
    
    output_template = widgets.Text(
        value='%(title)s.%(ext)s',
        description='Filename:',
        layout=widgets.Layout(width='80%')
    )
    
    download_subtitles = widgets.Checkbox(
        value=False,
        description='Download subtitles',
        indent=False
    )
    
    subtitles_lang = widgets.Text(
        value='en',
        description='Subtitle lang:',
        layout=widgets.Layout(width='80%'),
        disabled=True
    )
    
    download_thumbnails = widgets.Checkbox(
        value=False,
        description='Download thumbnails',
        indent=False
    )
    
    download_playlist = widgets.Checkbox(
        value=False,
        description='Download entire playlist',
        indent=False
    )
    
    playlist_items = widgets.Text(
        placeholder='e.g. 1-5,8,10-12',
        description='Playlist items:',
        layout=widgets.Layout(width='80%'),
        disabled=True
    )
    
    download_button = widgets.Button(
        description='Start Download',
        button_style='success',
        icon='download',
        layout=widgets.Layout(width='200px')
    )
    
    info_button = widgets.Button(
        description='Get Video Info',
        button_style='info',
        icon='info',
        layout=widgets.Layout(width='200px')
    )
    
    progress_bar = widgets.FloatProgress(
        value=0,
        min=0,
        max=100,
        description='Progress:',
        bar_style='info',
        orientation='horizontal',
        layout=widgets.Layout(width='80%', visibility='hidden')
    )
    
    output_area = widgets.Output()
    
    # Helper functions
    def update_custom_format(change):
        custom_format.disabled = change['new'] != 'custom'
    
    def update_subtitles_lang(change):
        subtitles_lang.disabled = not change['new']
    
    def update_playlist_items(change):
        playlist_items.disabled = not change['new']
    
    def sanitize_filename(filename):
        # Remove invalid characters
        filename = re.sub(r'[<>:"/\\|?*]', '', filename)
        # Replace spaces with underscores
        filename = filename.replace(' ', '_')
        return filename
    
    def run_ytdlp_command(command):
        with output_area:
            clear_output()
            print(f"Running command: {' '.join(command)}\n")
            
            progress_bar.value = 0
            progress_bar.layout.visibility = 'visible'
            
            process = subprocess.Popen(
                command,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT,
                universal_newlines=True
            )
            
            for line in process.stdout:
                print(line, end='')
                # Simple progress detection (this can be improved)
                if '%' in line:
                    try:
                        percent = float(line.split('%')[0].split()[-1])
                        progress_bar.value = percent
                    except:
                        pass
            
            process.wait()
            progress_bar.layout.visibility = 'hidden'
            
            if process.returncode == 0:
                print("\n✅ Download completed successfully!")
            else:
                print("\n❌ Download failed. Check the error above.")
    
    def on_download_button_clicked(b):
        if not url_input.value.strip():
            with output_area:
                clear_output()
                print("⚠️ Please enter a YouTube URL")
            return
        
        command = [
            'yt-dlp',
            '-o', f'{download_path}/{output_template.value}',
            '--no-playlist' if not download_playlist.value else '',
            '--playlist-items', playlist_items.value if download_playlist.value and playlist_items.value else '',
            '--write-subs' if download_subtitles.value else '',
            '--sub-lang', subtitles_lang.value if download_subtitles.value else '',
            '--write-thumbnail' if download_thumbnails.value else '',
            '--embed-thumbnail' if download_thumbnails.value else '',
            '--embed-subs' if download_subtitles.value else '',
            '--convert-subs', 'srt' if download_subtitles.value else '',
            '--restrict-filenames',
            '--no-continue',
            '--newline'
        ]
        
        # Remove empty arguments
        command = [arg for arg in command if arg != '']
        
        # Handle format
        if format_dropdown.value == 'custom':
            command.extend(['-f', custom_format.value])
        else:
            command.extend(['-f', format_dropdown.value])
        
        # Add the URL at the end
        command.append(url_input.value.strip())
        
        run_ytdlp_command(command)
    
    def on_info_button_clicked(b):
        if not url_input.value.strip():
            with output_area:
                clear_output()
                print("⚠️ Please enter a YouTube URL")
            return
        
        command = [
            'yt-dlp',
            '--dump-json',
            '--no-playlist' if not download_playlist.value else '',
            url_input.value.strip()
        ]
        
        with output_area:
            clear_output()
            print("Fetching video information...\n")
            
            try:
                result = subprocess.run(command, capture_output=True, text=True, check=True)
                data = json.loads(result.stdout)
                
                print(f"📹 Title: {data.get('title', 'N/A')}")
                print(f"👤 Channel: {data.get('uploader', 'N/A')}")
                print(f"🔗 URL: {data.get('webpage_url', 'N/A')}")
                print(f"⏱ Duration: {data.get('duration_string', 'N/A')}")
                print(f"📅 Upload date: {data.get('upload_date', 'N/A')}")
                print(f"👀 Views: {data.get('view_count', 'N/A')}")
                print(f"👍 Likes: {data.get('like_count', 'N/A')}")
                
                print("\nAvailable formats:")
                formats = data.get('formats', [])
                if formats:
                    print(f"{'ID':<5} {'Resolution':<12} {'FPS':<6} {'Ext':<6} {'Size':<10} {'Note'}")
                    for f in sorted(formats, key=lambda x: x.get('height', 0), reverse=True):
                        print(f"{f.get('format_id', ''):<5} {str(f.get('height', ''))+'p':<12} {f.get('fps', ''):<6} {f.get('ext', ''):<6} {f.get('filesize', 'N/A'):<10} {f.get('format_note', '')}")
            except subprocess.CalledProcessError as e:
                print(f"Error getting video info: {e.stderr}")
            except json.JSONDecodeError:
                print("Error parsing video information.")
    
    # Set up event handlers
    format_dropdown.observe(update_custom_format, names='value')
    download
    

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.