forked from mlflow/mlflow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_log_image.py
314 lines (241 loc) · 10.9 KB
/
test_log_image.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
import json
import os
import posixpath
import pytest
import mlflow
from mlflow.utils.file_utils import local_file_uri_to_path
from mlflow.utils.time import get_current_time_millis
@pytest.mark.parametrize("subdir", [None, ".", "dir", "dir1/dir2", "dir/.."])
def test_log_image_numpy(subdir):
import numpy as np
from PIL import Image
filename = "image.png"
artifact_file = filename if subdir is None else posixpath.join(subdir, filename)
image = np.random.randint(0, 256, size=(100, 100, 3), dtype=np.uint8)
with mlflow.start_run():
mlflow.log_image(image, artifact_file)
artifact_path = None if subdir is None else posixpath.normpath(subdir)
artifact_uri = mlflow.get_artifact_uri(artifact_path)
run_artifact_dir = local_file_uri_to_path(artifact_uri)
assert os.listdir(run_artifact_dir) == [filename]
logged_path = os.path.join(run_artifact_dir, filename)
loaded_image = np.asarray(Image.open(logged_path), dtype=np.uint8)
np.testing.assert_array_equal(loaded_image, image)
@pytest.mark.parametrize("subdir", [None, ".", "dir", "dir1/dir2", "dir/.."])
def test_log_image_pillow(subdir):
from PIL import Image, ImageChops
filename = "image.png"
artifact_file = filename if subdir is None else posixpath.join(subdir, filename)
image = Image.new("RGB", (100, 100))
with mlflow.start_run():
mlflow.log_image(image, artifact_file)
artifact_path = None if subdir is None else posixpath.normpath(subdir)
artifact_uri = mlflow.get_artifact_uri(artifact_path)
run_artifact_dir = local_file_uri_to_path(artifact_uri)
assert os.listdir(run_artifact_dir) == [filename]
logged_path = os.path.join(run_artifact_dir, filename)
loaded_image = Image.open(logged_path)
# How to check Pillow image equality: https://stackoverflow.com/a/6204954/6943581
assert ImageChops.difference(loaded_image, image).getbbox() is None
def test_log_image_raises_for_unsupported_objects():
with mlflow.start_run():
with pytest.raises(TypeError, match="Unsupported image object type"):
mlflow.log_image("not_image", "image.png")
@pytest.mark.parametrize(
"size",
[
(100, 100), # Grayscale (2D)
(100, 100, 1), # Grayscale (3D)
(100, 100, 3), # RGB
(100, 100, 4), # RGBA
],
)
def test_log_image_numpy_shape(size):
import numpy as np
filename = "image.png"
image = np.random.randint(0, 256, size=size, dtype=np.uint8)
with mlflow.start_run():
mlflow.log_image(image, filename)
artifact_uri = mlflow.get_artifact_uri()
run_artifact_dir = local_file_uri_to_path(artifact_uri)
assert os.listdir(run_artifact_dir) == [filename]
@pytest.mark.parametrize(
"dtype",
[
# Ref.: https://numpy.org/doc/stable/user/basics.types.html#array-types-and-conversions-between-types
"int8",
"int16",
"int32",
"int64",
"uint8",
"uint16",
"uint32",
"uint64",
"float16",
"float32",
"float64",
"bool",
],
)
def test_log_image_numpy_dtype(dtype):
import numpy as np
filename = "image.png"
image = np.random.randint(0, 2, size=(100, 100, 3)).astype(np.dtype(dtype))
with mlflow.start_run():
mlflow.log_image(image, filename)
artifact_uri = mlflow.get_artifact_uri()
run_artifact_dir = local_file_uri_to_path(artifact_uri)
assert os.listdir(run_artifact_dir) == [filename]
@pytest.mark.parametrize(
"array",
# 1 pixel images with out-of-range values
[[[-1]], [[256]], [[-0.1]], [[1.1]]],
)
def test_log_image_numpy_emits_warning_for_out_of_range_values(array):
import numpy as np
image = np.array(array).astype(type(array[0][0]))
if isinstance(array[0][0], int):
with mlflow.start_run(), pytest.raises(
ValueError, match="Integer pixel values out of acceptable range"
):
mlflow.log_image(image, "image.png")
else:
with mlflow.start_run(), pytest.warns(
UserWarning, match="Float pixel values out of acceptable range"
):
mlflow.log_image(image, "image.png")
def test_log_image_numpy_raises_exception_for_invalid_array_data_type():
import numpy as np
with mlflow.start_run(), pytest.raises(TypeError, match="Invalid array data type"):
mlflow.log_image(np.tile("a", (1, 1, 3)), "image.png")
def test_log_image_numpy_raises_exception_for_invalid_array_shape():
import numpy as np
with mlflow.start_run(), pytest.raises(ValueError, match="`image` must be a 2D or 3D array"):
mlflow.log_image(np.zeros((1,), dtype=np.uint8), "image.png")
def test_log_image_numpy_raises_exception_for_invalid_channel_length():
import numpy as np
with mlflow.start_run(), pytest.raises(ValueError, match="Invalid channel length"):
mlflow.log_image(np.zeros((1, 1, 5), dtype=np.uint8), "image.png")
def test_log_image_raises_exception_for_unsupported_image_object_type():
with mlflow.start_run(), pytest.raises(TypeError, match="Unsupported image object type"):
mlflow.log_image("not_image", "image.png")
def test_log_image_with_steps():
import numpy as np
from PIL import Image
image = np.random.randint(0, 256, size=(100, 100, 3), dtype=np.uint8)
with mlflow.start_run():
mlflow.log_image(image, key="dog", step=0, synchronous=True)
logged_path = "images/"
artifact_uri = mlflow.get_artifact_uri(logged_path)
run_artifact_dir = local_file_uri_to_path(artifact_uri)
files = os.listdir(run_artifact_dir)
# .png file for the image and .webp file for compressed image
assert len(files) == 2
for file in files:
assert file.startswith("dog%step%0")
logged_path = os.path.join(run_artifact_dir, file)
if file.endswith(".png"):
loaded_image = np.asarray(Image.open(logged_path), dtype=np.uint8)
np.testing.assert_array_equal(loaded_image, image)
elif file.endswith(".json"):
with open(logged_path) as f:
metadata = json.load(f)
assert metadata["filepath"].startswith("images/dog%step%0")
assert metadata["key"] == "dog"
assert metadata["step"] == 0
assert metadata["timestamp"] <= get_current_time_millis()
def test_log_image_with_timestamp():
import numpy as np
from PIL import Image
image = np.random.randint(0, 256, size=(100, 100, 3), dtype=np.uint8)
with mlflow.start_run():
mlflow.log_image(image, key="dog", timestamp=100, synchronous=True)
logged_path = "images/"
artifact_uri = mlflow.get_artifact_uri(logged_path)
run_artifact_dir = local_file_uri_to_path(artifact_uri)
files = os.listdir(run_artifact_dir)
# .png file for the image, and .webp file for compressed image
assert len(files) == 2
for file in files:
assert file.startswith("dog%step%0")
logged_path = os.path.join(run_artifact_dir, file)
if file.endswith(".png"):
loaded_image = np.asarray(Image.open(logged_path), dtype=np.uint8)
np.testing.assert_array_equal(loaded_image, image)
elif file.endswith(".json"):
with open(logged_path) as f:
metadata = json.load(f)
assert metadata["filepath"].startswith("images/dog%step%0")
assert metadata["key"] == "dog"
assert metadata["step"] == 0
assert metadata["timestamp"] == 100
def test_duplicated_log_image_with_step():
"""
MLflow will save both files if there are multiple calls to log_image
with the same key and step.
"""
import numpy as np
image1 = np.random.randint(0, 256, size=(100, 100, 3), dtype=np.uint8)
image2 = np.random.randint(0, 256, size=(100, 100, 3), dtype=np.uint8)
with mlflow.start_run():
mlflow.log_image(image1, key="dog", step=100, synchronous=True)
mlflow.log_image(image2, key="dog", step=100, synchronous=True)
logged_path = "images/"
artifact_uri = mlflow.get_artifact_uri(logged_path)
run_artifact_dir = local_file_uri_to_path(artifact_uri)
files = os.listdir(run_artifact_dir)
assert len(files) == 2 * 2 # 2 images and 2 files per image
def test_duplicated_log_image_with_timestamp():
"""
MLflow will save both files if there are multiple calls to log_image
with the same key, step, and timestamp.
"""
import numpy as np
image1 = np.random.randint(0, 256, size=(100, 100, 3), dtype=np.uint8)
image2 = np.random.randint(0, 256, size=(100, 100, 3), dtype=np.uint8)
with mlflow.start_run():
mlflow.log_image(image1, key="dog", step=100, timestamp=100, synchronous=True)
mlflow.log_image(image2, key="dog", step=100, timestamp=100, synchronous=True)
logged_path = "images/"
artifact_uri = mlflow.get_artifact_uri(logged_path)
run_artifact_dir = local_file_uri_to_path(artifact_uri)
files = os.listdir(run_artifact_dir)
assert len(files) == 2 * 2
@pytest.mark.parametrize(
"args",
[
{"key": "image"},
{"step": 0},
{"timestamp": 0},
{"timestamp": 0, "step": 0},
["image"],
["image", 0],
],
)
def test_log_image_raises_exception_for_unexpected_arguments_used(args):
# It will overwrite if the user wants the exact same timestamp for the logged images
import numpy as np
exception = "The `artifact_file` parameter cannot be used in conjunction"
if isinstance(args, dict):
with mlflow.start_run(), pytest.raises(TypeError, match=exception):
mlflow.log_image(np.zeros((1,), dtype=np.uint8), "image.png", **args)
elif isinstance(args, list):
with mlflow.start_run(), pytest.raises(TypeError, match=exception):
mlflow.log_image(np.zeros((1,), dtype=np.uint8), "image.png", *args)
def test_log_image_raises_exception_for_missing_arguments():
import numpy as np
exception = "Invalid arguments: Please specify exactly one of `artifact_file` or `key`"
with mlflow.start_run(), pytest.raises(TypeError, match=exception):
mlflow.log_image(np.zeros((1,), dtype=np.uint8))
def test_async_log_image_flush():
import numpy as np
image1 = np.random.randint(0, 256, size=(100, 100, 3), dtype=np.uint8)
with mlflow.start_run():
for i in range(100):
mlflow.log_image(image1, key="dog", step=i, timestamp=i, synchronous=False)
mlflow.flush_artifact_async_logging()
logged_path = "images/"
artifact_uri = mlflow.get_artifact_uri(logged_path)
run_artifact_dir = local_file_uri_to_path(artifact_uri)
files = os.listdir(run_artifact_dir)
assert len(files) == 100 * 2