File size: 12,800 Bytes
b7e49b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
"""Host input / output helpers of DepthPro2 (numpy + Pillow; no torch, no ttnn at import).

Inputs: images (PNG / JPEG / any format Pillow decodes; upright per EXIF orientation; 16-bit images scaled to
8 bits) as base64, bytes, paths, PIL images or arrays; the 35 mm-equivalent EXIF focal length converted to pixels
(as the official command line does); clips of frames as a list of images or one ``(T, H, W, 3)`` uint8 ``.npy`` /
``.npz``. Outputs: float16 / float32 ``.npy`` arrays in base64, 16-bit depth PNGs, depth statistics.
"""
from __future__ import annotations

import base64
import io
import math
import numbers
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence, Tuple

import numpy as np

from .ttaw.io import InputError, b64decode


class CapacityError(InputError):
    """A request needs a resource the model holds a fixed number of (unbuffered video streams). HTTP 429."""


__all__ = ["InputError", "CapacityError", "MIN_IMAGE_SIDE", "MAX_IMAGE_SIDE", "MAX_IMAGE_PIXELS", "DecodedImage", "decode_image_bytes",
           "decode_image_b64", "load_image", "load_frames", "decode_clip", "fpx_from_f35", "encode_npy",
           "decode_npy_b64", "depth_png16", "depth_stats", "PNG_SCALE_DEFAULT"]

MIN_IMAGE_SIDE = 16
MAX_IMAGE_SIDE = 8192
MAX_IMAGE_PIXELS = 50_000_000
PNG_SCALE_DEFAULT = 1000.0  # 16-bit depth PNG: uint16 = round(depth_m * scale) -> millimetres, up to 65.534 m


class DecodedImage:
    """An RGB uint8 ``(H, W, 3)`` image and the focal length in pixels from its EXIF data (or None)."""

    __slots__ = ("rgb", "exif_f_px")

    def __init__(self, rgb: np.ndarray, exif_f_px: Optional[float] = None):
        self.rgb = rgb
        self.exif_f_px = exif_f_px


def fpx_from_f35(width: float, height: float, f_mm: float) -> float:
    """A 35 mm-equivalent focal length (mm) -> pixels of a ``width x height`` image (the diagonal ratio to the
    36 x 24 mm frame)."""
    return float(f_mm) * math.hypot(width, height) / math.hypot(36.0, 24.0)


def _check_size(h: int, w: int, field: str) -> None:
    if min(h, w) < MIN_IMAGE_SIDE or max(h, w) > MAX_IMAGE_SIDE or h * w > MAX_IMAGE_PIXELS:
        raise InputError(f"{field}: image is {w}x{h} pixels; each side must be {MIN_IMAGE_SIDE}..{MAX_IMAGE_SIDE} "
                         f"and at most {MAX_IMAGE_PIXELS // 1_000_000} megapixels")


def decode_image_bytes(raw: bytes, *, field: str = "image", exif: bool = True) -> DecodedImage:
    """Image file bytes -> :class:`DecodedImage`. Turned upright per the EXIF orientation; 16-bit greyscale scaled
    to 8 bits; the EXIF ``FocalLengthIn35mmFilm`` converted to pixels when ``exif`` (else ``exif_f_px`` is None)."""
    from PIL import ExifTags, Image, ImageOps, UnidentifiedImageError

    try:
        with Image.open(io.BytesIO(raw)) as im:
            w0, h0 = im.size
            _check_size(h0, w0, field)
            f35 = None
            if exif:
                try:
                    f35 = im.getexif().get_ifd(ExifTags.IFD.Exif).get(ExifTags.Base.FocalLengthIn35mmFilm)
                except Exception:  # noqa: BLE001 -- a malformed EXIF block is ignored, as if absent
                    f35 = None
            try:
                im = ImageOps.exif_transpose(im)
            except Exception:  # noqa: BLE001 -- a malformed orientation tag: decode as stored
                pass
            if im.mode.startswith("I;16"):
                im = Image.fromarray((np.asarray(im).astype(np.uint16) >> 8).astype(np.uint8))
            elif im.mode in ("I", "F"):
                raise InputError(f"{field}: unsupported image mode {im.mode} (32-bit integer / float)")
            rgb = np.array(im.convert("RGB"), dtype=np.uint8)  # a writable copy
    except InputError:
        raise
    except (UnidentifiedImageError, OSError, ValueError, SyntaxError, Image.DecompressionBombError) as e:
        raise InputError(f"{field} could not be decoded as an image: {type(e).__name__}: {e}") from None
    f_px = None
    if isinstance(f35, numbers.Real) and not isinstance(f35, bool) and f35 > 0:
        f_px = fpx_from_f35(rgb.shape[1], rgb.shape[0], float(f35))
    return DecodedImage(rgb, f_px)


