Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

enh: store basic software info in png metadata #4553

Merged
merged 3 commits into from
Jul 3, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 25 additions & 2 deletions yt/funcs.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,13 @@
from copy import deepcopy
from functools import lru_cache, wraps
from numbers import Number as numeric_type
from typing import Any, Callable, Optional, Type
from typing import Any, Callable, Dict, Optional, Type

import numpy as np
from more_itertools import always_iterable, collapse, first

from yt._maintenance.deprecation import issue_deprecation_warning
from yt._version import __version__ as yt_version
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would prefer we nest this import in get_version_stack to avoid having to support people relying on from yt.funcs import yt_version in the future. (I know people already use the indirection from yt.funcs import mylog)

from yt.config import ytcfg
from yt.units import YTArray, YTQuantity
from yt.utilities.exceptions import YTFieldNotFound, YTInvalidWidthError
Expand Down Expand Up @@ -566,7 +567,7 @@ def get_version_stack():
import matplotlib

version_info = {}
version_info["yt"] = get_yt_version()
version_info["yt"] = yt_version
version_info["numpy"] = np.version.version
version_info["matplotlib"] = matplotlib.__version__
return version_info
Expand Down Expand Up @@ -1447,3 +1448,25 @@ def validate_moment(moment, weight_field):
"Weighted projections can only be made of averages "
"(moment = 1) or standard deviations (moment = 2)!"
)


def setdefault_mpl_metadata(mpl_kwargs: Dict[str, Any], name: str) -> None:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

took me a minute to realise but in this context, I think save_kwargs may be a better name than mpl_kwargs (which is also used in other places for completely different stuff)

Copy link
Member Author

@Xarthisius Xarthisius Jun 30, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's specifically a matplotlib kwarg {"metadata": {...}}, not just yt's save.

"""
Set a default Software metadata entry for use with Matplotlib outputs.
"""
_, ext = os.path.splitext(name.lower())
if ext in (".eps", ".ps", ".svg", ".pdf"):
key = "Creator"
elif ext == ".png":
key = "Software"
else:
return
default_software = (
"Matplotlib version{matplotlib}, https://matplotlib.org|NumPy-{numpy}|yt-{yt}"
)
if "metadata" in mpl_kwargs:
mpl_kwargs["metadata"].setdefault(
key, default_software.format(**get_version_stack())
)
else:
mpl_kwargs["metadata"] = {key: default_software.format(**get_version_stack())}
Xarthisius marked this conversation as resolved.
Show resolved Hide resolved
10 changes: 9 additions & 1 deletion yt/utilities/png_writer.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
from io import BytesIO

import PIL
from PIL import Image
from PIL.PngImagePlugin import PngInfo

from .._version import __version__ as yt_version


def call_png_write_png(buffer, fileobj, dpi):
Image.fromarray(buffer).save(fileobj, dpi=(dpi, dpi), format="png")
metadata = PngInfo()
metadata.add_text("Software", f"{PIL.__name__}-{PIL.__version__}|yt-{yt_version}")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

isn't PIL.__name__ always going to be 'PIL' ? (seems to be the case even with pillow)

Image.fromarray(buffer).save(
fileobj, dpi=(dpi, dpi), format="png", pnginfo=metadata
)


def write_png(buffer, filename, dpi=100):
Expand Down
9 changes: 8 additions & 1 deletion yt/visualization/base_plot_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,13 @@
import numpy as np
from matplotlib.ticker import LogFormatterMathtext

from yt.funcs import get_interactivity, is_sequence, matplotlib_style_context, mylog
from yt.funcs import (
get_interactivity,
is_sequence,
matplotlib_style_context,
mylog,
setdefault_mpl_metadata,
)
from yt.visualization._handlers import ColorbarHandler, NormHandler

from ._commons import (
Expand Down Expand Up @@ -162,6 +168,7 @@ def save(self, name, mpl_kwargs=None, canvas=None):
mpl_kwargs = {}

name = validate_image_name(name)
setdefault_mpl_metadata(mpl_kwargs, name)

try:
canvas = get_canvas(self.figure, name)
Expand Down