Skip to content

Instantly share code, notes, and snippets.

@changbowen
Created August 17, 2022 13:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save changbowen/7d8dd9ae2e00b91de1e67ed64522dd66 to your computer and use it in GitHub Desktop.
Save changbowen/7d8dd9ae2e00b91de1e67ed64522dd66 to your computer and use it in GitHub Desktop.
download youtube chaptered videos into separate files, without downloading chapters that already exist based on checking on the names
import os, sys
from pathlib import Path
import yt_dlp
url = sys.argv[1] if len(sys.argv) > 1 else None
download_root = sys.argv[2] if (len(sys.argv) > 2) else None
proxy = sys.argv[3] if (len(sys.argv) > 3) else None
if (None in [url, download_root, proxy]):
raise RuntimeError('Missing arguments.')
titles = set(Path(fn).stem for fn in os.listdir(download_root))
def get_sections_to_download(info, ydl):
if (info.get('chapters')):
chapters = []
for chapter in info.get('chapters'):
title = chapter['title']
if (len([x for x in titles if title.startswith(x)]) == 0):
titles.add(title)
chapters.append(chapter)
if (chapters):
return chapters
raise RuntimeError('No chapter needs downloading.')
def video_filter(info, *, incomplete: bool):
if (not info.get('title')): return
if (info.get('live_status') in {'is_live', 'was_live'}):
return 'Skipping live stream'
opt = {
'proxy': proxy,
'format': 'bestvideo+bestaudio/best',
'paths': { 'home': download_root },
'outtmpl': {
'default': '%(section_title,title)s.%(ext)s'
},
'download_ranges': get_sections_to_download,
'match_filter': video_filter,
'ignoreerrors': True
}
with yt_dlp.YoutubeDL(opt) as dl:
dl.download(url)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment