File size: 11,029 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
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""Build and send DepthPro2 requests. Standard library only (any Python 3.9+, no numpy, no install).

    # the shipped sample -> req.json, then send it with curl
    python3 code/tt_depthpro2/server/client.py --sample --out req.json
    curl -s localhost:20000/predict -H 'Content-Type: application/json' -d @req.json

    # an image, sent directly: prints the response without the arrays, saves the depth as .npy (float16, metres)
    python3 code/tt_depthpro2/server/client.py --image photo.jpg --url http://127.0.0.1:20000 --save depth.npy

    # a 16-bit depth PNG (uint16 = round(depth_m * 1000); 0 = sky / infinite)
    python3 code/tt_depthpro2/server/client.py --image photo.jpg --png --url http://127.0.0.1:20000 --save depth.png

    # video: frames as image files (in order), or an .mp4 decoded here with PyAV or the ffmpeg command when either
    # is installed on the client (the server takes frames, not video files)
    python3 code/tt_depthpro2/server/client.py --video f000.png f001.png ... --url http://127.0.0.1:20000 --save d.npy
    python3 code/tt_depthpro2/server/client.py --video clip.mp4 --max-frames 64 --url http://127.0.0.1:20000
"""
from __future__ import annotations

import argparse
import base64
import json
import shutil
import struct
import subprocess
import sys
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence, Tuple

HERE = Path(__file__).resolve().parent
SAMPLE_DIR = HERE.parent / "samples" / "kropa_street"
VIDEO_SUFFIXES = (".mp4", ".mov", ".mkv", ".webm", ".avi")


def b64file(path: Any) -> str:
    return base64.b64encode(Path(path).read_bytes()).decode("ascii")


def build_request(image: Any, *, f_px: Optional[float] = None, output_format: Optional[str] = None,
                  include_inverse_depth: bool = False, use_exif: Optional[bool] = None) -> Dict[str, Any]:
    """The ``/predict`` body for an image file; optional fields are left out when None / False."""
    body: Dict[str, Any] = {"image": b64file(image)}
    for k, v in (("f_px", f_px), ("output_format", output_format), ("use_exif", use_exif)):
        if v is not None:
            body[k] = v
    if include_inverse_depth:
        body["include_inverse_depth"] = True
    return body


def sample_request(**kw: Any) -> Dict[str, Any]:
    """The shipped sample (a 640 x 480 CC0 street photo) as a ``/predict`` body."""
    meta = json.loads((SAMPLE_DIR / "sample.json").read_text())
    return build_request(SAMPLE_DIR / meta["file"], **kw)


def png_frames_from_stream(data: bytes) -> List[bytes]:
    """Split a concatenation of PNG files (``ffmpeg -f image2pipe -c:v png``) into the files."""
    sig, out, i = b"\x89PNG\r\n\x1a\n", [], 0
    while i < len(data):
        if data[i:i + 8] != sig:
            raise ValueError("not a PNG stream")
        j = i + 8
        while True:
            (n,) = struct.unpack(">I", data[j:j + 4])
            kind = data[j + 4:j + 8]
            j += 12 + n
            if kind == b"IEND":
                break
        out.append(data[i:j])
        i = j
    return out


def video_frames(path: Path, max_frames: int, every: int = 1) -> List[bytes]:
    """PNG files of the first ``max_frames`` frames (every ``every``-th) of a video file: PyAV when importable, else
    the ``ffmpeg`` command. Raises RuntimeError when neither is available."""
    try:
        import io

        import av  # type: ignore

        frames: List[bytes] = []
        with av.open(str(path)) as c:
            for k, f in enumerate(c.decode(video=0)):
                if k % every:
                    continue
                buf = io.BytesIO()
                f.to_image().save(buf, format="PNG")
                frames.append(buf.getvalue())
                if len(frames) >= max_frames:
                    break
        return frames
    except ImportError:
        pass
    ff = shutil.which("ffmpeg")
    if not ff:
        raise RuntimeError("decoding a video file needs PyAV (pip install av) or the ffmpeg command on this client; "
                           "or pass the frames as image files")
    vf = f"select=not(mod(n\\,{every}))" if every > 1 else "null"
    cmd = [ff, "-v", "error", "-i", str(path), "-vf", vf, "-vsync", "0", "-frames:v", str(max_frames),
           "-f", "image2pipe", "-c:v", "png", "-"]
    data = subprocess.run(cmd, check=True, capture_output=True).stdout
    return png_frames_from_stream(data)


def build_video_request(frames: Sequence[Any], *, mode: str = "buffered", f_px: Optional[float] = None,
                        output_format: Optional[str] = None, stream_id: Optional[str] = None,
                        end: bool = False, max_frames: int = 64, every: int = 1) -> Dict[str, Any]:
    """The ``/predict_video`` body: image files (or PNG bytes) in order, or one video file (decoded here)."""
    items: List[Any] = list(frames)
    if len(items) == 1 and Path(str(items[0])).suffix.lower() in VIDEO_SUFFIXES:
        items = video_frames(Path(items[0]), max_frames, every)
    enc = [base64.b64encode(x).decode("ascii") if isinstance(x, (bytes, bytearray)) else b64file(x) for x in items]
    body: Dict[str, Any] = {"frames": enc, "mode": mode}
    for k, v in (("f_px", f_px), ("output_format", output_format)):
        if v is not None:
            body[k] = v
    if stream_id:
        body["stream"] = {"id": stream_id, "end": bool(end)}
    return body


def post_json(url: str, route: str, payload: Dict[str, Any], timeout: float = 600.0) -> Tuple[int, Dict[str, Any]]:
    data = json.dumps(payload).encode("utf-8")
    r = urllib.request.Request(url.rstrip("/") + route, data=data, headers={"Content-Type": "application/json"})
    try:
        with urllib.request.urlopen(r, timeout=timeout) as resp:
            return resp.status, json.loads(resp.read().decode("utf-8"))
    except urllib.error.HTTPError as e:
        body = e.read().decode("utf-8", "replace")
        try:
            return e.code, json.loads(body)
        except ValueError:
            return e.code, {"detail": body}


def post_png(url: str, image: Any, *, f_px: Optional[float] = None, png_scale: Optional[float] = None,
             use_exif: Optional[bool] = None, timeout: float = 600.0) -> Tuple[int, bytes, Dict[str, str]]:
    """``POST /predict_png`` with the raw file -> ``(status, body bytes, headers)``."""
    q = {k: v for k, v in (("f_px", f_px), ("png_scale", png_scale)) if v is not None}
    if use_exif is not None:
        q["use_exif"] = "true" if use_exif else "false"
    raw = image if isinstance(image, (bytes, bytearray)) else Path(image).read_bytes()
    full = url.rstrip("/") + "/predict_png" + (("?" + urllib.parse.urlencode(q)) if q else "")
    r = urllib.request.Request(full, data=bytes(raw), headers={"Content-Type": "application/octet-stream"})
    try:
        with urllib.request.urlopen(r, timeout=timeout) as resp:
            return resp.status, resp.read(), dict(resp.headers)
    except urllib.error.HTTPError as e:
        return e.code, e.read(), dict(e.headers)


def summarize(resp: Dict[str, Any]) -> Dict[str, Any]:
    """The response without base64 payloads."""
    out = {}
    for k, v in resp.items():
        if isinstance(v, dict) and "data" in v:
            out[k] = {kk: (f"<{len(vv)} base64 chars>" if kk == "data" else vv) for kk, vv in v.items()}
        else:
            out[k] = v
    return out


def main(argv: Optional[List[str]] = None) -> int:
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    src = ap.add_mutually_exclusive_group(required=True)
    src.add_argument("--sample", action="store_true", help="the shipped sample image")
    src.add_argument("--image", type=Path, help="an image file")
    src.add_argument("--video", nargs="+", help="frame image files in order, or one video file (needs PyAV / ffmpeg)")
    ap.add_argument("--f-px", type=float, help="focal length in pixels (default: EXIF, else the FOV estimate)")
    ap.add_argument("--no-exif", action="store_true", help="ignore the image's EXIF focal length")
    ap.add_argument("--format", dest="output_format", choices=["npy16", "npy32", "png16", "none"])
    ap.add_argument("--inverse-depth", action="store_true", help="also return the inverse depth")
    ap.add_argument("--png", action="store_true", help="POST /predict_png (raw file in, 16-bit PNG out)")
    ap.add_argument("--png-scale", type=float, help="uint16 per metre of the PNG (default 1000)")
    ap.add_argument("--mode", default="buffered", choices=["buffered", "clip", "unbuffered"], help="video mode")
    ap.add_argument("--stream-id", help="video: keep a buffered stream open under this id")
    ap.add_argument("--end", action="store_true", help="video: the last request of the stream")
    ap.add_argument("--max-frames", type=int, default=64, help="video file: frames to send (default 64)")
    ap.add_argument("--every", type=int, default=1, help="video file: keep every n-th frame")
    ap.add_argument("--out", type=Path, help="write the request JSON here (instead of / before sending)")
    ap.add_argument("--url", help="send it to this server")
    ap.add_argument("--save", type=Path, help="save the depth: .npy (from /predict, /predict_video) or .png")
    a = ap.parse_args(argv)
    use_exif = False if a.no_exif else None
    if a.png:
        if a.video or not a.url:
            ap.error("--png needs --image / --sample and --url")
        img = a.image or (SAMPLE_DIR / json.loads((SAMPLE_DIR / "sample.json").read_text())["file"])
        code, body, headers = post_png(a.url, img, f_px=a.f_px, png_scale=a.png_scale, use_exif=use_exif)
        if code != 200:
            print(body.decode("utf-8", "replace"))
            return 1
        print(json.dumps({k: v for k, v in headers.items() if k.lower().startswith("x-")}, indent=1))
        if a.save:
            a.save.write_bytes(body)
        return 0
    if a.video:
        body = build_video_request(a.video, mode=a.mode, f_px=a.f_px, output_format=a.output_format,
                                   stream_id=a.stream_id, end=a.end, max_frames=a.max_frames, every=a.every)
        route = "/predict_video"
    else:
        kw = dict(f_px=a.f_px, output_format=a.output_format, include_inverse_depth=a.inverse_depth,
                  use_exif=use_exif)
        body = sample_request(**kw) if a.sample else build_request(a.image, **kw)
        route = "/predict"
    if a.out:
        a.out.write_text(json.dumps(body))
    if a.url:
        code, resp = post_json(a.url, route, body)
        print(json.dumps(summarize(resp), indent=1))
        if code == 200 and a.save and isinstance(resp.get("depth"), dict):
            a.save.write_bytes(base64.b64decode(resp["depth"]["data"]))
        return 0 if code == 200 else 1
    if not a.out:
        print(json.dumps(body))
    return 0


if __name__ == "__main__":
    sys.exit(main())