def decode_image_b64(data: Any, *, field: str = "image", max_bytes: Optional[int] = None,
                     exif: bool = True) -> DecodedImage:
    """base64 (standard or URL-safe, ``data:`` URI tolerated) image -> :class:`DecodedImage`."""
    return decode_image_bytes(b64decode(data, field=field, max_bytes=max_bytes), field=field, exif=exif)


def load_image(image: Any, *, exif: bool = True) -> DecodedImage:
    """Python-API image input -> :class:`DecodedImage`: a path, file bytes, a PIL image, an RGB uint8 ``(H, W, 3)``
    array, a ``(3, H, W)`` array / tensor, or a float array in [0, 1]. EXIF is read from paths and bytes only."""
    if isinstance(image, DecodedImage):
        return image
    if isinstance(image, (str, Path)):
        p = Path(image)
        if not p.is_file():
            raise InputError(f"image file {p} does not exist")
        return decode_image_bytes(p.read_bytes(), field=str(p), exif=exif)
    if isinstance(image, (bytes, bytearray, memoryview)):
        return decode_image_bytes(bytes(image), exif=exif)
    if hasattr(image, "mode") and hasattr(image, "size") and hasattr(image, "convert"):  # PIL
        from PIL import ImageOps

        im = ImageOps.exif_transpose(image)
        rgb = np.array(im.convert("RGB"), dtype=np.uint8)
        _check_size(rgb.shape[0], rgb.shape[1], "image")
        return DecodedImage(rgb, None)
    if hasattr(image, "detach") and hasattr(image, "cpu"):
        image = image.detach().cpu().numpy()
    a = np.asarray(image)
    if a.ndim == 3 and a.shape[0] == 3 and a.shape[2] != 3:
        a = np.transpose(a, (1, 2, 0))
    if a.ndim == 2:
        a = np.repeat(a[:, :, None], 3, axis=2)
    if a.ndim != 3 or a.shape[2] not in (3, 4):
        raise InputError(f"image array must be (H, W, 3) RGB (or (3, H, W) / (H, W)), got {a.shape}")
    a = a[:, :, :3]
    if np.issubdtype(a.dtype, np.floating):
        if not np.isfinite(a).all():
            raise InputError("image array has non-finite values")
        a = np.clip(np.round(a * 255.0), 0, 255)
    elif a.dtype != np.uint8:
        if a.size and (a.min() < 0 or a.max() > 255):
            raise InputError(f"integer image array must be in 0..255, got {a.dtype} {a.min()}..{a.max()}")
    rgb = np.array(a, dtype=np.uint8, order="C")  # a writable copy (torch.from_numpy needs one)
    _check_size(rgb.shape[0], rgb.shape[1], "image")
    return DecodedImage(rgb, None)


def load_frames(frames: Any, *, exif: bool = False, max_frames: Optional[int] = None) -> Tuple[np.ndarray, List[Optional[float]]]:
    """Clip input -> ``(uint8 (T, H, W, 3), [exif f_px per frame])``: a ``(T, H, W, 3)`` uint8 array / tensor or a
    sequence of images (anything :func:`load_image` takes). All frames must have one size."""
    if hasattr(frames, "detach") and hasattr(frames, "cpu"):
        frames = frames.detach().cpu().numpy()
    if isinstance(frames, np.ndarray) and frames.ndim == 4:
        seq: Sequence[Any] = list(frames)
    elif isinstance(frames, (list, tuple)):
        seq = frames
    else:
        try:
            seq = list(frames)
        except TypeError:
            raise InputError(f"frames must be a sequence of images or a (T, H, W, 3) array, got "
                             f"{type(frames).__name__}") from None
    if not len(seq):
        raise InputError("no frames given")
    if max_frames is not None and len(seq) > max_frames:
        raise InputError(f"{len(seq)} frames given; at most {max_frames} per call")
    imgs = [load_image(f, exif=exif) for f in seq]
    shape = imgs[0].rgb.shape
    for i, im in enumerate(imgs):
        if im.rgb.shape != shape:
            raise InputError(f"frame {i} is {im.rgb.shape[1]}x{im.rgb.shape[0]}, frame 0 is {shape[1]}x{shape[0]}: "
                             "all frames of a clip must have one size")
    return np.stack([im.rgb for im in imgs]), [im.exif_f_px for im in imgs]


def decode_npy_b64(data: Any, *, field: str = "data", max_bytes: Optional[int] = None, key: Optional[str] = None):
    """base64 ``.npy`` or ``.npz`` (first array, or ``key``) -> numpy array (no pickles)."""
    raw = b64decode(data, field=field, max_bytes=max_bytes)
    try:
        obj = np.load(io.BytesIO(raw), allow_pickle=False)
        if isinstance(obj, np.lib.npyio.NpzFile):
            with obj:
                names = list(obj.keys())
                if not names:
                    raise InputError(f"{field}: empty .npz")
                if key is not None and key not in names:
                    raise InputError(f"{field}: .npz has no array {key!r} (has {names})")
                return obj[key or names[0]]
        return obj
    except InputError:
        raise
    except (ValueError, OSError, EOFError) as e:
        raise InputError(f"{field}: not a .npy / .npz array: {e}") from None


