Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
mikf
GitHub Repository: mikf/gallery-dl
Path: blob/master/gallery_dl/ytdl.py
5457 views
1
# -*- coding: utf-8 -*-
2
3
# Copyright 2021-2025 Mike Fährmann
4
#
5
# This program is free software; you can redistribute it and/or modify
6
# it under the terms of the GNU General Public License version 2 as
7
# published by the Free Software Foundation.
8
9
"""Helpers for interacting with youtube-dl"""
10
11
import shlex
12
import itertools
13
from . import text, util, exception
14
15
16
def import_module(module_name):
17
if module_name is None:
18
try:
19
return __import__("yt_dlp")
20
except (ImportError, SyntaxError):
21
return __import__("youtube_dl")
22
return util.import_file(module_name)
23
24
25
def construct_YoutubeDL(module, obj, user_opts, system_opts=None):
26
opts = argv = None
27
config = obj.config
28
29
if not config("deprecations"):
30
module.YoutubeDL.deprecated_feature = util.false
31
module.YoutubeDL.deprecation_warning = util.false
32
33
if cfg := config("config-file"):
34
with open(util.expand_path(cfg)) as fp:
35
contents = fp.read()
36
argv = shlex.split(contents, comments=True)
37
38
if cmd := config("cmdline-args"):
39
if isinstance(cmd, str):
40
cmd = shlex.split(cmd)
41
argv = (argv + cmd) if argv else cmd
42
43
try:
44
opts = parse_command_line(module, argv) if argv else user_opts
45
except SystemExit:
46
raise exception.AbortExtraction("Invalid command-line option")
47
48
if opts.get("format") is None:
49
opts["format"] = config("format")
50
if opts.get("nopart") is None:
51
opts["nopart"] = not config("part", True)
52
if opts.get("updatetime") is None:
53
opts["updatetime"] = config("mtime", True)
54
if opts.get("min_filesize") is None:
55
opts["min_filesize"] = text.parse_bytes(config("filesize-min"), None)
56
if opts.get("max_filesize") is None:
57
opts["max_filesize"] = text.parse_bytes(config("filesize-max"), None)
58
if opts.get("ratelimit") is None:
59
if rate := config("rate"):
60
func = util.build_selection_func(rate, 0, text.parse_bytes)
61
if hasattr(func, "args"):
62
opts["__gdl_ratelimit_func"] = func
63
else:
64
opts["ratelimit"] = func() or None
65
else:
66
opts["ratelimit"] = None
67
68
if raw_opts := config("raw-options"):
69
opts.update(raw_opts)
70
if config("logging", True):
71
opts["logger"] = obj.log
72
if system_opts:
73
opts.update(system_opts)
74
75
opts["__gdl_initialize"] = True
76
return module.YoutubeDL(opts)
77
78
79
def parse_command_line(module, argv):
80
parser, opts, args = module.parseOpts(argv)
81
82
ytdlp = hasattr(module, "cookies")
83
std_headers = module.std_headers
84
85
try:
86
parse_bytes = module.parse_bytes
87
except AttributeError:
88
parse_bytes = module.FileDownloader.parse_bytes
89
90
# HTTP headers
91
if opts.user_agent is not None:
92
std_headers["User-Agent"] = opts.user_agent
93
if opts.referer is not None:
94
std_headers["Referer"] = opts.referer
95
if opts.headers:
96
if isinstance(opts.headers, dict):
97
std_headers.update(opts.headers)
98
else:
99
for h in opts.headers:
100
key, _, value = h.partition(":")
101
std_headers[key] = value
102
103
if opts.ratelimit is not None:
104
opts.ratelimit = parse_bytes(opts.ratelimit)
105
if getattr(opts, "throttledratelimit", None) is not None:
106
opts.throttledratelimit = parse_bytes(opts.throttledratelimit)
107
if opts.min_filesize is not None:
108
opts.min_filesize = parse_bytes(opts.min_filesize)
109
if opts.max_filesize is not None:
110
opts.max_filesize = parse_bytes(opts.max_filesize)
111
if opts.max_sleep_interval is None:
112
opts.max_sleep_interval = opts.sleep_interval
113
if getattr(opts, "overwrites", None):
114
opts.continue_dl = False
115
if opts.retries is not None:
116
opts.retries = parse_retries(opts.retries)
117
if getattr(opts, "file_access_retries", None) is not None:
118
opts.file_access_retries = parse_retries(opts.file_access_retries)
119
if opts.fragment_retries is not None:
120
opts.fragment_retries = parse_retries(opts.fragment_retries)
121
if getattr(opts, "extractor_retries", None) is not None:
122
opts.extractor_retries = parse_retries(opts.extractor_retries)
123
if opts.buffersize is not None:
124
opts.buffersize = parse_bytes(opts.buffersize)
125
if opts.http_chunk_size is not None:
126
opts.http_chunk_size = parse_bytes(opts.http_chunk_size)
127
if opts.extractaudio:
128
opts.audioformat = opts.audioformat.lower()
129
if opts.audioquality:
130
opts.audioquality = opts.audioquality.strip("kK")
131
if opts.recodevideo is not None:
132
opts.recodevideo = opts.recodevideo.replace(" ", "")
133
if getattr(opts, "remuxvideo", None) is not None:
134
opts.remuxvideo = opts.remuxvideo.replace(" ", "")
135
if getattr(opts, "wait_for_video", None) is not None:
136
min_wait, _, max_wait = opts.wait_for_video.partition("-")
137
opts.wait_for_video = (module.parse_duration(min_wait),
138
module.parse_duration(max_wait))
139
140
if opts.date is not None:
141
date = module.DateRange.day(opts.date)
142
else:
143
date = module.DateRange(opts.dateafter, opts.datebefore)
144
145
decodeOption = getattr(module, "decodeOption", util.identity)
146
compat_opts = getattr(opts, "compat_opts", ())
147
148
def _unused_compat_opt(name):
149
if name not in compat_opts:
150
return False
151
compat_opts.discard(name)
152
compat_opts.update([f"*{name}"])
153
return True
154
155
def set_default_compat(
156
compat_name, opt_name, default=True, remove_compat=True):
157
attr = getattr(opts, opt_name, None)
158
if compat_name in compat_opts:
159
if attr is None:
160
setattr(opts, opt_name, not default)
161
return True
162
else:
163
if remove_compat:
164
_unused_compat_opt(compat_name)
165
return False
166
elif attr is None:
167
setattr(opts, opt_name, default)
168
return None
169
170
set_default_compat("abort-on-error", "ignoreerrors", "only_download")
171
set_default_compat("no-playlist-metafiles", "allow_playlist_files")
172
set_default_compat("no-clean-infojson", "clean_infojson")
173
if "format-sort" in compat_opts:
174
opts.format_sort.extend(module.InfoExtractor.FormatSort.ytdl_default)
175
_video_multistreams_set = set_default_compat(
176
"multistreams", "allow_multiple_video_streams",
177
False, remove_compat=False)
178
_audio_multistreams_set = set_default_compat(
179
"multistreams", "allow_multiple_audio_streams",
180
False, remove_compat=False)
181
if _video_multistreams_set is False and _audio_multistreams_set is False:
182
_unused_compat_opt("multistreams")
183
184
if isinstance(opts.outtmpl, dict):
185
outtmpl = opts.outtmpl
186
outtmpl_default = outtmpl.get("default")
187
else:
188
opts.outtmpl = outtmpl = outtmpl_default = ""
189
190
if "filename" in compat_opts:
191
if outtmpl_default is None:
192
outtmpl_default = outtmpl["default"] = "%(title)s-%(id)s.%(ext)s"
193
else:
194
_unused_compat_opt("filename")
195
196
if opts.extractaudio and not opts.keepvideo and opts.format is None:
197
opts.format = "bestaudio/best"
198
199
if ytdlp:
200
def metadataparser_actions(f):
201
if isinstance(f, str):
202
yield module.MetadataFromFieldPP.to_action(f)
203
else:
204
REPLACE = module.MetadataParserPP.Actions.REPLACE
205
args = f[1:]
206
for x in f[0].split(","):
207
action = [REPLACE, x]
208
action += args
209
yield action
210
211
parse_metadata = getattr(opts, "parse_metadata", None)
212
if isinstance(parse_metadata, dict):
213
if opts.metafromtitle is not None:
214
if "pre_process" not in parse_metadata:
215
parse_metadata["pre_process"] = []
216
parse_metadata["pre_process"].append(
217
f"title:{opts.metafromtitle}")
218
opts.parse_metadata = {
219
k: list(itertools.chain.from_iterable(map(
220
metadataparser_actions, v)))
221
for k, v in parse_metadata.items()
222
}
223
else:
224
if parse_metadata is None:
225
parse_metadata = []
226
if opts.metafromtitle is not None:
227
parse_metadata.append(f"title:{opts.metafromtitle}")
228
opts.parse_metadata = list(itertools.chain.from_iterable(map(
229
metadataparser_actions, parse_metadata)))
230
231
opts.metafromtitle = None
232
else:
233
opts.parse_metadata = ()
234
235
download_archive_fn = module.expand_path(opts.download_archive) \
236
if opts.download_archive is not None else opts.download_archive
237
238
if getattr(opts, "getcomments", None):
239
opts.writeinfojson = True
240
241
if getattr(opts, "no_sponsorblock", None):
242
opts.sponsorblock_mark = set()
243
opts.sponsorblock_remove = set()
244
else:
245
opts.sponsorblock_mark = \
246
getattr(opts, "sponsorblock_mark", None) or set()
247
opts.sponsorblock_remove = \
248
getattr(opts, "sponsorblock_remove", None) or set()
249
opts.remove_chapters = getattr(opts, "remove_chapters", None) or ()
250
251
try:
252
postprocessors = list(module.get_postprocessors(opts))
253
except AttributeError:
254
postprocessors = legacy_postprocessors(
255
opts, module, ytdlp, compat_opts)
256
257
match_filter = (
258
None if opts.match_filter is None
259
else module.match_filter_func(opts.match_filter))
260
261
if cookiesfrombrowser := getattr(opts, "cookiesfrombrowser", None):
262
pattern = util.re(r"""(?x)
263
(?P<name>[^+:]+)
264
(?:\s*\+\s*(?P<keyring>[^:]+))?
265
(?:\s*:\s*(?!:)(?P<profile>.+?))?
266
(?:\s*::\s*(?P<container>.+))?""")
267
if match := pattern.fullmatch(cookiesfrombrowser):
268
browser, keyring, profile, container = match.groups()
269
if keyring is not None:
270
keyring = keyring.upper()
271
cookiesfrombrowser = (browser.lower(), profile, keyring, container)
272
else:
273
cookiesfrombrowser = None
274
275
return {
276
"usenetrc": opts.usenetrc,
277
"netrc_location": getattr(opts, "netrc_location", None),
278
"username": opts.username,
279
"password": opts.password,
280
"twofactor": opts.twofactor,
281
"videopassword": opts.videopassword,
282
"ap_mso": opts.ap_mso,
283
"ap_username": opts.ap_username,
284
"ap_password": opts.ap_password,
285
"quiet": opts.quiet,
286
"no_warnings": opts.no_warnings,
287
"forceurl": opts.geturl,
288
"forcetitle": opts.gettitle,
289
"forceid": opts.getid,
290
"forcethumbnail": opts.getthumbnail,
291
"forcedescription": opts.getdescription,
292
"forceduration": opts.getduration,
293
"forcefilename": opts.getfilename,
294
"forceformat": opts.getformat,
295
"forceprint": getattr(opts, "forceprint", None) or (),
296
"force_write_download_archive": getattr(
297
opts, "force_write_download_archive", None),
298
"simulate": opts.simulate,
299
"skip_download": opts.skip_download,
300
"format": opts.format,
301
"allow_unplayable_formats": getattr(
302
opts, "allow_unplayable_formats", None),
303
"ignore_no_formats_error": getattr(
304
opts, "ignore_no_formats_error", None),
305
"format_sort": getattr(
306
opts, "format_sort", None),
307
"format_sort_force": getattr(
308
opts, "format_sort_force", None),
309
"allow_multiple_video_streams": opts.allow_multiple_video_streams,
310
"allow_multiple_audio_streams": opts.allow_multiple_audio_streams,
311
"check_formats": getattr(
312
opts, "check_formats", None),
313
"outtmpl": opts.outtmpl,
314
"outtmpl_na_placeholder": opts.outtmpl_na_placeholder,
315
"paths": getattr(opts, "paths", None),
316
"autonumber_size": opts.autonumber_size,
317
"autonumber_start": opts.autonumber_start,
318
"restrictfilenames": opts.restrictfilenames,
319
"windowsfilenames": getattr(opts, "windowsfilenames", None),
320
"ignoreerrors": opts.ignoreerrors,
321
"force_generic_extractor": opts.force_generic_extractor,
322
"ratelimit": opts.ratelimit,
323
"throttledratelimit": getattr(opts, "throttledratelimit", None),
324
"overwrites": getattr(opts, "overwrites", None),
325
"retries": opts.retries,
326
"file_access_retries": getattr(opts, "file_access_retries", None),
327
"fragment_retries": opts.fragment_retries,
328
"extractor_retries": getattr(opts, "extractor_retries", None),
329
"skip_unavailable_fragments": opts.skip_unavailable_fragments,
330
"keep_fragments": opts.keep_fragments,
331
"concurrent_fragment_downloads": getattr(
332
opts, "concurrent_fragment_downloads", None),
333
"buffersize": opts.buffersize,
334
"noresizebuffer": opts.noresizebuffer,
335
"http_chunk_size": opts.http_chunk_size,
336
"continuedl": opts.continue_dl,
337
"noprogress": True if opts.noprogress is None else opts.noprogress,
338
"playliststart": opts.playliststart,
339
"playlistend": opts.playlistend,
340
"playlistreverse": opts.playlist_reverse,
341
"playlistrandom": opts.playlist_random,
342
"noplaylist": opts.noplaylist,
343
"logtostderr": outtmpl_default == "-",
344
"consoletitle": opts.consoletitle,
345
"nopart": opts.nopart,
346
"updatetime": opts.updatetime,
347
"writedescription": opts.writedescription,
348
"writeannotations": opts.writeannotations,
349
"writeinfojson": opts.writeinfojson,
350
"allow_playlist_files": opts.allow_playlist_files,
351
"clean_infojson": opts.clean_infojson,
352
"getcomments": getattr(opts, "getcomments", None),
353
"writethumbnail": opts.writethumbnail is True,
354
"write_all_thumbnails": getattr(opts, "write_all_thumbnails", None) or
355
opts.writethumbnail == "all",
356
"writelink": getattr(opts, "writelink", None),
357
"writeurllink": getattr(opts, "writeurllink", None),
358
"writewebloclink": getattr(opts, "writewebloclink", None),
359
"writedesktoplink": getattr(opts, "writedesktoplink", None),
360
"writesubtitles": opts.writesubtitles,
361
"writeautomaticsub": opts.writeautomaticsub,
362
"allsubtitles": opts.allsubtitles,
363
"subtitlesformat": opts.subtitlesformat,
364
"subtitleslangs": opts.subtitleslangs,
365
"matchtitle": decodeOption(opts.matchtitle),
366
"rejecttitle": decodeOption(opts.rejecttitle),
367
"max_downloads": opts.max_downloads,
368
"prefer_free_formats": opts.prefer_free_formats,
369
"trim_file_name": getattr(opts, "trim_file_name", None),
370
"verbose": opts.verbose,
371
"dump_intermediate_pages": opts.dump_intermediate_pages,
372
"write_pages": opts.write_pages,
373
"test": opts.test,
374
"keepvideo": opts.keepvideo,
375
"min_filesize": opts.min_filesize,
376
"max_filesize": opts.max_filesize,
377
"min_views": opts.min_views,
378
"max_views": opts.max_views,
379
"daterange": date,
380
"cachedir": opts.cachedir,
381
"youtube_print_sig_code": opts.youtube_print_sig_code,
382
"age_limit": opts.age_limit,
383
"download_archive": download_archive_fn,
384
"break_on_existing": getattr(opts, "break_on_existing", None),
385
"break_on_reject": getattr(opts, "break_on_reject", None),
386
"break_per_url": getattr(opts, "break_per_url", None),
387
"skip_playlist_after_errors": getattr(
388
opts, "skip_playlist_after_errors", None),
389
"cookiefile": opts.cookiefile,
390
"cookiesfrombrowser": cookiesfrombrowser,
391
"nocheckcertificate": opts.no_check_certificate,
392
"prefer_insecure": opts.prefer_insecure,
393
"proxy": opts.proxy,
394
"socket_timeout": opts.socket_timeout,
395
"bidi_workaround": opts.bidi_workaround,
396
"debug_printtraffic": opts.debug_printtraffic,
397
"prefer_ffmpeg": opts.prefer_ffmpeg,
398
"include_ads": opts.include_ads,
399
"default_search": opts.default_search,
400
"dynamic_mpd": getattr(opts, "dynamic_mpd", None),
401
"extractor_args": getattr(opts, "extractor_args", None),
402
"youtube_include_dash_manifest": getattr(
403
opts, "youtube_include_dash_manifest", None),
404
"youtube_include_hls_manifest": getattr(
405
opts, "youtube_include_hls_manifest", None),
406
"encoding": opts.encoding,
407
"extract_flat": opts.extract_flat,
408
"live_from_start": getattr(opts, "live_from_start", None),
409
"wait_for_video": getattr(opts, "wait_for_video", None),
410
"mark_watched": opts.mark_watched,
411
"merge_output_format": opts.merge_output_format,
412
"postprocessors": postprocessors,
413
"fixup": opts.fixup,
414
"source_address": opts.source_address,
415
"sleep_interval_requests": getattr(
416
opts, "sleep_interval_requests", None),
417
"sleep_interval": opts.sleep_interval,
418
"max_sleep_interval": opts.max_sleep_interval,
419
"sleep_interval_subtitles": getattr(
420
opts, "sleep_interval_subtitles", None),
421
"external_downloader": opts.external_downloader,
422
"playlist_items": opts.playlist_items,
423
"xattr_set_filesize": opts.xattr_set_filesize,
424
"match_filter": match_filter,
425
"no_color": getattr(opts, "no_color", None),
426
"ffmpeg_location": opts.ffmpeg_location,
427
"hls_prefer_native": opts.hls_prefer_native,
428
"hls_use_mpegts": opts.hls_use_mpegts,
429
"hls_split_discontinuity": getattr(
430
opts, "hls_split_discontinuity", None),
431
"external_downloader_args": opts.external_downloader_args,
432
"postprocessor_args": opts.postprocessor_args,
433
"cn_verification_proxy": opts.cn_verification_proxy,
434
"geo_verification_proxy": opts.geo_verification_proxy,
435
"geo_bypass": getattr(
436
opts, "geo_bypass", "default"),
437
"geo_bypass_country": getattr(
438
opts, "geo_bypass_country", None),
439
"geo_bypass_ip_block": getattr(
440
opts, "geo_bypass_ip_block", None),
441
"compat_opts": compat_opts,
442
}
443
444
445
def parse_retries(retries, name=""):
446
if retries in ("inf", "infinite"):
447
return float("inf")
448
return int(retries)
449
450
451
def legacy_postprocessors(opts, module, ytdlp, compat_opts):
452
postprocessors = []
453
454
sponsorblock_query = opts.sponsorblock_mark | opts.sponsorblock_remove
455
if opts.metafromtitle:
456
postprocessors.append({
457
"key": "MetadataFromTitle",
458
"titleformat": opts.metafromtitle,
459
})
460
if getattr(opts, "add_postprocessors", None):
461
postprocessors += list(opts.add_postprocessors)
462
if sponsorblock_query:
463
postprocessors.append({
464
"key": "SponsorBlock",
465
"categories": sponsorblock_query,
466
"api": opts.sponsorblock_api,
467
"when": "pre_process",
468
})
469
if opts.parse_metadata:
470
postprocessors.append({
471
"key": "MetadataParser",
472
"actions": opts.parse_metadata,
473
"when": "pre_process",
474
})
475
if opts.convertsubtitles:
476
pp = {"key": "FFmpegSubtitlesConvertor",
477
"format": opts.convertsubtitles}
478
if ytdlp:
479
pp["when"] = "before_dl"
480
postprocessors.append(pp)
481
if getattr(opts, "convertthumbnails", None):
482
postprocessors.append({
483
"key": "FFmpegThumbnailsConvertor",
484
"format": opts.convertthumbnails,
485
"when": "before_dl",
486
})
487
if getattr(opts, "exec_before_dl_cmd", None):
488
postprocessors.append({
489
"key": "Exec",
490
"exec_cmd": opts.exec_before_dl_cmd,
491
"when": "before_dl",
492
})
493
if opts.extractaudio:
494
postprocessors.append({
495
"key": "FFmpegExtractAudio",
496
"preferredcodec": opts.audioformat,
497
"preferredquality": opts.audioquality,
498
"nopostoverwrites": opts.nopostoverwrites,
499
})
500
if getattr(opts, "remuxvideo", None):
501
postprocessors.append({
502
"key": "FFmpegVideoRemuxer",
503
"preferedformat": opts.remuxvideo,
504
})
505
if opts.recodevideo:
506
postprocessors.append({
507
"key": "FFmpegVideoConvertor",
508
"preferedformat": opts.recodevideo,
509
})
510
if opts.embedsubtitles:
511
pp = {"key": "FFmpegEmbedSubtitle"}
512
if ytdlp:
513
pp["already_have_subtitle"] = (
514
opts.writesubtitles and "no-keep-subs" not in compat_opts)
515
postprocessors.append(pp)
516
if not opts.writeautomaticsub and "no-keep-subs" not in compat_opts:
517
opts.writesubtitles = True
518
if opts.allsubtitles and not opts.writeautomaticsub:
519
opts.writesubtitles = True
520
remove_chapters_patterns, remove_ranges = [], []
521
for regex in opts.remove_chapters:
522
if regex.startswith("*"):
523
dur = list(map(module.parse_duration, regex[1:].split("-")))
524
if len(dur) == 2 and all(t is not None for t in dur):
525
remove_ranges.append(tuple(dur))
526
continue
527
remove_chapters_patterns.append(util.re(regex))
528
if opts.remove_chapters or sponsorblock_query:
529
postprocessors.append({
530
"key": "ModifyChapters",
531
"remove_chapters_patterns": remove_chapters_patterns,
532
"remove_sponsor_segments": opts.sponsorblock_remove,
533
"remove_ranges": remove_ranges,
534
"sponsorblock_chapter_title": opts.sponsorblock_chapter_title,
535
"force_keyframes": opts.force_keyframes_at_cuts,
536
})
537
addchapters = getattr(opts, "addchapters", None)
538
embed_infojson = getattr(opts, "embed_infojson", None)
539
if opts.addmetadata or addchapters or embed_infojson:
540
pp = {"key": "FFmpegMetadata"}
541
if ytdlp:
542
if embed_infojson is None:
543
embed_infojson = "if_exists"
544
pp["add_metadata"] = opts.addmetadata
545
pp["add_chapters"] = addchapters
546
pp["add_infojson"] = embed_infojson
547
548
postprocessors.append(pp)
549
if getattr(opts, "sponskrub", False) is not False:
550
postprocessors.append({
551
"key": "SponSkrub",
552
"path": opts.sponskrub_path,
553
"args": opts.sponskrub_args,
554
"cut": opts.sponskrub_cut,
555
"force": opts.sponskrub_force,
556
"ignoreerror": opts.sponskrub is None,
557
"_from_cli": True,
558
})
559
if opts.embedthumbnail:
560
already_have_thumbnail = (opts.writethumbnail or
561
getattr(opts, "write_all_thumbnails", False))
562
postprocessors.append({
563
"key": "EmbedThumbnail",
564
"already_have_thumbnail": already_have_thumbnail,
565
})
566
if not already_have_thumbnail:
567
opts.writethumbnail = True
568
if isinstance(opts.outtmpl, dict):
569
opts.outtmpl["pl_thumbnail"] = ""
570
if getattr(opts, "split_chapters", None):
571
postprocessors.append({
572
"key": "FFmpegSplitChapters",
573
"force_keyframes": opts.force_keyframes_at_cuts,
574
})
575
if opts.xattrs:
576
postprocessors.append({"key": "XAttrMetadata"})
577
if opts.exec_cmd:
578
postprocessors.append({
579
"key": "Exec",
580
"exec_cmd": opts.exec_cmd,
581
"when": "after_move",
582
})
583
584
return postprocessors
585
586