| 1 |
|
| 2 |
|
| 3 |
n |
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
"""Write metadata to external files""" |
| 10 |
|
| 11 |
from .common import PostProcessor |
| 12 |
from .. import util, formatter |
| 13 |
import json |
| 14 |
import sys |
| 15 |
import os |
| 16 |
|
| 17 |
|
| 18 |
class MetadataPP(PostProcessor): |
| 19 |
|
| 20 |
def __init__(self, job, options): |
| 21 |
PostProcessor.__init__(self, job) |
| 22 |
|
| 23 |
mode = options.get("mode") |
| 24 |
cfmt = options.get("content-format") or options.get("format") |
| 25 |
omode = "w" |
| 26 |
filename = None |
| 27 |
|
| 28 |
if mode == "tags": |
| 29 |
self.write = self._write_tags |
| 30 |
ext = "txt" |
| 31 |
elif mode == "modify": |
| 32 |
self.run = self._run_modify |
| 33 |
self.fields = { |
| 34 |
name: formatter.parse(value, None, util.identity).format_map |
| 35 |
for name, value in options.get("fields").items() |
| 36 |
} |
| 37 |
ext = None |
| 38 |
elif mode == "delete": |
| 39 |
self.run = self._run_delete |
| 40 |
self.fields = options.get("fields") |
| 41 |
ext = None |
| 42 |
elif mode == "custom" or not mode and cfmt: |
| 43 |
self.write = self._write_custom |
| 44 |
if isinstance(cfmt, list): |
| 45 |
cfmt = "\n".join(cfmt) + "\n" |
| 46 |
self._content_fmt = formatter.parse(cfmt).format_map |
| 47 |
ext = "txt" |
| 48 |
elif mode == "print": |
| 49 |
nl = "\n" |
| 50 |
if isinstance(cfmt, list): |
| 51 |
cfmt = f"{nl.join(cfmt)}{nl}" |
| 52 |
if cfmt[-1] != nl and (cfmt[0] != "\f" or cfmt[1] == "F"): |
| 53 |
cfmt = f"{cfmt}{nl}" |
| 54 |
self.write = self._write_custom |
| 55 |
self._content_fmt = formatter.parse(cfmt).format_map |
| 56 |
filename = "-" |
| 57 |
elif mode == "jsonl": |
| 58 |
self.write = self._write_json |
| 59 |
self._json_encode = self._make_encoder(options).encode |
| 60 |
omode = "a" |
| 61 |
filename = "data.jsonl" |
| 62 |
else: |
| 63 |
self.write = self._write_json |
| 64 |
self._json_encode = self._make_encoder(options, 4).encode |
| 65 |
ext = "json" |
| 66 |
|
| 67 |
if base_directory := options.get("base-directory"): |
| 68 |
if base_directory is True: |
| 69 |
self._base = lambda p: p.basedirectory |
| 70 |
else: |
| 71 |
sep = os.sep |
| 72 |
altsep = os.altsep |
| 73 |
base_directory = util.expand_path(base_directory) |
| 74 |
if altsep and altsep in base_directory: |
| 75 |
base_directory = base_directory.replace(altsep, sep) |
| 76 |
if base_directory[-1] != sep: |
| 77 |
base_directory += sep |
| 78 |
self._base = lambda p: base_directory |
| 79 |
|
| 80 |
directory = options.get("directory") |
| 81 |
if isinstance(directory, list): |
| 82 |
self._directory = self._directory_format |
| 83 |
self._directory_formatters = [ |
| 84 |
formatter.parse(dirfmt, util.NONE).format_map |
| 85 |
for dirfmt in directory |
| 86 |
] |
| 87 |
elif directory: |
| 88 |
self._directory = self._directory_custom |
| 89 |
sep = os.sep + (os.altsep or "") |
| 90 |
self._metadir = util.expand_path(directory).rstrip(sep) + os.sep |
| 91 |
|
| 92 |
filename = options.get("filename", filename) |
| 93 |
extfmt = options.get("extension-format") |
| 94 |
if filename: |
| 95 |
if filename == "-": |
| 96 |
self.run = self._run_stdout |
| 97 |
else: |
| 98 |
self._filename = self._filename_custom |
| 99 |
self._filename_fmt = formatter.parse(filename).format_map |
| 100 |
elif extfmt: |
| 101 |
self._filename = self._filename_extfmt |
| 102 |
self._extension_fmt = formatter.parse(extfmt).format_map |
| 103 |
else: |
| 104 |
self.extension = options.get("extension", ext) |
| 105 |
|
| 106 |
events = options.get("event") |
| 107 |
if events is None: |
| 108 |
events = ("file",) |
| 109 |
elif isinstance(events, str): |
| 110 |
events = events.split(",") |
| 111 |
job.register_hooks({event: self.run for event in events}, options) |
| 112 |
|
| 113 |
if self._archive_init(job, options, "_MD_"): |
| 114 |
self._archive_register(job) |
| 115 |
|
| 116 |
self.filter = self._make_filter(options) |
| 117 |
self.empty = options.get("empty", False) |
| 118 |
self.mtime = options.get("mtime", False) |
| 119 |
self.omode = options.get("open", omode) |
| 120 |
self.encoding = options.get("encoding", "utf-8") |
| 121 |
self.newline = options.get("newline") |
| 122 |
self.skip = options.get("skip", False) |
| 123 |
self.meta_path = options.get("metadata-path") |
| 124 |
|
| 125 |
def open(self, path): |
| 126 |
return open(path, self.omode, |
| 127 |
encoding=self.encoding, |
| 128 |
newline=self.newline) |
| 129 |
|
| 130 |
def run(self, pathfmt): |
| 131 |
archive = self.archive |
| 132 |
if archive and archive.check(pathfmt.kwdict): |
| 133 |
return |
| 134 |
|
| 135 |
if util.WINDOWS and pathfmt.extended: |
| 136 |
directory = pathfmt._extended_path(self._directory(pathfmt)) |
| 137 |
else: |
| 138 |
directory = self._directory(pathfmt) |
| 139 |
path = directory + self._filename(pathfmt) |
| 140 |
|
| 141 |
if self.meta_path is not None: |
| 142 |
pathfmt.kwdict[self.meta_path] = path |
| 143 |
|
| 144 |
if self.skip and os.path.exists(path): |
| 145 |
return |
| 146 |
|
| 147 |
content = self.write(pathfmt.kwdict) |
| 148 |
if content or self.empty: |
| 149 |
try: |
| 150 |
with self.open(path) as fp: |
| 151 |
fp.write(content) |
| 152 |
except FileNotFoundError: |
| 153 |
os.makedirs(directory, exist_ok=True) |
| 154 |
with self.open(path) as fp: |
| 155 |
fp.write(content) |
| 156 |
if self.mtime: |
| 157 |
pathfmt.set_mtime(path) |
| 158 |
|
| 159 |
if archive: |
| 160 |
archive.add(pathfmt.kwdict) |
| 161 |
|
| 162 |
def _run_stdout(self, pathfmt): |
| 163 |
sys.stdout.write(self.write(pathfmt.kwdict)) |
| 164 |
|
| 165 |
def _run_modify(self, pathfmt): |
| 166 |
kwdict = pathfmt.kwdict |
| 167 |
for key, func in self.fields.items(): |
| 168 |
obj = kwdict |
| 169 |
try: |
| 170 |
if "[" in key: |
| 171 |
obj, key = _traverse(obj, key) |
| 172 |
obj[key] = func(kwdict) |
| 173 |
except Exception: |
| 174 |
pass |
| 175 |
|
| 176 |
def _run_delete(self, pathfmt): |
| 177 |
kwdict = pathfmt.kwdict |
| 178 |
for key in self.fields: |
| 179 |
obj = kwdict |
| 180 |
try: |
| 181 |
if "[" in key: |
| 182 |
obj, key = _traverse(obj, key) |
| 183 |
del obj[key] |
| 184 |
except Exception: |
| 185 |
pass |
| 186 |
|
| 187 |
def _base(self, pathfmt): |
| 188 |
return pathfmt.realdirectory |
| 189 |
|
| 190 |
def _directory(self, pathfmt): |
| 191 |
return self._base(pathfmt) |
| 192 |
|
| 193 |
def _directory_custom(self, pathfmt): |
| 194 |
return os.path.join(self._base(pathfmt), self._metadir) |
| 195 |
|
| 196 |
def _directory_format(self, pathfmt): |
| 197 |
formatters = pathfmt.directory_formatters |
| 198 |
conditions = pathfmt.directory_conditions |
| 199 |
try: |
| 200 |
pathfmt.directory_formatters = self._directory_formatters |
| 201 |
pathfmt.directory_conditions = () |
| 202 |
if segments := pathfmt.build_directory(pathfmt.kwdict): |
| 203 |
directory = pathfmt.clean_path(os.sep.join(segments) + os.sep) |
| 204 |
else: |
| 205 |
directory = "." + os.sep |
| 206 |
return os.path.join(self._base(pathfmt), directory) |
| 207 |
finally: |
| 208 |
pathfmt.directory_conditions = conditions |
| 209 |
pathfmt.directory_formatters = formatters |
| 210 |
|
| 211 |
def _filename(self, pathfmt): |
| 212 |
return (pathfmt.filename or "metadata") + "." + self.extension |
| 213 |
|
| 214 |
def _filename_custom(self, pathfmt): |
| 215 |
return pathfmt.clean_path(pathfmt.clean_segment( |
| 216 |
self._filename_fmt(pathfmt.kwdict))) |
| 217 |
|
| 218 |
def _filename_extfmt(self, pathfmt): |
| 219 |
kwdict = pathfmt.kwdict |
| 220 |
ext = kwdict.get("extension") |
| 221 |
kwdict["extension"] = pathfmt.extension |
| 222 |
kwdict["extension"] = pathfmt.prefix + self._extension_fmt(kwdict) |
| 223 |
filename = pathfmt.build_filename(kwdict) |
| 224 |
kwdict["extension"] = ext |
| 225 |
return filename |
| 226 |
|
| 227 |
def _write_custom(self, kwdict): |
| 228 |
return self._content_fmt(kwdict) |
| 229 |
|
| 230 |
def _write_tags(self, kwdict): |
| 231 |
if not (tags := kwdict.get("tags") or kwdict.get("tag_string")): |
| 232 |
return "" |
| 233 |
|
| 234 |
if isinstance(tags, str): |
| 235 |
taglist = tags.split(", ") |
| 236 |
if len(taglist) < len(tags) / 16: |
| 237 |
taglist = tags.split(" ") |
| 238 |
tags = taglist |
| 239 |
elif isinstance(tags[0], dict): |
| 240 |
|
| 241 |
tags = [ |
| 242 |
tag |
| 243 |
for tagdict in tags |
| 244 |
for tag in tagdict.values() |
| 245 |
if isinstance(tag, str) |
| 246 |
] |
| 247 |
tags.sort() |
| 248 |
|
| 249 |
return "\n".join(tags) + "\n" if tags else "" |
| 250 |
|
| 251 |
def _write_json(self, kwdict): |
| 252 |
if self.filter: |
| 253 |
kwdict = self.filter(kwdict) |
| 254 |
return self._json_encode(kwdict) + "\n" if kwdict else "" |
| 255 |
|
| 256 |
def _make_filter(self, options): |
| 257 |
if include := options.get("include"): |
| 258 |
if isinstance(include, str): |
| 259 |
include = include.split(",") |
| 260 |
return lambda d: {k: d[k] for k in include if k in d} |
| 261 |
|
| 262 |
private = options.get("private") |
| 263 |
if exclude := options.get("exclude"): |
| 264 |
if isinstance(exclude, str): |
| 265 |
exclude = exclude.split(",") |
| 266 |
exclude = set(exclude) |
| 267 |
|
| 268 |
if private: |
| 269 |
return lambda d: {k: v for k, v in d.items() |
| 270 |
if k not in exclude} |
| 271 |
return lambda d: {k: v for k, v in util.filter_dict(d).items() |
| 272 |
if k not in exclude} |
| 273 |
|
| 274 |
if not private: |
| 275 |
return util.filter_dict |
| 276 |
|
| 277 |
def _make_encoder(self, options, indent=None): |
| 278 |
return json.JSONEncoder( |
| 279 |
ensure_ascii=options.get("ascii", False), |
| 280 |
sort_keys=options.get("sort", False), |
| 281 |
separators=options.get("separators"), |
| 282 |
indent=options.get("indent", indent), |
| 283 |
check_circular=False, |
| 284 |
default=util.json_default, |
| 285 |
) |
| 286 |
|
| 287 |
|
| 288 |
def _traverse(obj, key): |
| 289 |
name, _, key = key.partition("[") |
| 290 |
obj = obj[name] |
| 291 |
|
| 292 |
while "[" in key: |
| 293 |
name, _, key = key.partition("[") |
| 294 |
obj = obj[name.strip("\"']")] |
| 295 |
|
| 296 |
return obj, key.strip("\"']") |
| 297 |
|
| 298 |
|
| 299 |
__postprocessor__ = MetadataPP |