def decode_clip(spec: Dict[str, Any], *, field: str = "clip", max_bytes: Optional[int] = None,
                max_frames: Optional[int] = None) -> np.ndarray:
    """``{"format": "npy" | "npz", "data": <base64>, "key": <npz key>}`` -> uint8 ``(T, H, W, 3)``."""
    fmt = str(spec.get("format") or "npy").lower()
    if fmt not in ("npy", "npz"):
        raise InputError(f"{field}.format {fmt!r}: 'npy' or 'npz' (a uint8 (T, H, W, 3) array)")
    a = decode_npy_b64(spec.get("data"), field=f"{field}.data", max_bytes=max_bytes, key=spec.get("key"))
    if a.dtype != np.uint8 or a.ndim != 4 or a.shape[-1] != 3:
        raise InputError(f"{field}: expected a uint8 (T, H, W, 3) array, got {a.dtype} {tuple(a.shape)}")
    if a.shape[0] < 1:
        raise InputError(f"{field}: no frames")
    if max_frames is not None and a.shape[0] > max_frames:
        raise InputError(f"{field}: {a.shape[0]} frames; at most {max_frames} per request")
    _check_size(a.shape[1], a.shape[2], field)
    return np.array(a, dtype=np.uint8, order="C")  # a writable copy


def encode_npy(arr: Any, *, dtype: str = "float16") -> Dict[str, Any]:
    """A dense array as base64 ``.npy`` (little-endian, C order): ``{"format": "npy", "dtype", "shape", "data"}``.
    Decode: ``np.load(io.BytesIO(base64.b64decode(d["data"])))``."""
    with np.errstate(over="ignore"):  # float16: depths above 65504 m become inf
        a = np.ascontiguousarray(np.asarray(arr).astype(np.dtype(dtype).newbyteorder("<"), copy=False))
    buf = io.BytesIO()
    np.save(buf, a, allow_pickle=False)
    return {"format": "npy", "dtype": np.dtype(dtype).name, "shape": list(a.shape),
            "data": base64.b64encode(buf.getvalue()).decode("ascii")}


def depth_png16(depth: Any, scale: float = PNG_SCALE_DEFAULT) -> Tuple[bytes, Dict[str, Any]]:
    """Metric depth ``(H, W)`` -> a 16-bit greyscale PNG, ``uint16 = round(depth * scale)``: 0 marks infinite
    depth (sky) or no value, 65535 saturation (depth >= 65535 / scale). Returns ``(png bytes, meta)``."""
    from PIL import Image

    d = np.asarray(depth, dtype=np.float32)
    if d.ndim != 2:
        raise ValueError(f"depth_png16 expects (H, W), got {d.shape}")
    if not (scale > 0 and math.isfinite(scale)):
        raise InputError(f"png_scale must be a positive number, got {scale}")
    finite = np.isfinite(d) & (d > 0)
    v = np.where(finite, np.round(d.astype(np.float64) * scale), 0.0)
    saturated = int(np.count_nonzero(v > 65535))
    q = np.clip(v, 0, 65535).astype(np.uint16)
    q[finite & (q == 0)] = 1  # a finite depth below 0.5 / scale is not "no value"
    buf = io.BytesIO()
    Image.fromarray(q).save(buf, format="PNG", compress_level=1)  # uint16 (H, W) -> PNG I;16; fast zlib level
    meta = {"format": "png16", "scale": float(scale), "decode": "depth_m = uint16_value / scale (0: infinite / sky)",
            "saturation_m": 65535.0 / scale, "saturated_pixels": saturated,
            "infinite_pixels": int(d.size - np.count_nonzero(finite)), "shape": list(d.shape)}
    return buf.getvalue(), meta


def depth_stats(depth: Any) -> Dict[str, Any]:
    """min / 5th percentile / median / 95th percentile / max of the finite depth values (metres), the number of
    infinite (sky) pixels and of all pixels."""
    d = np.asarray(depth, dtype=np.float32)
    fin = d[np.isfinite(d)]
    out: Dict[str, Any] = {"pixels": int(d.size), "infinite_pixels": int(d.size - fin.size)}
    if fin.size:
        q = np.percentile(fin, [5, 50, 95])
        out.update({"min": float(fin.min()), "p05": float(q[0]), "median": float(q[1]), "p95": float(q[2]),
                    "max": float(fin.max())})
    else:
        out.update({"min": None, "p05": None, "median": None, "p95": None, "max": None})
    return out