"""Self-contained fast-v2 photo preprocessing for the v19 regressor. The public inference route is: EXIF-normalized photo -> one 448 px SegFormer pass -> 224 px water mask -> lower-water crop mapped to source coordinates -> masked 224x224 JPEG (quality 95, 4:4:4) -> ImageNet-normalized tensor. This is the coordinate-crop pipeline used to create v19 training inputs. """ from __future__ import annotations import io import math import time from dataclasses import dataclass from pathlib import Path import cv2 import numpy as np import torch from PIL import Image, ImageOps SEGMENTATION_MODEL_NAME = "nvidia/segformer-b2-finetuned-ade-512-512" SEGMENTATION_MODEL_REVISION = "de01bae28967510f9ddd496c60a969357195400c" SEGMENTATION_RESOLUTION = 448 WATER_CLASS_NAMES = {"water", "sea", "river", "lake"} OUTPUT_SIZE = (224, 224) IMAGENET_MEAN = (0.485, 0.456, 0.406) IMAGENET_STD = (0.229, 0.224, 0.225) LOWER_WATER_FRACTION = 0.35 MINIMUM_LOWER_RETENTION = 0.95 BLACK_RATIO_BUCKET = 0.005 MINIMUM_WATER_FRACTION = 0.0005 MINIMUM_CROP_AREA_FRACTION = 0.10 MINIMUM_CROP_WIDTH = 8 SUPPORTED_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".bmp", ".tif", ".tiff", ".heic", ".heif"} class PreprocessingError(RuntimeError): """Raised when a photo cannot be converted into a valid model input.""" def load_rgb_image(path: str | Path) -> Image.Image: """Load an image as RGB and apply its EXIF orientation (including iPhone HEIC).""" path = Path(path) if not path.is_file(): raise FileNotFoundError(f"Image not found: {path}") if path.suffix.lower() in {".heic", ".heif"}: try: from pillow_heif import register_heif_opener except ImportError as error: raise ImportError("HEIC/HEIF input requires pillow-heif; install requirements.txt") from error register_heif_opener() with Image.open(path) as opened: return ImageOps.exif_transpose(opened).convert("RGB") def encode_jpeg(image: Image.Image) -> bytes: """Encode the final training input using the fast-v2 JPEG settings.""" buffer = io.BytesIO() image.save(buffer, format="JPEG", quality=95, subsampling=0) return buffer.getvalue() def decode_image(encoded: bytes) -> Image.Image: with Image.open(io.BytesIO(encoded)) as decoded: return decoded.convert("RGB") @dataclass class WaterSegmenter: model: torch.nn.Module processor: object water_class_ids: tuple[int, ...] device: torch.device def load_segmenter(device: str | torch.device = "cpu") -> WaterSegmenter: """Load the exact pinned segmentation model used by the v19 training pipeline.""" try: from transformers import SegformerForSemanticSegmentation, SegformerImageProcessor except ImportError as error: raise ImportError("Water segmentation requires transformers; install requirements.txt") from error from transformers.utils import logging as transformers_logging transformers_logging.disable_progress_bar() device = torch.device(device) try: processor = SegformerImageProcessor.from_pretrained( SEGMENTATION_MODEL_NAME, revision=SEGMENTATION_MODEL_REVISION, size={"height": SEGMENTATION_RESOLUTION, "width": SEGMENTATION_RESOLUTION}, do_resize=True, ) model = SegformerForSemanticSegmentation.from_pretrained( SEGMENTATION_MODEL_NAME, revision=SEGMENTATION_MODEL_REVISION ) except OSError as error: raise RuntimeError( f"Could not load {SEGMENTATION_MODEL_NAME} at revision {SEGMENTATION_MODEL_REVISION}. " "Check network access or download the model with: " f"hf download {SEGMENTATION_MODEL_NAME} --revision {SEGMENTATION_MODEL_REVISION}" ) from error model.to(device).eval() id2label = {int(key): value.lower().strip() for key, value in model.config.id2label.items()} class_ids = tuple(index for index, name in id2label.items() if name in WATER_CLASS_NAMES) if not class_ids: raise RuntimeError(f"No water labels found in {SEGMENTATION_MODEL_NAME}") return WaterSegmenter(model, processor, class_ids, device) @torch.inference_mode() def segment_water_mask(image: Image.Image, segmenter: WaterSegmenter) -> np.ndarray: """Run one 448x448 segmentation pass and return the water classes at 448 px.""" started = time.perf_counter() inputs = segmenter.processor(images=image.convert("RGB"), return_tensors="pt") inputs = {name: tensor.to(segmenter.device) for name, tensor in inputs.items()} use_fp16 = segmenter.device.type == "cuda" context = torch.autocast(device_type="cuda", dtype=torch.float16) if use_fp16 else torch.autocast( device_type="cpu", enabled=False ) try: with context: logits = segmenter.model(**inputs).logits target_size = ( (image.height, image.width) if max(image.size) <= SEGMENTATION_RESOLUTION else (SEGMENTATION_RESOLUTION, SEGMENTATION_RESOLUTION) ) logits = torch.nn.functional.interpolate(logits, size=target_size, mode="bilinear", align_corners=False) except RuntimeError as error: retryable = any(word in str(error).lower() for word in ("out of memory", "engine to execute")) if segmenter.device.type != "cuda" or not retryable: raise print(f"CUDA segmentation failed ({error}); retrying this image on CPU.", flush=True) segmenter.device = torch.device("cpu") segmenter.model.to(segmenter.device) return segment_water_mask(image, segmenter) class_map = logits.argmax(dim=1)[0].to(device="cpu", dtype=torch.uint8).numpy() if class_map.shape != (SEGMENTATION_RESOLUTION, SEGMENTATION_RESOLUTION): class_map = np.asarray( Image.fromarray(class_map).resize( (SEGMENTATION_RESOLUTION, SEGMENTATION_RESOLUTION), Image.Resampling.NEAREST ), dtype=np.uint8, ) water = np.isin(class_map, segmenter.water_class_ids) print( f"Segmentation: one {SEGMENTATION_RESOLUTION}x{SEGMENTATION_RESOLUTION} pass " f"on {segmenter.device}, {time.perf_counter() - started:.3f}s", flush=True, ) return water def _summed_area(mask: np.ndarray) -> np.ndarray: return np.pad(mask.astype(np.int64), ((1, 0), (1, 0))).cumsum(0).cumsum(1) def _rect_sum(table: np.ndarray, left: int, top: int, right: int, bottom: int) -> int: return int(table[bottom, right] - table[top, right] - table[bottom, left] + table[top, left]) def _resized_content_size(width: int, height: int) -> tuple[int, int]: scale = min(224 / width, 224 / height) return max(1, round(width * scale)), max(1, round(height * scale)) def select_lower_water_crop(water_mask: np.ndarray) -> tuple[int, int, int, int] | None: """Select the fast-v2 bottom-anchored crop on the 224x224 water mask. This is the same lexicographic selector used during training. The black mask is all false for fast-v2 because the crop is selected on the raw source-photo mask before the final canvas is built. """ water_mask = np.ascontiguousarray(water_mask, dtype=bool) ys, xs = np.where(water_mask) if not len(xs): return None height, width = water_mask.shape left_bound, top_bound = int(xs.min()), int(ys.min()) right_bound, bottom_bound = int(xs.max()) + 1, int(ys.max()) + 1 bbox_width, bbox_height = right_bound - left_bound, bottom_bound - top_bound minimum_water_pixels = max(32, round(width * height * MINIMUM_WATER_FRACTION)) if int(water_mask.sum()) < minimum_water_pixels: return None lower_top = max(top_bound, bottom_bound - max(1, round(bbox_height * LOWER_WATER_FRACTION))) lower_total = int(water_mask[lower_top:bottom_bound].sum()) if lower_total < minimum_water_pixels: return None horizontal_step = max(1, round(width / 56.0)) boundaries = sorted(set(range(left_bound, right_bound + 1, horizontal_step)) | {right_bound}) water_table = _summed_area(water_mask) lower_table = _summed_area(water_mask & (np.arange(height)[:, None] >= lower_top)) minimum_area = max(256, round(bbox_width * bbox_height * MINIMUM_CROP_AREA_FRACTION)) best_key = None best_box = None for left_index, left in enumerate(boundaries[:-1]): for right in boundaries[left_index + 1:]: crop_width = right - left if crop_width < MINIMUM_CROP_WIDTH: continue lower_in_view = _rect_sum(lower_table, left, lower_top, right, bottom_bound) if lower_in_view < minimum_water_pixels: continue for top in range(top_bound, lower_top + 1): crop_height = bottom_bound - top crop_area = crop_width * crop_height if crop_height < 8 or crop_area < minimum_area: continue retention = _rect_sum(lower_table, left, top, right, bottom_bound) / lower_in_view if retention + 1e-12 < MINIMUM_LOWER_RETENTION: continue water_pixels = _rect_sum(water_table, left, top, right, bottom_bound) resized_width, resized_height = _resized_content_size(crop_width, crop_height) occupied = resized_width * resized_height / float(224 * 224) water_ratio = (water_pixels / crop_area) * occupied # Black pixels are zero for this source-coordinate profile. black_ratio = 1.0 - occupied tier = 3 if retention >= 0.995 else 2 if retention >= 0.98 else 1 bucket = int(np.rint(black_ratio / BLACK_RATIO_BUCKET)) key = (-tier, bucket, -water_pixels, -water_ratio, abs(math.log(crop_width / crop_height)), left, top, right) if best_key is None or key < best_key: best_key, best_box = key, (left, top, right, bottom_bound) return best_box def preprocess_photo_encoded( image: Image.Image, segmenter: WaterSegmenter, diagnostic_dir: str | Path | None = None, ) -> bytes: """Return the exact final 224x224 JPEG input format used for v19 training.""" started = time.perf_counter() source = np.asarray(image.convert("RGB"), dtype=np.uint8) water_448 = segment_water_mask(image, segmenter) output_dir = Path(diagnostic_dir) if diagnostic_dir is not None else None if output_dir is not None: output_dir.mkdir(parents=True, exist_ok=True) Image.fromarray(water_448.astype(np.uint8) * 255, mode="L").save(output_dir / "water-mask-448.png") water_224 = cv2.resize( water_448.astype(np.uint8), (224, 224), interpolation=cv2.INTER_NEAREST_EXACT ).astype(bool) if output_dir is not None: Image.fromarray(water_224.astype(np.uint8) * 255, mode="L").save(output_dir / "selector-mask-224.png") selected = select_lower_water_crop(water_224) if selected is None: raise PreprocessingError("No reliable lower-water crop could be selected from this photo.") left, top, right, bottom = selected source_height, source_width = source.shape[:2] x0 = max(0, min(source_width, int(np.floor(left * source_width / 224)))) x1 = max(x0 + 1, min(source_width, int(np.ceil(right * source_width / 224)))) y0 = max(0, min(source_height, int(np.floor(top * source_height / 224)))) y1 = max(y0 + 1, min(source_height, int(np.ceil(bottom * source_height / 224)))) source_roi = source[y0:y1, x0:x1] mask_roi = water_224[top:bottom, left:right] if output_dir is not None: Image.fromarray(source_roi, mode="RGB").save(output_dir / "selected-source-region.jpg", quality=95) scale = min(224 / source_roi.shape[1], 224 / source_roi.shape[0]) resized_width = max(1, min(224, round(source_roi.shape[1] * scale))) resized_height = max(1, min(224, round(source_roi.shape[0] * scale))) offset_x, offset_y = (224 - resized_width) // 2, (224 - resized_height) // 2 canvas = np.zeros((224, 224, 3), dtype=np.uint8) canvas_roi = canvas[offset_y:offset_y + resized_height, offset_x:offset_x + resized_width] cv2.resize(source_roi, (resized_width, resized_height), dst=canvas_roi, interpolation=cv2.INTER_LANCZOS4) final_mask = cv2.resize( mask_roi.astype(np.uint8), (resized_width, resized_height), interpolation=cv2.INTER_NEAREST_EXACT ) canvas_roi[final_mask == 0] = 0 result = Image.fromarray(canvas, mode="RGB") encoded = encode_jpeg(result) if output_dir is not None: (output_dir / "final-model-input.jpg").write_bytes(encoded) print( f"Lower-water crop: mask_box={selected}, source_box=({x0},{y0},{x1},{y1}), " f"complete in {time.perf_counter() - started:.3f}s", flush=True, ) return encoded def to_model_tensor(model_input: Image.Image) -> torch.Tensor: """Convert the decoded 224 px JPEG input to ImageNet-normalized NCHW float32.""" if model_input.mode != "RGB" or model_input.size != OUTPUT_SIZE: raise PreprocessingError(f"Expected RGB {OUTPUT_SIZE[0]}x{OUTPUT_SIZE[1]} model input") pixels = torch.from_numpy(np.asarray(model_input, dtype=np.uint8).copy()).permute(2, 0, 1).float() / 255.0 mean = torch.tensor(IMAGENET_MEAN, dtype=torch.float32)[:, None, None] std = torch.tensor(IMAGENET_STD, dtype=torch.float32)[:, None, None] return ((pixels - mean) / std).unsqueeze(0)