Spaces:
Paused
Paused
File size: 10,709 Bytes
73828b3 630bc9b 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 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 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 | """Orchestrates a refinement request end to end.
Flow
----
The browser sends the frame it is displaying -- the WebGL composite with tiles
already projected -- plus which segments carry which material. The original
photograph, the depth map and the per-segment masks all come from the
conversion job that produced the bundle, so nothing about the room has to be
re-derived and nothing has to be trusted from the client except the pixels it
drew.
Work happens at a reduced processing resolution because SDXL is quadratic in
area, then the result is scaled back and composited onto the full-resolution
original. The final composite is what guarantees correctness: every pixel
outside the refined surfaces comes from the untouched original, and that is
asserted rather than assumed.
Passes run sequentially over one working image, each writing only inside its
own group's mask. Grouping upstream guarantees the masks are disjoint, so
order does not affect the result.
"""
from __future__ import annotations
import time
import numpy as np
from PIL import Image
from config.refine import (
REFINE_BLEND_MODE,
REFINE_MAX_DIMENSION,
REFINE_SEED,
REFINE_UNLOAD_CV_MODELS,
REFINE_USE_CAMERA_NOISE,
REFINE_USE_LIGHTING_TRANSFER,
REFINE_USE_MATERIAL_MICRODETAIL,
REFINE_USE_POST_SHADOW_RESTORE,
REFINE_USE_SHADOW_TRANSFER,
)
from models.loader import load_diffusion_pipeline, unload_cv_models
from services.refine.diffusion import (
describe_vram,
get_processing_size,
run_diffusion_pass,
)
from services.refine.grouping import group_surfaces_by_material
from services.refine.guide import apply_diffusion_as_realism_guide, recover_detail
from services.refine.masks import (
composite_surface_only,
make_binary_mask,
mask_coverage,
outside_mask_difference,
prepare_safe_diffusion_mask,
)
from services.refine.photometric import (
add_camera_noise,
apply_shadow_map,
enhance_material_microdetail,
extract_shadow_map,
prepare_depth,
transfer_original_lighting,
)
from services.refine.profiles import (
CAMERA_NOISE_SIGMA,
DIFFUSION_EDGE_GUARD,
LIGHTING_BLUR_SIGMA,
LIGHTING_TRANSFER_STRENGTH,
POST_SHADOW_BLUR_SIGMA,
POST_SHADOW_TRANSFER_STRENGTH,
SHADOW_BLUR_SIGMA,
SHADOW_TRANSFER_STRENGTH,
build_prompts,
)
class RefinementError(RuntimeError):
"""A refinement request could not be completed."""
def _resize_mask(mask: np.ndarray, size: tuple[int, int]) -> Image.Image:
"""Nearest-neighbour so the mask stays hard through the downscale."""
return make_binary_mask(mask).resize(size, Image.Resampling.NEAREST)
def refine_composite(
composite_full: Image.Image,
original_full: Image.Image,
depth_full: Image.Image | None,
masks_by_id: dict[int, np.ndarray],
surfaces: list[dict],
progress_callback=None,
) -> tuple[Image.Image, dict]:
"""Return (refined image at original resolution, metadata)."""
started = time.perf_counter()
groups = group_surfaces_by_material(surfaces, masks_by_id)
if not groups:
raise RefinementError(
"No refinable surfaces. Check that the requested segment ids exist in this job."
)
final_width, final_height = original_full.size
if composite_full.size != original_full.size:
composite_full = composite_full.resize(original_full.size, Image.Resampling.LANCZOS)
def report(fraction: float, message: str):
if progress_callback:
progress_callback(max(0.0, min(1.0, fraction)) * 100.0, message)
report(0.02, "Preparing surfaces…")
# Confirm the pipeline can be imported before freeing anything. Unloading
# first and failing second would leave the GPU empty and the next
# conversion paying a reload for no benefit.
try:
import diffusers # noqa: F401
except ImportError as exc:
raise RefinementError(
"The diffusers package is not installed, so refinement cannot run. "
"Install the GPU requirements."
) from exc
if REFINE_UNLOAD_CV_MODELS:
unload_cv_models()
report(0.05, "Loading refinement model (the first run may take a few minutes)…")
pipe = load_diffusion_pipeline()
print(describe_vram("after model load"), flush=True)
width, height = get_processing_size(final_width, final_height, REFINE_MAX_DIMENSION)
print(
f"[REFINE] {final_width}x{final_height} -> processing at {width}x{height}, "
f"{len(groups)} pass(es), blend={REFINE_BLEND_MODE}",
flush=True,
)
original = original_full.resize((width, height), Image.Resampling.LANCZOS)
working = composite_full.resize((width, height), Image.Resampling.LANCZOS)
if depth_full is None:
raise RefinementError(
"This job has no stored depth map, so ControlNet cannot be conditioned. "
"Re-run the conversion to produce one."
)
depth_image = prepare_depth(depth_full.resize((width, height), Image.Resampling.BILINEAR))
pass_metadata = []
for index, group in enumerate(groups):
base_fraction = 0.10 + 0.85 * (index / len(groups))
span = 0.85 / len(groups)
material = group["materialType"]
kind = group["surfaceKind"]
report(base_fraction, f"Refining {kind} ({material})…")
mask = _resize_mask(group["mask"], (width, height))
if not np.asarray(mask).any():
pass_metadata.append({
"materialType": material, "surfaceKind": kind,
"skipped": True, "reason": "mask-empty-at-processing-resolution",
})
continue
prompt, negative_prompt, profile = build_prompts(
material, kind, group.get("materialDescription", ""),
)
pass_started = time.perf_counter()
before_diffusion = working
if REFINE_USE_LIGHTING_TRANSFER:
before_diffusion = transfer_original_lighting(
original, before_diffusion, mask,
sigma=LIGHTING_BLUR_SIGMA, strength=LIGHTING_TRANSFER_STRENGTH,
)
if REFINE_USE_SHADOW_TRANSFER:
shadow_map = extract_shadow_map(
original, mask,
blur_sigma=SHADOW_BLUR_SIGMA, strength=SHADOW_TRANSFER_STRENGTH,
)
before_diffusion = apply_shadow_map(before_diffusion, mask, shadow_map)
if REFINE_USE_MATERIAL_MICRODETAIL:
before_diffusion = enhance_material_microdetail(
before_diffusion, mask, profile["microdetail"], profile["local_contrast"],
)
safe_mask = prepare_safe_diffusion_mask(mask, DIFFUSION_EDGE_GUARD)
coverage = mask_coverage(safe_mask, mask)
if not np.asarray(safe_mask).any():
# Every pixel sits within the edge guard, so there is nothing SDXL
# may safely touch. The photometric work above still stands.
working = composite_surface_only(working, before_diffusion, mask)
pass_metadata.append({
"materialType": material, "surfaceKind": kind,
"skipped": True, "reason": "surface-thinner-than-edge-guard",
"pixels": group["pixels"],
})
continue
report(base_fraction + span * 0.35, f"Generating {kind} material…")
generated = run_diffusion_pass(
pipe,
image=before_diffusion,
mask_image=safe_mask,
depth_image=depth_image,
prompt=prompt,
negative_prompt=negative_prompt,
profile=profile,
width=width,
height=height,
seed=REFINE_SEED,
)
report(base_fraction + span * 0.85, f"Blending {kind}…")
if REFINE_BLEND_MODE == "realism-guide":
blended = apply_diffusion_as_realism_guide(
before_diffusion, generated, mask, edge_guard=DIFFUSION_EDGE_GUARD,
)
else:
blended = recover_detail(generated, before_diffusion, material)
working = composite_surface_only(before_diffusion, blended, mask)
if REFINE_USE_POST_SHADOW_RESTORE:
working = apply_shadow_map(
working, mask,
extract_shadow_map(
original, mask,
blur_sigma=POST_SHADOW_BLUR_SIGMA,
strength=POST_SHADOW_TRANSFER_STRENGTH,
),
)
if REFINE_USE_CAMERA_NOISE:
working = add_camera_noise(working, mask, CAMERA_NOISE_SIGMA, REFINE_SEED)
pass_metadata.append({
"materialType": material,
"surfaceKind": kind,
"segmentIds": group["segmentIds"],
"pixels": group["pixels"],
"diffusionCoverage": round(coverage, 4),
"diffusionStrength": profile["diffusion_strength"],
"steps": profile["steps"],
"elapsedMs": round((time.perf_counter() - pass_started) * 1000),
"skipped": False,
})
report(0.96, "Restoring full resolution…")
working_full = working.resize((final_width, final_height), Image.Resampling.LANCZOS)
# Union of everything refined. Compositing through it at full resolution is
# what makes the outside-mask guarantee hold: the LANCZOS upscale above
# would otherwise smear refined pixels a little way past every boundary.
combined = np.zeros((final_height, final_width), dtype=np.uint8)
for group in groups:
combined = np.maximum(combined, (group["mask"] > 0).astype(np.uint8))
final_image = composite_surface_only(original_full, working_full, combined)
difference = outside_mask_difference(final_image, original_full, combined)
if difference != 0:
raise RefinementError(
f"Refinement altered pixels outside the surface masks (max delta {difference}). "
"Refusing to return the result."
)
elapsed_ms = round((time.perf_counter() - started) * 1000)
metadata = {
"passes": pass_metadata,
"passCount": len([p for p in pass_metadata if not p.get("skipped")]),
"processingResolution": f"{width}x{height}",
"outputResolution": f"{final_width}x{final_height}",
"blendMode": REFINE_BLEND_MODE,
"maxOutsideMaskDifference": difference,
"refinedPixels": int(combined.sum()),
"elapsedMs": elapsed_ms,
}
print(
f"[REFINE] complete in {elapsed_ms / 1000:.2f}s, "
f"{metadata['passCount']} pass(es), outside-mask delta {difference}",
flush=True,
)
report(1.0, "Refinement complete")
return final_image, metadata
|