File size: 3,818 Bytes
73828b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Side-car storage of the inputs refinement needs from a conversion job.

Refinement runs minutes after conversion, in a process where the depth model
has been unloaded to make room for SDXL, so nothing can be recomputed. Two
things therefore have to survive the conversion: the depth map, and one mask
per surface segment.

Neither is recoverable from the .vizbundle. Depth is never written to it at
all, and its masks are packed bitsets inside a ZIP that only the frontend
decodes. A small side-car file is far less work than a bundle reader, and it
keeps the bundle format free to change.

Depth is stored as uint16 rather than float32 because ControlNet only ever
sees a percentile-normalised 8-bit version of it -- absolute metres would be
thrown away one step later. Masks are bit-packed, which takes a 1920x1080
surface from 2 MB to 260 KB before compression.
"""

from __future__ import annotations

from pathlib import Path

import numpy as np

from config.paths import JOB_DIR

DEPTH_SCALE = 65535.0


def refine_assets_path(job_id: str) -> Path:
    return JOB_DIR / f"{job_id}.refine.npz"


def write_refine_assets(
    job_id: str,
    depth: np.ndarray | None,
    masks_by_id: dict[int, np.ndarray],
    width: int,
    height: int,
) -> Path | None:
    """Persist depth and surface masks for a later refinement request."""
    if not masks_by_id:
        return None

    payload: dict[str, np.ndarray] = {
        "shape": np.asarray([height, width], dtype=np.int32),
        "ids": np.asarray(sorted(masks_by_id), dtype=np.int32),
    }

    if depth is not None:
        finite = np.isfinite(depth)
        if finite.any():
            low = float(depth[finite].min())
            high = float(depth[finite].max())
            span = high - low if high > low else 1.0
            normalized = np.clip((np.nan_to_num(depth, nan=low) - low) / span, 0.0, 1.0)
            payload["depth"] = (normalized * DEPTH_SCALE).astype(np.uint16)

    for segment_id, mask in masks_by_id.items():
        payload[f"mask_{segment_id}"] = np.packbits((np.asarray(mask) > 0).ravel())

    path = refine_assets_path(job_id)
    with path.open("wb") as handle:
        np.savez_compressed(handle, **payload)
    return path


def read_refine_assets(job_id: str) -> dict | None:
    """Return {"depth": uint16 HxW or None, "masks": {id: uint8 HxW}} or None."""
    path = refine_assets_path(job_id)
    if not path.exists():
        return None

    with np.load(path) as data:
        height, width = (int(value) for value in data["shape"])
        pixel_count = height * width
        masks = {}
        for segment_id in data["ids"].tolist():
            key = f"mask_{segment_id}"
            if key not in data:
                continue
            bits = np.unpackbits(data[key])[:pixel_count]
            masks[int(segment_id)] = bits.reshape(height, width).astype(np.uint8)
        depth = data["depth"] if "depth" in data else None
        return {
            "depth": None if depth is None else np.asarray(depth),
            "masks": masks,
            "width": width,
            "height": height,
        }


def surface_masks_from_bundle(bundle: dict) -> dict[int, np.ndarray]:
    """Rebuild each segment's uint8 mask from the bundle's flat index arrays."""
    import base64

    width = int(bundle["width"])
    height = int(bundle["height"])
    masks: dict[int, np.ndarray] = {}

    for segment in bundle.get("segments") or []:
        encoded = segment.get("mask")
        if not encoded:
            continue
        indices = np.frombuffer(base64.b64decode(encoded), dtype=np.uint32)
        mask = np.zeros(width * height, dtype=np.uint8)
        inside = indices[indices < mask.size]
        mask[inside] = 1
        masks[int(segment["id"])] = mask.reshape(height, width)

    return masks