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 all commits
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,7 +18,7 @@
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
Expand Down Expand Up @@ -565,8 +565,10 @@ def get_yt_version():
def get_version_stack():
import matplotlib

from yt._version import __version__ as yt_version

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 +1449,24 @@ 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(save_kwargs: Dict[str, Any], name: str) -> None:
"""
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}"
).format(**get_version_stack())

if "metadata" in save_kwargs:
save_kwargs["metadata"].setdefault(key, default_software)
else:
save_kwargs["metadata"] = {key: default_software}
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-{PIL.__version__}|yt-{yt_version}")
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
11 changes: 11 additions & 0 deletions yt/visualization/tests/test_save.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import re

import pytest
from PIL import Image

import yt
from yt.testing import fake_amr_ds
Expand All @@ -23,6 +24,16 @@ def test_save_to_path(simple_sliceplot, tmp_path):
assert len(list((tmp_path).glob("*.png"))) == 1


def test_metadata(simple_sliceplot, tmp_path):
simple_sliceplot.save(tmp_path / "ala.png")
with Image.open(tmp_path / "ala.png") as img:
assert "Software" in img.info
assert "yt-" in img.info["Software"]
simple_sliceplot.save(tmp_path / "ala.pdf")
with open(tmp_path / "ala.pdf", "rb") as f:
assert b"|yt-" in f.read()


def test_save_to_missing_path(simple_sliceplot, tmp_path):
# the missing layer should be created
p = simple_sliceplot
Expand Down