Debian Codegraph @

gallery_dl/postprocessor/python.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2023-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 """Run Python functions"""
10
11 from .common import PostProcessor
12 from .. import util, formatter
13
14
15 class PythonPP(PostProcessor):
16
17 def __init__(self, job, options):
18 PostProcessor.__init__(self, job)
19
20 mode = options.get("mode")
21 if mode == "eval" or not mode and options.get("expression"):
22 self.function = util.compile_expression(options["expression"])
23 else:
24 spec = options["function"]
25 module_name, _, function_name = spec.rpartition(":")
26 module = util.import_file(module_name)
27 self.function = getattr(module, function_name)
28
29 args = options.get("args")
30 kwargs = options.get("kwargs")
31 if args or kwargs:
32 self._func = self.function
33 self.function = self._call_with_args
34
35 if args:
36 self.args = [formatter.parse(arg).format_map
37 for arg in args]
38 else:
39 self.args = ()
40
41 if kwargs:
42 if isinstance(kwargs, dict):
43 kwargs = kwargs.items()
44 self.kwargs = [(name, formatter.parse(arg).format_map)
45 for name, arg in kwargs]
46 else:
47 self.kwargs = ()
48
49 if archive := self._archive_init(job, options):
50 self.run = self.run_archive
51
52 events = options.get("event")
53 if events is None:
54 events = ("file",)
55 elif isinstance(events, str):
56 events = events.split(",")
57 job.register_hooks({event: self.run for event in events}, options)
58
59 if archive:
60 self._archive_register(job)
61
62 def run(self, pathfmt):
63 self.function(pathfmt.kwdict)
64
65 def run_archive(self, pathfmt):
66 kwdict = pathfmt.kwdict
67 if self.archive.check(kwdict):
68 return
69 self.function(kwdict)
70 self.archive.add(kwdict)
71
72 def _call_with_args(self, kwdict):
73 return self._func(
74 kwdict,
75 *[arg(kwdict) for arg in self.args],
76 **{name: arg(kwdict) for name, arg in self.kwargs})
77
78
79 __postprocessor__ = PythonPP