|
| 1 | +"""Normalize image runner outputs to PNG bytes (in-memory, no disk).""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import base64 |
| 6 | +import os |
| 7 | +import time |
| 8 | +from io import BytesIO |
| 9 | +from typing import Any, Optional |
| 10 | + |
| 11 | +import torch |
| 12 | +from PIL import Image |
| 13 | +from loguru import logger |
| 14 | + |
| 15 | +try: |
| 16 | + from torchvision.io import encode_png as tv_encode_png |
| 17 | +except Exception: |
| 18 | + tv_encode_png = None |
| 19 | + |
| 20 | + |
| 21 | +def _get_png_compression_level() -> int: |
| 22 | + raw = os.getenv("LIGHTX2V_SYNC_PNG_COMPRESSION", "6") |
| 23 | + try: |
| 24 | + level = int(raw) |
| 25 | + except ValueError: |
| 26 | + logger.warning(f"Invalid LIGHTX2V_SYNC_PNG_COMPRESSION={raw}, fallback to 6") |
| 27 | + return 6 |
| 28 | + if level < 0 or level > 9: |
| 29 | + logger.warning(f"LIGHTX2V_SYNC_PNG_COMPRESSION={level} out of range [0,9], clamped") |
| 30 | + level = max(0, min(9, level)) |
| 31 | + return level |
| 32 | + |
| 33 | + |
| 34 | +PNG_COMPRESSION_LEVEL = _get_png_compression_level() |
| 35 | + |
| 36 | + |
| 37 | +def _pil_to_png_bytes(pil_image: Image.Image) -> bytes: |
| 38 | + buf = BytesIO() |
| 39 | + img = pil_image |
| 40 | + if img.mode not in ("RGB", "RGBA"): |
| 41 | + img = img.convert("RGB") |
| 42 | + img.save(buf, format="PNG", compress_level=PNG_COMPRESSION_LEVEL) |
| 43 | + return buf.getvalue() |
| 44 | + |
| 45 | + |
| 46 | +def _pil_images_structure_to_png(images: Any) -> bytes: |
| 47 | + first = images[0] |
| 48 | + if isinstance(first, list): |
| 49 | + pil_image = first[0] |
| 50 | + else: |
| 51 | + pil_image = first |
| 52 | + if not hasattr(pil_image, "save"): |
| 53 | + raise TypeError(f"Unexpected image element type: {type(pil_image)}") |
| 54 | + return _pil_to_png_bytes(pil_image) |
| 55 | + |
| 56 | + |
| 57 | +def _tensor_to_png_bytes(image_tensor: torch.Tensor) -> bytes: |
| 58 | + total_start = time.perf_counter() |
| 59 | + task_tag = f"shape={tuple(image_tensor.shape)},dtype={image_tensor.dtype},device={image_tensor.device}" |
| 60 | + |
| 61 | + cpu_start = time.perf_counter() |
| 62 | + tensor = image_tensor.detach().cpu() |
| 63 | + cpu_ms = (time.perf_counter() - cpu_start) * 1000 |
| 64 | + |
| 65 | + if tensor.ndim == 4: |
| 66 | + tensor = tensor[0] |
| 67 | + if tensor.ndim != 3: |
| 68 | + raise TypeError(f"Unsupported tensor shape: {tuple(tensor.shape)}") |
| 69 | + |
| 70 | + prep_start = time.perf_counter() |
| 71 | + # Normalize layout once: keep CHW for fast PNG encoding path. |
| 72 | + if tensor.shape[0] in (1, 3, 4): |
| 73 | + tensor_chw = tensor |
| 74 | + elif tensor.shape[-1] in (1, 3, 4): |
| 75 | + tensor_chw = tensor.permute(2, 0, 1) |
| 76 | + else: |
| 77 | + raise TypeError(f"Unsupported tensor channel layout: {tuple(tensor.shape)}") |
| 78 | + |
| 79 | + if tensor_chw.dtype.is_floating_point: |
| 80 | + # Most runners output floats in [0, 1]. |
| 81 | + if float(tensor_chw.max()) <= 1.0: |
| 82 | + tensor_chw = (tensor_chw.clamp(0.0, 1.0) * 255.0).round() |
| 83 | + else: |
| 84 | + tensor_chw = tensor_chw.clamp(0.0, 255.0).round() |
| 85 | + |
| 86 | + tensor_chw = tensor_chw.to(torch.uint8) |
| 87 | + prep_ms = (time.perf_counter() - prep_start) * 1000 |
| 88 | + |
| 89 | + # Fast path: encode PNG directly from CHW uint8 tensor. |
| 90 | + if tv_encode_png is not None: |
| 91 | + encode_start = time.perf_counter() |
| 92 | + png_bytes = tv_encode_png(tensor_chw, compression_level=PNG_COMPRESSION_LEVEL).numpy().tobytes() |
| 93 | + encode_ms = (time.perf_counter() - encode_start) * 1000 |
| 94 | + total_ms = (time.perf_counter() - total_start) * 1000 |
| 95 | + logger.info(f"Tensor->PNG(tv) cost total={total_ms:.2f}ms cpu_copy={cpu_ms:.2f}ms preprocess={prep_ms:.2f}ms encode={encode_ms:.2f}ms level={PNG_COMPRESSION_LEVEL} [{task_tag}]") |
| 96 | + return png_bytes |
| 97 | + |
| 98 | + encode_start = time.perf_counter() |
| 99 | + arr = tensor_chw.permute(1, 2, 0).numpy() |
| 100 | + if arr.shape[-1] == 1: |
| 101 | + arr = arr[:, :, 0] |
| 102 | + png_bytes = _pil_to_png_bytes(Image.fromarray(arr)) |
| 103 | + encode_ms = (time.perf_counter() - encode_start) * 1000 |
| 104 | + total_ms = (time.perf_counter() - total_start) * 1000 |
| 105 | + logger.info(f"Tensor->PNG(pil) cost total={total_ms:.2f}ms cpu_copy={cpu_ms:.2f}ms preprocess={prep_ms:.2f}ms encode={encode_ms:.2f}ms level={PNG_COMPRESSION_LEVEL} [{task_tag}]") |
| 106 | + return png_bytes |
| 107 | + |
| 108 | + |
| 109 | +def encode_pipeline_return_to_png_bytes(pipeline_return: Any) -> Optional[bytes]: |
| 110 | + """Convert run_pipeline return value to a single PNG byte string, or None if not applicable.""" |
| 111 | + if pipeline_return is None: |
| 112 | + return None |
| 113 | + try: |
| 114 | + if isinstance(pipeline_return, tuple) and len(pipeline_return) > 0: |
| 115 | + # e.g. BagelRunner returns (images, audio_or_none) |
| 116 | + pipeline_return = pipeline_return[0] |
| 117 | + if isinstance(pipeline_return, dict): |
| 118 | + images = pipeline_return.get("images") |
| 119 | + if images is None: |
| 120 | + return None |
| 121 | + if isinstance(images, torch.Tensor): |
| 122 | + return _tensor_to_png_bytes(images) |
| 123 | + return _pil_images_structure_to_png(images) |
| 124 | + if isinstance(pipeline_return, list) and len(pipeline_return) > 0: |
| 125 | + if isinstance(pipeline_return[0], torch.Tensor): |
| 126 | + return _tensor_to_png_bytes(pipeline_return[0]) |
| 127 | + return _pil_images_structure_to_png(pipeline_return) |
| 128 | + if isinstance(pipeline_return, torch.Tensor): |
| 129 | + return _tensor_to_png_bytes(pipeline_return) |
| 130 | + if isinstance(pipeline_return, Image.Image): |
| 131 | + return _pil_to_png_bytes(pipeline_return) |
| 132 | + if isinstance(pipeline_return, str): |
| 133 | + raw = base64.b64decode(pipeline_return) |
| 134 | + img = Image.open(BytesIO(raw)).convert("RGB") |
| 135 | + return _pil_to_png_bytes(img) |
| 136 | + except Exception as e: |
| 137 | + logger.exception(f"Failed to encode pipeline output to PNG: {e}") |
| 138 | + return None |
| 139 | + return None |
0 commit comments