# 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")