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 all yt-dlp settings and features without ever touching the command line.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Below is one self-contained Python script that you can paste into one single code-cell in Google Colab.
It
• installs/updates everything (yt-dlp, ffmpeg, ipywidgets, …)
• builds a point-and-click Graphical UI with ipywidgets (runs completely inside the notebook)
• lets you set the most-used options (and even advanced, free-text ones)
• shows live progress, logs, and basic media-info – no command line needed.
Just run the cell, wait for the small set-up to finish, and the interface will appear.
python
# ==========================================
# All-in-one yt-dlp GUI for Google Colab
# Author: 2024-06 • License: MIT
# ==========================================
# 1) Install / update everything we need
import subprocess, sys, json, shlex, textwrap, os, math, time, contextlib, pathlib
def _p(cmd):
"""Run a shell/pip/apt command silently but show errors if they happen."""
res = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
if res.returncode != 0:
print('[!] Command failed:', cmd)
print(res.stderr[:4000])
return res
with contextlib.redirect_stdout(open(os.devnull, 'w')):
_p('pip -q install -U yt-dlp ipywidgets nest_asyncio')
_p('apt -qq install -y ffmpeg')
_p('jupyter nbextension enable --py widgetsnbextension')
import yt_dlp, nest_asyncio, ipywidgets as W
from IPython.display import display, Markdown, clear_output
nest_asyncio.apply()
# ------------------------------------------------
# 2) Helper: nice progress hook -> widget updates
# ------------------------------------------------
progress_bar = W.IntProgress(value=0, min=0, max=100, description='Progress', bar_style='')
speed_label = W.Label('')
eta_label = W.Label('')
def _hook(d):
if d['status'] == 'downloading':
pct = d.get('_percent_str', '0%').strip().rstrip('%')
try: pct = float(pct)
except: pct = 0
progress_bar.value = math.floor(pct)
progress_bar.description= f'{pct:4.1f}%'
speed_label.value = f"Speed : {d.get('_speed_str','?')}"
eta_label.value = f"ETA : {d.get('_eta_str','?')}"
elif d['status'] == 'finished':
progress_bar.value = 100
progress_bar.description= 'Done! ✔'
speed_label.value = ''
eta_label.value = ''
# ------------------------------------------------
# 3) Widgets (GUI)
# ------------------------------------------------
url_box = W.Textarea(
placeholder='Paste one or many video / playlist URLs, one per line',
description='URL(s)',
layout=W.Layout(width='98%', height='100px'))
dl_type = W.ToggleButtons(
options=[('Best video+audio', 'bestvideo+bestaudio/best'),
('Best video (no audio)','bestvideo'),
('Best audio (mp3)','bestaudio'),
('Custom format id','custom')],
value='bestvideo+bestaudio/best',
description='Format')
res_dropdown = W.Dropdown(
options=['best','4320','2160','1440','1080','720','480','360','240','144'],
value='best',
description='Max ‑p')
subs_check = W.Checkbox(value=False, description='Download & embed subtitles')
thumb_check = W.Checkbox(value=False, description='Embed thumbnail')
playlist_check = W.Checkbox(value=True , description='Process entire playlist (if any)')
merge_audio = W.Checkbox(value=True , description='Merge/convert with ffmpeg')
output_tmpl = W.Text(
value='%(title).200s [%(id)s].%(ext)s',
description='Save as',
layout=W.Layout(width='80%'))
adv_opts = W.Textarea(
placeholder='Any additional yt-dlp option, e.g. --cookies-from-browser chrome',
description='Extra',
layout=W.Layout(width='98%', height='60px'))
info_btn = W.Button(description='Fetch info', button_style='info')
dl_btn = W.Button(description='Download', button_style='success')
clear_log_btn = W.Button(description='Clear log')
log_area = W.Output(layout={'border':'1px solid silver','height':'220px','overflow_y':'auto'})
# ------------------------------------------------
# 4) Core functions
# ------------------------------------------------
def build_opts(for_info=False):
"""Translate widget state into a real yt-dlp options dict."""
opts = {
'outtmpl' : {'default': output_tmpl.value},
'quiet' : False,
'nocheckcertificate': True,
'progress_hooks': [_hook],
'concurrent_fragment_downloads':5,
'ignoreerrors' : True,
}
# ====== format ==========================================================
if dl_type.value == 'custom':
# user will type a raw format code in the "Extra" box
pass
else:
fmt = dl_type.value
if res_dropdown.value != 'best' and 'bestvideo' in fmt:
fmt = f"bestvideo[height<={res_dropdown.value}]+bestaudio/best"
opts['format'] = fmt
# ====== subtitles / thumb / playlist / audio-only =======================
if subs_check.value:
opts.update({'writesubtitles':True,'writeautomaticsub':True,'embedsubtitles':True})
if thumb_check.value:
opts.update({'embedthumbnail':True, 'addmetadata':True})
if not playlist_check.value:
opts['noplaylist'] = True
if dl_type.value == 'bestaudio':
opts.update({
'format':'bestaudio',
'postprocessors': [{
'key':'FFmpegExtractAudio',
'preferredcodec':'mp3',
'preferredquality':'0',
}]
})
if not merge_audio.value:
opts['postprocessors'] = []
opts['postprocessor_args'] = []
opts['merge_output_format']=''
# ====== extra raw options ==============================================
if adv_opts.value.strip():
# we parse the raw CLI string & hand it to yt-dlp parser itself
extra_list = shlex.split(adv_opts.value.strip())
try:
parsed = yt_dlp.parse_options(extra_list)[0]
opts.update(parsed)
except Exception as e:
with log_area:
print('[!] Could not parse extra options:', e)
# info-only?
if for_info:
opts['skip_download'] = True
opts.pop('progress_hooks', None)
return opts
def fetch_info(_=None):
log_area.clear_output()
url = url_box.value.strip()
if not url:
with log_area: print('Please enter at least one URL.')
return
opts = build_opts(for_info=True)
with yt_dlp.YoutubeDL(opts) as ydl:
with log_area:
try:
info = ydl.extract_info(url, download=False)
print(json.dumps(info, indent=2)[:8000], '...') # avoid flooding
except Exception as e:
print('[!] Error:', e)
def download(_=None):
log_area.clear_output()
progress_bar.value=0; progress_bar.description='Starting'
url = url_box.value.strip()
if not url:
with log_area: print('Please enter at least one URL.')
return
opts = build_opts(for_info=False)
with yt_dlp.YoutubeDL(opts) as ydl:
with log_area:
try:
ydl.download(url.splitlines())
print('\n✅ Finished.')
except Exception as e:
print('[!] Error:', e)
def clear_log(_=None):
log_area.clear_output()
info_btn.on_click(fetch_info)
dl_btn.on_click(download)
clear_log_btn.on_click(clear_log)
# ------------------------------------------------
# 5) Draw the interface
# ------------------------------------------------
header = Markdown(textwrap.dedent("""
# 🎬 yt-dlp Colab GUI
Point-and-click interface for **yt-dlp** right inside Google Colab.
Use responsibly; always respect copyright and the terms of service of the site you are downloading from.
"""))
left = W.VBox([url_box, dl_type, res_dropdown, playlist_check, subs_check,
thumb_check, merge_audio])
right = W.VBox([output_tmpl, adv_opts, W.HBox([info_btn, dl_btn, clear_log_btn]),
progress_bar, speed_label, eta_label, log_area])
ui = W.HBox([left, right])
display(header, ui)
# ------------------------------------------------
# 6) Friendly reminder
# ------------------------------------------------
print("ℹ️ Tip: Hold Shift while pressing Enter inside text boxes to add new lines without submitting.")
––––––––––––––––––––––––––––––
How to use
Run the cell (first run installs everything – takes ~30 s).
Paste one or many video / playlist URLs.
Choose your preferred format & options.
Click Fetch info (optional) to preview, or Download to start.
Watch the live progress bar and logs.
Files end up in the current Colab working directory; click the folder icon on the left to download them to your machine or mount Google Drive.