File size: 9,834 Bytes
532466c 3e1a674 532466c 8e53f1d 532466c 3e1a674 532466c 8e53f1d 532466c 1003449 532466c 1003449 8e53f1d 532466c 8e53f1d 532466c | 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 | """Bundle encoding, mask compression, and manifest packaging utilities."""
from __future__ import annotations
import base64
import io
import json
import zipfile
import cv2
import numpy as np
from PIL import Image
from config.paths import JOB_DIR
from config.runtime import BUNDLE_IMAGE_FORMAT, BUNDLE_IMAGE_QUALITY
from state import OCCLUDER_CLASSES, class_ids
from utils import seg_class_mask
# ---------------------------------------------------------------------------
# Image encoding helpers
# ---------------------------------------------------------------------------
def encode_bundle_image_data_url(img_np: np.ndarray) -> str:
image_format = BUNDLE_IMAGE_FORMAT
if image_format in {"jpg", "jpeg"}:
pil_format = "JPEG"
mime_type = "image/jpeg"
extension = "jpg"
elif image_format == "webp":
pil_format = "WEBP"
mime_type = "image/webp"
extension = "webp"
else:
pil_format = "JPEG"
mime_type = "image/jpeg"
extension = "jpg"
image = Image.fromarray(img_np.astype(np.uint8))
buffer = io.BytesIO()
try:
save_kwargs = {
"quality": int(np.clip(BUNDLE_IMAGE_QUALITY, 1, 100)),
"optimize": True,
}
if pil_format == "WEBP":
save_kwargs["method"] = 4
image.save(buffer, format=pil_format, **save_kwargs)
except Exception as exc:
print(f"Bundle {extension} encoding failed ({exc}); falling back to JPEG.", flush=True)
buffer = io.BytesIO()
image.save(buffer, format="JPEG", quality=92, optimize=True)
mime_type = "image/jpeg"
encoded = base64.b64encode(buffer.getvalue()).decode()
return f"data:{mime_type};base64,{encoded}"
def data_url_to_bytes(value: str) -> tuple[str, bytes]:
if value.startswith("data:"):
header, encoded = value.split(",", 1)
mime_type = header[5:].split(";", 1)[0] or "application/octet-stream"
return mime_type, base64.b64decode(encoded)
return "application/octet-stream", base64.b64decode(value)
def bundle_image_extension(mime_type: str) -> str:
if mime_type == "image/webp":
return "webp"
if mime_type == "image/png":
return "png"
return "jpg"
# ---------------------------------------------------------------------------
# Binary reference / mask helpers
# ---------------------------------------------------------------------------
def make_binary_ref(path: str, data: bytes, dtype: str) -> dict:
return {
"path": path,
"dtype": dtype,
"byteLength": len(data),
}
def encode_surface_uv_asset(value) -> tuple[bytes, dict]:
"""Quantize smooth metric UV pairs and delta-code them for HTTP gzip."""
if isinstance(value, np.ndarray):
surface_uv = np.asarray(value, dtype=np.float32).reshape(-1)
elif isinstance(value, str):
surface_uv = np.frombuffer(base64.b64decode(value), dtype=np.float32)
else:
surface_uv = np.frombuffer(bytes(value), dtype=np.float32)
if surface_uv.size == 0 or surface_uv.size % 2:
data = surface_uv.astype("<f4", copy=False).tobytes()
return data, {"dtype": "float32"}
uv_pairs = surface_uv.reshape(-1, 2)
valid_pairs = np.isfinite(uv_pairs).all(axis=1)
if not valid_pairs.any():
data = surface_uv.astype("<f4", copy=False).tobytes()
return data, {"dtype": "float32"}
finite_uv = uv_pairs[valid_pairs]
uv_offset = finite_uv.min(axis=0).astype(np.float64)
uv_max = finite_uv.max(axis=0).astype(np.float64)
# Reserve 65535/65535 as the invalid-UV sentinel.
uv_scale = (uv_max - uv_offset) / 65534.0
safe_scale = np.where(uv_scale > 0, uv_scale, 1.0)
quantized = np.full(uv_pairs.shape, 65535, dtype=np.uint16)
finite_quantized = np.rint((finite_uv - uv_offset) / safe_scale)
quantized[valid_pairs] = np.clip(finite_quantized, 0, 65534).astype(np.uint16)
delta = np.empty_like(quantized)
if len(quantized):
delta[0] = quantized[0]
if len(quantized) > 1:
difference = quantized[1:].astype(np.int32) - quantized[:-1].astype(np.int32)
delta[1:] = np.bitwise_and(difference, 0xFFFF).astype(np.uint16)
data = delta.astype("<u2", copy=False).tobytes()
return data, {
"dtype": "uint16",
"encoding": "delta-quantized-uv-v1",
"elementCount": int(surface_uv.size),
"uvOffset": [float(uv_offset[0]), float(uv_offset[1])],
"uvScale": [float(uv_scale[0]), float(uv_scale[1])],
}
def encode_mask_bitset(mask_bytes: bytes, pixel_count: int) -> bytes:
"""Encode uint32 pixel indices as an exact, least-significant-bit-first bitset."""
indices = np.frombuffer(mask_bytes, dtype=np.uint32)
if indices.size and int(indices.max()) >= pixel_count:
raise ValueError("Mask contains a pixel index outside the source image.")
bits = np.zeros(pixel_count, dtype=np.uint8)
bits[indices] = 1
return np.packbits(bits, bitorder="little").tobytes()
def foreground_occlusion_mask(surface_mask: np.ndarray, seg_map: np.ndarray) -> np.ndarray:
h, w = surface_mask.shape[:2]
kern_size = max(5, min(h, w) // 180) | 1
kern = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (kern_size, kern_size))
occluder_mask = seg_class_mask(seg_map, class_ids(OCCLUDER_CLASSES))
if not occluder_mask.any() or not surface_mask.any():
return np.zeros((h, w), dtype=np.uint8)
near_surface = cv2.dilate(surface_mask.astype(np.uint8), kern, iterations=5)
return ((occluder_mask > 0) & (near_surface > 0)).astype(np.uint8)
# ---------------------------------------------------------------------------
# Manifest / zip bundle
# ---------------------------------------------------------------------------
def build_manifest_segmentation_bundle(
bundle: dict,
job_id: str,
*,
image_url: str | None = None,
include_image: bool = False,
) -> bytes:
metadata = dict(bundle)
metadata["format"] = "baetes-vizbundle"
metadata["bundleVersion"] = 3
metadata["encoding"] = "zip-store"
metadata["assetBaseUrl"] = f"/viz2d/jobs/{job_id}/assets/"
metadata["pixels"] = None
if image_url:
metadata["imageUrl"] = image_url
metadata["segments"] = []
asset_dir = JOB_DIR / f"{job_id}.assets"
asset_dir.mkdir(parents=True, exist_ok=True)
buffer = io.BytesIO()
with zipfile.ZipFile(buffer, "w", compression=zipfile.ZIP_STORED) as archive:
if include_image:
pixels_mime, pixels = data_url_to_bytes(bundle["pixels"])
image_path = f"image.{bundle_image_extension(pixels_mime)}"
archive.writestr(image_path, pixels)
metadata["pixels"] = {
"path": image_path,
"mimeType": pixels_mime,
"byteLength": len(pixels),
}
lazy_asset_fields = {
"surfacePlaneIds": ("surface-plane-ids.u8", "uint8"),
"shadeMap": ("shade.u8", "uint8"),
"showroomShadeMap": ("showroom-shade.u8", "uint8"),
"reflectionMap": ("reflection.u8", "uint8"),
}
for segment_index, segment in enumerate(bundle.get("segments", [])):
segment_metadata = dict(segment)
pixel_count = int(metadata["width"]) * int(metadata["height"])
for mask_field in ("mask", "occlusionMask"):
mask_value = segment.get(mask_field)
if mask_value:
mask_bytes = base64.b64decode(mask_value)
mask_bitset = encode_mask_bitset(mask_bytes, pixel_count)
mask_path = f"segments/{segment_index}/{mask_field}.bitset"
archive.writestr(mask_path, mask_bitset)
segment_metadata[mask_field] = {
**make_binary_ref(mask_path, mask_bitset, "bitset"),
"encoding": "bitset-lsb0",
"pixelCount": pixel_count,
}
print(
f"[BUNDLE] Compressed {mask_field} for job {job_id}: "
f"{len(mask_bytes)} -> {len(mask_bitset)} bytes",
flush=True,
)
surface_uv = segment.get("surfaceUv")
if surface_uv is not None:
data, encoding_metadata = encode_surface_uv_asset(surface_uv)
extension = "u16" if encoding_metadata["dtype"] == "uint16" else "f32"
asset_path = f"segments/{segment_index}/surface-uv.{extension}"
archive.writestr(asset_path, data)
segment_metadata["surfaceUv"] = {
**make_binary_ref(asset_path, data, encoding_metadata["dtype"]),
**encoding_metadata,
}
for field, (filename, dtype) in lazy_asset_fields.items():
value = segment.get(field)
if value is None:
continue
# Accept both raw numpy arrays and base64-encoded strings
if isinstance(value, np.ndarray):
data = value.tobytes()
elif isinstance(value, str):
data = base64.b64decode(value)
else:
data = bytes(value)
asset_path = f"segments/{segment_index}/{filename}"
archive.writestr(asset_path, data)
segment_metadata[field] = {
**make_binary_ref(asset_path, data, dtype),
}
metadata["segments"].append(segment_metadata)
archive.writestr(
"metadata.json",
json.dumps(metadata, separators=(",", ":")).encode("utf-8"),
)
return buffer.getvalue()
|