Skip to content

Instantly share code, notes, and snippets.

@telugu-boy
Last active August 17, 2024 21:54
Show Gist options
  • Save telugu-boy/a2ca5b99d501e6f5f295333537a2a849 to your computer and use it in GitHub Desktop.
Save telugu-boy/a2ca5b99d501e6f5f295333537a2a849 to your computer and use it in GitHub Desktop.
takes youtube video with chapters and downloads and splits into playlist based on the chapter timestamps
# https://www.github.com/telugu-boy/
import youtube_dl
import getopt
import sys
import os
# https://www.youtube.com/watch?v=obLq6k3clHo
ydl_opts = {
"extractaudio": False,
}
helpstring = """
chapters_to_playlist.py [options] [url]
-x to extract audio only
-k to keep downloaded file
-o to specify working/output directory
-h to show this
"""
if __name__ == "__main__":
opts, args = getopt.getopt(sys.argv[1:], "hxko:")
keepfile = False
createdirs = False
providedURL = None
#don't want anything happening during argument parsing except setting flags
#for further processing. like creating dirs
for opt, arg in opts:
if '-x' == opt:
ydl_opts['extractaudio'] = True
if '-o' == opt:
createdirs = True
if '-k' == opt:
keepfile = True
if '-h' == opt:
print(helpstring)
exit()
if createdirs:
if not os.path.exists(arg):
os.makedirs(arg)
os.chdir(arg)
if len(args) < 1:
print("Need URL")
exit()
else:
providedURL = args[0]
ydl_opts['outtmpl'] = os.path.join(os.getcwd(), "%(title)s.%(ext)s")
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
info_dict = ydl.extract_info(providedURL, download=False)
if "chapters" not in info_dict or not info_dict["chapters"]:
print("This video does not have chapters")
exit()
title = info_dict["title"]
ext = info_dict["ext"]
filename = f"{title}.{ext}"
ydl.download([providedURL])
for idx, chapter in enumerate(info_dict["chapters"]):
start_time = chapter["start_time"]
end_time = chapter["end_time"]
chapter_title = chapter["title"]
cmd = None
if ydl_opts['extractaudio']:
cmd = f"""ffmpeg -i "{title}.{ext}" -ss {start_time} -to {end_time} -map 0:a -acodec mp3 \"{idx}-{chapter_title}.mp3\""""
else:
cmd = f"""ffmpeg -i "{title}.{ext}" -ss {start_time} -to {end_time} -c copy \"{idx}-{chapter_title}.{ext}\""""
os.system(cmd)
if not keepfile:
print("Deleting original. Pass -k to keep")
os.remove(filename)
print("Done")
@kwakueshun
Copy link

@Twinsheet313421 did you install youtube-dl as shown here?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment