"""GenRF: Generative Registration-free Image Fusion - Hugging Face Space entry point.""" from pathlib import Path from functools import lru_cache import html import os import tempfile import time import gradio as gr from PIL import Image, ImageOps ZERO_GPU = os.getenv("GENRF_ZERO_GPU", "1") == "1" if ZERO_GPU: from spaces import GPU else: def GPU(**kwargs): return lambda function: function try: import torch _HAS_TORCH = True except Exception: # CPU-only / local UI preview torch = None _HAS_TORCH = False ROOT = Path(__file__).resolve().parent BASE = "black-forest-labs/flux-3-image-klein-base" DEFAULT = "Fuse the infrared and visible images. Restore degraded visibility, preserve the visible scene geometry and natural colors, and make salient infrared targets clear without ghosts or halos." PROMPTS = { "IVIF": DEFAULT, "MEF": "Fuse the two differently exposed images of the same scene into a naturally exposed RGB image. Preserve scene geometry, realistic colors, and fine details in both shadows and highlights. Avoid ghosting, halos, clipped highlights, and invented details.", "MFF": "Fuse the two differently focused images of the same scene into a sharp all-in-focus RGB image. Preserve scene geometry, realistic colors, and fine details in both near and far focus regions. Avoid ghosting, halos, defocus blur, and invented details.", } MODES = { "IVIF": "IVIF · Infrared / Visible", "MEF": "MEF · Multi-exposure", "MFF": "MFF · Multi-focus", } INPUTS = { "IVIF": (("ir", "Infrared"), ("vi", "Visible")), "MEF": (("over", "Overexposed"), ("under", "Underexposed")), "MFF": (("near", "Near focus"), ("far", "Far focus")), } GROUPS = [ ("IVIF", "Infrared / Visible Image Fusion"), ("MEF", "Multi-exposure Image Fusion"), ("MFF", "Multi-focus Image Fusion"), ] DEFAULTS = {"steps": 30, "cfg": 3.5, "seed": 2026} PAGE_TITLE = "GenRF: Generative Registration-free Image Fusion" def task_name(mode): return mode.split(" · ")[0] def scenes(mode): return sorted( path.name for path in (ROOT / "examples" / task_name(mode).lower()).iterdir() if path.is_dir() ) def example(mode, name): folder = ROOT / "examples" / task_name(mode).lower() / name if name not in scenes(mode): raise gr.Error("Select an example from the list.") files = [ next(path for path in folder.glob(stem + ".*") if path.is_file()) for stem, _ in INPUTS[task_name(mode)] ] with Image.open(files[0]) as first, Image.open(files[1]) as second, \ Image.open(folder / "genrf.png") as result: return first.copy(), second.copy(), result.copy(), None def align_pair(first, second): """Bring two differently sized sources to a common size without distortion. The first (infrared / reference) image is padded symmetrically with zeros until its aspect ratio equals that of the second (visible) image. The visible image is then resampled to the padded size, so neither source is stretched. Returns the aligned pair together with a flag indicating whether alignment was applied. """ if first.size == second.size: return first, second, False wi, hi = first.size wv, hv = second.size ratio = wv / hv if wi / hi > ratio: target_h = max(hi, round(wi / ratio)) top = (target_h - hi) // 2 bottom = target_h - hi - top first = ImageOps.expand(first, border=(0, top, 0, bottom), fill=0) else: target_w = max(wi, round(hi * ratio)) left = (target_w - wi) // 2 right = target_w - wi - left first = ImageOps.expand(first, border=(left, 0, right, 0), fill=0) second = second.resize(first.size, Image.Resampling.LANCZOS) return first, second, True @lru_cache(maxsize=1) def pipeline(): import torch from diffusers import ModularPipeline token = os.environ.get("HF_TOKEN") pipe = ModularPipeline.from_pretrained(BASE, token=token) pipe._blocks.sub_blocks.pop("prompt_upsampler", None) pipe._blocks.sub_blocks.pop("text_encoder", None) pipe.load_components(names=["vae", "transformer"], dtype=torch.bfloat16) pipe.to("cuda") pipe.update_components(guider=pipe.guider.new(guidance_scale=DEFAULTS["cfg"])) pipe.load_lora_weights(str(ROOT / "weights")) pipe.vae.enable_tiling() pipe.vae.enable_slicing() return pipe @lru_cache(maxsize=4) def embeddings(prompt): import torch from transformers import AutoTokenizer, Qwen3VLForConditionalGeneration cache = torch.load(ROOT / "eval_prompt_flux3.pt", map_location="cpu", weights_only=True) if prompt == cache["prompt"]: return cache["pos"], cache["neg"] token = os.environ.get("HF_TOKEN") tokenizer = AutoTokenizer.from_pretrained(BASE, subfolder="text_encoder", token=token) encoder = Qwen3VLForConditionalGeneration.from_pretrained( BASE, subfolder="text_encoder", token=token, torch_dtype=torch.bfloat16 ).eval().to("cuda") try: with torch.inference_mode(): raw = tokenizer.apply_chat_template( [{"role": "user", "content": prompt}], tokenize=False, add_generation_prompt=True ) inputs = tokenizer( [raw], return_tensors="pt", padding="max_length", padding_side="right", truncation=True, max_length=512, ).to("cuda") attn = inputs["attention_mask"] positions = torch.arange(512, device="cuda")[None].masked_fill(attn == 0, 1) hidden = encoder( input_ids=inputs["input_ids"], attention_mask=attn, position_ids=positions, output_hidden_states=True, use_cache=False, ).hidden_states pos = torch.stack(hidden[4:33:4], dim=2).flatten(2).cpu() finally: del encoder torch.cuda.empty_cache() return pos, cache["neg"] @GPU(duration=120) def fuse(first, second, prompt, steps, cfg, seed): import numpy as np import torch if first is None or second is None: raise gr.Error("Upload both source images or pick an example below.") if not torch.cuda.is_available(): raise gr.Error("Live fusion requires a CUDA GPU. You can still browse the archived examples.") first, second = [ImageOps.exif_transpose(im).convert("RGB") for im in (first, second)] first, second, _ = align_pair(first, second) width, height = first.size if min(width, height) < 16: raise gr.Error("Each side must be at least 16 pixels.") limit = 1280 if max(width, height) > limit: size = tuple(max(16, round(side * limit / max(width, height))) for side in first.size) first, second = [im.resize(size, Image.Resampling.LANCZOS) for im in (first, second)] width, height = size right, bottom = (-width) % 16, (-height) % 16 inputs = [ Image.fromarray(np.pad(np.asarray(im), ((0, bottom), (0, right), (0, 0)), mode="reflect")) for im in (first, second) ] pos, neg = embeddings(prompt) pipe = pipeline() pipe.update_components(guider=pipe.guider.new(guidance_scale=float(cfg))) with torch.inference_mode(): image = pipe( image=inputs, height=height + bottom, width=width + right, num_inference_steps=int(steps), generator=torch.Generator("cpu").manual_seed(int(seed)), prompt_embeds=pos.to("cuda"), negative_prompt_embeds=neg.to("cuda"), output="images", )[0] return image.crop((0, 0, width, height)) # -------------------------------------------------------------------------- # Presentation layer # -------------------------------------------------------------------------- THEME = gr.themes.Soft( primary_hue=gr.themes.colors.indigo, secondary_hue=gr.themes.colors.slate, neutral_hue=gr.themes.colors.slate, font=["ui-sans-serif", "system-ui", "-apple-system", "Segoe UI", "sans-serif"], ) CSS = r""" :root { --genrf-bg:#f5f7fb; --genrf-surface:#ffffff; --genrf-surface-2:#f8fafc; --genrf-border:#e5eaf2; --genrf-border-strong:#d6deea; --genrf-ink:#0f172a; --genrf-ink-2:#526077; --genrf-muted:#94a3b8; --genrf-accent:#4f46e5; --genrf-accent-2:#7c6cf0; --genrf-accent-soft:#eef2ff; --genrf-shadow:0 1px 2px rgba(15,23,42,.04), 0 10px 28px rgba(15,23,42,.045); } .dark, body.dark, html.dark, .gradio-container.dark { --genrf-bg:#0b1120; --genrf-surface:#131c30; --genrf-surface-2:#101827; --genrf-border:#26334c; --genrf-border-strong:#33425f; --genrf-ink:#eef2fb; --genrf-ink-2:#aab7cd; --genrf-muted:#7b89a2; --genrf-accent:#8f96ff; --genrf-accent-2:#6f78ef; --genrf-accent-soft:#1c2540; --genrf-shadow:0 1px 2px rgba(0,0,0,.24), 0 10px 28px rgba(0,0,0,.22); } .gradio-container { max-width:1180px !important; margin-inline:auto !important; background:var(--genrf-bg) !important; } .dark .gradio-container { color:var(--genrf-ink) !important; } .genrf-hero { display:flex; flex-wrap:wrap; align-items:center; gap:18px 28px; position:relative; overflow:hidden; padding:24px 28px; margin-bottom:16px; border:1px solid var(--genrf-border); border-radius:20px; box-shadow:var(--genrf-shadow); background:radial-gradient(700px 220px at 8% -30%, rgba(99,102,241,.20), transparent 70%), linear-gradient(115deg, var(--genrf-accent-soft) 0%, var(--genrf-surface) 62%, var(--genrf-surface-2) 100%); } .genrf-hero-main { flex:1 1 520px; min-width:0; } .genrf-links { display:flex; gap:8px; flex-wrap:wrap; margin-left:auto; } .genrf-link { display:inline-flex; align-items:center; gap:7px; padding:8px 13px; border-radius:10px; border:1px solid var(--genrf-border-strong); background:var(--genrf-surface); color:var(--genrf-ink); font-size:12px; font-weight:600; text-decoration:none !important; box-shadow:0 1px 2px rgba(15,23,42,.04); transition:border-color .15s ease, color .15s ease, transform .15s ease; } .genrf-link:hover { border-color:var(--genrf-accent); color:var(--genrf-accent); transform:translateY(-1px); } .genrf-link svg { width:14px; height:14px; display:block; } .genrf-hero h1 { margin:14px 0 8px; font-size:clamp(21px,2.4vw,30px); font-weight:680; letter-spacing:-.025em; line-height:1.2; color:var(--genrf-ink); } .genrf-hero p { margin:0; max-width:80ch; font-size:13.5px; line-height:1.65; color:var(--genrf-ink-2); } .genrf-badge { display:inline-block; padding:4px 11px; border-radius:999px; color:#fff; background:linear-gradient(135deg,var(--genrf-accent),var(--genrf-accent-2)); font-size:11px; font-weight:700; letter-spacing:.08em; } .genrf-badge.ghost { margin-left:6px; background:var(--genrf-surface); color:var(--genrf-accent); border:1px solid var(--genrf-border-strong); font-weight:600; letter-spacing:0; } .genrf-tags { margin-top:14px; display:flex; gap:8px; flex-wrap:wrap; } .genrf-tags span { font-size:11px; padding:3px 9px; border-radius:6px; background:var(--genrf-accent-soft); color:var(--genrf-accent); border:1px solid var(--genrf-border); } .genrf-tags span.key { color:#fff; font-weight:650; border-color:transparent; background:linear-gradient(135deg,var(--genrf-accent),var(--genrf-accent-2)); } .genrf-panel { background:var(--genrf-surface) !important; border:1px solid var(--genrf-border) !important; border-radius:18px !important; padding:18px !important; box-shadow:var(--genrf-shadow); } .genrf-sec { font-size:13.5px; font-weight:650; line-height:1.4; color:var(--genrf-ink); margin:0 0 14px; padding-left:11px; border-left:3px solid var(--genrf-accent); } .genrf-sec small { display:block; margin:3px 0 0; font-weight:400; font-size:11px; color:var(--genrf-muted); } .genrf-panel .html-container, .genrf-panel .html-container .prose, .genrf-instr-head, .genrf-panel .styler, .genrf-panel .image-container, .genrf-panel .image-frame { background:transparent !important; border:0 !important; box-shadow:none !important; } .genrf-panel .styler { padding:0 !important; } .genrf-panel .html-container { padding:0 !important; } .genrf-sec-inline { margin:0 !important; } .genrf-hint { font-size:11.5px; line-height:1.7; color:var(--genrf-ink-2); } .genrf-note { margin-top:10px; font-size:11.5px; line-height:1.7; color:var(--genrf-muted); } .genrf-instr-head { align-items:center !important; gap:14px !important; margin-bottom:8px; } #genrf-preset { flex:0 0 250px !important; width:250px !important; min-width:250px !important; } #genrf-preset .wrap { border:1px solid var(--genrf-border-strong) !important; border-radius:999px !important; background:var(--genrf-surface-2) !important; box-shadow:none !important; transition:border-color .15s ease, box-shadow .15s ease; } #genrf-preset .wrap:hover { border-color:var(--genrf-accent) !important; } #genrf-preset .wrap:focus-within { border-color:var(--genrf-accent) !important; box-shadow:0 0 0 3px var(--genrf-accent-soft) !important; } #genrf-preset .wrap-inner { padding:4px 26px 4px 12px !important; } #genrf-preset input { font-size:12px !important; font-weight:600 !important; color:var(--genrf-ink) !important; height:auto !important; } #genrf-preset .icon-wrap { right:9px !important; width:14px !important; color:var(--genrf-muted) !important; } #genrf-prompt textarea { font-size:13px !important; line-height:1.65 !important; } .genrf-params [data-testid="block-info"] { background:transparent !important; border:0 !important; padding:0 0 0 2px !important; color:var(--genrf-ink-2) !important; font-weight:600 !important; font-size:11.5px !important; } #genrf-reset { background:var(--genrf-surface-2) !important; border:1px solid var(--genrf-border-strong) !important; border-radius:999px !important; padding:0 14px !important; color:var(--genrf-ink-2) !important; font-weight:600 !important; font-size:12px !important; box-shadow:none !important; transition:border-color .15s ease, color .15s ease; } #genrf-reset:hover { border-color:var(--genrf-accent) !important; color:var(--genrf-accent) !important; } .genrf-group { display:flex; align-items:center; gap:10px; margin:16px 0 8px; padding-bottom:8px; border-bottom:1px solid var(--genrf-border); font-size:12.5px; color:var(--genrf-ink-2); } .genrf-tagcode { font-family:ui-monospace,SFMono-Regular,Consolas,monospace; font-size:11px; font-weight:700; color:var(--genrf-accent); background:var(--genrf-accent-soft); border:1px solid var(--genrf-border); padding:2px 8px; border-radius:6px; } .genrf-count { margin-left:auto; color:var(--genrf-muted); font-size:11px; } .genrf-foot { margin-top:14px; padding:12px 4px; border-top:1px solid var(--genrf-border); font-size:11.5px; color:var(--genrf-muted); line-height:1.75; } #genrf-run { min-height:46px !important; font-size:14px !important; font-weight:650 !important; letter-spacing:.01em; border:0 !important; color:#fff !important; background:linear-gradient(135deg,var(--genrf-accent),var(--genrf-accent-2)) !important; box-shadow:0 6px 18px rgba(79,70,229,.22) !important; transition:transform .15s ease, box-shadow .15s ease, filter .15s ease !important; } #genrf-run:hover:not(:disabled) { transform:translateY(-2px); box-shadow:0 10px 26px rgba(79,70,229,.34) !important; } #genrf-run:disabled, #genrf-run.disabled { filter:grayscale(.55); opacity:.55; box-shadow:none !important; transform:none !important; } .genrf-status { border-radius:12px; padding:11px 14px; font-size:12.5px; line-height:1.65; background:var(--genrf-surface-2); border:1px solid var(--genrf-border); border-left:3px solid var(--genrf-border-strong); color:var(--genrf-ink); } .genrf-status b { display:block; margin-bottom:2px; font-size:12.5px; } .genrf-status span { color:var(--genrf-ink-2); } .genrf-status[data-kind="idle"] { border-left-color:#94a3b8; } .genrf-status[data-kind="archive"] { border-left-color:var(--genrf-accent); } .genrf-status[data-kind="running"], .genrf-status[data-kind="gallery"] { border-left-color:#f59e0b; } .genrf-status[data-kind="done"] { border-left-color:#16a34a; } .genrf-status[data-kind="error"] { border-left-color:#dc2626; } .genrf-legend { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); column-gap:9px; margin:10px 0 8px; padding:0 2px; font-size:10.5px; letter-spacing:.02em; text-transform:uppercase; font-weight:650; color:var(--genrf-muted); } .genrf-legend span:last-child { color:var(--genrf-accent); } @media (max-width:560px) { .genrf-legend { column-gap:6px; font-size:9.5px; } } .genrf-gallery .grid-wrap, .genrf-gallery .grid-wrap.fixed-height { min-height:0 !important; max-height:none !important; overflow-y:visible !important; } .genrf-gallery .grid-container { grid-template-columns:repeat(3,minmax(0,1fr)) !important; grid-template-rows:none !important; grid-auto-rows:auto !important; column-gap:9px !important; row-gap:18px !important; align-items:start !important; } @media (max-width:560px) { .genrf-gallery .grid-container { column-gap:6px !important; row-gap:12px !important; } } .genrf-gallery .gallery-item { aspect-ratio:auto !important; height:auto !important; } .genrf-gallery .thumbnail-item { aspect-ratio:auto !important; height:auto !important; } .genrf-gallery .thumbnail-item img { width:100% !important; height:auto !important; object-fit:fill !important; display:block; } .genrf-gallery .gallery-item { border-radius:10px !important; overflow:hidden; border:1px solid var(--genrf-border) !important; transition:transform .15s ease, box-shadow .15s ease; } .genrf-gallery .gallery-item:hover { transform:translateY(-2px); box-shadow:0 8px 20px rgba(15,23,42,.16); } .genrf-panel label[data-testid="block-label"] { background:var(--genrf-accent-soft) !important; color:var(--genrf-accent) !important; border:1px solid var(--genrf-border) !important; border-radius:8px !important; font-weight:600 !important; } #genrf-result { background:var(--genrf-surface) !important; border-color:var(--genrf-border) !important; } #genrf-result img { object-position:top center !important; } #genrf-result .image-container { align-items:flex-start !important; } footer { display:none !important; } #genrf-run:focus-visible { outline:2px solid var(--genrf-accent); outline-offset:2px; } @media (max-width:820px) { .genrf-hero { padding:18px 20px; } .genrf-links { margin-left:0; } .genrf-panel { padding:14px !important; } .genrf-instr-head { flex-wrap:wrap !important; } } @media (prefers-reduced-motion:reduce) { .genrf-hero, #genrf-run, .genrf-gallery .gallery-item, #genrf-preset .wrap { transition:none !important; } } """ # The arXiv entry is not live yet, so Paper points at the repository for now. PAPER_URL = "https://github.com/Linfeng-Tang/GenRF" CODE_URL = "https://github.com/Linfeng-Tang/GenRF" PAGE_URL = "https://linfeng-tang.github.io/GenRF/" HERO = """
Misaligned, degraded, partially overlapping captures go in —
a high-quality, coherent fused image comes out.