Spaces:
Paused
Paused
Download apps/renderer/services/pipeline/packaging.py from modventures/prevision: direct link, hf CLI and curl.
- Browser
- Download file 10 kB
-
https://huggingface.co/spaces/modventures/prevision/resolve/main/apps/renderer/services/pipeline/packaging.py
- Command line
-
hf download hf://spaces/modventures/prevision/apps/renderer/services/pipeline/packaging.py
-
curl -L -o packaging.py https://huggingface.co/spaces/modventures/prevision/resolve/main/apps/renderer/services/pipeline/packaging.py
10 kB
| """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) | |
| # The surface's own (anti-aliased) edge pixels are never hidden behind an occluder. | |
| return ((occluder_mask > 0) & (near_surface > 0) & (surface_mask == 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"), | |
| "edgeAlpha": ("edge-alpha.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() | |