Debian Codegraph @

gallery_dl/option.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2017-2026 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 """Command line option parsing"""
10
11 import argparse
12 import logging
13 import os.path
14 import sys
15 from . import job, util, version
16
17
18 class ConfigAction(argparse.Action):
19 """Set argparse results as config values"""
20 def __call__(self, parser, namespace, values, option_string=None):
21 namespace.options.append(((), self.dest, values))
22
23
24 class ConfigConstAction(argparse.Action):
25 """Set argparse const values as config values"""
26 def __call__(self, parser, namespace, values, option_string=None):
27 namespace.options.append(((), self.dest, self.const))
28
29
30 class AppendCommandAction(argparse.Action):
31 def __call__(self, parser, namespace, values, option_string=None):
32 items = getattr(namespace, self.dest, None) or []
33 val = self.const.copy()
34 val["command"] = values
35 items.append(val)
36 setattr(namespace, self.dest, items)
37
38
39 class DeprecatedConfigConstAction(argparse.Action):
40 """Set argparse const values as config values + deprecation warning"""
41 def __call__(self, parser, namespace, values, option_string=None):
42 sys.stderr.write(
43 f"Warning: {'/'.join(self.option_strings)} is deprecated. "
44 f"Use {self.choices} instead.\n")
45 namespace.options.append(((), self.dest, self.const))
46
47
48 class ConfigParseAction(argparse.Action):
49 """Parse KEY=VALUE config options"""
50 def __call__(self, parser, namespace, values, option_string=None):
51 key, value = _parse_option(values)
52 key = key.split(".") # splitting an empty string becomes [""]
53 namespace.options.append((key[:-1], key[-1], value))
54
55
56 class PPParseAction(argparse.Action):
57 """Parse KEY=VALUE post processor options"""
58 def __call__(self, parser, namespace, values, option_string=None):
59 key, value = _parse_option(values)
60 namespace.options_pp[key] = value
61
62
63 class InputfileAction(argparse.Action):
64 """Collect input files"""
65 def __call__(self, parser, namespace, value, option_string=None):
66 namespace.input_files.append((value, self.const))
67
68
69 class MtimeAction(argparse.Action):
70 """Configure mtime post processors"""
71 def __call__(self, parser, namespace, value, option_string=None):
72 namespace.postprocessors.append({
73 "name": "mtime",
74 "value": f"{{{self.const or value}}}",
75 })
76
77
78 class RenameAction(argparse.Action):
79 """Configure rename post processors"""
80 def __call__(self, parser, namespace, value, option_string=None):
81 if self.const:
82 namespace.postprocessors.append({
83 "name": "rename",
84 "to" : value,
85 })
86 else:
87 namespace.postprocessors.append({
88 "name": "rename",
89 "from": value,
90 })
91
92
93 class UgoiraAction(argparse.Action):
94 """Configure ugoira post processors"""
95 def __call__(self, parser, namespace, value, option_string=None):
96 value = self.const or value.strip().lower()
97
98 if value in {"webm", "vp9"}:
99 pp = {
100 "extension" : "webm",
101 "ffmpeg-args" : ("-c:v", "libvpx-vp9",
102 "-crf", "12",
103 "-b:v", "0",
104 "-pix_fmt", "yuv420p", "-an"),
105 }
106 elif value == "vp9-lossless":
107 pp = {
108 "extension" : "webm",
109 "ffmpeg-args" : ("-c:v", "libvpx-vp9",
110 "-lossless", "1",
111 "-pix_fmt", "yuv420p", "-an"),
112 }
113 elif value == "vp8":
114 pp = {
115 "extension" : "webm",
116 "ffmpeg-args" : ("-c:v", "libvpx",
117 "-crf", "4",
118 "-b:v", "5M",
119 "-pix_fmt", "yuv420p", "-an"),
120 }
121 elif value == "mp4":
122 pp = {
123 "extension" : "mp4",
124 "ffmpeg-args" : ("-c:v", "libx264",
125 "-b:v", "5M",
126 "-pix_fmt", "yuv420p", "-an"),
127 "libx264-prevent-odd": True,
128 }
129 elif value == "gif":
130 pp = {
131 "extension" : "gif",
132 "ffmpeg-args" : ("-filter_complex", "[0:v] split [a][b];"
133 "[a] palettegen [p];[b][p] paletteuse"),
134 "repeat-last-frame": False,
135 }
136 elif value in {"mkv", "copy"}:
137 pp = {
138 "extension" : "mkv",
139 "ffmpeg-args" : ("-c:v", "copy"),
140 "repeat-last-frame": False,
141 }
142 elif value in {"zip", "archive"}:
143 pp = {
144 "mode" : "archive",
145 }
146 else:
147 parser.error(f"Unsupported Ugoira format '{value}'")
148
149 pp["name"] = "ugoira"
150 pp["whitelist"] = ("pixiv", "danbooru")
151
152 namespace.options.append((("extractor",), "ugoira", "original"))
153 namespace.postprocessors.append(pp)
154
155
156 class PrintAction(argparse.Action):
157 def __call__(self, parser, namespace, value, option_string=None):
158 if self.const:
159 if self.const == "-":
160 namespace.options.append(((), "skip", False))
161 namespace.options.append(((), "download", False))
162 namespace.options.append((("output",), "mode", False))
163 filename = "-"
164 base = None
165 mode = "w"
166 else:
167 if self.const is None:
168 namespace.options.append(((), "skip", False))
169 namespace.options.append(((), "download", False))
170 value, path = value
171 base, filename = os.path.split(path)
172 mode = "a"
173
174 event, sep, format_string = value.partition(":")
175 if not sep:
176 format_string = event
177 event = ("prepare",)
178 else:
179 event = event.strip().lower()
180 if event not in {"init", "file", "after", "skip", "error",
181 "prepare", "prepare-after", "post", "post-after",
182 "finalize", "finalize-success", "finalize-error",
183 "child", "child-after"}:
184 format_string = value
185 event = ("prepare",)
186
187 if not format_string:
188 return
189
190 if format_string.startswith("\\f"):
191 format_string = "\f" + format_string[2:]
192
193 if format_string[0] == "\f":
194 if format_string[1] == "F" and format_string[-1] != "\n":
195 format_string += "\n"
196 elif "{" not in format_string and " " not in format_string:
197 format_string = f"{{{format_string}}}\n"
198 elif format_string[-1] != "\n":
199 format_string += "\n"
200
201 namespace.postprocessors.append({
202 "name" : "metadata",
203 "event" : event,
204 "filename" : filename,
205 "base-directory": base or ".",
206 "content-format": format_string,
207 "open" : mode,
208 })
209
210
211 class Formatter(argparse.HelpFormatter):
212 """Custom HelpFormatter class to customize help output"""
213 def __init__(self, prog):
214 argparse.HelpFormatter.__init__(self, prog, max_help_position=30)
215
216 def _format_action_invocation(self, action):
217 opts = action.option_strings
218 if action.metavar:
219 opts = opts.copy()
220 opts[-1] = f"{opts[-1]} {action.metavar}"
221 return ", ".join(opts)
222
223 def _format_usage(self, usage, actions, groups, prefix):
224 return f"Usage: {self._prog} [OPTIONS] URL [URL...]\n"
225
226
227 def _parse_option(opt):
228 key, _, value = opt.partition("=")
229 try:
230 value = util.json_loads(value)
231 except ValueError:
232 pass
233 return key, value
234
235
236 def build_parser():
237 """Build and configure an ArgumentParser object"""
238 SUPPRESS = argparse.SUPPRESS
239 parser = argparse.ArgumentParser(
240 formatter_class=Formatter,
241 add_help=False,
242 )
243
244 general = parser.add_argument_group("General Options")
245 general.add_argument(
246 "-h", "--help",
247 action="help",
248 help="Print this help message and exit",
249 )
250 general.add_argument(
251 "--version",
252 action="version", version=version.__version__,
253 help="Print program version and exit",
254 )
255 general.add_argument(
256 "-f", "--filename",
257 dest="filename", metavar="FORMAT",
258 help=("Filename format string for downloaded files "
259 "('/O' for \"original\" filenames)"),
260 )
261 general.add_argument(
262 "-d", "--destination",
263 dest="base-directory", metavar="PATH", action=ConfigAction,
264 help="Target location for file downloads",
265 )
266 general.add_argument(
267 "-D", "--directory",
268 dest="directory", metavar="PATH",
269 help="Exact location for file downloads",
270 )
271 general.add_argument(
272 "--restrict-filenames",
273 dest="path-restrict", metavar="VALUE", action=ConfigAction,
274 help=("Replace restricted filename characters with underscores. "
275 "One of 'windows', 'windows+', 'unix', 'ascii', 'ascii+', "
276 "or a custom set of characters"),
277 )
278 general.add_argument(
279 "--windows-filenames",
280 dest="path-restrict", nargs=0, action=ConfigConstAction,
281 const="windows",
282 help="Force filenames to be Windows-compatible",
283 )
284 general.add_argument(
285 "-X", "--extractors",
286 dest="extractor_sources", metavar="PATH", action="append",
287 help="Load external extractors from PATH",
288 )
289 general.add_argument(
290 "--compat",
291 dest="category-map", nargs=0, action=ConfigConstAction, const="compat",
292 help="Restore legacy 'category' names",
293 )
294 general.add_argument(
295 "-S", "--server",
296 dest="server", action="store_true",
297 help=("Enable server mode. "
298 "Send input URLs to a gallery-dl server or "
299 "create an IPC server when no input URLs are given"),
300 )
301
302 update = parser.add_argument_group("Update Options")
303 if util.EXECUTABLE:
304 update.add_argument(
305 "-U", "--update",
306 dest="update", action="store_const", const="latest",
307 help="Update to the latest version",
308 )
309 update.add_argument(
310 "--update-to",
311 dest="update", metavar="CHANNEL[@TAG]",
312 help=("Switch to a dfferent release channel (stable or dev) "
313 "or upgrade/downgrade to a specific version"),
314 )
315 update.add_argument(
316 "--update-check",
317 dest="update", action="store_const", const="check",
318 help="Check if a newer version is available",
319 )
320 else:
321 update.add_argument(
322 "-U", "--update-check",
323 dest="update", action="store_const", const="check",
324 help="Check if a newer version is available",
325 )
326
327 input = parser.add_argument_group("Input Options")
328 input.add_argument(
329 "urls",
330 metavar="URL", nargs="*",
331 help=SUPPRESS,
332 )
333 input.add_argument(
334 "-i", "--input-file",
335 dest="input_files", metavar="FILE", action=InputfileAction, const=None,
336 default=[],
337 help=("Download URLs found in FILE ('-' for stdin). "
338 "More than one --input-file can be specified"),
339 )
340 input.add_argument(
341 "-I", "--input-file-comment",
342 dest="input_files", metavar="FILE", action=InputfileAction, const="c",
343 help=("Download URLs found in FILE. "
344 "Comment them out after they were downloaded successfully."),
345 )
346 input.add_argument(
347 "-x", "--input-file-delete",
348 dest="input_files", metavar="FILE", action=InputfileAction, const="d",
349 help=("Download URLs found in FILE. "
350 "Delete them after they were downloaded successfully."),
351 )
352 input.add_argument(
353 "--no-input",
354 dest="input", nargs=0, action=ConfigConstAction, const=False,
355 help="Do not prompt for passwords/tokens",
356 )
357
358 output = parser.add_argument_group("Output Options")
359 output.add_argument(
360 "-q", "--quiet",
361 dest="loglevel", default=logging.INFO,
362 action="store_const", const=logging.ERROR,
363 help="Activate quiet mode",
364 )
365 output.add_argument(
366 "-w", "--warning",
367 dest="loglevel",
368 action="store_const", const=logging.WARNING,
369 help="Print only warnings and errors",
370 )
371 output.add_argument(
372 "-v", "--verbose",
373 dest="loglevel",
374 action="store_const", const=logging.DEBUG,
375 help="Print various debugging information",
376 )
377 output.add_argument(
378 "-g", "--get-urls",
379 dest="list_urls", action="count",
380 help="Print URLs instead of downloading",
381 )
382 output.add_argument(
383 "-G", "--resolve-urls",
384 dest="list_urls", action="store_const", const=128,
385 help="Print URLs instead of downloading; resolve intermediary URLs",
386 )
387 output.add_argument(
388 "-j", "--dump-json",
389 dest="dump_json", action="count",
390 help="Print JSON information",
391 )
392 output.add_argument(
393 "-J", "--resolve-json",
394 dest="dump_json", action="store_const", const=128,
395 help="Print JSON information; resolve intermediary URLs",
396 )
397 output.add_argument(
398 "-s", "--simulate",
399 dest="jobtype", action="store_const", const=job.SimulationJob,
400 help="Simulate data extraction; do not download anything",
401 )
402 output.add_argument(
403 "-E", "--extractor-info",
404 dest="jobtype", action="store_const", const=job.InfoJob,
405 help="Print extractor defaults and settings",
406 )
407 output.add_argument(
408 "-K", "--list-keywords",
409 dest="jobtype", action="store_const", const=job.KeywordJob,
410 help=("Print a list of available keywords and example values "
411 "for the given URLs"),
412 )
413 output.add_argument(
414 "-e", "--error-file",
415 dest="errorfile", metavar="FILE", action=ConfigAction,
416 help="Add input URLs which returned an error to FILE",
417 )
418 output.add_argument(
419 "-N", "--print",
420 dest="postprocessors", metavar="[EVENT:]FORMAT",
421 action=PrintAction, const="-", default=[],
422 help=("Write FORMAT during EVENT (default 'prepare') to standard "
423 "output instead of downloading files. "
424 "Can be used multiple times. "
425 "Examples: 'id' or 'post:{md5[:8]}'"),
426 )
427 output.add_argument(
428 "--Print",
429 dest="postprocessors", metavar="[EVENT:]FORMAT",
430 action=PrintAction, const="+",
431 help="Like --print, but downloads files as well",
432 )
433 output.add_argument(
434 "--print-to-file",
435 dest="postprocessors", metavar="[EVENT:]FORMAT FILE",
436 action=PrintAction, const=None, nargs=2,
437 help=("Append FORMAT during EVENT to FILE instead of downloading "
438 "files. Can be used multiple times"),
439 )
440 output.add_argument(
441 "--Print-to-file",
442 dest="postprocessors", metavar="[EVENT:]FORMAT FILE",
443 action=PrintAction, const=False, nargs=2,
444 help="Like --print-to-file, but downloads files as well",
445 )
446 output.add_argument(
447 "--list-modules",
448 dest="list_modules", action="store_true",
449 help="Print a list of available extractor modules",
450 )
451 output.add_argument(
452 "--list-extractors",
453 dest="list_extractors", metavar="[CATEGORIES]", nargs="*",
454 help=("Print a list of extractor classes "
455 "with description, (sub)category and example URL"),
456 )
457 output.add_argument(
458 "--write-log",
459 dest="logfile", metavar="FILE", action=ConfigAction,
460 help="Write logging output to FILE",
461 )
462 output.add_argument(
463 "--write-unsupported",
464 dest="unsupportedfile", metavar="FILE", action=ConfigAction,
465 help=("Write URLs, which get emitted by other extractors but cannot "
466 "be handled, to FILE"),
467 )
468 output.add_argument(
469 "--write-pages",
470 dest="write-pages", nargs=0, action=ConfigConstAction, const=True,
471 help=("Write downloaded intermediary pages to files "
472 "in the current directory to debug problems"),
473 )
474 output.add_argument(
475 "--print-traffic",
476 dest="print_traffic", action="store_true",
477 help="Display sent and read HTTP traffic",
478 )
479 output.add_argument(
480 "--no-colors",
481 dest="colors", action="store_false",
482 help="Do not emit ANSI color codes in output",
483 )
484
485 networking = parser.add_argument_group("Networking Options")
486 networking.add_argument(
487 "-R", "--retries",
488 dest="retries", metavar="N", type=int, action=ConfigAction,
489 help=("Maximum number of retries for failed HTTP requests "
490 "or -1 for infinite retries (default: 4)"),
491 )
492 networking.add_argument(
493 "-a", "--user-agent",
494 dest="user-agent", metavar="UA", action=ConfigAction,
495 help="User-Agent request header",
496 )
497 networking.add_argument(
498 "--http-timeout",
499 dest="timeout", metavar="SECONDS", type=float, action=ConfigAction,
500 help="Timeout for HTTP connections (default: 30.0)",
501 )
502 networking.add_argument(
503 "--proxy",
504 dest="proxy", metavar="URL", action=ConfigAction,
505 help="Use the specified proxy",
506 )
507 networking.add_argument(
508 "--xff",
509 dest="geo-bypass", metavar="VALUE", action=ConfigAction,
510 help=("Use a fake 'X-Forwarded-For' HTTP header to try bypassing "
511 "geographic restrictions. Can be IP blocks in CIDR notation "
512 "or two-letter ISO 3166-2 country codes (12.0.0.0/8,FR,CN)")
513 )
514 networking.add_argument(
515 "--source-address",
516 dest="source-address", metavar="IP", action=ConfigAction,
517 help="Client-side IP address to bind to",
518 )
519 networking.add_argument(
520 "-4", "--force-ipv4",
521 dest="source-address", nargs=0, action=ConfigConstAction,
522 const="0.0.0.0",
523 help="Make all connections via IPv4",
524 )
525 networking.add_argument(
526 "-6", "--force-ipv6",
527 dest="source-address", nargs=0, action=ConfigConstAction, const="::",
528 help="Make all connections via IPv6",
529 )
530 networking.add_argument(
531 "--no-check-certificate",
532 dest="verify", nargs=0, action=ConfigConstAction, const=False,
533 help="Disable HTTPS certificate validation",
534 )
535
536 downloader = parser.add_argument_group("Downloader Options")
537 downloader.add_argument(
538 "-r", "--limit-rate",
539 dest="rate", metavar="RATE", action=ConfigAction,
540 help="Maximum download rate (e.g. 500k, 2.5M, or 800k-2M)",
541 )
542 downloader.add_argument(
543 "--chunk-size",
544 dest="chunk-size", metavar="SIZE", action=ConfigAction,
545 help="Size of in-memory data chunks (default: 32k)",
546 )
547 downloader.add_argument(
548 "--no-part",
549 dest="part", nargs=0, action=ConfigConstAction, const=False,
550 help="Do not use .part files",
551 )
552 downloader.add_argument(
553 "--no-skip",
554 dest="skip", nargs=0, action=ConfigConstAction, const=False,
555 help="Do not skip downloads; overwrite existing files",
556 )
557 downloader.add_argument(
558 "--no-mtime",
559 dest="mtime", nargs=0, action=ConfigConstAction, const=False,
560 help=("Do not set file modification times according to "
561 "Last-Modified HTTP response headers")
562 )
563 downloader.add_argument(
564 "--no-download",
565 dest="download", nargs=0, action=ConfigConstAction, const=False,
566 help=("Do not download any files")
567 )
568
569 sleep = parser.add_argument_group("Sleep Options")
570 sleep.add_argument(
571 "--sleep",
572 dest="sleep", metavar="SECONDS", action=ConfigAction,
573 help=("Number of seconds to wait before each download. "
574 "This can be either a constant value or a range "
575 "(e.g. 2.7 or 2.0-3.5)"),
576 )
577 sleep.add_argument(
578 "--sleep-skip",
579 dest="sleep-skip", metavar="SECONDS", action=ConfigAction,
580 help=("Number of seconds to wait after skipping a file download"),
581 )
582 sleep.add_argument(
583 "--sleep-extractor",
584 dest="sleep-extractor", metavar="SECONDS", action=ConfigAction,
585 help=("Number of seconds to wait before starting data extraction "
586 "for an input URL"),
587 )
588 sleep.add_argument(
589 "--sleep-request",
590 dest="sleep-request", metavar="SECONDS", action=ConfigAction,
591 help=("Number of seconds to wait between HTTP requests "
592 "during data extraction"),
593 )
594 sleep.add_argument(
595 "--sleep-retries",
596 dest="sleep-retries", metavar="[TYPE=]SECONDS", action=ConfigAction,
597 help=("Number of seconds to wait before retrying an HTTP request. "
598 "Can be prefixed with "
599 "'lin[:START[:MAX]]' or 'exp[:BASE[:START[:MAX]]]' "
600 "for linear or exponential growth between consecutive retries "
601 "(e.g. '30', 'exp=40', 'lin:20=30-60'"),
602 )
603 sleep.add_argument(
604 "--sleep-429",
605 dest="sleep-429", metavar="[TYPE=]SECONDS", action=ConfigAction,
606 help=("Number of seconds to wait when receiving a "
607 "'429 Too Many Requests' response"),
608 )
609
610 configuration = parser.add_argument_group("Configuration Options")
611 configuration.add_argument(
612 "-o", "--option",
613 dest="options", metavar="KEY=VALUE",
614 action=ConfigParseAction, default=[],
615 help=("Additional options. "
616 "Example: -o browser=firefox") ,
617 )
618 configuration.add_argument(
619 "-c", "--config",
620 dest="configs_extra", metavar="FILE", action="append",
621 help="Additional configuration files in default format",
622 )
623 configuration.add_argument(
624 "--config-json",
625 dest="configs_json", metavar="FILE", action="append",
626 help="Additional configuration files in JSON format",
627 )
628 configuration.add_argument(
629 "--config-yaml",
630 dest="configs_yaml", metavar="FILE", action="append",
631 help="Additional configuration files in YAML format",
632 )
633 configuration.add_argument(
634 "--config-toml",
635 dest="configs_toml", metavar="FILE", action="append",
636 help="Additional configuration files in TOML format",
637 )
638 configuration.add_argument(
639 "--config-type",
640 dest="config_type", metavar="TYPE",
641 help=("Set filetype of default configuration files "
642 "(json, yaml, toml)"),
643 )
644 configuration.add_argument(
645 "--config-ignore",
646 dest="config_load", action="store_false",
647 help="Do not load default configuration files",
648 )
649 configuration.add_argument(
650 "--ignore-config",
651 dest="config_load", action="store_false",
652 help=SUPPRESS,
653 )
654 configuration.add_argument(
655 "--config-create",
656 dest="config", action="store_const", const="init",
657 help="Create a basic configuration file",
658 )
659 configuration.add_argument(
660 "--config-status",
661 dest="config", action="store_const", const="status",
662 help="Show configuration file status",
663 )
664 configuration.add_argument(
665 "--config-open",
666 dest="config", action="store_const", const="open",
667 help="Open configuration file in external application",
668 )
669
670 cache = parser.add_argument_group("Cache Options")
671 cache.add_argument(
672 "--cache-file",
673 dest="cache_file", metavar="PATH",
674 help="Use PATH as cache file",
675 )
676 cache.add_argument(
677 "--cache-status",
678 dest="cache_status", action="store_true",
679 help="Show cache file information",
680 )
681 cache.add_argument(
682 "--cache-show",
683 dest="cache_show", metavar="MODULE",
684 help="Show cached values for MODULE (ALL to show all entries, EXP to "
685 "show only expired entries, VAL to show only valid entries)",
686 )
687 cache.add_argument(
688 "--cache-clear",
689 dest="cache_clear", metavar="MODULE",
690 help="Delete cached login sessions, cookies, etc. for MODULE "
691 "(ALL to delete everything, EXP to delete only expired values)",
692 )
693 cache.add_argument(
694 "--cache-vacuum",
695 dest="cache_vacuum", action="store_const", const="vacuum",
696 help="Clean up the cache database by removing unused space and "
697 "reorganizing the data to improve performance",
698 )
699 cache.add_argument(
700 "--clear-cache", dest="cache_clear", help=SUPPRESS)
701
702 authentication = parser.add_argument_group("Authentication Options")
703 authentication.add_argument(
704 "-u", "--username",
705 dest="username", metavar="USER", action=ConfigAction,
706 help="Username to login with",
707 )
708 authentication.add_argument(
709 "-p", "--password",
710 dest="password", metavar="PASS", action=ConfigAction,
711 help="Password belonging to the given username",
712 )
713 authentication.add_argument(
714 "--netrc",
715 dest="netrc", nargs=0, action=ConfigConstAction, const=True,
716 help="Enable .netrc authentication data",
717 )
718
719 cookies = parser.add_argument_group("Cookie Options")
720 cookies.add_argument(
721 "-C", "--cookies",
722 dest="cookies", metavar="FILE", action=ConfigAction,
723 help="File to load additional cookies from",
724 )
725 cookies.add_argument(
726 "--cookies-export",
727 dest="cookies-update", metavar="FILE", action=ConfigAction,
728 help="Export session cookies to FILE",
729 )
730 cookies.add_argument(
731 "--cookies-from-browser",
732 dest="cookies_from_browser",
733 metavar="BROWSER[/DOMAIN][+KEYRING][:PROFILE][::CONTAINER]",
734 help=("Name of the browser to load cookies from, with optional "
735 "domain prefixed with '/', "
736 "keyring name prefixed with '+', "
737 "profile prefixed with ':', and "
738 "container prefixed with '::' "
739 "('none' for no container (default), 'all' for all containers)"),
740 )
741
742 selection = parser.add_argument_group("Selection Options")
743 selection.add_argument(
744 "-A", "--abort",
745 dest="abort", metavar="N[:TARGET]",
746 help=("Stop current extractor(s) "
747 "after N consecutive file downloads were skipped. "
748 "Specify a TARGET to set how many levels to ascend or "
749 "to which subcategory to jump to. "
750 "Examples: '-A 3', '-A 3:2', '-A 3:manga'"),
751 )
752 selection.add_argument(
753 "-T", "--terminate",
754 dest="terminate", metavar="N",
755 help=("Stop current & parent extractors "
756 "and proceed with the next input URL "
757 "after N consecutive file downloads were skipped"),
758 )
759 selection.add_argument(
760 "--filesize-min",
761 dest="filesize-min", metavar="SIZE", action=ConfigAction,
762 help="Do not download files smaller than SIZE (e.g. 500k or 2.5M)",
763 )
764 selection.add_argument(
765 "--filesize-max",
766 dest="filesize-max", metavar="SIZE", action=ConfigAction,
767 help="Do not download files larger than SIZE (e.g. 500k or 2.5M)",
768 )
769 selection.add_argument(
770 "--download-archive",
771 dest="archive", metavar="FILE", action=ConfigAction,
772 help=("Record successfully downloaded files in FILE and "
773 "skip downloading any file already in it"),
774 )
775 selection.add_argument(
776 "--date-before",
777 dest="date-before", metavar="DATE", action=ConfigAction,
778 help=("Process only posts created before this date given in "
779 "ISO 8601 format or as Unix timestamp (e.g. '2025-10-31', "
780 "'2026-01-09T15:30:00', '1767972600')")
781 )
782 selection.add_argument(
783 "--date-after",
784 dest="date-after", metavar="DATE", action=ConfigAction,
785 help=("Process only posts created after this date. "
786 "Stop extraction when an older post is encountered")
787 )
788 selection.add_argument(
789 "--blacklist",
790 dest="blacklist", metavar="CATEGORIES", action=ConfigAction,
791 help=("Ignore the given comma-separated category names or "
792 "category:subcategory pairs when spawning child extractors for "
793 "external URLs (e.g. 'pixiv', 'pixiv:user,*:artist')"),
794 )
795 selection.add_argument(
796 "--whitelist",
797 dest="whitelist", metavar="CATEGORIES", action=ConfigAction,
798 help=("Allow only the given comma-separated category names or "
799 "category:subcategory pairs to allow when spawning child "
800 "extractors for external URLs"),
801 )
802 selection.add_argument(
803 "--tags-blacklist",
804 dest="tags-blacklist", metavar="TAGS", action=ConfigAction,
805 help=("Ignore posts tagged with any of the tags given as comma-"
806 "separated list or path to a file containing them. "
807 "Danbooru blacklist rules are supported. Can be '/import' to "
808 "use your account's blacklist. "
809 r"(e.g. '1girl', 'shirt,highres -blush,smile', "
810 r"'C:\path\to\list.txt')"),
811 )
812 selection.add_argument(
813 "--tags-whitelist",
814 dest="tags-whitelist", metavar="TAGS", action=ConfigAction,
815 help=("Allow only posts tagged with at least one of the tags given as "
816 "comma-separated list or path to a file containing them"),
817 )
818 selection.add_argument(
819 "--range",
820 dest="file-range", metavar="RANGE", action=ConfigAction,
821 help=("Index range(s) specifying which files to download. "
822 "These can be either a constant value, range, or slice "
823 "(e.g. '5', '8-20', or '1:24:3')"),
824 )
825 selection.add_argument(
826 "--post-range",
827 dest="post-range", metavar="RANGE", action=ConfigAction,
828 help=("Like '--range', but for posts"),
829 )
830 selection.add_argument(
831 "--child-range",
832 dest="child-range", metavar="RANGE", action=ConfigAction,
833 help=("Like '--range', but for child extractors handling "
834 "manga chapters, external URLs, etc."),
835 )
836 selection.add_argument(
837 "--filter",
838 dest="file-filter", metavar="EXPR", action=ConfigAction,
839 help=("Python expression controlling which files to download. "
840 "Files for which the expression evaluates to False are ignored. "
841 "Available keys are the filename-specific ones listed by '-K'. "
842 "Example: --filter \"image_width >= 1000 and "
843 "rating in ('s', 'q')\""),
844 )
845 selection.add_argument(
846 "--post-filter",
847 dest="post-filter", metavar="EXPR", action=ConfigAction,
848 help=("Like '--filter', but for posts"),
849 )
850 selection.add_argument(
851 "--child-filter",
852 dest="child-filter", metavar="EXPR", action=ConfigAction,
853 help=("Like '--filter', but for child extractors handling "
854 "manga chapters, external URLs, etc."),
855 )
856 selection.add_argument(
857 "--file-range", "--image-range",
858 dest="file-range", action=ConfigAction, help=SUPPRESS)
859 selection.add_argument(
860 "--chapter-range",
861 dest="child-range", action=ConfigAction, help=SUPPRESS)
862 selection.add_argument(
863 "--file-filter", "--image-filter",
864 dest="file-filter", action=ConfigAction, help=SUPPRESS)
865 selection.add_argument(
866 "--chapter-filter",
867 dest="child-filter", action=ConfigAction, help=SUPPRESS)
868
869 infojson = {
870 "name" : "metadata",
871 "event" : "init",
872 "filename": "info.json",
873 }
874 postprocessor = parser.add_argument_group("Post-processing Options")
875 postprocessor.add_argument(
876 "-P", "--postprocessor",
877 dest="postprocessors", metavar="NAME", action="append",
878 help="Activate the specified post processor",
879 )
880 postprocessor.add_argument(
881 "--no-postprocessors",
882 dest="postprocess", nargs=0, action=ConfigConstAction, const=False,
883 help=("Do not run any post processors")
884 )
885 postprocessor.add_argument(
886 "-O", "--postprocessor-option",
887 dest="options_pp", metavar="KEY=VALUE",
888 action=PPParseAction, default={},
889 help="Additional post processor options",
890 )
891 postprocessor.add_argument(
892 "--write-metadata",
893 dest="postprocessors",
894 action="append_const", const="metadata",
895 help="Write metadata to separate JSON files",
896 )
897 postprocessor.add_argument(
898 "--write-info-json",
899 dest="postprocessors",
900 action="append_const", const=infojson,
901 help="Write gallery metadata to a info.json file",
902 )
903 postprocessor.add_argument(
904 "--write-infojson",
905 dest="postprocessors",
906 action="append_const", const=infojson,
907 help=SUPPRESS,
908 )
909 postprocessor.add_argument(
910 "--write-tags",
911 dest="postprocessors",
912 action="append_const", const={"name": "metadata", "mode": "tags"},
913 help="Write image tags to separate text files",
914 )
915 postprocessor.add_argument(
916 "--zip",
917 dest="postprocessors",
918 action="append_const", const="zip",
919 help="Store downloaded files in a ZIP archive",
920 )
921 postprocessor.add_argument(
922 "--cbz",
923 dest="postprocessors",
924 action="append_const", const={
925 "name" : "zip",
926 "extension": "cbz",
927 },
928 help="Store downloaded files in a CBZ archive",
929 )
930 postprocessor.add_argument(
931 "--mtime",
932 dest="postprocessors", metavar="NAME", action=MtimeAction,
933 help=("Set file modification times according to metadata "
934 "selected by NAME. Examples: 'date' or 'status[date]'"),
935 )
936 postprocessor.add_argument(
937 "--mtime-from-date",
938 dest="postprocessors", nargs=0, action=MtimeAction,
939 const="date|status[date]",
940 help=SUPPRESS,
941 )
942 postprocessor.add_argument(
943 "--rename",
944 dest="postprocessors", metavar="FORMAT", action=RenameAction, const=0,
945 help=("Rename previously downloaded files from FORMAT "
946 "to the current filename format"),
947 )
948 postprocessor.add_argument(
949 "--rename-to",
950 dest="postprocessors", metavar="FORMAT", action=RenameAction, const=1,
951 help=("Rename previously downloaded files from the current filename "
952 "format to FORMAT"),
953 )
954 postprocessor.add_argument(
955 "--ugoira",
956 dest="postprocessors", metavar="FMT", action=UgoiraAction,
957 help=("Convert Pixiv Ugoira to FMT using FFmpeg. "
958 "Supported formats are 'webm', 'mp4', 'gif', "
959 "'vp8', 'vp9', 'vp9-lossless', 'copy', 'zip'."),
960 )
961 postprocessor.add_argument(
962 "--ugoira-conv",
963 dest="postprocessors", nargs=0, action=UgoiraAction, const="vp8",
964 help=SUPPRESS,
965 )
966 postprocessor.add_argument(
967 "--ugoira-conv-lossless",
968 dest="postprocessors", nargs=0, action=UgoiraAction,
969 const="vp9-lossless",
970 help=SUPPRESS,
971 )
972 postprocessor.add_argument(
973 "--ugoira-conv-copy",
974 dest="postprocessors", nargs=0, action=UgoiraAction, const="copy",
975 help=SUPPRESS,
976 )
977 postprocessor.add_argument(
978 "--exec",
979 dest="postprocessors", metavar="CMD",
980 action=AppendCommandAction, const={"name": "exec"},
981 help=("Execute CMD for each downloaded file. "
982 "Supported replacement fields are "
983 "{} or {_path}, {_temppath}, {_directory}, {_filename}. "
984 "On Windows, use {_path_unc} or {_directory_unc} for UNC paths. "
985 "Example: --exec \"convert {} {}.png && rm {}\""),
986 )
987 postprocessor.add_argument(
988 "--exec-after",
989 dest="postprocessors", metavar="CMD",
990 action=AppendCommandAction, const={
991 "name": "exec", "event": "finalize"},
992 help=("Execute CMD after all files were downloaded. "
993 "Example: --exec-after \"cd {_directory} "
994 "&& convert * ../doc.pdf\""),
995 )
996
997 try:
998 # restore normal behavior when adding '-4' or '-6' as arguments
999 parser._has_negative_number_optionals.clear()
1000 except Exception:
1001 pass
1002
1003 return parser