prithivMLmods/Photo-Mate-i2i
129
1import os2import gradio as gr3import numpy as np4import spaces5import torch6import random7from PIL import Image8from typing import Iterable9 10from diffusers import FluxKontextPipeline11from diffusers.utils import load_image12from huggingface_hub import hf_hub_download13 14device = torch.device("cuda" if torch.cuda.is_available() else "cpu")15 16from gradio.themes import Soft17from gradio.themes.utils import colors, fonts, sizes18 19colors.orange_red = colors.Color(20 name="orange_red",21 c50="#FFF0E5",22 c100="#FFE0CC",23 c200="#FFC299",24 c300="#FFA366",25 c400="#FF8533",26 c500="#FF4500",27 c600="#E63E00",28 c700="#CC3700",29 c800="#B33000",30 c900="#992900",31 c950="#802200",32)33 34class OrangeRedTheme(Soft):35 def __init__(36 self,37 *,38 primary_hue: colors.Color | str = colors.gray,39 secondary_hue: colors.Color | str = colors.orange_red,40 neutral_hue: colors.Color | str = colors.slate,41 text_size: sizes.Size | str = sizes.text_lg,42 font: fonts.Font | str | Iterable[fonts.Font | str] = (43 fonts.GoogleFont("Outfit"), "Arial", "sans-serif",44 ),45 font_mono: fonts.Font | str | Iterable[fonts.Font | str] = (46 fonts.GoogleFont("IBM Plex Mono"), "ui-monospace", "monospace",47 ),48 ):49 super().__init__(50 primary_hue=primary_hue,51 secondary_hue=secondary_hue,52 neutral_hue=neutral_hue,53 text_size=text_size,54 font=font,55 font_mono=font_mono,56 )57 super().set(58 background_fill_primary="*primary_50",59 background_fill_primary_dark="*primary_900",60 body_background_fill="linear-gradient(135deg, *primary_200, *primary_100)",61 body_background_fill_dark="linear-gradient(135deg, *primary_900, *primary_800)",62 button_primary_text_color="white",63 button_primary_text_color_hover="white",64 button_primary_background_fill="linear-gradient(90deg, *secondary_500, *secondary_600)",65 button_primary_background_fill_hover="linear-gradient(90deg, *secondary_600, *secondary_700)",66 button_primary_background_fill_dark="linear-gradient(90deg, *secondary_600, *secondary_700)",67 button_primary_background_fill_hover_dark="linear-gradient(90deg, *secondary_500, *secondary_600)",68 button_secondary_text_color="black",69 button_secondary_text_color_hover="white",70 button_secondary_background_fill="linear-gradient(90deg, *primary_300, *primary_300)",71 button_secondary_background_fill_hover="linear-gradient(90deg, *primary_400, *primary_400)",72 button_secondary_background_fill_dark="linear-gradient(90deg, *primary_500, *primary_600)",73 button_secondary_background_fill_hover_dark="linear-gradient(90deg, *primary_500, *primary_500)",74 slider_color="*secondary_500",75 slider_color_dark="*secondary_600",76 block_title_text_weight="600",77 block_border_width="3px",78 block_shadow="*shadow_drop_lg",79 button_primary_shadow="*shadow_drop_lg",80 button_large_padding="11px",81 color_accent_soft="*primary_100",82 block_label_background_fill="*primary_200",83 )84 85orange_red_theme = OrangeRedTheme()86 87MAX_SEED = np.iinfo(np.int32).max88pipe = FluxKontextPipeline.from_pretrained("black-forest-labs/FLUX.1-Kontext-dev", torch_dtype=torch.bfloat16).to("cuda")89 90pipe.load_lora_weights("prithivMLmods/PhotoCleanser-i2i", weight_name="PhotoCleanser-i2i.safetensors", adapter_name="cleanser")91pipe.load_lora_weights("prithivMLmods/Photo-Restore-i2i", weight_name="Photo-Restore-i2i.safetensors", adapter_name="restorer")92pipe.load_lora_weights("prithivMLmods/Polaroid-Warm-i2i", weight_name="Polaroid-Warm-i2i.safetensors", adapter_name="polaroid")93pipe.load_lora_weights("prithivMLmods/Monochrome-Pencil", weight_name="Monochrome-Pencil-i2i.safetensors", adapter_name="pencil")94pipe.load_lora_weights("prithivMLmods/LZO-1-Preview", weight_name="LZO-1-Preview.safetensors", adapter_name="lzo")95pipe.load_lora_weights("prithivMLmods/Kontext-Watermark-Remover", weight_name="Kontext-Watermark-Remover.safetensors", adapter_name="watermark-remover")96pipe.load_lora_weights("prithivMLmods/Kontext-Unblur-Upscale", weight_name="Kontext-Image-Upscale.safetensors", adapter_name="unblur-upscale")97pipe.load_lora_weights("prithivMLmods/FLUX.1-Kontext-Dev-Ultra-Realistic-Portrait", weight_name="K-URP_20.safetensors", adapter_name="k-dev")98 99@spaces.GPU100def infer(input_image, prompt, lora_adapter, seed=42, randomize_seed=False, guidance_scale=2.5, steps=28, progress=gr.Progress(track_tqdm=True)):101 if not input_image:102 raise gr.Error("Please upload an image for editing.")103 104 if lora_adapter == "PhotoCleanser":105 pipe.set_adapters(["cleanser"], adapter_weights=[1.0])106 elif lora_adapter == "PhotoRestorer":107 pipe.set_adapters(["restorer"], adapter_weights=[1.0])108 elif lora_adapter == "PolaroidWarm":109 pipe.set_adapters(["polaroid"], adapter_weights=[1.0])110 elif lora_adapter == "MonochromePencil":111 pipe.set_adapters(["pencil"], adapter_weights=[1.0])112 elif lora_adapter == "LZO-Zoom":113 pipe.set_adapters(["lzo"], adapter_weights=[1.0])114 elif lora_adapter == "Kontext-Watermark-Remover":115 pipe.set_adapters(["watermark-remover"], adapter_weights=[1.0])116 elif lora_adapter == "Kontext-Unblur-Upscale":117 pipe.set_adapters(["unblur-upscale"], adapter_weights=[1.0])118 elif lora_adapter == "Kontext-Dev-Ultra-Realistic-Portrait":119 pipe.set_adapters(["k-dev"], adapter_weights=[1.0])120 121 if randomize_seed:122 seed = random.randint(0, MAX_SEED)123 124 original_image = input_image.copy().convert("RGB")125 126 image = pipe(127 image=original_image, 128 prompt=prompt,129 guidance_scale=guidance_scale,130 width = original_image.size[0],131 height = original_image.size[1],132 num_inference_steps=steps,133 generator=torch.Generator().manual_seed(seed),134 ).images[0]135 136 return image, seed137 138@spaces.GPU139def infer_example(input_image, prompt, lora_adapter):140 image, seed = infer(input_image, prompt, lora_adapter)141 return image, seed142 143css="""144#col-container {145 margin: 0 auto;146 max-width: 960px;147}148#main-title h1 {font-size: 2.2em !important;}149"""150 151with gr.Blocks() as demo:152 153 with gr.Column(elem_id="col-container"):154 gr.Markdown("# **Photo-Mate-i2i**", elem_id="main-title")155 gr.Markdown("Image manipulation with FLUX.1 Kontext adapters. [How to Use](https://huggingface.co/spaces/prithivMLmods/Photo-Mate-i2i/discussions/2) [[Version 2.0]](https://huggingface.co/spaces/prithivMLmods/Kontext-Photo-Mate-v2)")156 157 with gr.Row():158 with gr.Column():159 input_image = gr.Image(label="Upload Image", type="pil", height=290)160 161 prompt = gr.Text(162 label="Edit Prompt",163 show_label=True,164 placeholder="e.g., transform into anime..",165 )166 167 run_button = gr.Button("Edit Image", variant="primary")168 169 with gr.Accordion("Advanced Settings", open=False):170 171 seed = gr.Slider(172 label="Seed",173 minimum=0,174 maximum=MAX_SEED,175 step=1,176 value=0,177 )178 179 randomize_seed = gr.Checkbox(label="Randomize seed", value=True)180 181 guidance_scale = gr.Slider(182 label="Guidance Scale",183 minimum=1,184 maximum=10,185 step=0.1,186 value=2.5,187 ) 188 189 steps = gr.Slider(190 label="Steps",191 minimum=1,192 maximum=30,193 value=28,194 step=1195 )196 197 with gr.Column():198 output_image = gr.Image(label="Output Image", interactive=False, format="png", height=419)199 200 with gr.Row():201 lora_adapter = gr.Dropdown(202 label="Chosen LoRA",203 choices=["PhotoCleanser", "PhotoRestorer", "PolaroidWarm", "MonochromePencil", "LZO-Zoom", "Kontext-Watermark-Remover", "Kontext-Unblur-Upscale", "Kontext-Dev-Ultra-Realistic-Portrait"],204 value="PhotoCleanser"205 )206 207 gr.Examples(208 examples=[209 ["photocleanser/2.png", "[photo content], remove the cat from the image while preserving the background and remaining elements, maintaining realism and original details.", "PhotoCleanser"],210 ["photocleanser/1.png", "[photo content], remove the football from the image while preserving the background and remaining elements, maintaining realism and original details.", "PhotoCleanser"],211 ["watermark/12.jpeg", "[photo content], remove any watermark text or logos from the image while preserving the background, texture, lighting, and overall realism. Ensure the edited areas blend seamlessly with surrounding details, leaving no visible traces of watermark removal.", "Kontext-Watermark-Remover"],212 ["photorestore/1.png", "[photo content], restore and enhance the image by repairing any damage, scratches, or fading. Colorize the photo naturally while preserving authentic textures and details, maintaining a realistic and historically accurate look.", "PhotoRestorer"],213 ["lzo/1.jpg", "[photo content], zoom in on the specified [face close-up], enhancing resolution and detail while preserving sharpness, realism, and original context. Maintain natural proportions and background continuity around the zoomed area.", "LZO-Zoom"],214 ["photorestore/2.png", "[photo content], restore and enhance the image by repairing any damage, scratches, or fading. Colorize the photo naturally while preserving authentic textures and details, maintaining a realistic and historically accurate look.", "PhotoRestorer"],215 ["polaroid/1.png", "[photo content], in the style of a vintage Polaroid, with warm, faded tones, and a white border.", "PolaroidWarm"],216 ["K-URP/1.jpg", "ultra-realistic portrait.", "Kontext-Dev-Ultra-Realistic-Portrait"],217 ["unblur/1.jpg", "[photo content], upscale the low-quality image to 4K resolution, enhancing sharpness, clarity, and fine details while preserving the original texture, colors, lighting, and natural appearance. Remove noise, blur, and compression artifacts without over-smoothing or distorting facial or object features. Ensure realistic depth, balanced contrast, and accurate tones, achieving a high-definition, lifelike result that maintains the integrity of the original image.", "Kontext-Unblur-Upscale"],218 ["pencil/1.png", "[photo content], replicate the image as a pencil illustration, black and white, with sketch-like detailing.", "MonochromePencil"],219 ["unblur/11.jpg", "[photo content], upscale the low-quality image to 4K resolution, enhancing sharpness, clarity, and fine details while preserving the original texture, colors, lighting, and natural appearance. Remove noise, blur, and compression artifacts without over-smoothing or distorting facial or object features. Ensure realistic depth, balanced contrast, and accurate tones, achieving a high-definition, lifelike result that maintains the integrity of the original image.", "Kontext-Unblur-Upscale"],220 ],221 inputs=[input_image, prompt, lora_adapter],222 outputs=[output_image, seed],223 fn=infer_example,224 cache_examples=False,225 label="Examples"226 )227 228 gr.on(229 triggers=[run_button.click, prompt.submit],230 fn=infer,231 inputs=[input_image, prompt, lora_adapter, seed, randomize_seed, guidance_scale, steps],232 outputs=[output_image, seed]233 )234 235demo.launch(css=css, theme=orange_red_theme, mcp_server=True, ssr_mode=False, show_error=True)