Skip to content

Commit

Permalink
Merge pull request #404 from European-XFEL/hack/thumbnail-data-valida…
Browse files Browse the repository at this point in the history
…tion

Hack/thumbnail data validation
  • Loading branch information
tmichela authored Feb 26, 2025
2 parents 6b8cfcd + f837be0 commit dacdd66
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions damnit/ctxsupport/ctxrunner.py
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,16 @@ def __init__(self, data: bytes):
self.data = data


def is_png_data(obj):
# insinstance(obj, PNGData) returns false if the PNGData object has been
# instantiated from the context file code, so we need to check the data
# attribute.
try:
return obj.data.startswith(b'\x89PNG\r\n\x1a\n')
except:
return False


def figure2png(fig, dpi=None):
bio = io.BytesIO()
fig.savefig(bio, dpi=dpi, format='png')
Expand Down Expand Up @@ -618,7 +628,7 @@ def save_hdf5(self, hdf5_path, reduced_only=False):

if isinstance(obj, str):
f.create_dataset(path, shape=(), dtype=h5py.string_dtype())
elif isinstance(obj, PNGData): # Thumbnail
elif is_png_data(obj): # Thumbnail
f.create_dataset(path, shape=len(obj.data), dtype=np.uint8)
elif obj.ndim > 0 and (
np.issubdtype(obj.dtype, np.number) or
Expand All @@ -631,7 +641,7 @@ def save_hdf5(self, hdf5_path, reduced_only=False):

# Fill with data
for path, obj, _ in dsets:
if isinstance(obj, PNGData):
if is_png_data(obj):
f[path][()] = np.frombuffer(obj.data, dtype=np.uint8)
else:
f[path][()] = obj
Expand Down

0 comments on commit dacdd66

Please sign in to comment.