""" Deus Inpaint — Imagen 3 Logo Removal Tool ========================================== Gradio UI wrapping the Imagen 3 inpainting + composite pipeline. Run: python app.py Requires: pip install gradio google-genai Pillow numpy """ import io import os import sys import time import json import tempfile import numpy as np from pathlib import Path from PIL import Image, ImageFilter # ── GCP Auth (for Hugging Face Spaces) ───────────────────────────── creds_json = os.environ.get("GOOGLE_APPLICATION_CREDENTIALS_JSON") if creds_json: try: # Validate it's parseable JSON parsed = json.loads(creds_json) # Write to temp file tmp = tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) json.dump(parsed, tmp) tmp.close() os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = tmp.name print(f"✅ GCP credentials loaded for {parsed.get('client_email', 'unknown')}") except json.JSONDecodeError as e: print(f"❌ GOOGLE_APPLICATION_CREDENTIALS_JSON is not valid JSON: {e}") else: print("⚠️ GOOGLE_APPLICATION_CREDENTIALS_JSON not found in env") # Debug: check other required env vars for var in ["GOOGLE_CLOUD_PROJECT", "GOOGLE_CLOUD_LOCATION", "GOOGLE_GENAI_USE_VERTEXAI"]: val = os.environ.get(var) print(f" {var} = {val or 'NOT SET'}") # ── Theme & CSS ──────────────────────────────────────────────────── CUSTOM_CSS = """ @import url('https://fonts.googleapis.com/css2?family=DM+Sans:ital,opsz,wght@0,9..40,300;0,9..40,400;0,9..40,500;1,9..40,300&family=JetBrains+Mono:wght@400;500&display=swap'); :root { --bg-primary: #0a0a0a; --bg-secondary: #111111; --bg-elevated: #181818; --bg-input: #141414; --border-subtle: #222222; --border-active: #333333; --text-primary: #e8e8e8; --text-secondary: #888888; --text-muted: #555555; --accent: #c8ff00; --accent-dim: #c8ff0022; --danger: #ff4444; --success: #44ff88; } /* Global overrides */ .gradio-container { background: var(--bg-primary) !important; font-family: 'DM Sans', -apple-system, sans-serif !important; max-width: 1800px !important; margin: 0 auto !important; } /* Header */ .app-header { padding: 32px 0 24px 0; border-bottom: 1px solid var(--border-subtle); margin-bottom: 28px; } .app-header h1 { font-family: 'DM Sans', sans-serif !important; font-size: 28px !important; font-weight: 400 !important; letter-spacing: -0.5px; color: var(--text-primary) !important; margin: 0 !important; } .app-header h1 span { color: var(--accent) !important; } .app-header p { font-size: 13px !important; color: var(--text-secondary) !important; margin: 6px 0 0 0 !important; font-weight: 300; } /* Panels */ .panel-label { font-size: 11px !important; text-transform: uppercase; letter-spacing: 1.5px; color: var(--text-muted) !important; font-weight: 500; margin-bottom: 12px !important; } /* Image containers */ .image-upload-area { border: 1px dashed var(--border-subtle) !important; border-radius: 8px !important; background: var(--bg-input) !important; transition: border-color 0.2s ease; } .image-upload-area:hover { border-color: var(--border-active) !important; } /* Buttons */ .run-btn { background: var(--accent) !important; color: #000 !important; font-family: 'DM Sans', sans-serif !important; font-weight: 500 !important; font-size: 14px !important; letter-spacing: 0.3px; border: none !important; border-radius: 6px !important; padding: 12px 32px !important; transition: all 0.15s ease !important; min-height: 48px !important; } .run-btn:hover { filter: brightness(0.9) !important; transform: translateY(-1px); } .run-btn:active { transform: translateY(0); } .secondary-btn { background: var(--bg-elevated) !important; color: var(--text-primary) !important; border: 1px solid var(--border-subtle) !important; border-radius: 6px !important; font-family: 'DM Sans', sans-serif !important; font-size: 13px !important; font-weight: 400 !important; } .secondary-btn:hover { border-color: var(--border-active) !important; } /* Sliders & inputs */ .gradio-slider input[type="range"] { accent-color: var(--accent) !important; } /* Accordion */ .gradio-accordion { background: var(--bg-secondary) !important; border: 1px solid var(--border-subtle) !important; border-radius: 8px !important; } /* Gallery */ .gradio-gallery { background: var(--bg-secondary) !important; border: 1px solid var(--border-subtle) !important; border-radius: 8px !important; } /* Metrics text */ .metrics-box { font-family: 'JetBrains Mono', monospace !important; font-size: 12px !important; line-height: 1.7 !important; color: var(--text-secondary) !important; background: var(--bg-input) !important; border: 1px solid var(--border-subtle) !important; border-radius: 6px !important; padding: 16px !important; } /* Tab styling */ .tabs .tab-nav button { font-family: 'DM Sans', sans-serif !important; font-size: 13px !important; font-weight: 400 !important; letter-spacing: 0.3px; color: var(--text-secondary) !important; border: none !important; background: transparent !important; } .tabs .tab-nav button.selected { color: var(--text-primary) !important; border-bottom: 2px solid var(--accent) !important; } /* Status bar */ .status-text { font-family: 'JetBrains Mono', monospace !important; font-size: 12px !important; color: var(--text-muted) !important; } /* Hide gradio footer */ footer { display: none !important; } /* Scrollbar */ ::-webkit-scrollbar { width: 6px; } ::-webkit-scrollbar-track { background: var(--bg-primary); } ::-webkit-scrollbar-thumb { background: var(--border-subtle); border-radius: 3px; } ::-webkit-scrollbar-thumb:hover { background: var(--border-active); } """ # ── Imagen 3 API ─────────────────────────────────────────────────── def call_imagen3_inpaint( image_path, mask_path, prompt="", edit_mode="EDIT_MODE_INPAINT_REMOVAL", steps=12, guidance=10, mask_dilation=0.01, samples=4, ): from google import genai from google.genai.types import ( RawReferenceImage, MaskReferenceImage, MaskReferenceConfig, EditImageConfig, ) from google.genai.types import Image as GenImage client = genai.Client() raw_ref = RawReferenceImage( reference_image=GenImage.from_file(location=image_path), reference_id=0, ) mask_ref = MaskReferenceImage( reference_id=1, reference_image=GenImage.from_file(location=mask_path), config=MaskReferenceConfig( mask_mode="MASK_MODE_USER_PROVIDED", mask_dilation=mask_dilation, ), ) result = client.models.edit_image( model="imagen-3.0-capability-001", prompt=prompt, reference_images=[raw_ref, mask_ref], config=EditImageConfig( edit_mode=edit_mode, number_of_images=samples, base_steps=steps, guidance_scale=guidance, ), ) images = [] for gen_img in result.generated_images: images.append(Image.open(io.BytesIO(gen_img.image.image_bytes))) return images # ── Color matching ───────────────────────────────────────────────── def color_match(original, inpainted, mask_binary, border_width=30): mask_pil = Image.fromarray(mask_binary) dilated = mask_pil.filter(ImageFilter.MaxFilter(size=border_width * 2 + 1)) dilated_arr = np.array(dilated) border_zone = (dilated_arr > 128) & (mask_binary < 128) if np.sum(border_zone) < 100: return inpainted offset = (np.mean(original[border_zone], axis=0) - np.mean(inpainted[border_zone], axis=0)) return np.clip(inpainted + offset[np.newaxis, np.newaxis, :], 0, 255) # ── Composite ────────────────────────────────────────────────────── def composite_inpaint(original, inpainted, mask, feather=5, do_color_match=True): if inpainted.size != original.size: inpainted = inpainted.resize(original.size, Image.LANCZOS) if mask.size != original.size: mask = mask.resize(original.size, Image.LANCZOS) mask_arr = np.array(mask.convert("L")) mask_arr = np.where(mask_arr > 128, 255, 0).astype(np.uint8) if do_color_match: orig_f = np.array(original).astype(np.float64) inp_f = np.array(inpainted).astype(np.float64) inp_corrected = color_match(orig_f, inp_f, mask_arr) inpainted = Image.fromarray(inp_corrected.astype(np.uint8)) if feather > 0: mask_pil = Image.fromarray(mask_arr) mask_pil = mask_pil.filter(ImageFilter.GaussianBlur(radius=feather)) mask_arr = np.array(mask_pil) alpha = Image.fromarray(mask_arr, mode="L") return Image.composite(inpainted, original, alpha) # ── Quality analysis ─────────────────────────────────────────────── def analyze(original, result, mask): orig = np.array(original).astype(float) res = np.array(result.resize(original.size, Image.LANCZOS)).astype(float) m = np.array(mask.convert("L").resize(original.size, Image.LANCZOS)) lines = [] outside = m < 128 if np.any(outside): mse = np.mean((orig[outside] - res[outside]) ** 2) maxd = np.max(np.abs(orig[outside] - res[outside])) lines.append(f"Outside mask MSE {mse:.4f}") lines.append(f"Outside max diff {maxd:.0f}") inside = m >= 128 if np.any(inside): mse_in = np.mean((orig[inside] - res[inside]) ** 2) lines.append(f"Inside mask MSE {mse_in:.1f}") oe = np.array(original.convert("L").filter(ImageFilter.FIND_EDGES)) re = np.array(result.convert("L").filter(ImageFilter.FIND_EDGES)) os_v = np.var(oe.astype(float)) rs_v = np.var(re.astype(float)) pct = ((rs_v / os_v) - 1) * 100 if os_v > 0 else 0 lines.append(f"Sharpness {rs_v:.0f} vs {os_v:.0f} ({pct:+.1f}%)") return "\n".join(lines) # ── Main pipeline ────────────────────────────────────────────────── def run_inpaint( image_editor_data, mask_upload, ref_image_data, steps, guidance, dilation, feather, samples, do_color_match, mode, prompt, progress=None, ): """Main pipeline: extract images → API → composite → return gallery.""" # --- Extract original image and mask --- original_pil = None mask_pil = None # From ImageEditor if image_editor_data is not None: bg = image_editor_data.get("background") layers = image_editor_data.get("layers", []) if bg is not None: if isinstance(bg, np.ndarray): original_pil = Image.fromarray(bg).convert("RGB") elif isinstance(bg, Image.Image): original_pil = bg.convert("RGB") elif isinstance(bg, str): original_pil = Image.open(bg).convert("RGB") # Extract mask from drawn layers if layers and original_pil is not None: w, h = original_pil.size combined_mask = np.zeros((h, w), dtype=np.uint8) for layer in layers: if isinstance(layer, np.ndarray): layer_arr = layer elif isinstance(layer, Image.Image): layer_arr = np.array(layer) elif isinstance(layer, str): layer_arr = np.array(Image.open(layer)) else: continue # Check alpha channel or brightness if layer_arr.ndim == 3 and layer_arr.shape[2] == 4: alpha = layer_arr[:, :, 3] combined_mask = np.maximum(combined_mask, alpha) elif layer_arr.ndim == 3: gray = np.mean(layer_arr[:, :, :3], axis=2) combined_mask = np.maximum(combined_mask, gray.astype(np.uint8)) elif layer_arr.ndim == 2: combined_mask = np.maximum(combined_mask, layer_arr) if np.any(combined_mask > 20): mask_pil = Image.fromarray( np.where(combined_mask > 20, 255, 0).astype(np.uint8), mode="L" ) # Fallback: diff composite vs background to detect brush strokes if mask_pil is None and original_pil is not None: comp = image_editor_data.get("composite") if comp is not None: if isinstance(comp, np.ndarray): comp_arr = comp elif isinstance(comp, str): comp_arr = np.array(Image.open(comp)) else: comp_arr = np.array(comp) bg_arr = np.array(original_pil) if comp_arr.shape[:2] == bg_arr.shape[:2]: # Compare only RGB channels comp_rgb = comp_arr[:, :, :3] if comp_arr.ndim == 3 else comp_arr bg_rgb = bg_arr[:, :, :3] if bg_arr.ndim == 3 else bg_arr diff = np.max(np.abs( comp_rgb.astype(int) - bg_rgb.astype(int) ), axis=2) if np.any(diff > 30): mask_pil = Image.fromarray( np.where(diff > 30, 255, 0).astype(np.uint8), mode="L" ) # Override mask with uploaded file if provided if mask_upload is not None: if isinstance(mask_upload, np.ndarray): mask_pil = Image.fromarray(mask_upload).convert("L") elif isinstance(mask_upload, str): mask_pil = Image.open(mask_upload).convert("L") else: mask_pil = mask_upload.convert("L") # Validate if original_pil is None: raise ValueError("Upload an image first") if mask_pil is None: raise ValueError("Draw a mask on the image or upload a mask file") # Resize mask to match image if mask_pil.size != original_pil.size: mask_pil = mask_pil.resize(original_pil.size, Image.LANCZOS) # --- Save temp files for API --- tmp_dir = tempfile.mkdtemp() img_path = os.path.join(tmp_dir, "input.png") mask_path = os.path.join(tmp_dir, "mask.png") original_pil.save(img_path, "PNG") # Threshold mask to pure B&W mask_arr = np.array(mask_pil) mask_arr = np.where(mask_arr > 128, 255, 0).astype(np.uint8) Image.fromarray(mask_arr, mode="L").save(mask_path, "PNG") # --- Reference image: pre-composite onto product --- ref_pil = None if ref_image_data is not None: if isinstance(ref_image_data, np.ndarray): ref_pil = Image.fromarray(ref_image_data).convert("RGBA") elif isinstance(ref_image_data, str): ref_pil = Image.open(ref_image_data).convert("RGBA") else: ref_pil = ref_image_data.convert("RGBA") if ref_pil is not None: # Find mask bounding box ys, xs = np.where(mask_arr > 128) if len(ys) > 0: y_min, y_max = ys.min(), ys.max() x_min, x_max = xs.min(), xs.max() box_w = x_max - x_min box_h = y_max - y_min # Resize ref image to fit inside mask bbox (80% to leave breathing room) scale = min((box_w * 0.8) / ref_pil.width, (box_h * 0.8) / ref_pil.height) new_w = max(1, int(ref_pil.width * scale)) new_h = max(1, int(ref_pil.height * scale)) ref_resized = ref_pil.resize((new_w, new_h), Image.LANCZOS) # Center in the mask bounding box cx = x_min + box_w // 2 cy = y_min + box_h // 2 paste_x = cx - new_w // 2 paste_y = cy - new_h // 2 # Paste onto original (using alpha if present) input_with_ref = original_pil.copy().convert("RGBA") input_with_ref.paste(ref_resized, (paste_x, paste_y), ref_resized) input_with_ref = input_with_ref.convert("RGB") input_with_ref.save(img_path, "PNG") # Force insert mode so Imagen blends it edit_mode = "EDIT_MODE_INPAINT_INSERTION" if not prompt: prompt = "blend seamlessly into the surface, match lighting and material" # Resolve edit mode if ref_pil is not None: final_edit_mode = "EDIT_MODE_INPAINT_INSERTION" elif mode == "Remove": final_edit_mode = "EDIT_MODE_INPAINT_REMOVAL" else: final_edit_mode = "EDIT_MODE_INPAINT_INSERTION" # --- Call API --- t0 = time.time() try: raw_images = call_imagen3_inpaint( image_path=img_path, mask_path=mask_path, prompt=prompt if prompt else "", edit_mode=final_edit_mode, steps=int(steps), guidance=int(guidance) * 5, mask_dilation=float(dilation), samples=int(samples), ) except Exception as e: raise ValueError(f"API error: {e}") api_time = time.time() - t0 # --- Composite --- mask_for_comp = Image.fromarray(mask_arr, mode="L") composited = [] metrics_all = [] for i, raw in enumerate(raw_images): comp = composite_inpaint( original_pil, raw, mask_for_comp, feather=int(feather), do_color_match=do_color_match, ) composited.append(comp) m = analyze(original_pil, comp, mask_for_comp) metrics_all.append(f"── Result {i+1} ──\n{m}") # Build gallery pairs (composited + raw for comparison) gallery_items = [] for i, comp in enumerate(composited): gallery_items.append((comp, f"Result {i+1}")) for i, raw in enumerate(raw_images): gallery_items.append((raw, f"Raw {i+1} (no composite)")) # Status cost = len(raw_images) * 0.02 status = ( f"{len(raw_images)} results · {api_time:.1f}s · " f"~${cost:.2f} · {original_pil.size[0]}×{original_pil.size[1]}px" ) metrics_text = "\n\n".join(metrics_all) # Cleanup try: os.remove(img_path) os.remove(mask_path) os.rmdir(tmp_dir) except: pass return gallery_items, status, metrics_text # ── Build UI ─────────────────────────────────────────────────────── def create_app(): import gradio as gr theme = gr.themes.Base( primary_hue=gr.themes.colors.lime, neutral_hue=gr.themes.colors.gray, font=gr.themes.GoogleFont("DM Sans"), font_mono=gr.themes.GoogleFont("JetBrains Mono"), ).set( body_background_fill="#0a0a0a", body_background_fill_dark="#0a0a0a", body_text_color="#e8e8e8", body_text_color_dark="#e8e8e8", body_text_color_subdued="#888888", body_text_color_subdued_dark="#888888", background_fill_primary="#111111", background_fill_primary_dark="#111111", background_fill_secondary="#181818", background_fill_secondary_dark="#181818", border_color_primary="#222222", border_color_primary_dark="#222222", block_background_fill="#111111", block_background_fill_dark="#111111", block_border_color="#222222", block_border_color_dark="#222222", block_label_text_color="#888888", block_label_text_color_dark="#888888", block_title_text_color="#e8e8e8", block_title_text_color_dark="#e8e8e8", input_background_fill="#141414", input_background_fill_dark="#141414", input_border_color="#222222", input_border_color_dark="#222222", button_primary_background_fill="#c8ff00", button_primary_background_fill_dark="#c8ff00", button_primary_text_color="#000000", button_primary_text_color_dark="#000000", button_secondary_background_fill="#181818", button_secondary_background_fill_dark="#181818", button_secondary_text_color="#e8e8e8", button_secondary_text_color_dark="#e8e8e8", button_secondary_border_color="#222222", button_secondary_border_color_dark="#222222", ) with gr.Blocks(title="Deus Inpaint", fill_width=False) as app: # Header gr.HTML("""
Imagen 3 logo removal · pixel-perfect composite · color matched
Input
') with gr.Row(): with gr.Column(scale=7): with gr.Tabs() as input_tabs: with gr.Tab("Draw mask", id="draw"): image_editor = gr.ImageEditor( label="Upload image, then draw over the area to remove", type="numpy", sources=["upload", "clipboard"], brush=gr.Brush( default_size=25, colors=["#ffffff"], color_mode="fixed", ), eraser=gr.Eraser(default_size=20), layers=False, transforms=[], height=720, format="png", elem_classes=["image-upload-area"], ) with gr.Tab("Upload mask", id="upload"): gr.HTML('Upload a separate mask file (white = area to remove)
') mask_upload = gr.Image( label="Mask", type="numpy", height=400, sources=["upload", "clipboard"], elem_classes=["image-upload-area"], ) with gr.Column(scale=3): gr.HTML('Reference image (optional)
') ref_image = gr.Image( label="Logo or image to place in masked area", type="numpy", height=280, sources=["upload", "clipboard"], elem_classes=["image-upload-area"], ) # ── Settings ─────────────────────────────────── gr.HTML('Settings
') with gr.Row(): mode = gr.Radio( ["Remove", "Insert"], value="Remove", label="Mode", ) prompt = gr.Textbox( label="Prompt", placeholder="Leave empty for removal, or describe what to fill", value="", scale=3, ) with gr.Row(): steps = gr.Slider( 12, 75, value=35, step=1, label="Steps", info="12=fast, 75=max quality", ) guidance = gr.Slider( 0, 100, value=2, step=1, label="Guidance", info="Lower = more faithful", ) feather = gr.Slider( 0, 25, value=5, step=1, label="Feather", info="Edge blend (px)", ) dilation = gr.Slider( 0, 0.2, value=0.01, step=0.005, label="Dilation", info="Mask expansion", ) samples = gr.Slider( 1, 4, value=4, step=1, label="Samples", ) with gr.Row(): with gr.Accordion("Advanced", open=False): do_color_match = gr.Checkbox( label="Color matching", value=True, info="Corrects Imagen's color shift", ) run_btn = gr.Button( "Run inpaint", variant="primary", elem_classes=["run-btn"], ) status_text = gr.Textbox( label="", interactive=False, elem_classes=["status-text"], show_label=False, max_lines=1, ) # ── Output ───────────────────────────────────── gr.HTML('Output
') gallery = gr.Gallery( label="Results", columns=4, height=420, object_fit="contain", buttons=["download", "fullscreen"], format="png", ) with gr.Accordion("Quality metrics", open=False): metrics = gr.Textbox( label="", interactive=False, show_label=False, lines=12, elem_classes=["metrics-box"], ) # ── Events ───────────────────────────────────── run_btn.click( fn=run_inpaint, inputs=[ image_editor, mask_upload, ref_image, steps, guidance, dilation, feather, samples, do_color_match, mode, prompt, ], outputs=[gallery, status_text, metrics], ) return app, theme # ── Entry point ──────────────────────────────────────────────────── app, theme = create_app() if __name__ == "__main__": app.launch( server_name="0.0.0.0", server_port=7860, share=False, show_error=True, theme=theme, css=CUSTOM_CSS, ) else: # HF Spaces: launch is handled automatically app.launch( theme=theme, css=CUSTOM_CSS, )