|
| 1 | +import torch |
| 2 | + |
| 3 | +from comfy.cli_args import args as cli_args |
| 4 | + |
| 5 | +if not torch.cuda.is_available(): |
| 6 | + cli_args.cpu = True |
| 7 | + |
| 8 | +import comfy.model_management # noqa: E402 |
| 9 | +from comfy_extras.nodes_upscale_model import ImageUpscaleWithModel # noqa: E402 |
| 10 | + |
| 11 | + |
| 12 | +class StubUpscaleModel: |
| 13 | + """Stands in for a spandrel ImageModelDescriptor that only accepts RGB.""" |
| 14 | + |
| 15 | + scale = 2 |
| 16 | + |
| 17 | + class patcher: |
| 18 | + load_device = torch.device("cpu") |
| 19 | + |
| 20 | + def __init__(self): |
| 21 | + self.seen_channels = None |
| 22 | + |
| 23 | + def __call__(self, image): |
| 24 | + self.seen_channels = image.shape[1] |
| 25 | + assert image.shape[1] == 3, "model was handed a non-RGB tensor" |
| 26 | + return torch.nn.functional.interpolate(image, scale_factor=self.scale, mode="nearest") |
| 27 | + |
| 28 | + |
| 29 | +def rgba_image(): |
| 30 | + """16x16 RGBA where the top half is transparent and the bottom half opaque.""" |
| 31 | + image = torch.zeros(1, 16, 16, 4) |
| 32 | + image[..., :3] = 0.5 |
| 33 | + image[0, 8:, :, 3] = 1.0 |
| 34 | + return image |
| 35 | + |
| 36 | + |
| 37 | +def upscale(image, monkeypatch): |
| 38 | + monkeypatch.setattr(comfy.model_management, "load_models_gpu", lambda *args, **kwargs: None) |
| 39 | + model = StubUpscaleModel() |
| 40 | + return model, ImageUpscaleWithModel.execute(model, image) |
| 41 | + |
| 42 | + |
| 43 | +def test_rgba_input_does_not_crash_and_alpha_is_preserved(monkeypatch): |
| 44 | + model, out = upscale(rgba_image(), monkeypatch) |
| 45 | + image = out.result[0] |
| 46 | + |
| 47 | + assert model.seen_channels == 3 |
| 48 | + assert image.shape == (1, 32, 32, 4) |
| 49 | + assert image[0, :14, :, 3].max() < 0.1 |
| 50 | + assert image[0, 18:, :, 3].min() > 0.9 |
| 51 | + |
| 52 | + |
| 53 | +def test_rgb_input_is_untouched(monkeypatch): |
| 54 | + model, out = upscale(torch.zeros(1, 16, 16, 3), monkeypatch) |
| 55 | + image = out.result[0] |
| 56 | + |
| 57 | + assert model.seen_channels == 3 |
| 58 | + assert image.shape == (1, 32, 32, 3) |
0 commit comments