Skip to content
Open
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
20 changes: 12 additions & 8 deletions src/diffusers/utils/export_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -341,14 +341,18 @@ def encode_video(
video = torch.from_numpy(video)
elif isinstance(video, np.ndarray):
# Pipeline output_type="np".
is_denormalized = np.logical_and(np.zeros_like(video) <= video, video <= np.ones_like(video))
if np.all(is_denormalized):
video = (video * 255).round().astype("uint8")
else:
logger.warning(
"Supplied `numpy.ndarray` does not have values in [0, 1]. The values will be assumed to be pixel "
"values in [0, ..., 255] and will be used as is."
)
if np.issubdtype(video.dtype, np.floating):
is_denormalized = np.logical_and(np.zeros_like(video) <= video, video <= np.ones_like(video))
if np.all(is_denormalized):
video = (video * 255).round().astype("uint8")
else:
logger.warning(
"Supplied `numpy.ndarray` does not have values in [0, 1]. The values will be assumed to be pixel "
"values in [0, ..., 255] and will be used as is."
)
video = video.round().clip(0, 255).astype("uint8")
elif video.dtype != np.uint8:
video = video.clip(0, 255).astype("uint8")
video = torch.from_numpy(video)

if isinstance(video, torch.Tensor):
Expand Down
96 changes: 96 additions & 0 deletions tests/others/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -503,3 +503,99 @@ def is_staging_test(test_case):
return pytest.mark.skip("test is staging test")(test_case)
else:
return pytest.mark.is_staging_test()(test_case)


class TestEncodeVideo:
def _run_encode_video(self, monkeypatch, video, tmp_path):
import types

import numpy as np

from diffusers.utils import export_utils

captured = []

class _FakeStream:
width = 0
height = 0
pix_fmt = ""

def encode(self, frame=None):
return []

class _FakeContainer:
def add_stream(self, codec, rate):
return _FakeStream()

def mux(self, packet):
pass

def close(self):
pass

fake_av = types.SimpleNamespace(
open=lambda path, mode="w": _FakeContainer(),
VideoFrame=types.SimpleNamespace(
from_ndarray=lambda frame_array, format="rgb24": (
captured.append((frame_array.copy(), frame_array.dtype, format)) or frame_array
)
),
)
monkeypatch.setattr(export_utils, "_import_av", lambda: fake_av)
out_path = os.path.join(tmp_path, "out.mp4")
export_utils.encode_video(video, fps=8, output_path=out_path)
return np.stack([arr for arr, _, _ in captured], axis=0), captured

def test_encode_video_preserves_uint8_binary_values(self, monkeypatch, tmp_path):
import numpy as np

from diffusers.utils import export_utils

video = np.zeros((2, 4, 4, 3), dtype=np.uint8)
video[1, :, :, :] = 1

with CaptureLogger(export_utils.logger) as cl:
recorded, captured = self._run_encode_video(monkeypatch, video, tmp_path)

assert cl.out == ""
assert all(dtype == np.uint8 and fmt == "rgb24" for _, dtype, fmt in captured)
assert np.array_equal(recorded, video)

def test_encode_video_scales_float_unit_range(self, monkeypatch, tmp_path):
import numpy as np

video = np.zeros((2, 4, 4, 3), dtype=np.float32)
video[1, :, :, :] = 1.0

recorded, _ = self._run_encode_video(monkeypatch, video, tmp_path)

assert recorded[0].max() == 0
assert recorded[1].min() == 255

def test_encode_video_warns_and_casts_out_of_unit_float(self, monkeypatch, tmp_path):
import numpy as np

from diffusers.utils import export_utils

video = np.full((2, 4, 4, 3), 128.0, dtype=np.float32)

with CaptureLogger(export_utils.logger) as cl:
recorded, captured = self._run_encode_video(monkeypatch, video, tmp_path)

assert "does not have values in [0, 1]" in cl.out
assert all(dtype == np.uint8 for _, dtype, _ in captured)
assert np.all(recorded == 128)

def test_encode_video_casts_non_uint8_integers_without_scaling(self, monkeypatch, tmp_path):
import numpy as np

from diffusers.utils import export_utils

video = np.ones((2, 4, 4, 3), dtype=np.int32)

with CaptureLogger(export_utils.logger) as cl:
recorded, captured = self._run_encode_video(monkeypatch, video, tmp_path)

assert cl.out == ""
assert all(dtype == np.uint8 for _, dtype, _ in captured)
assert np.all(recorded == 1)