Spaces:
Paused
Paused
Download services/refine/runner.py from modventures/room-visualizer: direct link, hf CLI and curl.
- Browser
- Download file 10.7 kB
-
https://huggingface.co/spaces/modventures/room-visualizer/resolve/main/services/refine/runner.py
- Command line
-
hf download hf://spaces/modventures/room-visualizer/services/refine/runner.py
-
curl -L -o runner.py https://huggingface.co/spaces/modventures/room-visualizer/resolve/main/services/refine/runner.py
10.7 kB
| """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 | |