ginigen/FLUX.1-Kontext-Dev
2
1import gradio as gr2import numpy as np3import spaces4import torch5import random6from PIL import Image7 8from diffusers import FluxKontextPipeline9from diffusers.utils import load_image10 11MAX_SEED = np.iinfo(np.int32).max12 13pipe = FluxKontextPipeline.from_pretrained("black-forest-labs/FLUX.1-Kontext-dev", torch_dtype=torch.bfloat16).to("cuda")14 15@spaces.GPU16def infer(input_image, prompt, seed=42, randomize_seed=False, guidance_scale=2.5, steps=28, progress=gr.Progress(track_tqdm=True)):17 """18 Perform image editing using the FLUX.1 Kontext pipeline.19 20 This function takes an input image and a text prompt to generate a modified version21 of the image based on the provided instructions. It uses the FLUX.1 Kontext model22 for contextual image editing tasks.23 24 Args:25 input_image (PIL.Image.Image): The input image to be edited. Will be converted26 to RGB format if not already in that format.27 prompt (str): Text description of the desired edit to apply to the image.28 Examples: "Remove glasses", "Add a hat", "Change background to beach".29 seed (int, optional): Random seed for reproducible generation. Defaults to 42.30 Must be between 0 and MAX_SEED (2^31 - 1).31 randomize_seed (bool, optional): If True, generates a random seed instead of32 using the provided seed value. Defaults to False.33 guidance_scale (float, optional): Controls how closely the model follows the34 prompt. Higher values mean stronger adherence to the prompt but may reduce35 image quality. Range: 1.0-10.0. Defaults to 2.5.36 steps (int, optional): Controls how many steps to run the diffusion model for.37 Range: 1-30. Defaults to 28.38 progress (gr.Progress, optional): Gradio progress tracker for monitoring39 generation progress. Defaults to gr.Progress(track_tqdm=True).40 41 Returns:42 tuple: A 3-tuple containing:43 - PIL.Image.Image: The generated/edited image44 - int: The seed value used for generation (useful when randomize_seed=True)45 - gr.update: Gradio update object to make the reuse button visible46 47 Example:48 >>> edited_image, used_seed, button_update = infer(49 ... input_image=my_image,50 ... prompt="Add sunglasses",51 ... seed=123,52 ... randomize_seed=False,53 ... guidance_scale=2.554 ... )55 """56 if randomize_seed:57 seed = random.randint(0, MAX_SEED)58 59 if input_image:60 input_image = input_image.convert("RGB")61 image = pipe(62 image=input_image, 63 prompt=prompt,64 guidance_scale=guidance_scale,65 num_inference_steps=steps,66 generator=torch.Generator().manual_seed(seed),67 ).images[0]68 else:69 image = pipe(70 prompt=prompt,71 guidance_scale=guidance_scale,72 num_inference_steps=steps,73 generator=torch.Generator().manual_seed(seed),74 ).images[0]75 return image, seed, gr.update(visible=True)76 77css="""78#col-container {79 margin: 0 auto;80 max-width: 960px;81}82"""83 84with gr.Blocks(css=css) as demo:85 86 with gr.Column(elem_id="col-container"):87 gr.Markdown(f"""# FLUX.1 Kontext [dev]88Image editing and manipulation model guidance-distilled from FLUX.1 Kontext [pro], [[blog]](https://bfl.ai/announcements/flux-1-kontext-dev) [[model]](https://huggingface.co/black-forest-labs/FLUX.1-Kontext-dev)89 """)90 with gr.Row():91 with gr.Column():92 input_image = gr.Image(label="Upload the image for editing", type="pil")93 with gr.Row():94 prompt = gr.Text(95 label="Prompt",96 show_label=False,97 max_lines=1,98 placeholder="Enter your prompt for editing (e.g., 'Remove glasses', 'Add a hat')",99 container=False,100 )101 run_button = gr.Button("Run", scale=0)102 with gr.Accordion("Advanced Settings", open=False):103 104 seed = gr.Slider(105 label="Seed",106 minimum=0,107 maximum=MAX_SEED,108 step=1,109 value=0,110 )111 112 randomize_seed = gr.Checkbox(label="Randomize seed", value=True)113 114 guidance_scale = gr.Slider(115 label="Guidance Scale",116 minimum=1,117 maximum=10,118 step=0.1,119 value=2.5,120 ) 121 122 steps = gr.Slider(123 label="Steps",124 minimum=1,125 maximum=30,126 value=28,127 step=1128 )129 130 with gr.Column():131 result = gr.Image(label="Result", show_label=False, interactive=False)132 reuse_button = gr.Button("Reuse this image", visible=False)133 134 135 gr.on(136 triggers=[run_button.click, prompt.submit],137 fn = infer,138 inputs = [input_image, prompt, seed, randomize_seed, guidance_scale, steps],139 outputs = [result, seed, reuse_button]140 )141 reuse_button.click(142 fn = lambda image: image,143 inputs = [result],144 outputs = [input_image]145 )146 147demo.launch(mcp_server=True)