Spaces:
Paused
Paused
Download apps/renderer/services/enhance/lighting.py from modventures/prevision: direct link, hf CLI and curl.
- Browser
- Download file 8.87 kB
-
https://huggingface.co/spaces/modventures/prevision/resolve/main/apps/renderer/services/enhance/lighting.py
- Command line
-
hf download hf://spaces/modventures/prevision/apps/renderer/services/enhance/lighting.py
-
curl -L -o lighting.py https://huggingface.co/spaces/modventures/prevision/resolve/main/apps/renderer/services/enhance/lighting.py
8.87 kB
| """Lighting from the AI's answer, as smooth and clamped gain fields per wall. | |
| The AI relit the corrected preview. Per layer and per mapping plane (so light | |
| never leaks between walls or across a corner), the brightness ratio between its | |
| answer and the preview is measured and turned into: | |
| - a level per wall (how much brighter or darker the wall reads overall), clamped, | |
| - a spatial light field around that level (falloff, sunbeams, cast shadows, darker | |
| corners), blurred below the scale of the print and clamped; if it follows the | |
| print it falls back to a much coarser blur, | |
| - a darkening-only contact term near the layer's edges (soft shadows at the ceiling, | |
| corners, skirting and furniture), | |
| - one constant tint for the light's colour. | |
| Pixels where the answer's fine structure differs from the preview (it redrew | |
| something) barely count. A term that follows the wallpaper's own pattern is | |
| dropped, and a field that swings wildly leaves that wall unchanged. The pattern | |
| itself is never taken from the answer: the gain only scales our own layer. | |
| """ | |
| from __future__ import annotations | |
| import math | |
| from dataclasses import dataclass | |
| import cv2 | |
| import numpy as np | |
| from services.enhance.composite import LUMA, to_linear | |
| WORK_SIDE = 512 | |
| COARSE_SIGMA = 0.04 # of the image height: the fallback when the light field follows the print | |
| LIGHT_SIGMA = 0.015 | |
| FINE_SIGMA = 0.012 | |
| MIN_FINE_SIGMA_PX = 2.0 | |
| CONTACT_BAND = 0.03 | |
| EXPOSURE_SIGMA = 0.2 # of the image height | |
| MIN_LEVEL, MAX_LEVEL = 0.50, 1.25 # a wall's overall brightness change | |
| MIN_LIGHT, MAX_LIGHT = 0.55, 1.70 # the light field around that level (shade .. sunbeam) | |
| MIN_GAIN, MAX_GAIN = 0.35, 1.80 # everything together | |
| MIN_CONTACT = 0.75 | |
| MAX_TINT = 0.10 | |
| CHANGE_TOLERANCE = 0.15 # log-luminance high-pass difference treated as "redrawn" | |
| MAX_PATTERN_CORRELATION = 0.2 | |
| MAX_COARSE_STD = 0.45 | |
| EPS = 0.01 | |
| class LayerLighting: | |
| gain: np.ndarray # float32 (H, W) multiplier, 1 = unchanged | |
| tint: np.ndarray # float32 (3,) | |
| status: str # "applied" | "unchanged" | |
| stats: dict | |
| def _masked_blur(values: np.ndarray, weight: np.ndarray, sigma: float) -> tuple[np.ndarray, np.ndarray]: | |
| w = cv2.GaussianBlur(weight, (0, 0), sigma) | |
| return cv2.GaussianBlur(values * weight, (0, 0), sigma) / np.maximum(w, 1e-6), w | |
| def _high_pass(log_luma: np.ndarray) -> np.ndarray: | |
| return log_luma - cv2.GaussianBlur(log_luma, (0, 0), 2.0) | |
| def _correlation(a: np.ndarray, b: np.ndarray) -> float: | |
| a = a - a.mean() | |
| b = b - b.mean() | |
| denominator = math.sqrt(float((a * a).sum()) * float((b * b).sum())) | |
| return float((a * b).sum()) / denominator if denominator > 1e-9 else 0.0 | |
| def estimate_lighting( | |
| preview: np.ndarray, answer: np.ndarray, layer_rgb: np.ndarray, alpha: np.ndarray, planes: np.ndarray, | |
| outside: np.ndarray | None = None, | |
| ) -> LayerLighting: | |
| """`outside`: pixels the result keeps from the photo; the answer's overall exposure change | |
| there is divided out, so a globally brighter or darker answer does not relight only the walls.""" | |
| height, width = preview.shape[:2] | |
| scale = min(1.0, WORK_SIDE / max(height, width)) | |
| size = (max(16, round(width * scale)), max(16, round(height * scale))) | |
| small_h = size[1] | |
| def small(image: np.ndarray, interpolation=cv2.INTER_AREA) -> np.ndarray: | |
| return cv2.resize(image, size, interpolation=interpolation) | |
| y_preview = np.log(small(to_linear(preview)) @ LUMA + EPS) | |
| y_answer = np.log(small(to_linear(answer)) @ LUMA + EPS) | |
| y_layer = np.log(small(to_linear(layer_rgb)) @ LUMA + EPS) | |
| region_all = small((alpha > 0.5).astype(np.float32)) > 0.75 | |
| plane_ids = small(planes, cv2.INTER_NEAREST) | |
| ratio = y_answer - y_preview | |
| trust = np.exp(-(((_high_pass(y_answer) - _high_pass(y_preview)) / CHANGE_TOLERANCE) ** 2)).astype(np.float32) | |
| exposure = np.zeros_like(ratio) | |
| if outside is not None: | |
| # What the answer did to the room around each wall, which the result keeps as photographed: | |
| # that change is the AI's, not the wall's, and is divided out (smoothly, so a half-darker | |
| # answer is handled per side, falling back to the overall median far from any reference). | |
| reference = ((small(outside.astype(np.float32)) > 0.9) & (trust > 0.5)).astype(np.float32) | |
| if reference.sum() > 0.02 * reference.size: | |
| overall = float(np.median(ratio[reference > 0])) | |
| local, local_weight = _masked_blur(ratio.astype(np.float32), reference, EXPOSURE_SIGMA * small_h) | |
| blend = np.clip(local_weight / 0.05, 0.0, 1.0) | |
| exposure = (blend * local + (1.0 - blend) * overall).astype(np.float32) | |
| ratio = ratio - exposure | |
| log_gain = np.zeros(region_all.shape, np.float32) | |
| unchanged = np.ones(region_all.shape, bool) | |
| statuses = [] | |
| for plane in np.unique(plane_ids[region_all]): | |
| region = region_all & (plane_ids == plane) | |
| if region.sum() < 64: | |
| continue | |
| weight = region.astype(np.float32) * trust | |
| if float(weight.sum()) < 0.05 * float(region.sum()): | |
| statuses.append("unchanged") | |
| continue | |
| level = float(np.clip(_weighted_median(ratio[region], weight[region]), math.log(MIN_LEVEL), math.log(MAX_LEVEL))) | |
| light, coarse_weight = _masked_blur(ratio.astype(np.float32), weight, LIGHT_SIGMA * small_h) | |
| if region.sum() > 256 and abs(_correlation(_high_pass(light)[region], _high_pass(y_layer)[region])) > MAX_PATTERN_CORRELATION: | |
| light, coarse_weight = _masked_blur(ratio.astype(np.float32), weight, COARSE_SIGMA * small_h) | |
| coarse = level + np.clip(light - level, math.log(MIN_LIGHT), math.log(MAX_LIGHT)) | |
| if float(coarse[region].std()) > MAX_COARSE_STD or float(coarse_weight[region].mean()) < 0.05: | |
| statuses.append("unchanged") | |
| continue | |
| fine, _ = _masked_blur(ratio.astype(np.float32), weight, max(MIN_FINE_SIGMA_PX, FINE_SIGMA * small_h)) | |
| contact = np.minimum(fine - coarse, 0.0) | |
| distance = cv2.distanceTransform(region.astype(np.uint8), cv2.DIST_L2, 3) | |
| contact = np.where(distance <= CONTACT_BAND * small_h, contact, 0.0) | |
| contact = np.maximum(contact, math.log(MIN_CONTACT)) | |
| if region.sum() > 256 and abs(_correlation(_high_pass(contact)[region], _high_pass(y_layer)[region])) > MAX_PATTERN_CORRELATION: | |
| contact[:] = 0.0 # the "shadow" follows the print: the answer redrew the pattern | |
| log_gain[region] = (coarse + contact)[region] | |
| unchanged[region] = False | |
| statuses.append("applied") | |
| # The layer's soft edge pixels (alpha below 0.5) take the nearest measured values. | |
| measured = (region_all & ~unchanged).astype(np.float32) | |
| spread, spread_weight = _masked_blur(log_gain, measured, 2.0) | |
| log_gain = np.where(region_all, log_gain, np.where(spread_weight > 0.01, spread, 0.0)).astype(np.float32) | |
| gain = np.exp(cv2.resize(log_gain, (width, height), interpolation=cv2.INTER_CUBIC)).astype(np.float32) | |
| gain = np.clip(gain, MIN_GAIN * MIN_CONTACT, MAX_GAIN) | |
| tint = _tint(preview, answer, alpha) if "applied" in statuses else np.ones(3, np.float32) | |
| status = "applied" if "applied" in statuses else "unchanged" | |
| if status == "unchanged": | |
| gain[:] = 1.0 | |
| inside = gain[alpha > 0.5] | |
| stats = { | |
| "gainMin": round(float(inside.min()), 3) if inside.size else 1.0, | |
| "gainMax": round(float(inside.max()), 3) if inside.size else 1.0, | |
| "gainMean": round(float(inside.mean()), 3) if inside.size else 1.0, | |
| "tint": [round(float(v), 4) for v in tint], | |
| "planes": statuses, | |
| "exposureCorrection": round(float(np.exp(-np.median(exposure[region_all]))) if region_all.any() else 1.0, 3), | |
| } | |
| return LayerLighting(gain=gain, tint=tint, status=status, stats=stats) | |
| def _weighted_median(values: np.ndarray, weights: np.ndarray) -> float: | |
| order = np.argsort(values) | |
| cumulative = np.cumsum(weights[order]) | |
| return float(values[order][np.searchsorted(cumulative, cumulative[-1] / 2)]) | |
| def _tint(preview: np.ndarray, answer: np.ndarray, alpha: np.ndarray) -> np.ndarray: | |
| """The light's colour on the layer's pale, neutral pixels: one gentle per-channel factor.""" | |
| inside = alpha > 0.5 | |
| p = to_linear(preview[inside]) | |
| a = to_linear(answer[inside]) | |
| yp = p @ LUMA + EPS | |
| neutral = (p.max(axis=1) - p.min(axis=1)) < 0.15 * yp | |
| if neutral.sum() < 200: | |
| neutral = np.ones_like(neutral) | |
| chroma_p = (p[neutral] / yp[neutral, None]).mean(axis=0) | |
| ya = a @ LUMA + EPS | |
| chroma_a = (a[neutral] / ya[neutral, None]).mean(axis=0) | |
| tint = chroma_a / np.maximum(chroma_p, 1e-6) | |
| tint = tint / max(float(tint @ LUMA), 1e-6) # colour only, brightness stays the gain's | |
| return np.clip(tint, 1.0 - MAX_TINT, 1.0 + MAX_TINT).astype(np.float32) | |